diff --git "a/4544.jsonl" "b/4544.jsonl" new file mode 100644--- /dev/null +++ "b/4544.jsonl" @@ -0,0 +1,721 @@ +{"seq_id":"381268267","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport django_filters\nfrom django_filters import MethodFilter\nfrom .models import Colaborador\nfrom django.db.models import Q\n\nclass CustomFilterList(django_filters.Filter):\n def filter(self, qs, value):\n if value not in (None, ''):\n values = [v for v in value.split(',')]\n q = Q()\n for q_object in values:\n name = \"%s__%s\" % (self.name, self.lookup_type)\n q.add(Q(**{name:q_object}),Q.OR)\n return qs.filter(q)\n return qs\n\nclass ColaboradorFilter(django_filters.FilterSet):\n nombre = MethodFilter(action='nombre_filtro')\n cedula = MethodFilter(action='cedula_filtro')\n\n cargo = MethodFilter(action='cargo_filtro')\n area = MethodFilter(action='area_filtro')\n\n jefe = MethodFilter(action='jefe_filtro')\n fecha_ingreso = MethodFilter(action='fecha_ingreso_filtro')\n\n evaluacion = MethodFilter(action='evaluacion_filtro')\n formato = MethodFilter(action='formato_filtro')\n\n fecha_induccion = MethodFilter(action='fecha_induccion_filtro')\n nota_evaluacion = MethodFilter(action='nota_evaluacion_filtro')\n\n class Meta:\n model = Colaborador\n fields = ['nombre','cedula','cargo','area','fecha_ingreso','jefe','evaluacion','formato','fecha_induccion','nota_evaluacion']\n\n def nombre_filtro(self, qs, value):\n if value not in (None, ''):\n values = [v for v in value.split(',')]\n q = Q()\n for q_object in values:\n name = \"%s__%s\" % ('nombre', 'icontains')\n q.add(Q(**{name:q_object}),Q.OR)\n return qs.filter(q)\n return qs\n\n def cedula_filtro(self, qs, value):\n if value not in (None, ''):\n values = [v for v in value.split(',')]\n q = Q()\n for q_object in values:\n name = \"%s__%s\" % ('cedula', 'icontains')\n q.add(Q(**{name:q_object}),Q.OR)\n return qs.filter(q)\n return qs\n\n def cargo_filtro(self, qs, value):\n if value not in (None, ''):\n values = [v for v in value.split(',')]\n q = Q()\n for q_object in values:\n name = \"%s__%s\" % ('cargo', 'icontains')\n q.add(Q(**{name:q_object}),Q.OR)\n return qs.filter(q)\n return qs\n\n def area_filtro(self, qs, value):\n if value not in (None, ''):\n values = [v for v in value.split(',')]\n q = Q()\n for q_object in values:\n name = \"%s__%s\" % ('area', 'icontains')\n q.add(Q(**{name:q_object}),Q.OR)\n return qs.filter(q)\n return qs\n\n def jefe_filtro(self, qs, value):\n if value not in (None, ''):\n values = [v for v in value.split(',')]\n q = Q()\n for q_object in values:\n name = \"%s__%s\" % ('jefe', 'icontains')\n q.add(Q(**{name:q_object}),Q.OR)\n return qs.filter(q)\n return qs\n\n def evaluacion_filtro(self, qs, value):\n if value not in (None, ''):\n values = [v for v in value.split(',')]\n q = Q()\n for q_object in values:\n if q_object == 'Si' or q_object == 'si' or q_object == 'SI' or q_object == 'sI':\n qs = qs.filter(evaluacion=True)\n elif q_object == \"No\" or q_object == \"no\" or q_object == \"NO\" or q_object == \"nO\":\n qs = qs.filter(evaluacion=False)\n return qs.filter(q)\n return qs\n\n def formato_filtro(self, qs, value):\n if value not in (None, ''):\n values = [v for v in value.split(',')]\n q = Q()\n for q_object in values:\n if q_object == 'Si' or q_object == 'si' or q_object == 'SI' or q_object == 'sI':\n qs = qs.filter(formato=True)\n elif q_object == \"No\" or q_object == \"no\" or q_object == \"NO\" or q_object == \"nO\":\n qs = qs.filter(formato=False)\n return qs","sub_path":"personal/filters.py","file_name":"filters.py","file_ext":"py","file_size_in_byte":4074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"303092254","text":"import numpy as np\nfrom data import preprocess, transform, build_up_for_auxiliary_model\nfrom model import classifier, Seq2Seq\nimport torch\nimport pickle\n\nw2id = pickle.load(open('e2e-dataset/w2id.pkl', 'rb'))\nid2w = pickle.load(open('e2e-dataset/id2w.pkl', 'rb'))\nv2id = pickle.load(open('e2e-dataset/v2id.pkl', 'rb'))\nprint(v2id)\n\nmr, mr_lengths = transform(w2id, 'e2e-dataset/devset_mr.txt')\nref, ref_lengths = transform(w2id, 'e2e-dataset/devset_ref.txt')\nbinary_representation = build_up_for_auxiliary_model('e2e-dataset/devset.csv', False)\n\nembedding_size = 50\nhidden_size = 128\nbatch_size = 20\nvocab_size = len(w2id)\nvalue_size = binary_representation.shape[1]\n\ndata_size = len(ref)\niters = data_size//batch_size\nif iters * batch_size < data_size:\n iters += 1\n\nclf = classifier(vocab_size, embedding_size, hidden_size, value_size)\nfor k in range(1):\n clf.load_state_dict(torch.load('checkpoint/'+str(112)+'-parameter.pkl'))\n loss = np.zeros(value_size)\n for i in range(iters):\n start = i*batch_size\n end = min((i+1)*batch_size, data_size)\n y = clf.forward(torch.LongTensor(ref[start:end]), torch.LongTensor(ref_lengths[start:end]))\n y[y <= 0.5] = 0\n y[y > 0.5] = 1\n t_tgt = binary_representation[start:end]\n loss += np.sum(abs(y.detach().numpy()-t_tgt), axis=0)\n print(sum(loss))\n print(loss)\n\n# seq2seq = Seq2Seq(vocab_size, hidden_size, embedding_size)\n# seq2seq.load_state_dict(torch.load('checkpoint/s2s-600-parameter.pkl'))\n# txt = seq2seq.generate(torch.LongTensor(mr[0]), torch.LongTensor([mr_lengths[0]]), 5).detach().numpy()\n#\n# for s in txt:\n# for index in s:\n# print(id2w[index], end=' ')\n# if index == 0:\n# break\n# print('')\n","sub_path":"dev.py","file_name":"dev.py","file_ext":"py","file_size_in_byte":1746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"240248473","text":"from django.db import models\nfrom django import forms\n\nfrom samples.custom import models as cmodels\n\n\nclass Patient(models.Model):\n name = models.CharField(\n verbose_name=\"Nome do paciente\",\n max_length=255,\n )\n\n def __str__(self):\n return self.name\n\n\nclass AdmissionNote(models.Model):\n patient = models.ForeignKey(\n Patient,\n null=True,\n )\n observed_symptoms = models.ManyToManyField(\n 'Symptom',\n through='ObservedSymptom',\n )\n id_gal_origin = models.CharField(\n verbose_name=\"ID Gal Origem\",\n max_length=255,\n )\n\n def __str__(self):\n return \"ID Gal: {}\".format(self.id_gal_origin)\n\n\nclass FluVaccine(models.Model):\n was_applied = cmodels.YesNoIgnoredField(\n verbose_name=\"Recebeu vacina contra gripe?\",\n )\n date_applied = models.DateField(\n verbose_name=\"Data de aplicação\",\n null=True,\n blank=True,\n )\n admission_note = models.OneToOneField(\n AdmissionNote,\n on_delete=models.CASCADE,\n )\n\n def __str__(self):\n return \"Vacina contra gripe\"\n\n\nclass CollectionType(models.Model):\n method_name = models.CharField(\n verbose_name=\"Método de coleta\",\n max_length=255,\n )\n is_primary = models.BooleanField(\n verbose_name=\"Principal?\",\n default=True,\n )\n\n def __str__(self):\n return self.method_name\n\n\nclass CollectedSample(models.Model):\n collection_date = models.DateField(\n verbose_name=\"Data de coleta\",\n )\n admission_note = models.ForeignKey(\n AdmissionNote,\n )\n collection_type = models.ForeignKey(\n CollectionType,\n on_delete=models.SET_NULL,\n null=True,\n )\n\n def __str__(self):\n return \"Amostra coletada\"\n\n\nclass Symptom(models.Model):\n name = models.CharField(\n verbose_name=\"Nome do sintoma\",\n max_length=255,\n )\n is_primary = models.BooleanField(\n verbose_name=\"Principal?\",\n default=True,\n )\n\n def __str__(self):\n return self.name\n\n\nclass ObservedSymptom(models.Model):\n symptom = models.ForeignKey(\n Symptom,\n on_delete=models.CASCADE,\n )\n admission_note = models.ForeignKey(\n AdmissionNote,\n on_delete=models.CASCADE,\n )\n observed = models.NullBooleanField(\n verbose_name=\"Apresenta sintoma?\",\n default=None,\n )\n\n class Meta:\n unique_together = (\n ('symptom', 'admission_note'),\n )\n\n def __str__(self):\n return \"Sintoma apresentado\"\n","sub_path":"samples/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"79126424","text":"import os\nimport cv2 \nimport numpy as np\nfrom math import floor\nfrom segment_graph import *\nfrom sklearn.decomposition import PCA\n\ndef calcRgbHistFeature(image, bin_num, mask = None):\n if mask is None:\n height, width, _ = image.shape\n img = np.reshape(image, newshape = (height*width,3))\n else:\n img = reshapeMaskedImg(image, mask)\n length, channel = img.shape\n assert channel == 3 \n interval = 256 / bin_num\n colorspace = np.zeros(shape = (bin_num, bin_num, bin_num), dtype = float)\n for p in range(length):\n pix_val = img[p,:]\n i, j, k = floor(pix_val[0]/interval), floor(pix_val[1]/interval), floor(pix_val[2]/interval)\n colorspace[i, j, k] += 1\n fvec = np.reshape(colorspace, newshape= bin_num ** 3)\n fvec = fvec / length\n return fvec\n\ndef reshapeMaskedImg(image, mask):\n assert image.shape[:2] == mask.shape\n front_size = len(mask[mask==255])\n ret = np.zeros(shape=(front_size, 3), dtype = np.uint8)\n h, w, _ = image.shape\n i = 0\n for r in range(h):\n for c in range(w):\n if mask[r,c] == 255:\n ret[i] = image[r,c]\n return ret\n\ndef comp2Mask(comp, djs, ht):\n mask = np.zeros(shape=(ht.h,ht.w), dtype= np.uint8)\n vertices = djs.all_vertices_in_comp(comp)\n for v in vertices:\n pix = ht.vertice2pix(v)\n mask[pix[0],pix[1]] = 255\n return mask\n\ndef calcFeatureMatrix(img, bin_num, djs, ht):\n img_rgb_fvec = calcRgbHistFeature(img, bin_num)\n fmat = []\n for comp in djs.all_comp():\n mask = comp2Mask(comp, djs, ht)\n comp_rgb_fvec = calcRgbHistFeature(img, bin_num, mask)\n fvec = np.concatenate((comp_rgb_fvec, img_rgb_fvec))\n fmat.append(fvec)\n fmat = np.array(fmat)\n return fmat\n\ndef calcLabelVec(ht, comps, gt_seg):\n y_train = []\n for comp in comps:\n (y, x) = ht.vertice2pix(comp)\n if gt_seg[y,x] == 255:\n y_train.append(1)\n else:\n y_train.append(0)\n return y_train\n\ndef make_blobs(im_path, gt_path, gt_seg_path):\n pic_list = os.listdir(im_path)\n k, sigma, min, bin_num, n_features = 80, 0.8, 20, 8, 50\n pca = PCA(n_components=n_features)\n data, label = [], []\n\n for (i,pic) in enumerate(pic_list):\n print(i,\"/\", len(pic_list))\n img, gt, gt_seg = cv2.imread(im_path+pic), cv2.imread(gt_path+pic), cv2.imread(gt_seg_path+pic)\n gt, gt_seg = cv2.cvtColor(gt,cv2.COLOR_BGR2GRAY), cv2.cvtColor(gt_seg,cv2.COLOR_BGR2GRAY)\n\n djs = segment(img, sigma, k, min)\n ht = vp_hash_table(img.shape[0], img.shape[1])\n\n fmat = calcFeatureMatrix(img, bin_num, djs, ht)\n for fvec in fmat:\n data.append(fvec)\n\n label = label + calcLabelVec(ht, djs.all_comp(), gt_seg)\n data = pca.fit_transform(data)\n data, label = np.array(data), np.array(label)\n return data, label","sub_path":"src/q3/data_generation.py","file_name":"data_generation.py","file_ext":"py","file_size_in_byte":2924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"378924641","text":"import operator\n\ndef difference(n):\n \"\"\"This problem was optimized for the HackerRank interface. Since there will\n be multiple values being passed in, rather than computing the differences for\n each and every value, it would be more efficient to compute the difference for\n the largest value, then store all intermediate entries in an array and reference\n them when returning the final value. This takes up unnecessary space, but is easy\n to implement. The more space efficient version would only append to the output list\n when the i-th iteration is a value in the input n.\n :param n: The list of numbers to evaluate the sum square difference.\"\"\"\n differences = []\n\n # Map all values of n to int.\n n = map(int, n)\n # First evaluate the sum square difference of the highest value in the list.\n highest = max(n)\n\n # Keep track of each point in the iteration to make computation simpler.\n sum_square = 0\n square_sum = 0\n\n for i in range(1, highest+1):\n sum_square += i ** 2\n square_sum += i\n\n differences.append(square_sum ** 2 - sum_square)\n\n return [differences[i-1] for i in n]","sub_path":"ProjectEuler/006/sum_square_difference.py","file_name":"sum_square_difference.py","file_ext":"py","file_size_in_byte":1153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"550624001","text":"dict1 = dict()\nprint('請輸入第1個字典: ')\nwhile True:\n key = input('key: ')\n if key =='end':\n break\n value = input('Value: ')\n dict1[key] = value\ndict2 = dict()\nprint('請輸入第2個字典: ')\nwhile True:\n key = input('key: ')\n if key =='end':\n break\n value = input('Value: ')\n dict2[key] = value\n\ndict1.update( dict2 )\n\nfor i in sorted(dict1.keys()):\n print(i,': ',dict1[i],sep='')","sub_path":"practice05.py","file_name":"practice05.py","file_ext":"py","file_size_in_byte":436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"506741081","text":"# Lint as: python2, python3\n# Copyright 2019 Google LLC. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Generic TFX RedisExampleGen executor.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport datetime\nfrom typing import Any, Dict, Iterable, Text, Tuple\n\nimport apache_beam as beam\nimport redis\nfrom redis_proto import redis_config_pb2\nfrom redis_proto import redis_hash_query_pb2\nimport tensorflow as tf\nfrom tfx.components.example_gen import base_example_gen_executor\nfrom tfx.proto import example_gen_pb2\n\nfrom google.protobuf import json_format\n\n\n@beam.typehints.with_input_types(Text)\n@beam.typehints.with_output_types(beam.typehints.Iterable[Tuple[Text, Text, Text]])\nclass _ReadRedisDoFn(beam.DoFn):\n \"\"\"Beam DoFn class that reads from Redis.\n\n Attributes:\n redis_conn: A Redis client connection.\n \"\"\"\n\n def __init__(self, redis_config: Dict):\n self.redis_config = redis_config\n\n def hash_iter(self, pattern):\n for result in self.redis_conn.scan_iter(match=pattern, _type='HASH'):\n yield self.redis_conn.hgetall(result)\n\n def process(self, query: Text) -> Iterable[Tuple[Text, Text, Text]]:\n # \"\"\"Yields rows from Redis pattern scan results.\n #\n # Args:\n # pattern: The pattern of the keys where each data point is stored.\n #\n # Yields:\n # One row from the query result, represented by a list of tuples. Each tuple\n # contains information on column name, column data type, data.\n # \"\"\"\n self.redis_conn = redis.Redis(**(self.redis_config))\n cols = []\n col_types = []\n query_pb = redis_hash_query_pb2.RedisHashQuery()\n query_pb = json_format.Parse(query, query_pb)\n for i in range(len(query_pb.schema)):\n pair_schema = query_pb.schema[i]\n cols.append(pair_schema.name)\n col_types.append(redis_hash_query_pb2.redis_hash_pair_schema.hash_field_type.Name(pair_schema.type))\n for result in self.hash_iter(query_pb.hash_key_pattern):\n values = [result.get(col_name) for col_name in cols]\n yield list(zip(cols, col_types, values))\n\n def teardown(self):\n if self.redis_conn:\n self.redis_conn.close()\n\n\ndef _deserialize_conn_config(conn_config: redis_config_pb2.RedisConnConfig) -> Dict:\n \"\"\"Deserializes Redis connection config to Redis python client.\n\n Args:\n conn_config: Protobuf-encoded connection config for Redis client.\n\n Returns:\n A redis.Redis instance initialized with user-supplied\n parameters.\n \"\"\"\n params = {'decode_responses': True}\n # Only deserialize rest of parameters if set by user\n if conn_config.HasField('host'):\n params['host'] = conn_config.host\n if conn_config.HasField('port'):\n params['port'] = conn_config.port\n if conn_config.HasField('username'):\n params['username'] = conn_config.username\n if conn_config.HasField('password'):\n params['password'] = conn_config.password\n if conn_config.HasField('db'):\n params['db'] = conn_config.db\n return params\n\n\ndef _row_to_example(instance: Iterable[Tuple[Text, Text, Text]]) -> tf.train.Example:\n \"\"\"Convert Redis result row to tf example.\"\"\"\n feature = {}\n for key, data_type, value in instance:\n if value is None:\n feature[key] = tf.train.Feature()\n continue\n elif data_type == 'integer':\n feature[key] = tf.train.Feature(\n int64_list=tf.train.Int64List(value=[int(float(value)) if value != 'nan' else 0]))\n elif data_type == 'float':\n feature[key] = tf.train.Feature(\n float_list=tf.train.FloatList(value=[float(value) if value != 'nan' else 0.0]))\n elif data_type == 'string':\n feature[key] = tf.train.Feature(\n bytes_list=tf.train.BytesList(value=[tf.compat.as_bytes(value if value != 'nan' else '')]))\n else:\n raise RuntimeError(\n 'Column type {} is not supported.'.format(data_type))\n return tf.train.Example(features=tf.train.Features(feature=feature))\n\n\n@beam.ptransform_fn\n@beam.typehints.with_input_types(beam.Pipeline)\n@beam.typehints.with_output_types(tf.train.Example)\ndef _RedisToExample( # pylint: disable=invalid-name\n pipeline: beam.Pipeline,\n exec_properties: Dict[Text, Any],\n split_pattern: Text) -> beam.pvalue.PCollection:\n \"\"\"Read from Redis and transform to TF examples.\n\n Args:\n pipeline: beam pipeline.\n exec_properties: A dict of execution properties.\n split_pattern: Split.pattern in Input config, a Redis keys pattern string.\n\n Returns:\n PCollection of TF examples.\n \"\"\"\n conn_config = example_gen_pb2.CustomConfig()\n json_format.Parse(exec_properties['custom_config'], conn_config)\n redis_config = redis_config_pb2.RedisConnConfig()\n conn_config.custom_config.Unpack(redis_config)\n\n client_config = _deserialize_conn_config(redis_config)\n return (pipeline\n | 'Query' >> beam.Create([split_pattern])\n | 'QueryRedis' >> beam.ParDo(_ReadRedisDoFn(client_config))\n | 'ToTFExample' >> beam.Map(_row_to_example))\n\n\nclass Executor(base_example_gen_executor.BaseExampleGenExecutor):\n \"\"\"Generic TFX RedisExampleGen executor.\"\"\"\n\n def GetInputSourceToExamplePTransform(self) -> beam.PTransform:\n \"\"\"Returns PTransform for Redis to TF examples.\"\"\"\n return _RedisToExample\n","sub_path":"redis_component/executor.py","file_name":"executor.py","file_ext":"py","file_size_in_byte":6083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"579971680","text":"'''\nCreated by auto_sdk on 2014-12-17 11:49:33\n'''\nfrom top.api.base import RestApi\n\n\nclass AlibabaXiamiApiTagGenreAlbumRequest(RestApi):\n def __init__(self, domain='gw.api.taobao.com', port=80):\n RestApi.__init__(self, domain, port)\n self.id = None\n self.type = None\n self.page = 1\n self.limit = 20\n\n def getapiname(self):\n return 'alibaba.xiami.api.tag.genre.album.get'\n","sub_path":"src/top/api/rest/AlibabaXiamiApiTagGenreAlbumRequest.py","file_name":"AlibabaXiamiApiTagGenreAlbumRequest.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"561237845","text":"def rotate(matrix: list):\n L = []\n lenOfRow = len(matrix[0])\n numOfRow = len(matrix)\n \n for i in range(lenOfRow):\n L.append([])\n \n for i in range(numOfRow): \n for j in range(lenOfRow):\n L[j].append(matrix[i][lenOfRow - j - 1])\n \n return L\n\ndef printMatrix(matrix: list):\n print(f\"{len(matrix)} {len(matrix[0])}\")\n for row in matrix:\n for number in row:\n print(number, end = ' ')\n print()\n\ndef main():\n while True:\n try:\n R, C, M = map(int, input().split())\n except:\n break\n \n matrix = []\n for i in range(R):\n matrix.append(list(map(int, input().split())))\n \n cmdList = list(map(int, input().split()))\n \n for cmd in cmdList[::-1]:\n if cmd == 0:\n matrix = rotate(matrix)\n else:\n matrix.reverse()\n \n printMatrix(matrix)\n \n \nmain()\n","sub_path":"IOI&APCS/b266/b266.py","file_name":"b266.py","file_ext":"py","file_size_in_byte":1005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"540588884","text":"from nltk.classify import NaiveBayesClassifier\nfrom nltk import precision\nfrom sklearn.naive_bayes import MultinomialNB\nfrom src.textprocessing.Word_Corpus import WordCorpus\nfrom src.textprocessing.Text_Cleanup import TextCleanup\nfrom src.textprocessing.Scoring_Functions import Scoring_Functions\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n#\nclass SentimentAnalyzer():\n #\n \"\"\"\n Example:\n\n from src.textprocessing.SentimentAnalyzer import SentimentAnalyzer\n sa = SentimentAnalyzer()\n pred = sa.predict(\"I will never go there again\")\n print(pred)\n \"\"\"\n def __init__(self):\n self.vectorizer = TfidfVectorizer()\n self.__word_corpus = WordCorpus()\n X, y = self.__format_vocab()\n self.__NBclassifier = self.__train_classifier(X, y)\n self.text_cleanup = TextCleanup()\n #\n def __format_vocab(self):\n \"\"\" Returns an entire set of vocab which is marked as either 1) Positive, 2) Negative, 3) Neutral for NLTK\n classification \"\"\"\n positive_vocab, negative_vocab, neutral_vocab = self.__word_corpus.get_vocab()\n pos_list, neu_list, neg_list = [],[],[]\n #\n [(pos_list.append('pos')) for i in range(len(positive_vocab))]\n [(neu_list.append('neu')) for i in range(len(neutral_vocab))]\n [(neg_list.append('neg')) for i in range(len(negative_vocab))]\n #\n return positive_vocab + negative_vocab + neutral_vocab, pos_list + neu_list + neg_list\n #\n def __train_classifier(self, X, y=None):\n \"\"\" Takes the training vocab (consisting of pos,neg,neu) vocab and trains itself \"\"\"\n #\n # Scikit Naive Bayes Multinomial classifier.\n X = self.vectorizer.fit_transform(X)\n print(self.vectorizer)\n classifier = MultinomialNB().fit(X,y)\n print(classifier)\n return classifier\n #\n def __classify(self, word):\n \"\"\" Takes input sample and classifies it as either pos / neu / neg \"\"\"\n #\n # Scikit Naive Bayes Multinomial classifier.\n word = self.vectorizer.transform([word])\n return self.__NBclassifier.predict(word)\n #\n def predict(self,sentence):\n \"\"\" Public function. Takes a sentence as parameter and assigns a sentiment label to it (pos/neg/neu) \"\"\"\n pos,neg,neu = 0,0,0\n neutral_weight = 0 # We introduce a weight to positive and negative scalar counts, to classify as neutral in the case of close pos-neg tie ins\n #\n filtered_words = self.text_cleanup.clean_sentence(sentence)\n #self.__NBclassifier.show_most_informative_features()\n for word in filtered_words:\n prediction = self.__classify(word)\n #print(str(word) + \" - \" + str(prediction))\n if prediction == \"pos\":\n pos += 1\n elif prediction == \"neg\":\n neg += 1\n elif prediction == \"neu\":\n neu += 1\n #\n if pos-neutral_weight > neg and pos-neutral_weight > neu:\n return \"pos\"\n elif neg-neutral_weight > pos and neg-neutral_weight > neu:\n return \"neg\"\n else:\n return \"neu\"\n #\n def test_set(self):\n \"\"\" Public function. Uses the classifier on the testing set of data to determine the accuracy \"\"\"\n #\n y_pred, y_true = [], []\n test_sentences, y_true = self.__word_corpus.get_test_corpus()\n #\n [(y_pred.append(self.predict(sentence))) for sentence in test_sentences]\n #\n score_func = Scoring_Functions(y_pred, y_true)\n accuracy = score_func.accuracy()\n precision = score_func.precision()\n recall = score_func.recall()\n f_measure = score_func.f_measure()\n return \"Accuracy: \" + str(accuracy) + \"\\nPrecision: \" + str(precision) + \"\\nRecall: \" + str(recall) + \"\\nF_Measure: \" + str(f_measure)\n","sub_path":"src/textprocessing/SentimentAnalyzer_NB.py","file_name":"SentimentAnalyzer_NB.py","file_ext":"py","file_size_in_byte":3880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"162408906","text":"import pygame\n\nfrom pygame.sprite import Sprite\nfrom game_object import GameObject\n\n\"\"\"The falling tetronimo class. Created every time a new tetronimo must fall from the top of the screen.\"\"\"\nclass TetronimoFalling(GameObject):\n\tdef __init__(self, object_id, tag, position_x, position_y, tetronimo_type, \\\n\t\t\tobject_factory, settings, input_manager, collision_box, sprite_images):\n\t\t\"\"\"Initialized the tetronimo falling game object.\"\"\"\n\t\t\t\n\t\t# Call the inherited class constructor.\n\t\tsuper(TetronimoFalling, self).__init__(object_id, tag, position_x, position_y, \\\n\t\t\t\tcollision_box, sprite_images)\n\t\t\n\t\t# Checks if the tetronimo is falling.\n\t\tself.is_falling = True\n\t\t\n\t\t# Checks if the tetronimo can move left.\n\t\tself.can_move_left = True\n\t\t\n\t\t# Checks if the tetronimo can move right.\n\t\tself.can_move_right = True\n\t\t\n\t\t# Checks if the tetronimo can rotate.\n\t\tself.can_rotate = True\n\t\t\n\t\t# Checks if the left key was pressed.\n\t\tself.pressed_left = False\n\t\t\n\t\t# Checks if the right key was pressed.\n\t\tself.pressed_right = False\n\t\t\n\t\t# Checks if the rotate key was pressed.\n\t\tself.pressed_rotate = False\n\t\t\n\t\t# Checks if the auto land key was pressed.\n\t\tself.pressed_autoland = False\n\t\t\n\t\t# The tetronimo type. Use the number, not the character in parenthesis.\n\t\t# Rotation states are also shown. This follows the SRS Tetris format (except the s \n\t\t# and z tetronimos).\n\t\t#------------------------------\n\t\t# Type R1 R2 R3 R4\n\t\t#------------------------------\n\t\t# 0(O) - .OO. .OO. .OO. .OO.\n\t\t#\t .OO. .OO. .OO. .OO.\n\t\t# .... .... .... ....\n\t\t#\n\t\t# 1(I) - .... ..O. .... .O..\n\t\t# OOOO ..O. .... .O..\n\t\t# .... ..O. OOOO .O..\n\t\t# .... ..O. .... .O..\n\t\t#\n\t\t# 2(L) - ..O .O. ... OO.\n\t\t# OOO .O. OOO .O.\n\t\t# ... .OO O.. .O.\n\t\t#\n\t\t# 3(J) - O.. .OO ... .O.\n\t\t# OOO .O. OOO .O.\n\t\t# ... .O. ..O OO.\n\t\t#\n\t\t# 4(S) - .OO O.. .OO O..\n\t\t# OO. OO. OO. OO.\n\t\t# ... .O. ... .O.\n\t\t#\n\t\t# 5(Z) - OO. ..O OO. ..O\n\t\t# .OO .OO .OO .OO\n\t\t# ... .O. ... .O.\n\t\t#\n\t\t# 6(T) - .O. .O. ... .O.\n\t\t# OOO .OO OOO OO.\n\t\t# ... .O. .O. .O.\n\t\tself.tetronimo_type = tetronimo_type\n\t\t\n\t\t# The rotation state of the tetronimo. See the graph above for the 4 rotation \n\t\t# states.\n\t\tself.rotation_state = 0\n\t\t\n\t\t# The current horizontal frame for horizontal movement.\n\t\tself.cur_horizontal_frame = 0\n\t\t\n\t\t# The maximum horizontal frame for horizontal movement.\n\t\tself.max_horizontal_frame = 8\n\t\t\n\t\t# A list of all the tetronimo blocks that belong to this game object.\n\t\tself.tetronimo_blocks = []\n\t\t\n\t\t# The four rotations of the tetronimo. Contains a list of tuples for the x and y \n\t\t# positions of each block.\n\t\tself.rotations = []\n\t\t\n\t\t# The kick positions for the tetronimo for all 4 rotations. Contains tuples with 4 \n\t\t# values:\n\t\t# 0 - position_x,\n\t\t# 1 - position_y,\n\t\t# 2 - direction - 0 - left, 1 - right, 2 - up, 3 - down,\n\t\t# 3 - kick_offset,\n\t\tself.kick_positions = []\n\t\t\n\t\t# A reference to the game object factory. It is used to create the tetronimo \n\t\t# blocks.\n\t\tself.object_factory = object_factory\n\t\t\n\t\t# A reference to the game settings.\n\t\tself.settings = settings\n\t\t\n\t\t# A reference to the input manager.\n\t\tself.input_manager = input_manager\n\t\t\n\t\t# Create the tetronimo blocks that belong to this game object.\n\t\tself.create_tetronimo_blocks()\n\t\t\n\tdef create_tetronimo_blocks(self):\n\t\t\"\"\"Create the tetronimo blocks for the falling tetronimo.\"\"\"\n\t\t\n\t\t# The cached x and y position of the tetronimo.\n\t\tpos_x = self.position_x\n\t\tpos_y = self.position_y\n\t\t\t\n\t\t# The rotation position lists of the tetronimo.\n\t\trotation1 = []\n\t\trotation2 = []\n\t\trotation3 = []\n\t\trotation4 = []\n\t\t\n\t\t# The kick position arrays of the tetronimos for different rotations.\n\t\tkick1 = []\n\t\tkick2 = []\n\t\tkick3 = []\n\t\tkick4 = []\n\t\t\n\t\t# Different types of tetronimo blocks will have different block positions and \n\t\t# colors.\n\t\tif self.tetronimo_type == 0:\n\t\t\t\n\t\t\t# .OO.\n\t\t\t# .OO.\n\t\t\t# ....\n\t\t\trotation1.append((-16, -16))\n\t\t\trotation1.append((16, -16))\n\t\t\trotation1.append((-16, 16))\n\t\t\trotation1.append((16, 16))\n\t\t\t\n\t\t\trotation2 = rotation1\n\t\t\trotation3 = rotation1\n\t\t\trotation4 = rotation1\n\t\t\t\n\t\telif self.tetronimo_type == 1:\n\t\t\t\n\t\t\t# 1(I) - .... ..O. .... .O..\n\t\t\t# OOOO ..O. .... .O..\n\t\t\t# .... ..O. OOOO .O..\n\t\t\t# .... ..O. .... .O..\n\t\t\trotation1.append((-48, 32))\n\t\t\trotation1.append((-16, 32))\n\t\t\trotation1.append((16, 32))\n\t\t\trotation1.append((48, 32))\n\t\t\t\n\t\t\trotation2.append((16, 96))\n\t\t\trotation2.append((16, 64))\n\t\t\trotation2.append((16, 32))\n\t\t\trotation2.append((16, 0))\n\t\t\t\n\t\t\trotation3.append((-48, 64))\n\t\t\trotation3.append((-16, 64))\n\t\t\trotation3.append((16, 64))\n\t\t\trotation3.append((48, 64))\n\t\t\t\n\t\t\trotation4.append((-16, 96))\n\t\t\trotation4.append((-16, 64))\n\t\t\trotation4.append((-16, 32))\n\t\t\trotation4.append((-16, 0))\n\t\t\t\n\t\t\tkick1.append((-16, 32, 0, 64))\n\t\t\tkick1.append((-48, 32, 0, 32))\n\t\t\tkick1.append((48, 32, 1, -32))\n\t\t\tkick1.append((16, 32, 1, -64))\n\t\t\t\n\t\t\tkick2.append((16, 0, 2, 32))\n\t\t\tkick2.append((16, 64, 3, -64))\n\t\t\tkick2.append((16, 96, 3, -32))\n\t\t\t\n\t\t\tkick3.append((-16, 64, 0, 64))\n\t\t\tkick3.append((-48, 64, 0, 32))\n\t\t\tkick3.append((48, 64, 1, -32))\n\t\t\tkick3.append((16, 64, 1, -64))\n\t\t\t\n\t\t\tkick4.append((-16, 0, 2, 32))\n\t\t\tkick4.append((-16, 32, 2, 64))\n\t\t\tkick4.append((-16, 96, 3, -32))\n\t\t\t\n\t\telif self.tetronimo_type == 2:\n\t\t\t\n\t\t\t# 2(L) - ..O .O. ... OO.\n\t\t\t# OOO .O. OOO .O.\n\t\t\t# ... .OO O.. .O.\n\t\t\trotation1.append((0, 0))\n\t\t\trotation1.append((-32, 0))\n\t\t\trotation1.append((32, 0))\n\t\t\trotation1.append((32, -32))\n\t\t\t\n\t\t\trotation2.append((0, 0))\n\t\t\trotation2.append((0, -32))\n\t\t\trotation2.append((0, 32))\n\t\t\trotation2.append((32, 32))\n\t\t\t\n\t\t\trotation3.append((0, 0))\n\t\t\trotation3.append((-32, 0))\n\t\t\trotation3.append((32, 0))\n\t\t\trotation3.append((-32, 32))\n\t\t\t\n\t\t\trotation4.append((0, 0))\n\t\t\trotation4.append((0, -32))\n\t\t\trotation4.append((0, 32))\n\t\t\trotation4.append((-32, -32))\n\t\t\t\n\t\t\tkick1.append((-32, 0, 0, 32))\n\t\t\tkick1.append((32, 0, 2, 32))\n\t\t\tkick1.append((32, -32, 1, -32))\n\t\t\tkick1.append((32, -32, 2, 32))\n\t\t\t\n\t\t\tkick2.append((0, -32, 2, 32))\n\t\t\tkick2.append((0, 32, 3, -32))\n\t\t\tkick2.append((32, 32, 3, -32))\n\t\t\tkick2.append((32, 32, 1, -32))\n\t\t\t\n\t\t\tkick3.append((-32, 0, 0, 32))\n\t\t\tkick3.append((32, 0, 1, -32))\n\t\t\tkick3.append((-32, 32, 3, -32))\n\t\t\tkick3.append((-32, 32, 0, 32))\n\t\t\t\n\t\t\tkick4.append((0, -32, 2, 32))\n\t\t\tkick4.append((0, 32, 3, -32))\n\t\t\tkick4.append((-32, -32, 2, 32))\n\t\t\tkick4.append((-32, -32, 0, 32))\n\t\t\n\t\telif self.tetronimo_type == 3:\n\t\t\t\n\t\t\t# 3(J) - O.. .OO ... .O.\n\t\t\t# OOO .O. OOO .O.\n\t\t\t# ... .O. ..O OO.\n\t\t\trotation1.append((0, 0))\n\t\t\trotation1.append((-32, 0))\n\t\t\trotation1.append((32, 0))\n\t\t\trotation1.append((-32, -32))\n\t\t\t\n\t\t\trotation2.append((0, 0))\n\t\t\trotation2.append((0, -32))\n\t\t\trotation2.append((0, 32))\n\t\t\trotation2.append((32, -32))\n\t\t\t\n\t\t\trotation3.append((0, 0))\n\t\t\trotation3.append((-32, 0))\n\t\t\trotation3.append((32, 0))\n\t\t\trotation3.append((32, 32))\n\t\t\t\n\t\t\trotation4.append((0, 0))\n\t\t\trotation4.append((0, 32))\n\t\t\trotation4.append((0, -32))\n\t\t\trotation4.append((-32, 32))\n\t\t\t\n\t\t\tkick1.append((-32, 0, 0, 32))\n\t\t\tkick1.append((32, 0, 1, -32))\n\t\t\tkick1.append((-32, -32, 0, 32))\n\t\t\tkick1.append((-32, -32, 2, 32))\n\t\t\t\n\t\t\tkick2.append((0, -32, 3, -32))\n\t\t\tkick2.append((0, 32, 2, 32))\n\t\t\tkick2.append((32, -32, 3, -32))\n\t\t\tkick2.append((32, -32, 1, -32))\n\t\t\t\n\t\t\tkick3.append((-32, 0, 0, 32))\n\t\t\tkick3.append((32, 0, 1, -32))\n\t\t\tkick3.append((32, 32, 3, -32))\n\t\t\tkick3.append((32, 32, 1, -32))\n\t\t\t\n\t\t\tkick4.append((0, -32, 2, 32))\n\t\t\tkick4.append((0, 32, 3, -32))\n\t\t\tkick4.append((-32, 32, 3, -32))\n\t\t\tkick4.append((-32, 32, 1, -32))\n\t\t\t\n\t\telif self.tetronimo_type == 4:\n\t\t\t\n\t\t\t# 4(S) - .OO O.. .OO O..\n\t\t\t# OO. OO. OO. OO.\n\t\t\t# ... .O. ... .O.\n\t\t\trotation1.append((0, 0))\n\t\t\trotation1.append((0, -32))\n\t\t\trotation1.append((32, -32))\n\t\t\trotation1.append((-32, 0))\n\t\t\t\n\t\t\trotation2.append((0, 0))\n\t\t\trotation2.append((-32, 0))\n\t\t\trotation2.append((-32, -32))\n\t\t\trotation2.append((0, 32))\n\t\t\t\n\t\t\trotation3.append((0, 0))\n\t\t\trotation3.append((0, -32))\n\t\t\trotation3.append((32, -32))\n\t\t\trotation3.append((-32, 0))\n\t\t\t\n\t\t\trotation4.append((0, 0))\n\t\t\trotation4.append((-32, 0))\n\t\t\trotation4.append((-32, -32))\n\t\t\trotation4.append((0, 32))\n\t\t\t\n\t\t\tkick1.append((-32, 0, 0, 32))\n\t\t\tkick1.append((0, -32, 2, 32))\n\t\t\tkick1.append((32, -32, 1, -32))\n\t\t\tkick1.append((32, -32, 2, 32))\n\t\t\t\n\t\t\tkick2.append((-32, 0, 0, 32))\n\t\t\tkick2.append((0, 32, 3, -32))\n\t\t\tkick2.append((-32, -32, 0, 32))\n\t\t\tkick2.append((-32, -32, 2, 32))\n\t\t\t\n\t\t\tkick3.append((-32, 0, 0, 32))\n\t\t\tkick3.append((0, -32, 2, 32))\n\t\t\tkick3.append((32, -32, 1, -32))\n\t\t\tkick3.append((32, -32, 2, 32))\n\t\t\t\n\t\t\tkick4.append((-32, 0, 0, 32))\n\t\t\tkick4.append((0, 32, 3, -32))\n\t\t\tkick4.append((-32, -32, 0, 32))\n\t\t\tkick4.append((-32, -32, 2, 32))\n\t\t\t\n\t\telif self.tetronimo_type == 5:\n\t\t\t\n\t\t\t# 5(Z) - OO. ..O OO. ..O\n\t\t\t# .OO .OO .OO .OO\n\t\t\t# ... .O. ... .O.\n\t\t\trotation1.append((0, 0))\n\t\t\trotation1.append((0, -32))\n\t\t\trotation1.append((-32, -32))\n\t\t\trotation1.append((32, 0))\n\t\t\t\n\t\t\trotation2.append((0, 0))\n\t\t\trotation2.append((0, 32))\n\t\t\trotation2.append((32, 0))\n\t\t\trotation2.append((32, -32))\n\t\t\t\n\t\t\trotation3.append((0, 0))\n\t\t\trotation3.append((0, -32))\n\t\t\trotation3.append((-32, -32))\n\t\t\trotation3.append((32, 0))\n\t\t\t\n\t\t\trotation4.append((0, 0))\n\t\t\trotation4.append((0, 32))\n\t\t\trotation4.append((32, 0))\n\t\t\trotation4.append((32, -32))\n\t\t\t\n\t\t\tkick1.append((32, 0, 1, -32))\n\t\t\tkick1.append((0, -32, 2, 32))\n\t\t\tkick1.append((-32, -32, 0, 32))\n\t\t\tkick1.append((-32, -32, 2, 32))\n\t\t\t\n\t\t\tkick2.append((32, 0, 1, -32))\n\t\t\tkick2.append((0, 32, 3, -32))\n\t\t\tkick2.append((32, -32, 0, 32))\n\t\t\tkick2.append((32, -32, 2, 32))\n\t\t\t\n\t\t\tkick3.append((32, 0, 1, -32))\n\t\t\tkick3.append((0, -32, 2, 32))\n\t\t\tkick3.append((-32, -32, 0, 32))\n\t\t\tkick3.append((-32, -32, 2, 32))\n\t\t\t\n\t\t\tkick4.append((32, 0, 1, -32))\n\t\t\tkick4.append((0, 32, 3, -32))\n\t\t\tkick4.append((32, -32, 0, 32))\n\t\t\tkick4.append((32, -32, 2, 32))\n\t\t\t\n\t\telif self.tetronimo_type == 6:\n\t\t\t\n\t\t\t# 6(T) - .O. .O. ... .O.\n\t\t\t# OOO .OO OOO OO.\n\t\t\t# ... .O. .O. .O.\n\t\t\trotation1.append((0, 0))\n\t\t\trotation1.append((-32, 0))\n\t\t\trotation1.append((32, 0))\n\t\t\trotation1.append((0, -32))\n\t\t\t\n\t\t\trotation2.append((0, 0))\n\t\t\trotation2.append((0, -32))\n\t\t\trotation2.append((0, 32))\n\t\t\trotation2.append((32, 0))\n\t\t\t\n\t\t\trotation3.append((0, 0))\n\t\t\trotation3.append((-32, 0))\n\t\t\trotation3.append((32, 0))\n\t\t\trotation3.append((0, 32))\n\t\t\t\n\t\t\trotation4.append((0, 0))\n\t\t\trotation4.append((0, -32))\n\t\t\trotation4.append((0, 32))\n\t\t\trotation4.append((-32, 0))\n\t\t\t\n\t\t\tkick1.append((32, 0, 1, -32))\n\t\t\t\n\t\t\tkick2.append((0, 32, 3, -32))\n\t\t\t\n\t\t\tkick3.append((-32, 0, 0, 32))\n\t\t\t\n\t\t\tkick4.append((0, -32, 1, 32))\n\t\t\t\n\t\tself.rotations.append(rotation1)\n\t\tself.rotations.append(rotation2)\n\t\tself.rotations.append(rotation3)\n\t\tself.rotations.append(rotation4)\n\t\t\t\n\t\tself.kick_positions.append(kick1)\n\t\tself.kick_positions.append(kick2)\n\t\tself.kick_positions.append(kick3)\n\t\tself.kick_positions.append(kick4)\n\t\t\n\t\tself.create_4_tetronimo_blocks(pos_x, pos_y, rotation1)\n\t\t\t\n\tdef create_4_tetronimo_blocks(self, pos_x, pos_y, rotation):\n\t\t\"\"\"Creates the 4 tetronimo blocks for the tetronimo using the first rotation.\"\"\"\n\t\tself.create_tetronimo_block(pos_x + rotation[0][0], pos_y + rotation[0][1])\n\t\tself.create_tetronimo_block(pos_x + rotation[1][0], pos_y + rotation[1][1])\n\t\tself.create_tetronimo_block(pos_x + rotation[2][0], pos_y + rotation[2][1])\n\t\tself.create_tetronimo_block(pos_x + rotation[3][0], pos_y + rotation[3][1])\n\t\t\t\n\tdef create_tetronimo_block(self, position_x, position_y):\n\t\t\"\"\"Create a single tetronimo block.\"\"\"\n\t\t\n\t\t# The current tetronimo block being created.\n\t\tcur_tetronimo_block = self.object_factory.create_tetronimo_block(\n\t\t\t\tposition_x, position_y, self.tetronimo_type, self)\n\t\tself.tetronimo_blocks.append(cur_tetronimo_block)\n\t\t\n\tdef update(self, delta_time):\n\t\t\"\"\"Updates the falling tetronimo object.\"\"\"\n\t\t\n\t\tself.is_falling = True\n\t\tself.can_move_left = True\n\t\tself.can_move_right = True\n\t\tself.can_rotate = True\n\t\t\t\n\t\t# Check if the left or right key is pressed while a piece is falling. If so, \n\t\t# move the piece left or right.\n\t\tif self.settings.tetronimo_assembly_state == 0:\n\t\t\t\n\t\t\t# Check if pressing the left key.\n\t\t\tif self.input_manager.pressed_left:\n\t\t\t\t# Reset the movement frame if haven't pressed left previously.\n\t\t\t\tif not self.pressed_left:\n\t\t\t\t\tself.cur_horizontal_frame = self.max_horizontal_frame\n\t\t\t\tself.pressed_left = True\n\t\t\telse:\n\t\t\t\tself.pressed_left = False\n\t\t\t\t\n\t\t\t# Check if pressing the right key.\n\t\t\tif self.input_manager.pressed_right:\n\t\t\t\t# Reset the movement frame if haven't pressed left previously.\n\t\t\t\tif not self.pressed_right:\n\t\t\t\t\tself.cur_horizontal_frame = self.max_horizontal_frame\n\t\t\t\tself.pressed_right = True\n\t\t\telse:\n\t\t\t\tself.pressed_right = False\n\t\t\t\t\n\t\t\t# Check if pressing the rotate key.\n\t\t\tif self.input_manager.pressed_z:\n\t\t\t\t# If haven't rotated previously, rotate the tetronimo.\n\t\t\t\tif not self.pressed_rotate:\n\t\t\t\t\t# Increment the rotation index. If equal to 3, set it to zero.\n\t\t\t\t\tif self.rotation_state < 3:\n\t\t\t\t\t\tself.rotation_state += 1\n\t\t\t\t\telse:\n\t\t\t\t\t\tself.rotation_state = 0\n\t\t\t\t\t\n\t\t\t\t\t# Checks if the tetronimo can rotate.\n\t\t\t\t\tcan_rotate = True\n\t\t\t\t\t\n\t\t\t\t\t# Checks if the tetronimo was kicked.\n\t\t\t\t\tkicked = False\n\t\t\t\t\t\n\t\t\t\t\tself.rotate_blocks()\n\t\t\t\t\t\n\t\t\t\t\t# Before keeping a rotation, check to see if the tetronimo can \n\t\t\t\t\t# actually rotate, or if it needs to kick a wall. If not, change back \n\t\t\t\t\t# to the previous rotation.\n\t\t\t\t\tfor kick in self.kick_positions[self.rotation_state]:\n\t\t\t\t\t\t# The kick direction.\n\t\t\t\t\t\tkick_direction = kick[2]\n\t\t\t\t\t\t\n\t\t\t\t\t\t# The kick position in the x coordinate.\n\t\t\t\t\t\tkick_pos_x = kick[0]\n\t\t\t\t\t\t\n\t\t\t\t\t\t# The kick position in the y coordinate.\n\t\t\t\t\t\tkick_pos_y = kick[1]\n\t\t\t\t\t\t\n\t\t\t\t\t\t# The kick offset, in either the x or y coordinate.\n\t\t\t\t\t\tkick_offset = kick[3]\n\t\t\t\t\t\t\n\t\t\t\t\t\treturn_values = None\n\t\t\t\t\t\t\n\t\t\t\t\t\tif kick_direction == 0:\n\t\t\t\t\t\t\treturn_values = self.kick_tetronimo_attempt(\n\t\t\t\t\t\t\t\tkick_pos_x, kick_pos_y, kick_offset, True, False)\n\t\t\t\t\t\telif kick_direction == 1:\n\t\t\t\t\t\t\treturn_values = self.kick_tetronimo_attempt(\n\t\t\t\t\t\t\t\tkick_pos_x, kick_pos_y, kick_offset, True, True)\n\t\t\t\t\t\telif kick_direction == 2:\n\t\t\t\t\t\t\treturn_values = self.kick_tetronimo_attempt(\n\t\t\t\t\t\t\t\tkick_pos_x, kick_pos_y, kick_offset, False, False)\n\t\t\t\t\t\telif kick_direction == 3:\n\t\t\t\t\t\t\treturn_values = self.kick_tetronimo_attempt(\n\t\t\t\t\t\t\t\tkick_pos_x, kick_pos_y, kick_offset, False, True)\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\tcan_rotate = return_values[0]\n\t\t\t\t\t\tkicked = return_values[1]\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t# If the tetronimo was kicked, exit the kicking loop.\n\t\t\t\t\t\tif kicked or not can_rotate:\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\n\t\t\t\t\t# If the rotation failed, rotate the piece back to its original \n\t\t\t\t\t# position.\n\t\t\t\t\tif not can_rotate:\n\t\t\t\t\t\tself.rotation_state\n\t\t\t\t\t\t# Decrement the rotation index. If equal to 0, set it to 3.\n\t\t\t\t\t\tif self.rotation_state > 0:\n\t\t\t\t\t\t\tself.rotation_state -= 1\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tself.rotation_state = 3\n\t\t\t\t\t\t\t\n\t\t\t\t\t\tself.rotate_blocks()\n\t\t\t\t\t\n\t\t\t\tself.pressed_rotate = True\n\t\t\telse:\n\t\t\t\tself.pressed_rotate = False\n\t\t\t\t\n\t\t\t# Check if pressig the auto land key.\n\t\t\tif self.input_manager.pressed_x:\n\t\t\t\t# Get the largest block value and use that as the offset for the landing \n\t\t\t\t# position.\n\t\t\t\tlargest_y = 0 \n\t\t\t\t\n\t\t\t\t# First, check if the tetronimo can land on another tetronimo.\n\t\t\t\t\n\t\t\t\t# Checks if the tetronimo landed on another tetronimo.\n\t\t\t\tland_on_tetronimo = False\n\t\t\t\t\n\t\t\t\t# The amount by which to offset the tetronimo falling so that it reaches \n\t\t\t\t# the bottom of the screen or on top of another tetronimo.\n\t\t\t\toffset_amount_y = 0\n\t\t\t\t\n\t\t\t\t# The shortest y distance found. It will be used as the offset amount for\n\t\t\t\t# the tetronimo.\n\t\t\t\tshortest_y_distance = 999.0\n\t\t\t\t\n\t\t\t\t# First, check for the shortest distance between the owner's tetronimo \n\t\t\t\t# blocks and the other tetronimo blocks.\n\t\t\t\tfor cur_block in self.tetronimo_blocks:\n\t\t\t\t\tfor key in self.settings.tetronimo_blocks:\n\t\t\t\t\t\t# The current tetronimo block other.\n\t\t\t\t\t\tcur_block_other = self.settings.tetronimo_blocks[key]\n\t\t\t\t\t\t\n\t\t\t\t\t\t# Check if the other block has the same x coordinate as the \n\t\t\t\t\t\t# current block and is in the landed block state.\n\t\t\t\t\t\tif cur_block_other.block_state == 1 and \\\n\t\t\t\t\t\t\t\tcur_block.position_x == cur_block_other.position_x and \\\n\t\t\t\t\t\t\t\tcur_block.position_y < cur_block_other.position_y:\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tcur_y_distance = cur_block_other.position_y - \\\n\t\t\t\t\t\t\t\t\tcur_block.position_y - 32\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t# If the distance is shorter than the previous distance, \n\t\t\t\t\t\t\t# update the shortest y distance.\n\t\t\t\t\t\t\tif cur_y_distance < shortest_y_distance:\n\t\t\t\t\t\t\t\tshortest_y_distance = cur_y_distance\n\t\t\t\t\n\t\t\t\t# Next, check if the tetronimo can also reach the bottom of the screen.\n\t\t\t\t\n\t\t\t\t# Get the largest y position of the tetronimo.\n\t\t\t\tfor block in self.tetronimo_blocks:\n\t\t\t\t\tif block.position_y > largest_y:\n\t\t\t\t\t\tlargest_y = block.position_y\n\t\t\t\t\n\t\t\t\t# The amount by which to offset the tetronimo falling so that it reaches \n\t\t\t\t# the bottom of the screen.\n\t\t\t\tcur_y_distance = self.settings.tetronimo_container_bounds[3] - \\\n\t\t\t\t\t\tlargest_y - 16\n\t\t\t\t\t\t\n\t\t\t\t# If the distance is shorter than the previous distance, \n\t\t\t\t# update the shortest y distance.\n\t\t\t\tif cur_y_distance < shortest_y_distance:\n\t\t\t\t\tshortest_y_distance = cur_y_distance\n\t\t\t\t\n\t\t\t\toffset_amount_y = shortest_y_distance\n\t\t\t\t\n\t\t\t\tself.position_y += offset_amount_y\n\t\t\t\t\n\t\t\t\t# Also update the positions of the tetronimo blocks to reach the bottom of \n\t\t\t\t# the game screen.\n\t\t\t\tfor block in self.tetronimo_blocks:\n\t\t\t\t\tblock.position_y += offset_amount_y\n\t\t\t\t\t\n\t\t\t\tself.settings.delta_time_accum = 0\n\t\t\t\t\n\t\t\t\t# Force the tetronimo assembly to increment.\n\t\t\t\tself.settings.tetronimo_inc = True\n\t\t\t\tself.is_falling = False\n\t\t\t\t\n\t\t\t# Update all the tetronimo blocks that belong to this falling tetronimo object.\n\t\t\tfor block in self.tetronimo_blocks:\n\t\t\t\tblock.update(delta_time)\n\t\t\t\t\n\t\t\t# The drive for moving the tetronimo or setting it into the landed state.\n\t\t\tif self.settings.tetronimo_inc:\n\t\t\t\t# If no longer falling, destroy the tetronimo.\n\t\t\t\tif not self.is_falling:\n\t\t\t\t\t# Destroy the falling tetronimo. This will not destroy the blocks that make \n\t\t\t\t\t# the tetronimo, and the blocks will be landed.\n\t\t\t\t\tself.marked_for_deletion = True\n\t\t\t\t\t\n\t\t\t\t\tself.settings.tetronimo_assembly_state = 1\n\t\t\t\t\t\n\t\t\t\t\t# If moving downwards, switch over to the default speed to prevent too \n\t\t\t\t\t# many pieces from falling all at once.\n\t\t\t\t\tif self.input_manager.pressed_down:\n\t\t\t\t\t\tself.settings.tetronimo_timer_period = \\\n\t\t\t\t\t\t\tself.settings.tetronimo_timer_period_cache\n\t\t\t\t\t\n\t\t\t\t\t# Set the blocks to the landed state.\n\t\t\t\t\tfor block in self.tetronimo_blocks:\n\t\t\t\t\t\tblock.change_block_to_landed()\n\t\t\t\telse:\n\t\t\t\t\tself.move_blocks(0, 32)\n\t\t\t\t\n\t\t\tif not self.marked_for_deletion:\n\t\t\t\t# Drive the tetronimo to move left if able.\n\t\t\t\tif self.can_move_left and self.pressed_left:\n\t\t\t\t\tif self.cur_horizontal_frame == self.max_horizontal_frame:\n\t\t\t\t\t\tself.cur_horizontal_frame = 0\n\t\t\t\t\t\tself.position_x -= 32\n\t\t\t\t\t\tfor block in self.tetronimo_blocks:\n\t\t\t\t\t\t\tblock.position_x -= 32\n\t\t\t\t\telse:\n\t\t\t\t\t\tself.cur_horizontal_frame += 1\n\t\t\t\t\t\t\n\t\t\t\t# Drive the tetronimo to move right if able.\n\t\t\t\tif self.can_move_right and self.pressed_right:\n\t\t\t\t\tif self.cur_horizontal_frame == self.max_horizontal_frame:\n\t\t\t\t\t\tself.cur_horizontal_frame = 0\n\t\t\t\t\t\tself.position_x += 32\n\t\t\t\t\t\tfor block in self.tetronimo_blocks:\n\t\t\t\t\t\t\tblock.position_x += 32\n\t\t\t\t\telse:\n\t\t\t\t\t\tself.cur_horizontal_frame += 1\n\t\t\n\tdef move_blocks(self, delta_x, delta_y):\n\t\t\"\"\"Change the x or y position by a certain amount.\"\"\"\n\t\tself.position_x += delta_x\n\t\tself.position_y += delta_y\n\t\t\n\t\t# Update the x and y position for the tetronimo blocks that belong to this \n\t\t# tetronimo.\n\t\tfor block in self.tetronimo_blocks:\n\t\t\tblock.position_x += delta_x\n\t\t\tblock.position_y += delta_y\n\t\t\t\n\tdef rotate_blocks(self):\n\t\t# The current rotations for the tetronimo blocks being rotated.\n\t\trotations = self.rotations[self.rotation_state]\n\t\t\n\t\t# The block index of the tetronimo block being rotated.\n\t\tblock_index = 0\n\t\t\n\t\t# Change the tetronimo block positions.\n\t\tfor block in self.tetronimo_blocks:\n\t\t\tblock.position_x = self.position_x + rotations[block_index][0]\n\t\t\tblock.position_y = self.position_y + rotations[block_index][1]\n\t\t\tblock_index += 1\n\t\t\t\n\tdef check_tetronimo_block_collisions(self):\n\t\t# Checks if a collision has been found.\n\t\tfound_collision = False\n\t\t\n\t\t# Check if the tetronimo is intersecting any other \n\t\t# tetronimos.\n\t\tfor cur_block in self.tetronimo_blocks:\n\t\t\tfor key in self.settings.tetronimo_blocks:\n\t\t\t\t# The other tetronimo block being collided with.\n\t\t\t\tcur_block_other = self.settings.tetronimo_blocks[key]\n\t\t\t\t\n\t\t\t\tif cur_block_other.block_state == 1 and \\\n\t\t\t\t\tcur_block.position_x >= cur_block_other.position_x - 16 and \\\n\t\t\t\t\tcur_block.position_x < cur_block_other.position_x + 16 and \\\n\t\t\t\t\tcur_block.position_y >= cur_block_other.position_y - 16 and \\\n\t\t\t\t\tcur_block.position_y < cur_block_other.position_y + 16:\n\t\t\t\t\tfound_collision = True\n\t\t\t\t\tbreak;\n\t\t\tif found_collision:\n\t\t\t\tbreak\n\t\treturn found_collision\n\t\t\n\tdef kick_tetronimo_attempt(self, kick_pos_x, kick_pos_y, kick_offset, kick_x, kick_positive):\n\t\t\"\"\"Checks for tetronimo kicking.\"\"\"\n\t\n\t\t# Check if the tetronimo can rotate.\n\t\tcan_rotate = True\n\t\t\n\t\t# Checks if the tetronimo was kicked.\n\t\tkicked = False\n\t\t\n\t\t# The global kick position x.\n\t\tkick_position_global_x = kick_pos_x + self.position_x\n\t\t\n\t\t# The global kick position y.\n\t\tkick_position_global_y = kick_pos_y + self.position_y\n\t\t\n\t\t# Check if kicking on the x axis or the y axis.\n\t\tif kick_x:\n\t\t\t# The position value for the wall boundary.\n\t\t\twall_value = self.settings.tetronimo_container_bounds[1]\n\t\t\t\n\t\t\tif not kick_positive:\n\t\t\t\twall_value = self.settings.tetronimo_container_bounds[0]\n\t\t\t\n\t\t\t# Check if kicking the screen bounds.\n\t\t\tif (not kick_positive and kick_position_global_x < wall_value) or \\\n\t\t\t\t(kick_positive and kick_position_global_x > wall_value):\n\t\t\t\t\t\n\t\t\t\tkicked = True\n\t\t\t\tcan_rotate = self.apply_kick(kick_offset, kick_x, kick_positive)\n\t\telse:\n\t\t\t# The position value for the wall boundary.\n\t\t\twall_value = self.settings.tetronimo_container_bounds[3]\n\t\t\t\n\t\t\tif not kick_positive:\n\t\t\t\twall_value = self.settings.tetronimo_container_bounds[2]\n\t\t\t\n\t\t\t# Check if kicking the screen bounds.\n\t\t\tif (not kick_positive and kick_position_global_y < wall_value) or \\\n\t\t\t\t(kick_positive and kick_position_global_y > wall_value):\n\t\t\t\t\t\n\t\t\t\tkicked = True\n\t\t\t\tcan_rotate = self.apply_kick(kick_offset, kick_x, kick_positive)\n\t\t\t\t\t\n\t\t# Check if kicking the other blocks.\n\t\tif not kicked:\n\t\t\t# Iterate through every other tetronimo block and check for collisions with \n\t\t\t# this tetronimo's blocks.\n\t\t\tfor key in self.settings.tetronimo_blocks:\n\t\t\t\n\t\t\t\t# The other block being collided with.\n\t\t\t\tcur_block_other = self.settings.tetronimo_blocks[key]\n\t\t\t\t\n\t\t\t\t# Only collide with blocks that are in the block_state landed.\n\t\t\t\tif cur_block_other.block_state == 1:\n\t\t\t\t\n\t\t\t\t\t# Check if the x and y coordinates are the same.\n\t\t\t\t\tif kick_position_global_x >= cur_block_other.position_x - 8 and \\\n\t\t\t\t\t\tkick_position_global_x < cur_block_other.position_x + 8 and \\\n\t\t\t\t\t\tkick_position_global_y >= cur_block_other.position_y - 8 and \\\n\t\t\t\t\t\tkick_position_global_y < cur_block_other.position_y + 8:\n\t\t\t\t\t\t\n\t\t\t\t\t\tkicked = True\n\t\t\t\t\t\tcan_rotate = self.apply_kick(kick_offset, kick_x, kick_positive)\n\t\t\t\t\t\t\n\t\t# If it cannot rotate, then it cannot be kicked either.\n\t\tif can_rotate == False:\n\t\t\tkicked = False\n\t\t\t\t\t\n\t\treturn (can_rotate, kicked)\n\n\tdef apply_kick(self, offset, kick_x, kick_positive):\n\t\n\t\t# Checks if the tetronimo can rotate.\n\t\tcan_rotate = True\n\t\t\n\t\t# Kick the blocks.\n\t\tif kick_x:\n\t\t\tfor block in self.tetronimo_blocks:\n\t\t\t\tblock.position_x += offset\n\t\t\tself.position_x += offset\n\t\telse:\n\t\t\tfor block in self.tetronimo_blocks:\n\t\t\t\tblock.position_y += offset\n\t\t\tself.position_y += offset\n\t\t\n\t\t# Check if the tetronimo is intersecting any other \n\t\t# tetronimos after kicking right.\n\t\tfound_collision = self.check_tetronimo_block_collisions()\n\t\t\t\n\t\t# Check if blocks are now outside of the screen bounds.\n\t\tif found_collision == False:\n\t\t\t\t\n\t\t\tif kick_x:\n\t\t\t\t# Swap the wall values.\n\t\t\t\tif kick_positive:\n\t\t\t\t\twall_value = self.settings.tetronimo_container_bounds[0]\n\t\t\t\t\t\n\t\t\t\t\tfor block in self.tetronimo_blocks:\n\t\t\t\t\t\tif block.position_x <= wall_value:\n\t\t\t\t\t\t\tfound_collision = True\n\t\t\t\telse:\n\t\t\t\t\twall_value = self.settings.tetronimo_container_bounds[1]\n\t\t\t\t\t\n\t\t\t\t\tfor block in self.tetronimo_blocks:\n\t\t\t\t\t\tif block.position_x >= wall_value:\n\t\t\t\t\t\t\tfound_collision = True\n\t\t\telse:\t\n\t\t\t\tif kick_positive:\n\t\t\t\t\twall_value = self.settings.tetronimo_container_bounds[2]\n\t\t\t\t\t\n\t\t\t\t\tfor block in self.tetronimo_blocks:\n\t\t\t\t\t\tif block.position_y <= wall_value:\n\t\t\t\t\t\t\tfound_collision = True\n\t\t\t\telse:\n\t\t\t\t\twall_value = self.settings.tetronimo_container_bounds[3]\n\t\t\t\t\t\n\t\t\t\t\tfor block in self.tetronimo_blocks:\n\t\t\t\t\t\tif block.position_y >= wall_value:\n\t\t\t\t\t\t\tfound_collision = True\n\t\t\t\n\t\t# If a collision has been found, then the wall kick has failed. return to\n\t\t# The previous block positions.\n\t\tif found_collision:\n\t\t\t\n\t\t\t# Kick the blocks back to their previous position.\n\t\t\tif kick_x:\n\t\t\t\t# Kick every single block that this tetronimo owns.\n\t\t\t\tfor block in self.tetronimo_blocks:\n\t\t\t\t\tblock.position_x -= offset\n\t\t\t\tself.position_x -= offset\n\t\t\telse:\n\t\t\t\t# Kick every single block that this tetronimo owns.\n\t\t\t\tfor block in self.tetronimo_blocks:\n\t\t\t\t\tblock.position_y -= offset\n\t\t\t\tself.position_y -= offset\n\t\t\t\t\n\t\t\tcan_rotate = False\n\t\t\t\t\n\t\treturn can_rotate\n","sub_path":"scripts/tetronimo_falling.py","file_name":"tetronimo_falling.py","file_ext":"py","file_size_in_byte":25909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"330953203","text":"from django.urls import path\n\nfrom .views import home_page, practica, all_blog_posts, all_bloggers\n\napp_name = 'blog'\n\nurlpatterns = [\n path('', home_page, name='home_page'),\n path('blogs/', all_blog_posts, name='all_blog_posts'),\n path('bloggers/', all_bloggers, name='all_bloggers'),\n path('practica/', practica, name='practica'),\n]\n","sub_path":"task/blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"32372619","text":"# Cria uma lista vazia\nvalores = []\n\nfor cont in range(1,5,1):\n # Ler valores e armazena na lista\n valores.append(int(input(f\"Informe o {cont}º valor: \")))\n\n# Imprimi os valores da lista\nfor v in valores:\n print(v)","sub_path":"Python/project/Listas/10_valores.py","file_name":"10_valores.py","file_ext":"py","file_size_in_byte":224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"111313378","text":"import pandas as pd\nfrom os.path import join\nfrom os import listdir\nimport networkx as nx\n\nfrom scseirx.model_school import SEIRX_school\nfrom scseirx import analysis_functions as af\n\ndef compose_agents(measures, simulation_params):\n '''\n Utility function to compose agent dictionaries as expected by the simulation\n model as input from the dictionary of prevention measures.\n \n Parameters\n ----------\n prevention_measures : dictionary\n Dictionary of prevention measures. Needs to include the fields \n (student, teacher, family_member) _screen_interval, index_probability\n and _mask. \n \n Returns\n -------\n agent_types : dictionary of dictionaries\n Dictionary containing the fields \"screening_interval\", \n \"index_probability\" and \"mask\" for the agent groups \"student\", \"teacher\"\n and \"family_member\".\n \n '''\n agent_types = {\n 'student':{\n 'screening_interval':measures['student_screen_interval'],\n 'index_probability':simulation_params['student_index_probability'],\n 'mask':measures['student_mask']},\n\n 'teacher':{\n 'screening_interval': measures['teacher_screen_interval'],\n 'index_probability': simulation_params['student_index_probability'],\n 'mask':measures['teacher_mask']},\n\n 'family_member':{\n 'screening_interval':measures['family_member_screen_interval'],\n 'index_probability':simulation_params['family_member_index_probability'],\n 'mask':measures['family_member_mask']}\n }\n \n return agent_types\n\ndef run_model(G, agent_types, measures, simulation_params, index_case,\n ttype='same_day_antigen', s_screen_interval=None,\n t_screen_interval=None, student_mask=False, \n teacher_mask=False, half_classes=False, ventilation_mod=1,\n seed=None, N_steps=1000):\n '''\n Runs a simulation with an SEIRX_school model \n (see https://pypi.org/project/scseirx/1.3.0/), given a set of parameters \n which are calibrated.\n \n Parameters:\n -----------\n G : networkx Graph\n Contact network of the given school.\n agent_types : dict\n Dictionary of dictionaries, holding agent-specific information for each\n agent group.\n measures : dictionary\n Dictionary listing all prevention measures in place for the given\n scenario. Fields that are not specifically included in this dictionary\n will revert to SEIRX_school defaults.\n simulation_params : dictionary\n Dictionary holding simulation parameters such as \"verbosity\" and\n \"base_transmission_risk\". Fields that are not included will revert back\n to SEIRX_school defaults.\n index_case : string\n Agent group from which the index case is drawn. Can be \"student\" or\n \"teacher\".\n ttype : string\n Test type used for preventive screening. For example \"same_day_antigen\"\n s_screen_interval : integer\n Interval between preventive screens in the student agent group.\n t_screen_interval : integer\n Interval between preventive screens in the teacher agent group.\n student_mask : bool\n Wheter or not students wear masks.\n teacher_mask : bool\n Wheter or not teachers wear masks.\n half_classes : bool\n Wheter or not class sizes are reduced.\n ventilation_mod : float\n Modification to the transmission risk due to ventilation. \n 1 = no modification.\n seed : integer\n Seed for the simulation to fix randomness.\n N_steps : integer\n Number of maximum steps per run. This is a very conservatively chosen \n value that ensures that an outbreak will always terminate within the \n allotted time. Most runs are terminated way earlier anyways, as soon as \n the outbreak is over.\n \n Returns\n -------\n model : SEIRX_school model instance holding a completed simulation run and\n all associated data.\n '''\n\n # initialize the model\n model = SEIRX_school(G, \n simulation_params['verbosity'], \n base_transmission_risk = simulation_params['base_transmission_risk'],\n testing = measures['testing'],\n exposure_duration = simulation_params['exposure_duration'],\n time_until_symptoms = simulation_params['time_until_symptoms'],\n infection_duration = simulation_params['infection_duration'],\n quarantine_duration = measures['quarantine_duration'],\n subclinical_modifier = simulation_params['subclinical_modifier'],\n infection_risk_contact_type_weights = \\\n simulation_params['infection_risk_contact_type_weights'],\n K1_contact_types = measures['K1_contact_types'],\n diagnostic_test_type = measures['diagnostic_test_type'],\n preventive_screening_test_type = ttype,\n follow_up_testing_interval = \\\n measures['follow_up_testing_interval'],\n liberating_testing = measures['liberating_testing'],\n index_case = index_case,\n agent_types = agent_types, \n age_transmission_risk_discount = \\\n simulation_params['age_transmission_discount'],\n age_symptom_modification = simulation_params['age_symptom_discount'],\n mask_filter_efficiency = simulation_params['mask_filter_efficiency'],\n transmission_risk_ventilation_modifier = ventilation_mod,\n seed=seed)\n\n # run the model until the outbreak is over\n for i in range(N_steps):\n # break if first outbreak is over\n if len([a for a in model.schedule.agents if \\\n (a.exposed == True or a.infectious == True)]) == 0:\n break\n model.step()\n \n return model\n\ndef run_ensemble(N_runs, school_type, measures, simulation_params,\n school_characteristics, contact_network_src, res_path, index_case,\n ttype='same_day_antigen', s_screen_interval=None,\n t_screen_interval=None, student_mask=False, \n teacher_mask=False, half_classes=False, ventilation_mod=1,):\n '''\n Utility function to run an ensemble of simulations for a given school type\n and parameter combination.\n \n Parameters:\n ----------\n N_runs : integer\n Number of individual simulation runs in the ensemble.\n school_type : string\n School type for which the model is run. This affects the selected school\n characteristics and ratio of index cases between students and teachers.\n Can be \"primary\", \"primary_dc\", \"lower_secondary\", \"lower_secondary_dc\",\n \"upper_secondary\", \"secondary\" or \"secondary_dc\".\n school_type : string\n School type for which the ensemble is run. This affects the selected \n school characteristics and ratio of index cases between students and \n teachers. Can be \"primary\", \"primary_dc\", \"lower_secondary\", \n \"lower_secondary_dc\", \"upper_secondary\", \"secondary\" or \"secondary_dc\".\n measures : dictionary\n Dictionary listing all prevention measures in place for the given\n scenario. Fields that are not specifically included in this dictionary\n will revert to SEIRX_school defaults.\n simulation_params : dictionary\n Dictionary holding simulation parameters such as \"verbosity\" and\n \"base_transmission_risk\". Fields that are not included will revert back\n to SEIRX_school defaults.\n school_characteristics : dictionary\n Dictionary holding the characteristics of each possible school type. \n Needs to include the fields \"classes\" and \"students\" (i.e. the number)\n of students per class. The number of teachers is calculated\n automatically from the given school type and number of classes.\n res_path : string\n Path to the directory in which results will be saved.\n contact_network_src : string\n Absolute or relative path pointing to the location of the contact\n network used for the calibration runs. The location needs to hold the\n contact networks for each school types in a sub-folder with the same\n name as the school type. Networks need to be saved in networkx's .bz2\n format.\n index_case : string\n Agent group from which the index case is drawn. Can be \"student\" or\n \"teacher\".\n ttype : string\n Test type used for preventive screening. For example \"same_day_antigen\"\n s_screen_interval : integer\n Interval between preventive screens in the student agent group.\n t_screen_interval : integer\n Interval between preventive screens in the teacher agent group.\n student_mask : bool\n Wheter or not students wear masks.\n teacher_mask : bool\n Wheter or not teachers wear masks.\n half_classes : bool\n Wheter or not class sizes are reduced.\n ventilation_mod : float\n Modification to the transmission risk due to ventilation. \n 1 = no modification.\n \n Returns:\n --------\n ensemble_results : pandas DataFrame\n Data Frame holding the observable of interest of the ensemble, namely\n the number of infected students and teachers.\n '''\n characteristics = school_characteristics[school_type]\n # create the agent dictionaries based on the given parameter values and\n # prevention measures\n agent_types = compose_agents(measures, simulation_params)\n agent_types['student']['screening_interval'] = s_screen_interval\n agent_types['teacher']['screening_interval'] = t_screen_interval\n agent_types['student']['mask'] = student_mask\n agent_types['teacher']['mask'] = teacher_mask\n\n sname = '{}_classes-{}_students-{}'.format(school_type,\n characteristics['classes'], characteristics['students'])\n school_src = join(contact_network_src, school_type)\n \n half = ''\n if half_classes:\n half = '_half'\n\n # load the contact network, schedule and node_list corresponding to the school\n G = nx.readwrite.gpickle.read_gpickle(\\\n join(school_src, '{}_network{}.bz2'.format(sname, half))) \n\n turnovers = {'same':0, 'one':1, 'two':2, 'three':3}\n bmap = {True:'T', False:'F'}\n turnover, _, test = ttype.split('_')\n turnover = turnovers[turnover]\n \n measure_string = '{}_test-{}_turnover-{}_index-{}_tf-{}_sf-{}_tmask-{}'\\\n .format(school_type, test, turnover, index_case[0], t_screen_interval,\n s_screen_interval, bmap[teacher_mask]) +\\\n '_smask-{}_half-{}_vent-{}'\\\n .format(bmap[student_mask], bmap[half_classes], ventilation_mod)\n \n spath_ensmbl = join(res_path, school_type)\n \n ensemble_results = pd.DataFrame()\n for r in range(1, N_runs + 1):\n model = run_model(G, agent_types, measures,simulation_params,index_case,\n ttype, s_screen_interval, t_screen_interval, student_mask, \n teacher_mask, half_classes, ventilation_mod, seed=r)\n \n # collect the statistics of the single run\n row = af.get_ensemble_observables_school(model, r)\n row['seed'] = r\n # add run results to the ensemble results\n ensemble_results = ensemble_results.append(row,\n ignore_index=True)\n \n ensemble_results.to_csv(join(spath_ensmbl, measure_string + '.csv'))\n \n return ensemble_results \n\ndef get_data(stype, src_path):\n data = pd.DataFrame()\n stype_path = join(src_path, stype)\n files = listdir(stype_path)\n for f in files:\n screening_params, agents, half = af.get_measures(f.strip('.csv'))\n ensmbl = pd.read_csv(join(stype_path, f))\n try:\n ensmbl = ensmbl.drop(columns=['Unnamed: 0'])\n except KeyError:\n pass\n ensmbl['preventive_test_type'] = screening_params['preventive_test_type']\n ensmbl['index_case'] = screening_params['index_case']\n ensmbl['transmission_risk_ventilation_modifier'] = \\\n screening_params['transmission_risk_ventilation_modifier']\n ensmbl['student_mask'] = agents['student']['mask']\n ensmbl['teacher_mask'] = agents['teacher']['mask']\n ensmbl['student_screening_interval'] = agents['student']['screening_interval']\n ensmbl['teacher_screening_interval'] = agents['teacher']['screening_interval']\n ensmbl['half_classes'] = half\n\n data = pd.concat([data, ensmbl])\n\n data = data.reset_index(drop=True)\n data['teacher_screening_interval'] = data['teacher_screening_interval']\\\n .replace({None:'never'})\n data['student_screening_interval'] = data['student_screening_interval']\\\n .replace({None:'never'})\n return data\n\ndef set_individual_measures(data):\n data.loc[data[(data['transmission_risk_ventilation_modifier'] == 1) & \\\n (data['student_mask'] == False) & \\\n (data['teacher_mask'] == False) & \\\n (data['student_screening_interval'] == 'never') & \\\n (data['teacher_screening_interval'] == 'never') & \\\n (data['half_classes'] == False)].index, 'measure'] = 'no\\nmeasure'\n data.loc[data[(data['transmission_risk_ventilation_modifier'] == 1) & \\\n (data['student_mask'] == False) & \\\n (data['teacher_mask'] == True) & \\\n (data['student_screening_interval'] == 'never') & \\\n (data['teacher_screening_interval'] == 'never') & \\\n (data['half_classes'] == False)].index, 'measure'] = 'mask\\nteacher'\n data.loc[data[(data['transmission_risk_ventilation_modifier'] == 1) & \\\n (data['student_mask'] == True) & \\\n (data['teacher_mask'] == False) & \\\n (data['student_screening_interval'] == 'never') & \\\n (data['teacher_screening_interval'] == 'never') & \\\n (data['half_classes'] == False)].index, 'measure'] = 'mask\\nstudent'\n data.loc[data[(data['transmission_risk_ventilation_modifier'] == 0.36) & \\\n (data['student_mask'] == False) & \\\n (data['teacher_mask'] == False) & \\\n (data['student_screening_interval'] == 'never') & \\\n (data['teacher_screening_interval'] == 'never') & \\\n (data['half_classes'] == False)].index, 'measure'] = 'ventilation'\n data.loc[data[(data['transmission_risk_ventilation_modifier'] == 1) & \\\n (data['student_mask'] == False) & \\\n (data['teacher_mask'] == False) & \\\n (data['student_screening_interval'] == 'never') & \\\n (data['teacher_screening_interval'] == 'never') & \\\n (data['half_classes'] == True)].index, 'measure'] = 'halved\\nclasses'\n data.loc[data[(data['transmission_risk_ventilation_modifier'] == 1) & \\\n (data['student_mask'] == False) & \\\n (data['teacher_mask'] == False) & \\\n (data['student_screening_interval'] == 7) & \\\n (data['teacher_screening_interval'] == 'never') & \\\n (data['half_classes'] == False)].index, 'measure'] = 'student tests\\n1x / week'\n data.loc[data[(data['transmission_risk_ventilation_modifier'] == 1) & \\\n (data['student_mask'] == False) & \\\n (data['teacher_mask'] == False) & \\\n (data['student_screening_interval'] == 3) & \\\n (data['teacher_screening_interval'] == 'never') & \\\n (data['half_classes'] == False)].index, 'measure'] = 'student tests\\n2x / week'\n data.loc[data[(data['transmission_risk_ventilation_modifier'] == 1) & \\\n (data['student_mask'] == False) & \\\n (data['teacher_mask'] == False) & \\\n (data['student_screening_interval'] == 'never') & \\\n (data['teacher_screening_interval'] == 7) & \\\n (data['half_classes'] == False)].index, 'measure'] = 'teacher tests\\n1x / week'\n data.loc[data[(data['transmission_risk_ventilation_modifier'] == 1) & \\\n (data['student_mask'] == False) & \\\n (data['teacher_mask'] == False) & \\\n (data['student_screening_interval'] == 'never') & \\\n (data['teacher_screening_interval'] == 3) & \\\n (data['half_classes'] == False)].index, 'measure'] = 'teacher tests\\n2x / week'\n \n \ndef set_measure_packages(data):\n # ventilation + masks teachers\n data.loc[data[(data['transmission_risk_ventilation_modifier'] == 0.36) & \\\n (data['student_mask'] == False) & \\\n (data['teacher_mask'] == True) & \\\n (data['student_screening_interval'] == 'never') & \\\n (data['teacher_screening_interval'] == 'never') & \\\n (data['half_classes'] == False)].index, 'measure'] = \\\n 'ventilation + mask teachers'\n # ventilation + masks teachers + masks students\n data.loc[data[(data['transmission_risk_ventilation_modifier'] == 0.36) & \\\n (data['student_mask'] == True) & \\\n (data['teacher_mask'] == True) & \\\n (data['student_screening_interval'] == 'never') & \\\n (data['teacher_screening_interval'] == 'never') & \\\n (data['half_classes'] == False)].index, 'measure'] = \\\n 'ventilation + mask teachers + mask students'\n # ventilation + masks teachers + masks students + halved classes\n data.loc[data[(data['transmission_risk_ventilation_modifier'] == 0.36) & \\\n (data['student_mask'] == True) & \\\n (data['teacher_mask'] == True) & \\\n (data['student_screening_interval'] == 'never') & \\\n (data['teacher_screening_interval'] == 'never') & \\\n (data['half_classes'] == True)].index, 'measure'] = \\\n 'ventilation + mask teachers + mask students + halved classes'\n \n # ventilation + tests teachers 1x\n data.loc[data[(data['transmission_risk_ventilation_modifier'] == 0.36) & \\\n (data['student_mask'] == False) & \\\n (data['teacher_mask'] == False) & \\\n (data['student_screening_interval'] == 'never') & \\\n (data['teacher_screening_interval'] == 7) & \\\n (data['half_classes'] == False)].index, 'measure'] = \\\n 'ventilation + tests teachers 1x'\n # ventilation + tests teachers 1x + tests students 1x\n data.loc[data[(data['transmission_risk_ventilation_modifier'] == 0.36) & \\\n (data['student_mask'] == False) & \\\n (data['teacher_mask'] == False) & \\\n (data['student_screening_interval'] == 7) & \\\n (data['teacher_screening_interval'] == 7) & \\\n (data['half_classes'] == False)].index, 'measure'] =\\\n 'ventilation + tests teachers 1x + tests students 1x'\n # ventilation + tests teachers 2x + tests students 1x\n data.loc[data[(data['transmission_risk_ventilation_modifier'] == 0.36) & \\\n (data['student_mask'] == False) & \\\n (data['teacher_mask'] == False) & \\\n (data['student_screening_interval'] == 7) & \\\n (data['teacher_screening_interval'] == 3) & \\\n (data['half_classes'] == False)].index, 'measure'] = \\\n 'ventilation + tests teachers 2x + tests students 1x'\n # ventilation + tests teachers 2x + tests students 2x\n data.loc[data[(data['transmission_risk_ventilation_modifier'] == 0.36) & \\\n (data['student_mask'] == False) & \\\n (data['teacher_mask'] == False) & \\\n (data['student_screening_interval'] == 3) & \\\n (data['teacher_screening_interval'] == 3) & \\\n (data['half_classes'] == False)].index, 'measure'] = \\\n 'ventilation + tests teachers 2x + tests students 2x'\n \n # ventilation + masks teachers & students + tests 1x teachers & students\n data.loc[data[(data['transmission_risk_ventilation_modifier'] == 0.36) & \\\n (data['student_mask'] == True) & \\\n (data['teacher_mask'] == True) & \\\n (data['student_screening_interval'] == 7) & \\\n (data['teacher_screening_interval'] == 7) & \\\n (data['half_classes'] == False)].index, 'measure'] = \\\n 'ventilation + masks teachers & students + tests 1x teachers & students'\n # ventilation + halved classes + tests 1x teachers & students\n data.loc[data[(data['transmission_risk_ventilation_modifier'] == 0.36) & \\\n (data['student_mask'] == False) & \\\n (data['teacher_mask'] == False) & \\\n (data['student_screening_interval'] == 7) & \\\n (data['teacher_screening_interval'] == 7) & \\\n (data['half_classes'] == True)].index, 'measure'] = \\\n 'ventilation + halved classes + tests 1x teachers & students'\n \n # all measures\n data.loc[data[(data['transmission_risk_ventilation_modifier'] == 0.36) & \\\n (data['student_mask'] == True) & \\\n (data['teacher_mask'] == True) & \\\n (data['student_screening_interval'] == 3) & \\\n (data['teacher_screening_interval'] == 3) & \\\n (data['half_classes'] == True)].index, 'measure'] = \\\n 'all measures'\n \n \ndef format_none_column(x):\n if x == 'None':\n return None\n else:\n return int(x)","sub_path":"code/intervention_measures/data_creation_functions.py","file_name":"data_creation_functions.py","file_ext":"py","file_size_in_byte":21737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"495678496","text":"\n# Create the dictionary with graph elements\ngraph = { \"a\" : [\"b\",\"c\"],\n \"b\" : [\"a\", \"d\"],\n \"c\" : [\"a\", \"d\"],\n \"d\" : [\"e\"],\n \"e\" : [\"d\"]\n }\n\ndef printGraph():\n\tprint(\"\\nGraph : \\n\")\n\t\n\tfor v, nl in graph.iteritems():\n\t\tprint(str(\"VertexName : \"+v+\" -> neighbourList : \"+str(nl)))\n\n\n\ndef dfs(From):\n\tpath.append(From)\n\tvisited.add(From)\n\t\t\n\tfor To in graph[From]:\n\t\tif To not in visited:\n\t\t\tdfs(To)\n\n\ndef traverse(From, mode = \"BFS\"):\n\t\n\tQueue = []\n\n\tQueue.append(From)\n\tvisited.add(From)\n\n\n\twhile len(Queue) != 0:\n\n\t\tif mode == \"BFS\":\n\t\t\ts = Queue.pop(0)\n\t\tif mode == \"DFS\":\n\t\t\t# pop out the last index\n\t\t\ts = Queue.pop()\n\n\t\tpath.append(s)\t\t\n\t\t\n\t\tfor To in graph[s]:\n\t\t\tif To not in visited:\n\t\t\t\tQueue.append(To)\n\t\t\t\tvisited.add(To)\n\n\ndef allPath(From,To,path):\n\n\tpath.append(From)\n\tvisited.add(From)\n\n\tif From == To:\n\t\tprint(path)\n\n\tfor t in graph[From]:\n\t\tif t not in visited:\n\t\t\tallPath(t,To,path)\n\n\tpath.remove(From)\n\tvisited.remove(From)\n\n\n\n\n\n\nprintGraph()\n\nvisited = set()\npath = []\n\n\nmode = \"BFS\"\n# mode = \"DFS\"\n\n# traverse(\"a\",mode)\n\n# print(\"\\n\"+mode+\" : \"+str(path)+\"\\n\")\n\n\nmode = \"\\nAll paths a -> d \\n\"\nprint(mode)\nallPath(\"a\",\"d\",path)\n\n\n","sub_path":"quickGraph.py","file_name":"quickGraph.py","file_ext":"py","file_size_in_byte":1195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"21279994","text":"from torch.optim import Optimizer\nimport torch\n\nclass RK4(Optimizer):\n \"\"\"\n Arguments:\n params (iterable): iterable of parameters to optimize or dicts defining\n parameter groups\n lr (float, optional): learning rate (default: 1e-3)\n \"\"\"\n def __init__(self, params, lr=1e-2, momentum=0, dampening=0,\n weight_decay=0, nesterov=False):\n\n defaults = dict(lr=lr, momentum=momentum, dampening=dampening, \n weight_decay=weight_decay, nesterov=nesterov) \n if nesterov and (momentum <= 0 or dampening != 0): \n raise ValueError(\"Nesterov momentum requires a momentum and zero dampening\")\n\n super(RK4, self).__init__(params, defaults)\n\n def __setstate__(self, state):\n super(RK4, self).__setstate__(state)\n for group in self.param_groups: \n group.setdefault('nesterov', False)\n\n def step(self, closure):\n \"\"\"\n Performs a single optimization step.\n\n Arguments:\n closure (callable, optional): A closure that reevaluates the model\n and returns the loss.\n\n Note add the following function\n to your train function, so you pass\n\n for input, target in dataset:\n def closure():\n optimizer.zero_grad()\n output = model(input)\n loss = loss_fn(output, target)\n loss.backward()\n return loss\n optimizer.step(closure)\n \"\"\"\n if closure is not None: closure()\n grad_k1, grad_k2, grad_k3, grad_k4 = [], [], [], []\n\n for group in self.param_groups:\n p_real = [(p) for p in group['params']]\n weight_decay = group['weight_decay']\n momentum = group['momentum']\n dampening = group['dampening']\n nesterov = group['nesterov'] \n\n for group in self.param_groups:\n for i, p in enumerate(group['params']):\n if p.grad is None:\n continue\n\n grad_k1.append(-p.grad.data)\n p.data.add_(group['lr'] / 2, grad_k1[i])\n\n closure()\n for group in self.param_groups:\n for i, p in enumerate(group['params']):\n if p.grad is None:\n continue\n\n p.data = p_real[i].data\n for group_2 in self.param_groups:\n grad_k2.append(-group_2['params'][i].grad.data)\n\n p.data.add_(group['lr'] / 2, grad_k2[i])\n\n closure()\n for group in self.param_groups:\n for i, p in enumerate(group['params']):\n if p.grad is None:\n continue\n\n p.data = p_real[i].data\n for group_3 in self.param_groups:\n grad_k3.append(-group_3['params'][i].grad.data)\n\n p.data.add_(group['lr'], grad_k3[i])\n\n closure()\n for group in self.param_groups:\n for i, p in enumerate(group['params']):\n if p.grad is None:\n continue\n\n for group_4 in self.param_groups:\n grad_k4.append(-group_4['params'][i].grad.data)\n\n for group in self.param_groups:\n\n for j, p in enumerate(group['params']):\n if p.grad is None:\n continue\n\n d_p = grad_k1[j].add_(2, grad_k2[j]).add_(2, grad_k3[j]).add(grad_k4[j])\n\n if momentum != 0:\n param_state = self.state[p]\n if 'momentum_buffer' not in param_state:\n buf = param_state['momentum_buffer'] = torch.zeros(p_real[j].data.size())\n buf.mul_(momentum).add_(d_p.cpu())\n #d_p.cuda()\n #buf.cuda()\n else:\n buf = param_state['momentum_buffer']\n buf.mul_(momentum).add_(1 - dampening, d_p.cpu())\n if nesterov:\n d_p = d_p.add(momentum, buf)\n else:\n d_p = buf\n\n p_real[j].data.add_(group['lr'] / 6, d_p.cuda())\n p.data = p_real[j].data\n\n return closure()\n","sub_path":"code/linear_models_2/lasso_regression/modified_rk4.py","file_name":"modified_rk4.py","file_ext":"py","file_size_in_byte":4275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"210691955","text":"#!/usr/bin/env python\n\nimport argparse\nimport moviepy.editor as mpy\n\nimport cv2\n\nfrom model import Model\nfrom roi import ROI\nfrom tracker import Tracker\nfrom detector import detect\n\nWINDOWS = [152, 128, 72, 56]\nTHRESHOLD = 3\n\ndef recode(video, model):\n roi = ROI(video.size)\n tracker = Tracker()\n\n def track(frame):\n bb, _ = detect(frame, WINDOWS, THRESHOLD, model, roi)\n tracker.track(bb)\n for b in tracker.objects():\n cv2.rectangle(frame, (int(b[1]), int(b[0])), (int(b[3]), int(b[2])), \n color=(255, 0, 0), thickness=3)\n return frame\n\n return video.fl_image(track)\n\ndef main(args):\n m = Model.load(args.model)\n video = mpy.VideoFileClip(args.video)\n video = video.subclip(args.b, args.e)\n video = recode(video, m)\n video.write_videofile(args.filename, audio=False)\n \nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Video converseion utility')\n parser.add_argument('video', type=str,\n help='Input video file')\n parser.add_argument('-o', dest='filename', type=str, required=True,\n help='Output video file')\n parser.add_argument('-m', dest='model', type=str, required=True,\n help='Model to use')\n parser.add_argument('-b', type=int, default=0, help='Start time')\n parser.add_argument('-e', type=int, default=-1, help='End time')\n main(parser.parse_args())\n\n","sub_path":"video.py","file_name":"video.py","file_ext":"py","file_size_in_byte":1467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"605621416","text":"#!/usr/bin/python3 -v\n\nfrom datetime import datetime\nfrom datetime import date\nfrom datetime import timezone\nfrom datetime import timedelta\nimport json\nimport os\nimport sys\nimport mysql.connector\nimport smtplib\nimport time\n\nimport urllib.parse\n\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\nfrom email.header import Header\n\nSTOR=\"/var/wikiwatch.json\"\n\nSMTPSERV=\"localhost\"\n\nVARS=\"/usr/local/etc/watcher/vars.json\"\nSUSPEND=45*60\n\nWIKI_CONF = \"/usr/local/etc/wiki.json\"\nwith open(WIKI_CONF) as f:\n wiki_conf=json.load(f)\n\n\n\nclass MWSettings:\n def __init__(self):\n with open(VARS) as vfile:\n self.v=json.load(vfile)\n\n def openDB(self):\n return mysql.connector.connect(\n host=self.v.get('wgDBserver'),\n user=self.v.get('wgDBuser'),\n password=self.v.get('wgDBpassword'),\n database=self.v.get('wgDBname')\n )\n \n def urlbase(self):\n server = self.v.get('wgServer')\n path = self.v.get('wgScriptPath')\n return server+path+'/index.php?title='\n\n def namespaces(self):\n NSs = default_NSs.copy()\n NSs.update(self.v.get(\"wgExtraNamespaces\", {}))\n return NSs\n\n\n\ndef cmp_dicts(d1, d2):\n k1 = set(d1.keys())\n k2 = set(d2.keys())\n added = k2-k1\n removed = k1-k2\n tocompare = k1.intersection(k2)\n return added, removed, tocompare\n\ndefault_messages = {\n'new_category': \"new category: %(category)s pages: %(page)s\",\n'removed_category': \"removed category: %(category)s\",\n'page_added': \"page %(page)s added to category %(category)s\",\n'page_deleted': \"page %(page)s deleted from category %(category)s\",\n'page_new_in_category': \"new page %(page)s in category %(category)s\",\n'page_new': \"new page %(page)s without any category\",\n'page_edit': \"page %(page)s in category %(category)s was edited\",\n'page_edit_tmstmp': \"page %(page)s in category %(category)s was edited on %(tmstmp)s\",\n'page_removed': \"page %(page)s removed\", \n'subject': \"wiki watch notification\",\n'sender_name': \"Wiki Watcher\",\n'sender_address': \"wikiwatch@fidoman.ru\",\n'no_category': \"None\"\n}\n\ndefault_NSs = {\n '0': '',\n '1': 'Talk',\n '2': 'User',\n '3': 'User_talk',\n '4': 'Project',\n '5': 'Project_talk',\n '6': 'File',\n '7': 'File_talk',\n '8': 'MediaWiki',\n '9': 'MediaWiki_talk',\n '10': 'Template',\n '11': 'Template_talk',\n '12': 'Help',\n '13': 'Help_talk',\n '14': 'Category',\n '15': 'Category_talk',\n}\n\nMWvars = MWSettings()\nDB_CONN = MWvars.openDB\n\n\n\ndef anchorize(p, baseurl):\n pa = p.copy()\n if baseurl:\n if \"page\" in pa:\n link = baseurl + urllib.parse.quote(pa[\"page\"], safe=\":/\")\n pa[\"page\"] = '' + pa[\"page\"] + \"\"\n if \"file\" in pa:\n link = baseurl + urllib.parse.quote('File:' + pa[\"file\"], safe=\":/\")\n pa[\"file\"] = '' + pa[\"file\"] + \"\"\n if \"category\" in pa:\n link = baseurl + urllib.parse.quote('Category:' + pa[\"category\"], safe=\":/\")\n pa[\"category\"] = '' + pa[\"category\"] + \"\"\n return pa\n\nclass Notificator:\n \"\"\"Keeps data about emails and aggregates notifications\"\"\"\n def __init__(self, addresses, templates, baseurl, periodrewrite=None):\n self.page = {} # summary page \n self.messages = {} # email -> category -> [data lines]\n self.templates = templates\n self.cat_emails = addresses # list of emails for each watched category\n self.baseurl = baseurl\n if '*period' in self.cat_emails:\n self.period = self.cat_emails['*period'][0]\n else:\n self.period = 'monthly'\n\n if periodrewrite:\n self.period = periodrewrite\n\n if self.period==\"today\":\n begin = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)\n end = datetime.now().replace(hour=23, minute=59, second=59, microsecond=999999)\n elif self.period==\"monthly\":\n end=datetime.now()\n end=end.replace(day=1, hour=0, minute=0, second=0, microsecond=0)\n if end.month==1:\n begin=end.replace(year=end.year-1, month=12)\n else:\n begin=end.replace(month=end.month-1)\n elif self.period==\"weekly\":\n end=datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)\n days_since_monday=end.weekday() # 0 for monday\n end=end-timedelta(days=days_since_monday)\n begin=end-timedelta(weeks=1)\n elif self.period==\"oddweek\" or self.period==\"evenweek\":\n end=datetime.now().replace(hour=0, minute=0, second=0, microsecond=0) # today\n days_since_monday=end.weekday() # 0 for monday\n end=end-timedelta(days=days_since_monday) # monday\n ordinal = end.toordinal() # day number of monday\n if self.period==\"evenweek\" and (ordinal%2): # monday is odd, but we need it to be even (two week period starts with same oddity)\n end=end-timedelta(weeks=1)\n if self.period==\"oddweek\" and not (ordinal%2): # monday is even\n end=end-timedelta(weeks=1)\n if self.period==\"oddweek\" and not (ordinal%2):\n end=end-timedelta(weeks=1)\n begin=end-timedelta(weeks=2)\n\n elif self.period==\"daily\":\n end=datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)\n begin=end-timedelta(days=1)\n\n elif self.period.startswith(\"days=\"):\n try:\n period_days=int(self.period[5:])\n except:\n raise Exception(\"period: cannot converts days parameter to int\")\n end=datetime.now()\n begin=end-timedelta(days=period_days)\n\n else:\n raise Exception(\"unknown period code\")\n\n self.period_begin = begin\n self.period_end = end\n print(\"Period:\", begin, \"-\", end)\n\n\n\n # categories data: name by id, id by name, subcategories, pages in category\n# self.catn, self.cati, self.catsub, self.catp = load_MW_categories()\n #self.exp_cat_emails = {}\n\n # expand notifications lists\n #for c1, e1 in self.cat_emails.items():\n # #print(\"expand\", c1, \"for\", e1)\n # c1id = self.cati.get(c1)\n # #print(\"id\",c1id)\n # if c1id is None: continue\n # subcats = set()\n # category_tree(c1id, self.catn, self.catsub, subcats)\n # #print(\"subcats\",subcats)\n # for sc1 in subcats:\n # sc1n = self.catn.get(sc1, \"cat %d\"%sc1)\n # #print(sc1n)\n # self.exp_cat_emails.setdefault(sc1n, []).extend(e1)\n\n# def show_notification_lists(self):\n# import pprint\n# pprint.pprint(self.exp_cat_emails)\n\n def add(self, category, message, params):\n emails=self.cat_emails.get(category) # list(set()) - for each notify get all watcher and dedup list\n # + self.cat_emails.get('') # send all changes to * receivers\n if not emails: # None or []\n print(\"Notification for category '%s' will not be sent [%s]\"%(category, message))\n return\n tpl = self.templates.get(message)\n if not tpl:\n print(\"Notification will not be sent: no template for message '%s'\"%message)\n return\n #msg_text=tpl%params\n\n # email notification\n for email in emails:\n #print(\"Notify %s: %s\"%(email, message))\n self.messages.setdefault(email, {}).setdefault(message, {}).setdefault(category, []).append((tpl, params))\n\n # summary page\n self.page.setdefault(message, {}).setdefault(category, []).append((tpl, params))\n\n def send_all(self, subject=\"\", really_send=True):\n if not subject:\n subject = self.templates['subject']\n sendername = self.templates['sender_name']\n senderaddr = self.templates['sender_address']\n\n# _, _, _, _, _, catsuper = load_MW_categories()\n# print(catsuper)\n# exit()\n\n begin_text = self.period_begin.strftime(\"%Y-%m-%d\")\n end_text = (self.period_end-timedelta(seconds=1)).strftime(\"%Y-%m-%d\")\n\n header_line = self.templates['changes_header']%{'from': begin_text, 'to': end_text}\n footer_line = self.templates['changes_footer']%{'from': begin_text, 'to': end_text}\n\n\n for dst in self.messages.keys():\n# try:\n s=smtplib.SMTP(\"localhost\")\n\n msg = MIMEMultipart('alternative')\n msg['Subject'] = subject \n msg['From'] = Header(sendername)\n msg['From'].append(\"<\"+senderaddr+\">\")\n msg['To'] = \"<\"+dst+\">\"\n\n\n # self.messages[dst] is dict category -> list of tuples to write in body\n\n msg_lines_plain = [header_line.replace(\"
\", \"\\n\"), ''] # list of lines to include to text/plain part\n msg_lines_html = ['
'+header_line+'

'] # list of lines to include to text/html part\n\n message_data = self.messages[dst]\n\n def generate_lines(data, reverse_tmstmp=False):\n msg_types = set(data.keys())\n msg_types_order = ['change_created', 'change_edited']\n # groups: created/edited\n for msg_type in msg_types_order:\n msg_catgroups = data.get(msg_type, {})\n msg_catgroups.update(data.get(msg_type+\"_file\", {}))\n\n if not msg_catgroups:\n continue # use order, but skip empty\n\n yield(\n self.templates.get(msg_type+\"_group\"),\n '
'+self.templates.get(msg_type+\"_group\")+\"
\"\n )\n\n msg_cats = list(msg_catgroups.keys())\n msg_cats.sort()\n\n # by category\n for cat in msg_cats:\n # msg_catgroups now contains messages for category cat\n cat_messages = msg_catgroups[cat]\n # we must sort it by date\n # format of records is (template, params)\n # sort key is params[\"tmstmp\"]\n cat_messages.sort(key = lambda x: x[1].get(\"tmstmp\", \"\"), reverse = reverse_tmstmp)\n\n yield(\n self.templates.get(\"category\")+\": \"+(cat or self.templates['no_category']),\n '
'+self.templates.get(\"category\")+\": \"+(cat or self.templates['no_category'])+\"
\"\n )\n\n for tpl, param in cat_messages:\n yield(\n tpl%param, \n # for HTML: add to param values\n ''+tpl%(anchorize(param, self.baseurl))+'
'\n )\n\n yield(\n '',\n '
'\n )\n\n\n# ----\n # begin adding notifications here\n for lines in generate_lines(message_data):\n msg_lines_plain.append(lines[0])\n msg_lines_html.append(lines[1])\n\n\n msg_lines_plain.append(footer_line.replace(\"
\", \"\\n\"))\n msg_lines_html.append('
'+footer_line+'

')\n\n body = '\\n'.join(msg_lines_plain)\n part = MIMEText(body, 'plain')\n msg.attach(part)\n\n body = '\\n'.join(msg_lines_html)\n part = MIMEText(body, 'html')\n msg.attach(part)\n\n for l in msg_lines_plain:\n print(l)\n\n# for l in msg_lines_html:\n# print(l)\n\n print(\"sending to:\", dst)\n\n if not really_send:\n print(\"will not send message\")\n continue\n\n\n res=s.sendmail(senderaddr, dst, msg.as_string())\n s.quit()\n print(\"SMTP result:\", res)\n\n\n# except Exception as e:\n# print(\"send to\", dst, \"failed:\", e)\n\n with open(wiki_conf[\"watcher\"][\"summary_page\"], \"w\") as f:\n #f.write(header_line+\"
\\n\")\n for plain, html in generate_lines(self.page, reverse_tmstmp=True):\n f.write(html)\n f.write(footer_line)\n\n\n#START:\n#if exist .new file but not exist current: move # terminated after successful save and deletion \n#if exist current: discard .new if exist # failed before deletion OR completion of write\n\n#END:\n# save data to .new\n# move current to .old with overwrite\n# rename new to current\n\nclass ActivityStor:\n \"\"\"our memory about pages and categories\"\"\"\n def __init__(self, storfilename):\n self.fname = storfilename\n self.lockf=None\n\n def __enter__(self): \n self.lockf=os.open(self.fname+\".lock\", os.O_CREAT | os.O_EXCL)\n print(\"lock acquired for\", self.fname)\n\n if not os.path.exists(self.fname):\n if os.path.exists(self.fname+\".new\"):\n os.rename(self.fname+\".new\", self.fname)\n else:\n print(\"initializing data file\")\n x=open(self.fname, \"w\")\n json.dump(None, x)\n x.close()\n\n dataf = open(self.fname)\n self.data = json.load(dataf)\n dataf.close()\n #print(\"READ:\", repr(self.data))\n return self\n\n def commit(self):\n dataf=open(self.fname+\".new\", \"w\")\n json.dump(self.data, dataf)\n dataf.close()\n print(\"data flushed\")\n os.unlink(self.fname)\n os.rename(self.fname+\".new\", self.fname)\n\n def __exit__(self, et, ev, etb):\n if et:\n print(\"exiting\", str(et), ev, etb)\n if self.lockf is not None:\n #self.commit()\n print(\"releasing lock for\", self.fname)\n os.close(self.lockf)\n os.unlink(self.fname+\".lock\")\n\n\ndef pagename(NSs, pagens, title):\n nsname = NSs.get(pagens)\n if nsname is None:\n return \"NS#%s:%s\"%(pagens, title) # unknown namespace number\n if nsname=='': # MAIN\n return \"%s\"%(title)\n return \"%s:%s\"%(nsname, title)\n\n\n# === run functions ===\ndef diff():\n ntf = Notificator(load_addresses(), load_messages(), MWvars.urlbase())\n NSs = MWvars.namespaces()\n\n # ***\n # make list of notifications page notifications to remove dup\n # page added to category / new page in category\n # ?? or remove category check for new pages? (only category sees newly added pages)\n\n with ActivityStor(STOR) as x:\n if x.data is None:\n x.data=[{}, {}] # pages, categories\n\n db_catmembers={}\n db_pages={}\n db_pagecats={}\n\n a = DB_CONN()\n dbdata=a.cmd_query('select page_id, page_namespace, page_title, page_touched, cl_to from page, categorylinks where page_id=cl_from')\n # Для использования recent_changes надо поменять логику - отслеживать последнюю обработанную записть в таблице, иначе размер ответа разрастается\n# dbdata=a.cmd_query('select page_id, page_namespace, page_title, rc_timestamp, cl_to from page, categorylinks, recentchanges where page_id=cl_from and rc_namespace=page_namespace and rc_title=page_title')\n #print(dbdata)\n while True:\n d=a.get_row()\n #print(d[0],d[1])\n if d[0] is None:\n break\n pgid=d[0][0].decode(\"utf-8\")\n pgns=d[0][1].decode(\"utf-8\")\n pgtitle=d[0][2].decode(\"utf-8\")\n pgtmstmp=datetime.strptime(d[0][3].decode(\"ascii\")+\"+0000\", \"%Y%m%d%H%M%S%z\").timestamp() # assume UTC in database\n pgcat=d[0][4].decode(\"utf-8\")\n\n db_pages[pgid] = [pgns, pgtitle, pgtmstmp] # can be moved to separate query; use list as json make tuple lists and brokes comparation\n db_catmembers.setdefault(pgcat, []).append(pgid)\n db_pagecats.setdefault(pgid, []).append(pgcat)\n\n # add virtual category membership for category pages in themselves\n dbdata=a.cmd_query('select page_id, page_namespace, page_title, page_touched from page where page_namespace=14')\n #print(dbdata)\n while True:\n d=a.get_row()\n #print(d[0],d[1])\n if d[0] is None:\n break\n pgid=d[0][0].decode(\"utf-8\")\n pgns=d[0][1].decode(\"utf-8\")\n pgtitle=d[0][2].decode(\"utf-8\")\n pgtmstmp=datetime.strptime(d[0][3].decode(\"ascii\")+\"+0000\", \"%Y%m%d%H%M%S%z\").timestamp() # assume UTC in database\n pgcat=pgtitle\n\n #print(\"virtual membership for\", pgns, pgtitle, \"in\", pgcat)\n\n db_pages[pgid] = [pgns, pgtitle, pgtmstmp] # can be moved to separate query; use list as json make tuple lists and brokes comparation\n db_catmembers.setdefault(pgcat, []).append(pgid)\n db_pagecats.setdefault(pgid, []).append(pgcat)\n\n\n #print(\"Check categories\")\n cat_added, cat_removed, cat_check = cmp_dicts(x.data[1], db_catmembers)\n\n #... notify about new and removed categories, new - with page list\n if cat_added:\n print(\"new categories:\", cat_added)\n #messages.setdefault(cat_meta_email, []).append(\"new categories: %s\"%cat_added)\n for c1 in cat_added:\n pagelist = []\n for cp1 in db_catmembers[c1]:\n pagelist.append(pagename(NSs, *db_pages[cp1][:2])) #!!! add namespace\n ntf.add('', \"new_category\", {\"category\": c1, \"pages\": \", \".join(pagelist)})\n x.data[1][c1]=db_catmembers[c1] # copy catmembers to our stor\n if cat_removed:\n print(\"removed categories:\", cat_removed)\n for c1 in cat_removed:\n ntf.add('', \"removed_category\", {\"category\": c1, \"pages\": \"\"})\n x.data[1].pop(c1)\n\n #... check changed categories\n for c1 in cat_check:\n #print(\"check membership change for\", c1)\n #print(\"new\", db_catmembers[c1], \"old\", x.data[1][c1])\n added=set(db_catmembers[c1])-set(x.data[1][c1])\n removed=set(x.data[1][c1])-set(db_catmembers[c1])\n\n if added or removed:\n print(\"changes in\",c1,\":\", added, removed)\n\n for cp1 in added:\n ntf.add(c1, \"page_added\", {\"category\": c1, \"page\": pagename(NSs, *db_pages[cp1][0:2])})\n x.data[1][c1].append(cp1)\n\n for cp1 in removed:\n ntf.add(c1, \"page_deleted\", {\"category\": c1, \"page\": pagename(NSs, *x.data[0][cp1][0:2])})\n x.data[1][c1].remove(cp1)\n\n\n #print(\"Checking pages\")\n #print(x.data[0], db_pages)\n\n # should replace page_touch compare with recent_change list\n # keep latest viewed recent_changes mark in data file\n\n # as we already send notifications about new pages in categories (which covers all new pages)\n # and pages that left categories (what covers all deleted pages\n # there is no need to notify about categories in created/deleted pages\n\n # but we must overwrite notify 'page added/removed to category' with 'page created/deleted in category'\n\n pg_added, pg_removed, pg_check = cmp_dicts(x.data[0], db_pages)\n if pg_added:\n for p1 in pg_added:\n print(\"added\", p1, db_pagecats[p1])\n# for c1 in db_pagecats[p1]:\n# # *** - dup?\n# ntf.add(c1, \"page_new_in_category\", {\"page\": pagename(NSs, *db_pages[p1][0:2]), \"category\": c1})\n if not db_pagecats[p1]:\n ntf.add('', \"page_new\", {\"page\": pagename(NSs, *db_pages[p1][0:2]), \"category\": \"\"})\n x.data[0][p1] = db_pages[p1] # +[] if additional data is needed\n\n if pg_removed:\n for p1 in pg_removed:\n print(\"removed\", p1) # search categories in x.data[1]\n x.data[0].pop(p1)\n\n for p1 in pg_check:\n # intersection - compare time\n #print(\"checking modify time for page\", p1)\n oldtmstmp=x.data[0][p1][2]\n newtmstmp=db_pages[p1][2]\n curtmstmp=datetime.now(timezone.utc).timestamp()\n # notify if: 1) new>old and cur>new for more than 45 min; ?2) cur>old for more that 3 hrs\n #print(oldtmstmp, newtmstmp, curtmstmp)\n if newtmstmp>oldtmstmp:\n print(\"page\", p1, \"changed %ds ago\"%(curtmstmp-newtmstmp))\n if curtmstmp-newtmstmp < SUSPEND:\n print(\"suspend\")\n else:\n print(\"last edit was long ago!\")\n for c1 in db_pagecats[p1]:\n print(\"the page belongs to category\", c1)\n ntf.add(c1, \"page_edit\", {\"category\": c1, \"page\": pagename(NSs, *db_pages[p1][0:2])})\n x.data[0][p1][2] = newtmstmp\n else:\n pass # no new changes\n\n# do not send -- ntf.send_all()\n #print(\"updating stor\")\n x.commit()\n\n\n# === version 2016-09 ===\ndef summary(days):\n \"\"\"find changes from midnight `days` days ago up to current time\"\"\"\n NSs = MWvars.namespaces()\n\n curdt=datetime.now(timezone.utc)\n #print(curdt)\n tm=curdt.time()\n d=timedelta(days, hours=tm.hour, minutes=tm.minute, seconds=tm.second, microseconds=tm.microsecond)\n startdt=curdt-d\n starttmstmp=startdt.timestamp()\n endtmstmp=curdt.timestamp()\n #print(starttmstmp, endtmstmp)\n\n ntf = Notificator(load_addresses(), load_messages(), MWvars.urlbase())\n\n with ActivityStor(STOR) as x:\n for p1 in x.data[0]:\n #print(p1, x.data[0][p1])\n if x.data[0][p1][2]>starttmstmp:\n ascts=time.ctime(x.data[0][p1][2])\n print(p1, \"was edited\", ascts)\n for c1 in x.data[1]:\n if p1 in x.data[1][c1]:\n pgname = pagename(NSs, *x.data[0][p1][0:2])\n ntf.add(c1, \"page_edit_tmstmp\", {\"page\": pgname, \"category\": c1, \"tmstmp\": ascts})\n\n ntf.send_all(\"wiki edits in last %d days\"%days)\n\n\n# === version 2017-04 ===\ndef wikitmstmp(dt):\n return dt.strftime(\"%Y%m%d%H%M%S\")\n\ndef exp_summary(periodrewrite=None, dosend=None):\n \"\"\" mode = \n weekly - each monday\n oddweek - each odd monday\n evenweek - each even monday\n monthly - each 1st day of month\n \"\"\"\n ntf = Notificator(load_addresses(), load_messages(), MWvars.urlbase(), periodrewrite)\n do_send = ntf.period_end == datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)\n\n if dosend is not None:\n do_send = dosend\n\n begin = wikitmstmp(ntf.period_begin)\n end = wikitmstmp(ntf.period_end)\n print(\"summary of changes between\", begin, \"and\", end, \"send mails:\", do_send)\n\n\n a = DB_CONN()\n a.cmd_query(\"select count(*) from recentchanges where rc_timestamp>=%s and rc_timestamp<%s\"%(begin, end))\n while True:\n d, stat = a.get_row()\n if stat is None:\n print(\"count=\", d)\n else:\n break\n\n # make list of changed or new pages\n pagestat = {} # page_id => (created, updated) - only date\n a.cmd_query(\"select rc_timestamp, rc_namespace, rc_title, rc_new, rc_cur_id, rc_log_action from recentchanges where rc_timestamp>=%s and rc_timestamp<%s and rc_minor=0\"%(begin, end))\n # for file upload: rc_log_type == 'upload' && rc_old_len is null => new\n while True:\n d, stat = a.get_row()\n if stat is None:\n is_new = bool(int(d[3]))\n page_id = int(d[4])\n timestamp = d[0].decode(\"utf-8\")[:8] # YYYYMMDD\n\n # filter namespaces\n page_namespace = int(d[1])\n if page_namespace!=0 and page_namespace!=6 and page_namespace!=14 and (page_namespace<3000 or page_namespace%2):\n #print(\"NS=%d - do not care\"%page_namespace)\n # we need main, files, categories and custom\n continue\n\n if page_namespace in wiki_conf[\"watcher\"][\"ignore_ns\"]: # NS_DRAFTS\n continue\n\n if page_namespace==6:\n if d[5] == b'upload':\n is_new = True\n elif d[5] == b'overwrite':\n is_new = False\n else:\n continue\n #print(d[2].decode(\"utf-8\"), d[0], is_new)\n\n # skip files if they are pictures\n title = d[2].lower()\n title_ext = os.path.splitext(title)[1]\n if title_ext in set((b\".jpg\", b\".png\", b\".bmp\", b\".gif\", b\".jpeg\")):\n continue\n\n #if is_new:\n # print(d[0].decode(\"utf-8\"), int(d[1]), d[2].decode(\"utf-8\"), d[3], d[4])\n\n pstat = pagestat.get(page_id, [None, None])\n\n if is_new:\n idx = 0\n else:\n idx = 1\n\n if pstat[idx] is None:\n pstat[idx] = timestamp\n else:\n pstat[idx] = max(pstat[idx], timestamp)\n\n# --- code for method of selecting changes to display - created or last modified\n# old_pstat = pagestat.get(page_id)\n# # for new pages - keep creation timestamp\n# # for modified pages - last update timestamp\n# if old_pstat is not None:\n# if is_new:\n# pstat = (True, timestamp)\n# else:\n# if old_pstat[0]: # is_new\n# pstat = old_pstat\n# else:\n# pstat = (False, max(timestamp, old_pstat[1]))\n# else:\n# pstat = (is_new, timestamp)\n\n pagestat[page_id] = pstat\n\n else:\n break\n\n pagecats = walk_category_subtree()\n\n NSs = MWvars.namespaces()\n pagenames = load_MW_pages()\n\n def format_date(x):\n# return x[6:8]+'.'+x[4:6]+x[0:4]\n return x[0:4]+'-'+x[4:6]+'-'+x[6:8]\n\n for page_id, pstat in pagestat.items():\n print(page_id, pstat)\n page_code = pagenames.get(page_id)\n if page_code is None:\n print(\"page deleted\", page_id)\n continue\n page_name = pagename(NSs, *page_code)\n print(\"page name:\", page_name, repr(pstat))\n for c1 in pagecats.get(page_id, ['']):\n print(\"notify for category\", repr(c1))\n if pstat[0]:\n if page_code[0] == \"6\": # File \n ntf.add(c1, \"change_created_file\", {'category': c1, 'file': page_code[1], 'tmstmp': format_date(pstat[0])})\n else:\n ntf.add(c1, \"change_created\", {'category': c1, 'page': page_name, 'tmstmp': format_date(pstat[0])})\n if pstat[1] and pstat[1]!=pstat[0]: # to remove notifies about edits in same period check pstat[0] is None\n if page_code[0] == \"6\": # File \n ntf.add(c1, \"change_edited_file\", {'category': c1, 'file': page_code[1], 'tmstmp': format_date(pstat[1])})\n else:\n ntf.add(c1, \"change_edited\", {'category': c1, 'page': page_name, 'tmstmp': format_date(pstat[1])})\n\n# if pstat[0]:\n# print('new page')\n# if c1:\n# ntf.add(c1, \"page_new_in_category\", {'category': c1, 'page': page_name, 'timestamp': pstat[1]})\n# else: \n# ntf.add(c1, \"page_new\", {'category': c1, 'page': page_name, 'timestamp': pstat[1]})\n# else:\n# print('updated page')\n# if c1:\n# ntf.add(c1, \"page_edit_tmstmp\", {'category': c1, 'page': page_name, 'tmstmp': pstat[1]})\n# else: \n# ntf.add(c1, \"page_new\", {'category': c1, 'page': page_name, 'timestamp': pstat[1]})\n\n ntf.send_all(really_send=do_send)\n\n\n# ===\ndef run(slp=500):\n import traceback\n while True:\n try:\n diff()\n time.sleep(slp)\n except:\n traceback.print_exc()\n time.sleep(slp*12)\n time.sleep(slp)\n\n# ===\ndef usage():\n print(\"\"\"Mediawiki change watcher\n watcher.py clearlock -- remove stale lock file (run it on system startup)\n watcher.py summary -- notify about changes in last N days (midnight to midnight)\n watcher.py diff -- notify about changes since last diff\n watcher.py run [N] -- run diff each N seconds\n watcher.py emails -- show list of e-mails for categories\n watcher.py messages -- show list of localized messages\n watcher.py namespaces -- show list of custom namespaces\n watcher.py urlbase -- show base URL for mediawiki pages\n watcher.py cattree -- show tree of categories\n watcher.py pagecats -- show categories per page\n watcher.py pages -- show all pages\n watcher.py glossary -- show glossary\n\"\"\")\n\n# ===\ndef show_emails():\n print(\"Configured emails:\")\n for k, v in load_addresses().items():\n print(\"cat\", repr(k), \"email\", v)\n\n# ===\ndef show_messages():\n for k, v in load_messages().items():\n print(\"message :\", repr(k))\n print(\"localized:\", v)\n print()\n\n# ===\ndef show_publishers():\n for k, v in load_publishers().items():\n print(\"address :\", repr(k))\n print(\"namespace:\", v)\n print()\n\n# ===\ndef show_publishers_json():\n print(json.dumps(load_publishers()))\n\n# ===\ndef show_namespaces():\n for k, v in MWvars.namespaces().items():\n print(repr(k), repr(v))\n\n# ===\ndef show_namespaces_json():\n print(json.dumps(MWvars.namespaces()))\n\n# ===\n\ndef show_glossary():\n for term, definition in load_MW_glossary():\n print(term, \"--\", definition)\n\n# ===\n\ndef glossary_array():\n glossary = {}\n for term, definition in load_MW_glossary():\n glossary.setdefault(term, []).append(definition)\n\n glossary_array = []\n for term in glossary:\n defs = glossary[term]\n for d in defs:\n glossary_array.append((term, d))\n# if len(defs)==1:\n# glossary_array.append((term, defs[0]))\n# else:\n# glossary_array.append((term, \n# \"\".join(map(lambda x: \"-- \"+x+\"\\n\", defs))\n# ))\n\n return glossary_array\n\n# === database functions ===\ndef load_MW_page_dict(pagename):\n \"\"\" read dict from Mediawiki namespace page \"\"\"\n a = DB_CONN()\n a.cmd_query(\"select old_text from text, revision, page where page_namespace=8 and page_title='%s' and page_latest=rev_id and rev_text_id=old_id\"%pagename) # vulnerable!!! but no positional parameters in this function is supported\n pgtext = None\n while True:\n d, stat = a.get_row()\n #print(d, stat)\n if not d:\n break\n pgtext = d[0].decode(\"utf-8\")\n if pgtext is None:\n raise Exception(\"cannot find page %s in wiki database\"%pagename)\n\n addrs = {}\n\n cat = None\n for l1 in pgtext.strip().split(\"\\n\"):\n if l1.startswith(';'): # new 'definition'\n cat = None\n r = list(map(str.strip, l1[1:].split(':', 1)))\n if len(r) == 1: # term only\n cat = r[0]\n addrs[cat] = []\n if len(r) == 2:\n cat, email = r\n #print(cat, email)\n if cat=='*':\n cat=''\n cat = cat.replace(' ', '_')\n addrs[cat] = [email]\n elif l1.startswith(':'): # additional address\n email = l1[1:].strip()\n if cat is None:\n print( \"orphan e-mail\", l1)\n continue\n addrs[cat].append(email)\n\n return addrs\n\ndef load_addresses():\n return load_MW_page_dict('Category_notify')\n\ndef load_messages():\n msgs = default_messages.copy()\n for k, v in load_MW_page_dict('Category_notify_templates').items():\n msgs[k] = \"\\n\".join(v)\n return msgs\n\ndef load_publishers():\n return load_MW_page_dict('Publishers')\n\ndef load_publishing():\n by_mbox = load_MW_page_dict('Publishing')\n# print(by_mbox)\n by_mbox_and_sender = {}\n for k, v in by_mbox.items():\n for v1 in v:\n sender, action = map(str.strip, v1.split(\"-->\", 1))\n by_mbox_and_sender.setdefault(k, {})[sender] = action\n return by_mbox_and_sender\n\n\ndef load_MW_pages():\n \"\"\" use pagename() to get page title with namespace \"\"\"\n a = DB_CONN()\n a.cmd_query(\"select page_id, page_namespace, page_title from page\")\n pagename={} # id -> name\n #pageid=[]\n while True:\n d, stat = a.get_row()\n if stat:\n break\n pagename[int(d[0])] = (d[1].decode('utf-8'), d[2].decode('utf-8'))\n #categoryid[(int(d[1], d[2].decode('utf-8'))] = int(d[0])\n return pagename\n\n\ndef load_MW_categories():\n \"\"\" get dicts for categories:\n category -> subcategories\n category -> supercategories\n \"\"\"\n a = DB_CONN()\n a.cmd_query(\"select page_id, page_title from page where page_namespace=14\")\n categoryname={} # id -> name\n categoryid={} # name-> id\n while True:\n d, stat = a.get_row()\n if stat:\n break\n #print(int(d[0]), d[1].decode('utf-8'))\n categoryname[int(d[0])] = d[1].decode('utf-8')\n #print(\"categoryname\", int(d[0]), '=', d[1].decode('utf-8'))\n categoryid[d[1].decode('utf-8')] = int(d[0])\n\n # to be included into another category, it must have existing page\n categorysub={} # category -> subcategories\n categorysuper={} # category -> subercategories\n a.cmd_query(\"select cl_from, cl_to from categorylinks where cl_type='subcat'\")\n # cl_from - page\n # cl_to - category\n while True:\n d, stat = a.get_row()\n if stat:\n break\n member_id = int(d[0])\n category_name = d[1].decode(\"utf-8\")\n #category_id = categoryid[category_name]\n #print(categoryname[member_id], \"belongs to\", category_name)\n #categorysuper.setdefault(member_id, []).append(category_id)\n categorysub.setdefault(category_name, []).append(member_id)\n\n categorypages={}\n a.cmd_query(\"select cl_from, cl_to from categorylinks where cl_type='page' or cl_type='file'\") # or process files separately?\n while True:\n d, stat = a.get_row()\n if stat:\n break\n category_name = d[1].decode(\"utf-8\")\n categorypages.setdefault(category_name, []).append(int(d[0]))\n\n all_categories = []\n a.cmd_query(\"select cat_title from category\")\n while True:\n d, stat = a.get_row()\n if stat:\n break\n category_name = d[0].decode(\"utf-8\")\n all_categories.append(category_name)\n\n return all_categories, categoryname, categoryid, categorysub, categorypages, categorysuper\n\n# walk tree by relation records (merge all subrecords)\ndef category_tree(base, catnames, catsub, output): # output should be empty set\n \"\"\" use name, not page_id, as top category may not have page (but subcategories must do)\"\"\"\n output.add(base)\n #print(\"walk\", base)\n for subcat in catsub.get(base, []):\n subcat_name = catnames[subcat]\n if subcat_name not in output:\n category_tree(subcat_name, catnames, catsub, output)\n\ndef walk_category_subtree(dump=False):\n \"\"\" walk every category and make list of categories for each page\n print if dump is True \"\"\"\n all_cats, catn, cati, catsub, catp, catsuper = load_MW_categories()\n pagecats = {}\n for c1 in all_cats:\n if dump: print(\"category\", c1)\n subcats = set()\n category_tree(c1, catn, catsub, subcats)\n for sc1 in subcats:\n cp1 = catp.get(sc1, [])\n if dump: print(\" subcat\", sc1, \"pages\", cp1)\n for cp11 in cp1:\n pagecats.setdefault(cp11, set()).add(c1)\n return pagecats\n\ndef load_MW_glossary():\n a = DB_CONN()\n pagename = \"Глоссарий\"\n a.cmd_query(\"select old_text from text, revision, page where page_namespace=0 and page_title='%s' and page_latest=rev_id and rev_text_id=old_id\"%pagename)\n pgtext = None\n while True:\n d, stat = a.get_row()\n #print(d, stat)\n if not d:\n break\n pgtext = d[0].decode(\"utf-8\")\n if pgtext is None:\n raise Exception(\"cannot find page %s in wiki database\"%pagename)\n\n #print(pgtext)\n\n # mode\n # wait table\n # wait row \n # wait column\n # wait column\n mode = \"wait table\"\n data = []\n row = None\n for l in pgtext.split(\"\\n\"):\n l = l.lstrip()\n if mode == \"wait table\":\n if l.startswith(\"{|\"):\n #print(\"table begin\")\n mode = \"wait row\"\n elif mode == \"wait row\":\n if l.startswith(\"|-\"):\n #print(\"row begin\")\n row = []\n data.append(row)\n mode = \"wait column\"\n colno = 0\n elif l.startswith(\"|}\"):\n print(\"table end\")\n break\n elif mode == \"wait column\":\n if l.startswith(\"|-\"):\n #print(\"row begin\")\n row = []\n data.append(row)\n mode = \"wait column\"\n colno = 0\n elif l.startswith(\"|}\"):\n #print(\"table end\")\n break\n elif l.startswith(\"|\"): # column text with style\n #print(\"data\", colno, l[1:])\n x=l[1:].split(\"|\", 1)\n x=x[-1] # last section of column divided by \"|\"'s\n row.append(x.replace(\" \", \" \").strip())\n mode = \"wait column\"\n colno += 1\n \n# else: # column text\n# x = l[1:]\n# row.append(x.replace(\" \", \" \").strip())\n# mode = \"wait column\"\n# colno += 1\n\n\n def format_def(term, definition):\n term = term.replace(\";\", \"*\").replace(\":\", \"*\")\n definition = definition.replace(\";\", \"*\").replace(\":\", \"*\")\n return(\";\"+term+\":\"+definition)\n\n# glossary = {}\n# glossary_array = []\n for l in data:\n try:\n #print(\"***\", l)\n if l[2]:\n# if l[0]: make different definitions for short and long terms\n# print(\";\", l[0])\n# if l[1]:\n# print(\";\", l[1])\n# if l[0] or l[1]:\n# print(\":\", l[2])\n if l[0]:\n# print(format_def(l[0], l[2]))\n# glossary[l[0]] = l[2]\n yield (l[0], l[2])\n if l[1]:\n if l[0]:\n# print(format_def(l[1], l[0]+' - '+l[2]))\n# glossary[l[1]] = l[0]+' - '+l[2]\n yield (l[1], l[0]+' - '+l[2])\n else:\n# print(format_def(l[1], l[2]))\n# glossary[l[1]] = l[2]\n yield (l[1], l[2])\n\n else:\n if l[0] and l[1]: \n# print(format_def(l[1], l[0]))\n# glossary[l[1]] = l[0]\n yield (l[1], l[0])\n except:\n sys.stderr.write(\"error on %s\\n\"%repr(l))\n\n return #glossary\n\n\n# для получения оповещения:\n# для данного получателя получить список категорий\n# объединить список страниц по всем подкатегориям\n# проверить все страницы списка, были ли изменения\n\n# добавленные/удалённые/изменённые страницы\n# изменения категорий - в каком виде?\n# включение/исключение страницы/категории в категорию\n\n##########################################################\n\n\n\nif len(sys.argv)>1 and sys.argv[1]==\"clearlock\":\n try:\n os.unlink(STOR+\".lock\")\n print(\"lock file removed\")\n except:\n pass\n exit()\n\nif len(sys.argv)>1 and sys.argv[1]==\"summary\":\n exp_summary()\n exit()\n\nif len(sys.argv)>1 and sys.argv[1]==\"summary_html\":\n exp_summary(\"days=15\", False)\n exit()\n\nif len(sys.argv)>1 and sys.argv[1]==\"today\":\n exp_summary(\"today\", False)\n exit()\n\nif len(sys.argv)>1 and sys.argv[1]==\"test_daily\":\n exp_summary(\"daily\", False)\n exit()\n\nif len(sys.argv)>1 and sys.argv[1]==\"test_monthly\":\n exp_summary(\"monthly\", False)\n exit()\n\nif len(sys.argv)>1 and sys.argv[1]==\"test_oddweek\":\n exp_summary(\"oddweek\", False)\n exit()\n\nif len(sys.argv)>1 and sys.argv[1]==\"test_evenweek\":\n exp_summary(\"evenweek\", False)\n exit()\n\nif len(sys.argv)>1 and sys.argv[1]==\"diff\":\n diff()\n exit()\n\nif len(sys.argv)==2 and sys.argv[1]==\"run\":\n run()\n exit()\n\nif len(sys.argv)==3 and sys.argv[1]==\"run\":\n run(int(sys.argv[2]))\n exit()\n\nif len(sys.argv)>1 and sys.argv[1]==\"emails\":\n show_emails()\n exit()\n\nif len(sys.argv)>1 and sys.argv[1]==\"namespaces\":\n show_namespaces()\n exit()\n\nif len(sys.argv)>1 and sys.argv[1]==\"namespaces_json\":\n show_namespaces_json()\n exit()\n\nif len(sys.argv)>1 and sys.argv[1]==\"messages\":\n show_messages()\n exit()\n\nif len(sys.argv)>1 and sys.argv[1]==\"publishers\":\n show_publishers()\n exit()\n\nif len(sys.argv)>1 and sys.argv[1]==\"publishers_json\":\n show_publishers_json()\n exit()\n\nif len(sys.argv)>1 and sys.argv[1]==\"publishing\":\n for k, v in load_publishing().items():\n print(k, v)\n exit()\n\nif len(sys.argv)>1 and sys.argv[1]==\"publishing_json\":\n print(json.dumps(load_publishing()))\n exit()\n\nif len(sys.argv)>2 and sys.argv[1]==\"subcats_json\":\n all_cats, catn, cati, catsub, catp, catsuper = load_MW_categories()\n subcats = set()\n category_tree(sys.argv[2], catn, catsub, subcats)\n print(json.dumps(list(subcats)))\n exit()\n\nif len(sys.argv)>1 and sys.argv[1]==\"urlbase\":\n print(MWvars.urlbase())\n exit()\n\nif len(sys.argv)>1 and sys.argv[1]==\"cattree\":\n walk_category_subtree(True)\n exit()\n\nif len(sys.argv)>1 and sys.argv[1]==\"pagecats\":\n import pprint\n pprint.pprint(walk_category_subtree(False))\n exit()\n\nif len(sys.argv)>1 and sys.argv[1]==\"pages\":\n NSs = MWvars.namespaces()\n for page_id, page_code in load_MW_pages().items():\n page_NS, page_name = page_code\n# print (page_id, page_NS, page_name, pagename(NSs, page_NS, page_name))\n print(page_id, pagename(NSs, page_NS, page_name))\n exit()\n\nif len(sys.argv)>1 and sys.argv[1]==\"glossary\":\n show_glossary()\n exit()\n\nif len(sys.argv)>1 and sys.argv[1]==\"glossary_json_array\":\n import json\n json.dump(glossary_array(), sys.stdout)\n exit()\n\n\nusage()\nexit()\n","sub_path":"bin/watcher.py","file_name":"watcher.py","file_ext":"py","file_size_in_byte":39199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"350409345","text":"def main():\n # solve for puzzle input\n input = list(map(int, open(\"day06_input.txt\").read().split('\\t')))\n\n print(solve(input))\n\n\ndef solve(input):\n count = 0\n seen = []\n while input not in seen:\n seen.append(input[:])\n # find highest\n index = input.index(max(input))\n value = input[index]\n input[index] = 0\n while value > 0:\n index = (index + 1) % len(input)\n input[index] += 1\n value -= 1\n count += 1\n\n return count\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"2017/day06/day06_part1.py","file_name":"day06_part1.py","file_ext":"py","file_size_in_byte":561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"285621101","text":"from django.shortcuts import render, redirect\nfrom django.shortcuts import render, get_object_or_404\nfrom django.contrib.auth.models import User\nfrom django.contrib import auth\nfrom django.core.paginator import Paginator\nfrom .models import Snippet, Language\nfrom .forms import SnippetForm\n\n\ndef index(request):\n snippets = Snippet.objects.all()\n return render(request, 'index.html', {'snippets':snippets})\n\ndef language(request, language):\n language_obj = Language.objects.get(slug=language)\n snippets = Snippet.objects.filter(language=language_obj)\n return render(request, 'language_snippet.html', {'snippets':snippets, 'language':language_obj})\n\ndef user_snippets(request, pk):\n snippet_user = get_object_or_404(User, pk=pk)\n snippets = Snippet.objects.filter(user_id=pk)\n\n if request.user != snippet_user:\n snippets = snippets.filter(public=True)\n\n return render(request, 'snippets/user_snippets.html', {'snippets':snippets , 'snippet_user':snippet_user})\n\ndef snippet(request, pk):\n snippet_detail = get_object_or_404(Snippet, pk=pk)\n return render(request, 'snippets/snippet.html',{'snippet_detail':snippet_detail})\n\ndef snippet_add(request):\n languages = Language.objects.all()\n if request.method == 'POST':\n snippet_form = SnippetForm(request.POST)\n if snippet_form.is_valid():\n snippet_form.save(user=request.user)\n return redirect('index')\n else:\n snippet_form = SnippetForm()\n\n return render(request, 'snippets/snippet_add.html', {'snippet_form':snippet_form, 'languages': languages})\n\n\ndef snippet_edit(request, pk):\n snippet = get_object_or_404(Snippet, pk=pk)\n if request.method == \"POST\":\n snippet_form = SnippetForm(request.POST, instance=snippet)\n if snippet_form.is_valid():\n snippet.save()\n return redirect('index')\n else:\n snippet_form = SnippetForm(instance=snippet)\n return render(request, 'snippets/snippet_add.html', {'snippet_form': snippet_form})\n\n\ndef snippet_delete(request, pk):\n snippet = get_object_or_404(Snippet, pk=pk)\n if request.method == \"POST\":\n\t snippet.delete()\n\t return redirect('index')\n return render(request, 'snippets/snippet_delete.html', {'snippet':snippet})\n","sub_path":"snippets/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"157574610","text":"#!/usr/bin/env python\n#\n# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Builds the dependencies, runs the checks, and compiles the library.\"\"\"\n\nimport argparse\nimport build\nimport check\nimport gendeps\nimport shakaBuildHelpers\n\n\ndef main(args):\n parser = argparse.ArgumentParser(\n description='User facing build script for building the Shaka'\n ' Player Project.')\n\n parser.add_argument(\n '--fix',\n help='Automatically fix style violations.',\n action='store_true')\n\n parser.add_argument(\n '--force',\n '-f',\n help='Force building the library even if no files have changed.',\n action='store_true')\n\n parser.add_argument(\n '--debug',\n help='Limit which build types to build. Will at least build the debug '\n 'version.',\n action='store_true')\n\n parser.add_argument(\n '--release',\n help='Limit which build types to build. Will at least build the '\n 'release version.',\n action='store_true')\n\n parsed_args = parser.parse_args(args)\n\n code = gendeps.gen_deps([])\n if code != 0:\n return code\n\n check_args = ['--fix'] if parsed_args.fix else []\n code = check.main(check_args)\n if code != 0:\n return code\n\n build_args = ['--name', 'compiled', '+@complete']\n\n if parsed_args.force:\n build_args += ['--force']\n\n # Create the list of build modes to build with. If the list is empty\n # by the end, then populate it with every mode.\n modes = []\n modes += ['debug'] if parsed_args.debug else []\n modes += ['release'] if parsed_args.release else []\n\n # If --debug or --release are not given, build with everything.\n if not modes:\n modes += ['debug', 'release']\n\n result = 0\n\n for mode in modes:\n result = build.main(build_args + ['--mode', mode])\n\n # If a build fails then there is no reason to build the other modes.\n if result:\n break\n\n return result\n\nif __name__ == '__main__':\n shakaBuildHelpers.run_main(main)\n","sub_path":"build/all.py","file_name":"all.py","file_ext":"py","file_size_in_byte":2506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"204186788","text":"\r\nfrom flask import (Flask, render_template, request, \r\n\tjsonify, url_for, send_from_directory)\r\nimport requests\r\nimport csv\r\nimport json\r\nimport time\r\nimport random\r\nimport os\r\nimport sys\r\nimport traceback\r\n\r\n\r\n# cmd width to 95, height to 35 (unscrollable so no)\r\nos.system('mode con: cols=95 lines=1024')\r\n\r\n\r\ndef resource_path(relative_path):\r\n\t\"\"\" Get absolute path to resource, works for dev and for PyInstaller \"\"\"\r\n\ttry:\r\n\t\t# PyInstaller creates a temp folder and stores path in _MEIPASS\r\n\t\tbase_path = sys._MEIPASS\r\n\texcept Exception:\r\n\t\tbase_path = os.environ.get(\"_MEIPASS2\",os.path.abspath(\".\"))\r\n\r\n\treturn os.path.join(base_path, relative_path)\r\n_data = resource_path(\"dataset.txt\")\r\n\r\n\r\nif getattr(sys, 'frozen', False):\r\n template_folder = os.path.join(sys._MEIPASS, 'templates')\r\n app = Flask(__name__, template_folder=template_folder)\r\nelse:\r\n app = Flask(__name__)\r\n print(\"Could not load bootstrap and css...\")\r\n\r\n\r\nsplash = \"\"\" \r\n\t_|_|_| _|_|_|_| _|_|_| _|_|_|_|_| _|_| _|_|_| _|_|_| \r\n\t_| _| _| _| _| _| _| _| _| _| \r\n\t_|_|_| _|_|_| _|_| _| _|_|_| _|_|_|_| _|_|_| _| \r\n\t_| _| _| _| _| _| _| _| _| \r\n\t_| _| _|_|_|_| _|_|_| _| _| _| _| _|_|_|\r\n\r\n\t _|_|_|_|_| _|_|_|_| _|_|_| _|_|_|_|_| _|_|_|_| _|_|_| \r\n\t _| _| _| _| _| _| _| \r\n\t _| _|_|_| _|_| _| _|_|_| _|_|_| \r\n\t _| _| _| _| _| _| _|\r\n\t _| _|_|_|_| _|_|_| _| _|_|_|_| _| _|\r\n\"\"\"\r\n\r\nprint(splash)\r\n\r\nprint(' Welcome! Open localost on port 5000 using your browser to start.\\n')\r\n\r\n\r\nclass Book:\r\n\tdef __init__(self, _id, publisher, title, genre, author):\r\n\t\tself._id \t\t= _id\r\n\t\tself.publisher \t= publisher\r\n\t\tself.title \t\t= title\r\n\t\tself.genre \t\t= genre\r\n\t\tself.author \t= author\r\n\r\n\r\nbooks = []\r\nauthors = []\r\ngenres = []\r\ntitles = []\r\npublishers = []\r\ndef load_resources():\r\n\tif len(books) == 0:\r\n\t\twith open(_data, 'r') as outfile:\r\n\t\t\tdataset = csv.reader(outfile, delimiter=',')\r\n\t\t\tfor i in dataset:\r\n\t\t\t\ttry:\r\n\t\t\t\t\tbooks.append(Book(int(i[0]), i[1], i[2], i[3], i[4]).__dict__)\r\n\t\t\t\t\tif not i[1] in publishers:\r\n\t\t\t\t\t\tpublishers.append(i[1])\r\n\t\t\t\t\tif not i[2] in titles:\r\n\t\t\t\t\t\ttitles.append(i[2])\r\n\t\t\t\t\tif not i[3] in genres:\r\n\t\t\t\t\t\tgenres.append(i[3])\r\n\t\t\t\t\tif not i[4] in authors:\r\n\t\t\t\t\t\tauthors.append(i[4])\r\n\t\t\t\texcept:\r\n\t\t\t\t\tpass\r\n\r\n\r\n@app.route('/')\r\ndef main():\r\n\treturn render_template('mainpage.html')\r\n\r\n\r\n@app.route('/favicon.ico')\r\ndef favicon():\r\n return send_from_directory(os.path.join(app.root_path, 'static'),\r\n 'be.ico', mimetype='image/vnd.microsoft.icon')\r\n\r\n\r\n@app.route('/secretpage')\r\ndef easter_egg_during_april():\r\n\treturn render_template('secretpage.html')\r\n\r\n\r\n@app.route('/dataset')\r\ndef send_dataset():\r\n\theader = request.headers.get('x-psau-elite')\r\n\r\n\tif header == 'QkVQU0FVLTE0MjphamZWYVpVMQ==':\r\n\t\twith open(_data) as dataset:\r\n\t\t\treturn dataset.read()\r\n\telse:\r\n\t\treturn '

You need to send a request with headers to this endpoint ;-)

'\r\n\r\n\r\n@app.route('/sample')\r\ndef sample_solution():\r\n\r\n\ttry:\r\n\t\tlimit = str(request.args.get('limit')).strip()\r\n\t\tlimit = int(limit)\r\n\t\tif limit < 0:\r\n\t\t\treturn jsonify({\"status\":400,\"message\":\"limit is negative\"})\r\n\texcept:\r\n\t\tlimit = 50\r\n\r\n\ttry:\r\n\t\tskip = str(request.args.get('skip')).strip()\r\n\t\tskip = int(skip)\r\n\t\tif skip < 0:\r\n\t\t\treturn jsonify({\"status\":400,\"message\":\"number to skip cannot be negative\"})\r\n\t\telif skip > 999:\r\n\t\t\treturn jsonify({\"status\":400, \"message\": \"number to skip too high\"})\r\n\texcept:\r\n\t\tskip = 0\r\n\r\n\ttry:\r\n\t\torder = request.args.get('order')\r\n\texcept:\r\n\t\torder = 'ASC'\r\n\r\n\tload_resources()\r\n\r\n\ttry:\r\n\t\t_id = int(request.args.get('_id'))\r\n\texcept:\r\n\t\t_id = None\r\n\r\n\ttry:\r\n\t\tpublisher = request.args.get('publisher')\r\n\texcept:\r\n\t\tpublisher = None\r\n\r\n\ttry:\r\n\t\ttitle = request.args.get('title')\r\n\texcept:\r\n\t\ttitle = None\r\n\r\n\ttry:\r\n\t\tgenre = request.args.get('genre')\r\n\texcept:\r\n\t\tgenre = None\r\n\t\t\r\n\ttry:\r\n\t\tauthor = request.args.get('author')\r\n\texcept:\r\n\t\tauthor = None\r\n\r\n\tif (not (_id == None) or \r\n\t\tnot (author == None) or \r\n\t\tnot (genre == None) or \r\n\t\tnot (title == None) or \r\n\t\tnot (publisher == None)):\r\n\t\treturn_data = []\r\n\t\tfor book in books:\r\n\t\t\tif (book['_id'] == _id or\r\n\t\t\t\tbook['publisher'] == publisher or\r\n\t\t\t\tbook['title'] == title or\r\n\t\t\t\tbook['genre'] == genre or\r\n\t\t\t\tbook['author'] == author):\r\n\t\t\t\treturn_data.append(book)\r\n\t\treturn jsonify(return_data)\r\n\r\n\tif order == 'DESC':\r\n\t\tif skip == 0:\r\n\t\t\treturn_data = books[limit-1::-1]\r\n\t\telse:\r\n\t\t\treturn_data = books[limit-1:skip-1:-1]\r\n\telse:\r\n\t\treturn_data = books[skip:limit]\r\n\treturn jsonify(return_data)\r\n\r\n\r\n@app.route('/p6')\r\ndef problem6_sample():\r\n\treturn jsonify({\"status\": 400, \"message\": \"taker is undefined\"})\r\n\r\n\r\n@app.route('/p7')\r\ndef problem7_sample():\r\n\treturn jsonify({\"status\":400,\"message\":\"limit is negative\"})\r\n\r\n\r\n@app.route('/p8')\r\ndef problem8_sample():\r\n\treturn jsonify({\"status\":400,\"message\":\"number to skip cannot be negative\"})\r\n\r\n\r\n@app.route('/p9')\r\ndef problem9_sample():\r\n\treturn jsonify({\"status\":400, \"message\": \"number to skip too high\"})\r\n\r\n\r\n@app.route('/lookatconsole')\r\ndef no_more_hints():\r\n\treturn 'No more hints available, maybe...'\r\n\r\n\r\ndef checker(data, limit, skip, order, _id, author, genre, title, publisher):\r\n\t\r\n\tif limit < 0:\r\n\t\tif (data['status'] == 400 and data['message'] == 'limit is negative'):\r\n\t\t\treturn True\r\n\t\telse:\r\n\t\t\treturn False\r\n\r\n\tif skip < 0:\r\n\t\tif (data['status'] == 400 and data['message'] == 'number to skip cannot be negative'):\r\n\t\t\treturn True\r\n\t\telse:\r\n\t\t\treturn False\r\n\r\n\tif skip > len(books):\r\n\t\tif (data['status'] == 400 and data['message'] == 'number to skip too high'):\r\n\t\t\treturn True\r\n\t\telse:\r\n\t\t\treturn False\r\n\r\n\tif (not (_id == None) or \r\n\t\tnot (author == None) or \r\n\t\tnot (genre == None) or \r\n\t\tnot (title == None) or \r\n\t\tnot (publisher == None)):\r\n\t\tans = []\r\n\t\tfor book in books:\r\n\t\t\tif (book['_id'] == _id or\r\n\t\t\t\tbook['author'] == author or\r\n\t\t\t\tbook['genre'] == genre or\r\n\t\t\t\tbook['title'] == title or\r\n\t\t\t\tbook['publisher'] == publisher):\r\n\t\t\t\tans.append(book)\r\n\t\tif order == 'DESC':\r\n\t\t\tans.reverse()\r\n\telse:\r\n\t\tif order == 'ASC':\r\n\t\t\tans = books[skip:limit]\r\n\t\telif order == 'DESC':\r\n\t\t\tif skip == 0:\r\n\t\t\t\tans = books[limit-1::-1]\r\n\t\t\telse:\r\n\t\t\t\tans = books[limit-1:skip-1:-1]\r\n\t\telse:\r\n\t\t\ttry:\r\n\t\t\t\tif (data['status'] == 400 and data['message'] == order+' is undefined'):\r\n\t\t\t\t\treturn True\r\n\t\t\t\telse:\r\n\t\t\t\t\treturn False\r\n\t\t\texcept:\r\n\t\t\t\treturn False\r\n\r\n\tif not len(data) == len(ans):\r\n\t\treturn False\r\n\r\n\ttry:\r\n\t\tfor i in range(len(data)):\r\n\t\t\tif (not ans[i]['author'] \t== data[i]['author'] \tor\r\n\t\t\t\tnot ans[i]['genre'] \t== data[i]['genre'] \tor\r\n\t\t\t\tnot ans[i]['_id'] \t== data[i]['_id'] \tor\r\n\t\t\t\tnot ans[i]['publisher'] == data[i]['publisher'] or\r\n\t\t\t\tnot ans[i]['title'] \t== data[i]['title']):\r\n\t\t\t\treturn False\r\n\t\telse:\r\n\t\t\treturn True\r\n\texcept BaseException as e:\r\n\t\tprint(traceback.format_exc())\r\n\t\treturn False\r\n\r\n\r\nclass Problem:\r\n\tdef __init__(self, msg, hint_url, time, answered, skip=None, limit=None, \r\n\t\torder=None, error=None):\r\n\t\tself.msg \t\t= msg\r\n\t\tself.hint_url \t\t= hint_url\r\n\t\tself.time \t\t= time\r\n\t\tself.answered \t\t= answered\r\n\t\tself.skip \t\t= skip\r\n\t\tself.limit \t\t= limit\r\n\t\tself.order \t\t= order\r\n\t\tself.error \t\t= error\r\n\r\n\tresults = []\r\n\r\n\tdef create_problem(msg, hint_url, url, skip=0, limit=50, order='ASC', \r\n\t\tauthor=None, genre=None, _id=None, publisher=None, title=None):\r\n\t\terror = ''\r\n\t\ts = time.time()\r\n\r\n\t\ttry:\r\n\t\t\treq = requests.post('http://'+url)\r\n\t\t\tdata = json.loads(str(req.content, 'utf-8'))\r\n\r\n\t\t\tanswered = checker(data=data, limit=int(limit), skip=int(skip), order=order,\r\n\t\t\t\tauthor=author, genre=genre, _id=_id, publisher=publisher, title=title)\r\n\t\texcept BaseException as e:\r\n\t\t\terror = str(e)\r\n\t\t\tprint(traceback.format_exc())\r\n\t\t\tanswered = False\r\n\r\n\t\ttotal_time = time.time() - s\r\n\t\ttry:\r\n\t\t\tt = str(total_time)[0:5].replace('.', '')\r\n\t\texcept:\r\n\t\t\tt = str(total_time)[0:4].replace('.', '')\r\n\r\n\t\tProblem.results.append(\r\n\t\t\tProblem(msg, hint_url, t, answered, skip, limit, \r\n\t\t\torder, error).__dict__)\r\n\r\n\r\n@app.route('/', methods=['POST'])\r\ndef main_run():\r\n\tProblem.results.clear()\r\n\tload_resources()\r\n\r\n\tendpoint = request.form['endpoint_url']\r\n\tendpoint = endpoint[:-1] if endpoint.endswith('/') else endpoint\r\n\r\n\r\n\t# 0.) none specified, limit=50 skip=0\r\n\tProblem.create_problem(\r\n\t\tmsg='No limit and skip', \r\n\t\thint_url='/sample', \r\n\t\turl=endpoint)\r\n\r\n\r\n\t# 1.) 10 < limit < 80\r\n\tlimit = str(random.randint(10, 81))\r\n\tProblem.create_problem(\r\n\t\tmsg='limit='+limit, \r\n\t\thint_url='/sample?limit='+limit, \r\n\t\turl=endpoint+'?limit='+limit, limit=limit)\r\n\r\n\r\n\t# 2.) 5 < skip < 45\r\n\tskip = str(random.randint(5, 46))\r\n\tProblem.create_problem(\r\n\t\tmsg='skip='+skip, \r\n\t\thint_url='/sample?skip='+skip, \r\n\t\turl=endpoint+'?skip='+skip, skip=skip)\r\n\r\n\r\n\t# 3.) 450 < limit < 500 && 370 < skip 435\r\n\tlimit = str(random.randint(450, 501))\r\n\tskip = str(random.randint(370, 435))\r\n\tProblem.create_problem(\r\n\t\tmsg='limit='+limit+', skip='+skip, \r\n\t\thint_url='/sample?limit='+limit+'&skip='+skip, \r\n\t\turl=endpoint+'?limit='+limit+'&skip='+skip, \r\n\t\tlimit=limit, skip=skip)\r\n\r\n\r\n\t# 4.) 700 < skip < 740, limit = 800\r\n\tlimit = str(800)\r\n\tskip = str(random.randint(700, 741))\r\n\tProblem.create_problem(\r\n\t\tmsg='skip='+skip+', limit='+limit,\r\n\t\thint_url='/sample?limit='+limit+'&skip='+skip,\r\n\t\turl=endpoint+'?limit='+limit+'&skip='+skip,\r\n\t\tlimit=limit, skip=skip)\r\n\r\n\r\n\t# 5.) order = DESC, limit = 15, skip = 5\r\n\tlimit = str(random.randint(15, 26))\r\n\tskip = str(random.randint(1, 6))\r\n\torder = 'DESC'\r\n\tProblem.create_problem(\r\n\t\tmsg='limit='+limit+', skip='+skip+', order='+order, \r\n\t\thint_url='/sample?limit='+limit+'&skip='+skip+'&order='+order, \r\n\t\turl=endpoint+'?limit='+limit+'&skip='+skip+'&order='+order,\r\n\t\tlimit=limit, skip=skip, order=order)\r\n\r\n\r\n\t# 6.) order=taker\r\n\torder = 'taker'\r\n\tProblem.create_problem(\r\n\t\tmsg='order='+order, \r\n\t\thint_url='/p6', \r\n\t\turl=endpoint+'?order='+order,\r\n\t\torder=order)\r\n\r\n\r\n\t# 7.) limit = random negative number\r\n\tlimit = str(random.randint(20, 801) * -1)\r\n\tProblem.create_problem(\r\n\t\tmsg='limit='+limit,\r\n\t\thint_url='/p7',\r\n\t\turl=endpoint+'?limit='+limit,\r\n\t\tlimit=limit)\r\n\r\n\r\n\t# 8.) skip = random negative number\r\n\tskip = str(random.randint(500, 750) * -1)\r\n\tProblem.create_problem(\r\n\t\tmsg='skip='+skip,\r\n\t\thint_url='/p8',\r\n\t\turl=endpoint+'?skip='+skip,\r\n\t\tskip=skip)\r\n\r\n\r\n\t# 9.) skip > 1000\r\n\tskip = str(random.randint(1000, 5000))\r\n\tProblem.create_problem(\r\n\t\tmsg='skip='+skip,\r\n\t\thint_url='/p9',\r\n\t\turl=endpoint+'?skip='+skip,\r\n\t\tskip=skip)\r\n\r\n\r\n\t# 10.) Find id\r\n\t_id = random.randint(1000, 1800)\r\n\tProblem.create_problem(\r\n\t\tmsg='Find _id='+str(_id),\r\n\t\thint_url='/lookatconsole',\r\n\t\turl=endpoint+'?_id='+str(_id),\r\n\t\t_id=_id)\r\n\r\n\r\n\t# 11.) Find author\r\n\tauthor = authors[random.randint(0, len(authors))-1]\r\n\tProblem.create_problem(\r\n\t\tmsg='Find all author='+author,\r\n\t\thint_url='/lookatconsole',\r\n\t\turl=endpoint+'?author='+author,\r\n\t\tauthor=author)\r\n\r\n\r\n\t# 12.) Find genre\r\n\tgenre = genres[random.randint(0, len(genres))-1]\r\n\tProblem.create_problem(\r\n\t\tmsg='Find all genre='+genre,\r\n\t\thint_url='/lookatconsole',\r\n\t\turl=endpoint+'?genre='+genre,\r\n\t\tgenre=genre)\r\n\r\n\r\n\t# 13.) Find title\r\n\ttitle = titles[random.randint(0, len(titles))-1]\r\n\tProblem.create_problem(\r\n\t\tmsg='Find title='+title,\r\n\t\thint_url='/lookatconsole',\r\n\t\turl=endpoint+'?title='+title,\r\n\t\ttitle=title)\r\n\r\n\r\n\t# 14.) Find publisher\r\n\tpublisher = publishers[random.randint(0, len(publishers))-1]\r\n\tProblem.create_problem(\r\n\t\tmsg='Find all publisher='+publisher,\r\n\t\thint_url='/lookatconsole',\r\n\t\turl=endpoint+'?publisher='+publisher,\r\n\t\tpublisher=publisher)\r\n\r\n\r\n\t# 15.) Find list author and publisher\r\n\tpublisher = publishers[random.randint(0, len(publishers))-1]\r\n\tauthor = authors[random.randint(0, len(authors))-1]\r\n\tProblem.create_problem(\r\n\t\tmsg='Find all author='+author+' and publisher='+publisher,\r\n\t\thint_url='/lookatconsole',\r\n\t\turl=endpoint+'?author='+author+'&publisher='+publisher,\r\n\t\tauthor=author, publisher=publisher)\r\n\r\n\r\n\t# 16.) Find list genre and publisher DESC\r\n\tgenre = genres[random.randint(0, len(genres))-1]\r\n\tpublisher = publishers[random.randint(0, len(publishers))-1]\r\n\torder = 'DESC'\r\n\tProblem.create_problem(\r\n\t\tmsg='Find all genre='+genre+' and publisher='+publisher+' and order='+order,\r\n\t\thint_url='/lookatconsole',\r\n\t\turl=endpoint+'?genre='+genre+'&publisher='+publisher+'&order='+order,\r\n\t\tgenre=genre, publisher=publisher, order=order)\r\n\r\n\r\n\tfor i in range(15, len(Problem.results)):\r\n\t\tif Problem.results[i]['answered'] == False:\r\n\t\t\tProblem.results[i]['msg'] = '(hidden)'\r\n\r\n\treturn render_template('scoringpage.html', results=Problem.results, endpoint=endpoint)\r\n\r\n\r\nif __name__ == '__main__':\r\n\tapp.run(port=5000)\r\n","sub_path":"restapi_app.py","file_name":"restapi_app.py","file_ext":"py","file_size_in_byte":12965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"408756399","text":"import warnings\nwarnings.filterwarnings(action='ignore', category=UserWarning, module='gensim')\nfrom gensim.corpora import WikiCorpus\nimport jieba\nfrom gensim.models import word2vec\nfrom gensim import models\n\n\ndef clean_data():\n path = 'data/zhwiki-20180520-pages-articles.xml.bz2'\n print(\"start...\")\n wiki_corpus = WikiCorpus(path)\n print('wiki_corpus_done...')\n\n wiki_corpus_iter = wiki_corpus.get_texts()\n\n\n texts_num = 0\n with open('wiki_texts.txt', 'w', encoding='utf-8') as file:\n for text in wiki_corpus_iter:\n file.write(' '.join(text) + '\\n')\n # print(text)\n texts_num += 1\n\n if texts_num % 10000 == 0:\n print(texts_num, 'text done')\n\ndef cut_sentence():\n output = open('wiki_seg.txt', 'w', encoding='utf-8')\n with open('wiki_zh_tw.txt', 'r', encoding='utf-8') as content:\n for texts_num, line in enumerate(content):\n line = line.strip('\\n')\n words = jieba.cut(line, cut_all=False)\n for word in words:\n # if word not in stopword_set:\n # output.write(word + ' ')\n output.write(word + \" \")\n output.write('\\n')\n\n if (texts_num + 1) % 10000 == 0:\n # logging.info(\"已完成前 %d 行的斷詞\" % (texts_num + 1))\n print(\"done with\", texts_num)\n break\n output.close()\n\n\ndef main():\n\n #step 1. use the WikiCorpus to clean our data\n clean_data()\n \"\"\"\n step 2. use opencc traditional chinese to simplified chinese\n 1. \n \"\"\"\n #step 3. use jieba to cut sentence\n cut_sentence()\n\n\n\n\n#\n# def train():\n# sentences = word2vec.LineSentence(\"wiki_seg.txt\")\n# # for s in sentences:\n# # print(s)\n# model = word2vec.Word2Vec(sentences, size=250)\n#\n# # 保存模型,供日後使用\n# model.save(\"word2vec.model\")\n#\n# def test():\n# sentences = word2vec.LineSentence(\"wiki_seg.txt\")\n# for i, s in enumerate(sentences):\n# print(s)\n# if i == 10:\n# break\n# # logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)\n# model = models.Word2Vec.load('word2vec.model')\n#\n# print(\"提供 3 種測試模式\\n\")\n# print(\"輸入一個詞,則去尋找前一百個該詞的相似詞\")\n# print(\"輸入兩個詞,則去計算兩個詞的餘弦相似度\")\n# print(\"輸入三個詞,進行類比推理\")\n#\n# while True:\n# try:\n# query = input()\n# q_list = query.split()\n#\n# if len(q_list) == 1:\n# print(\"相似詞前 10 排序\")\n# res = model.most_similar(q_list[0], topn=10)\n# for item in res:\n# # print(item[0] + \",\" + str(item[1]))\n# print(item[0] + \",\" + str(1-item[1]))\n#\n# elif len(q_list) == 2:\n# print(\"計算 Cosine 相似度\")\n# res = model.similarity(q_list[0], q_list[1])\n# print(res)\n# else:\n# print(\"%s之於%s,如%s之於\" % (q_list[0], q_list[2], q_list[1]))\n# res = model.most_similar([q_list[0], q_list[1]], [q_list[2]], topn=100)\n# for item in res:\n# print(item[0] + \",\" + str(item[1]))\n# print(\"----------------------------\")\n# except Exception as e:\n# print(repr(e))\n#\n#\n#\n# if __name__ == \"__main__\":\n# # main()\n# # train()\n# test()\n\n","sub_path":"data_preprocess.py","file_name":"data_preprocess.py","file_ext":"py","file_size_in_byte":3553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"66184858","text":"from odps.udf import annotate\n\n\n@annotate(\"bigint,bigint->bigint\")\nclass pyudf_avt1(object):\n def evaluate(self, arg0):\n if arg0 is None or len(arg0.strip()) == 0:\n return None\n v_no_l = arg0.split('.')\n a1 = v_no_l[0]\n a2 = ('000' + v_no_l[1])[-3:]\n if len(v_no_l) == 3:\n a3 = ('000' + v_no_l[2])[-3:]\n # elif len(v_no_l) > 3:\n # 有四位版本号,第四版本号有字母\n # a4 = v_no_l[3]\n else:\n a3 = '000'\n return int('{0}{1}{2}'.format(a1, a2, a3))\n\n # input output\n # 6.14.2 6014002\n # 6.7.1 6007001\n # 10.2.1 10002001\n # 10.2.13 10002013\n # 9.2 90","sub_path":"test/pyudf_avt1.py","file_name":"pyudf_avt1.py","file_ext":"py","file_size_in_byte":748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"20030127","text":"#!/usr/bin/python\n\nfrom __future__ import division\nimport re\nimport os\nimport scipy.stats\nimport sys\n\ninput_name=sys.argv[1]\noutput_name=sys.argv[1]+\".txt\"\n\nmeta=open(output_name,'a+')\nprint(\"SNP\", \"RefAllele\", \"NonRefAllele\", \"P-value\", \"CorrelationEfficient\", \"STDERR\", \"N\", \"Probe\", sep=\" \", file=meta)\n\nfor line in open(sys.argv[1]):\n line = line.strip()\n if line.startswith('SNP'):\n pass\n else:\n ww=re.split(r'[ ]\\s*', line)\n snp=ww[0]\n p=ww[4]\n coefficient=ww[5]\n se=ww[6]\n n=ww[7]\n probe=ww[8]\n allele_1=ww[1]\n allele_2=ww[2]\n alt=ww[3]\n if allele_1==alt:\n ref=allele_2\n elif allele_2==alt:\n ref=allele_1\n print(snp, ref, alt, p, coefficient, se, n, probe, sep=\" \",file=meta)\nmeta.close()\n","sub_path":"Exome_microbiome_eqtl/tools/Change_allele.py","file_name":"Change_allele.py","file_ext":"py","file_size_in_byte":825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"357517385","text":"\"\"\"Keyring regrouping multiple keys.\"\"\"\n\n# This file is part of the 'tomate' project\n# (http://github.com/Descanonge/tomate) and subject\n# to the MIT License as defined in the file 'LICENSE',\n# at the root of this project. © 2020 Clément HAËCK\n\n\nimport logging\nfrom typing import (Any, Dict, Iterator, Iterable, List,\n Optional, Tuple, Union, TYPE_CHECKING)\n\nfrom tomate.keys.key import Key, KeyVar\n\nfrom tomate.custom_types import KeyLike\n\nif TYPE_CHECKING:\n from tomate.coordinates.coord import Coord\n from tomate.coordinates.variables import Variables\n\nlog = logging.getLogger(__name__)\n\n\nclass Keyring():\n \"\"\"Object for indexing an array.\n\n Multiple dimensions can be specified.\n\n See :doc:`../accessor` for more information.\n\n :param keys: What part of the data must be selected\n for a given dimension.\n \"\"\"\n\n @classmethod\n def get_default(cls, keyring: 'Keyring' = None,\n variables: 'Variables' = None,\n **keys: KeyLike) -> 'Keyring':\n \"\"\"Return a new keyring, eventually updated.\n\n :param keyring: Keyring to take values from.\n :param keys: Keys to add to the keyring.\n \"\"\"\n if keyring is None:\n keyring = cls()\n else:\n keyring = keyring.copy()\n keyring.update(keys)\n\n if variables is not None:\n if not variables.has_data():\n raise ValueError(\"Variables dimension is empty.\")\n keyring.make_var_idx(variables)\n\n return keyring\n\n def __init__(self, **keys: Union[Key, KeyLike]):\n self._keys = {}\n\n for name, key in keys.items():\n self[name] = key\n\n def __getitem__(self, item: str) -> Key:\n \"\"\"Return key for a dimension.\n\n :param item: Dimension name.\n \"\"\"\n try:\n return self._keys[item]\n except KeyError:\n raise KeyError(f\"'{item}' not in keyring.\")\n\n def __setitem__(self, item: str, value: Union[Key, KeyLike]):\n \"\"\"Set key value to dimension.\n\n :param item: str: Dimension name\n \"\"\"\n if not isinstance(value, Key):\n if item == 'var':\n value = KeyVar(value)\n else:\n value = Key(value)\n self._keys[item] = value\n\n def __iter__(self) -> Iterator[str]:\n \"\"\"Returns dict iterator over dimensions names.\"\"\"\n return iter(self._keys)\n\n def __len__(self) -> int:\n \"\"\"Returns number of dimensions.\"\"\"\n return len(self._keys)\n\n @property\n def dims(self) -> List[str]:\n \"\"\"List of dimensions present in the keyring.\"\"\"\n return list(self._keys.keys())\n\n @property\n def keys(self) -> List[Key]:\n \"\"\"List of keys present in the keyring.\"\"\"\n return list(self._keys.values())\n\n @property\n def keys_values(self) -> List[KeyLike]:\n \"\"\"List of keys values present in the keyring.\"\"\"\n return [k.value for k in self.keys]\n\n @property\n def kw(self) -> Dict[str, KeyLike]:\n \"\"\"Return dictionary of keys values.\"\"\"\n return dict(zip(self.dims, self.keys_values))\n\n @property\n def shape(self) -> List[int]:\n \"\"\"Return shape of all keys.\"\"\"\n return [k.shape for k in self.keys if k.shape != 0]\n\n def __bool__(self):\n \"\"\"If the keyring has keys.\"\"\"\n return len(self.dims) > 0\n\n def subset(self, dims: List[str]) -> 'Keyring':\n \"\"\"Return a subcopy of this keyring.\n\n :returns: Keyring with only specified keys.\n \"\"\"\n return Keyring(**{c: self[c] for c in dims})\n\n def items(self) -> Iterator[Tuple[str, Key]]:\n \"\"\"Iterate through dimensions and keys.\"\"\"\n return self._keys.items()\n\n def items_values(self) -> Iterator[Tuple[str, KeyLike]]:\n \"\"\"List of keys values present in the keyring.\"\"\"\n d = {name: key.value for name, key in self.items()}\n return d.items()\n\n def update(self, keys: Dict[str, Union[Key, KeyLike]]):\n \"\"\"Update keyring.\"\"\"\n for name, key in keys.items():\n self[name] = key\n\n def pop(self, dim: str) -> Key:\n \"\"\"Pop a key.\"\"\"\n return self._keys.pop(dim)\n\n def __repr__(self):\n s = []\n for c, key in self.items():\n s.append('%s: %s' % (c, str(key)))\n return str(', '.join(s))\n\n def copy(self) -> 'Keyring':\n \"\"\"Return copy of self.\"\"\"\n args = {c: k.copy() for c, k in self.items()}\n keyring = Keyring(**args)\n return keyring\n\n def set_shape(self, coords: Dict[str, 'Coord']):\n \"\"\"Set shape of keys using coordinates.\"\"\"\n for name, k in self.items():\n if name in coords:\n k.set_shape_coord(coords[name])\n\n def get_non_zeros(self) -> List[str]:\n \"\"\"Return dimensions name with a non zero shape.\n\n ie whose dimension would not be squeezed.\n \"\"\"\n return [name for name, k in self.items()\n if k.shape is None or k.shape > 0]\n\n def sort_by(self, order: List[str]):\n \"\"\"Sort keys by order.\n\n :param order: Dimensions present in the keyring.\n :raises IndexError: Order shorter then keyring, does\n not allow to sort unambiguously.\n \"\"\"\n if len(order) < len(self.keys):\n raise IndexError(\"Order given is too short.\")\n\n keys_ord = {}\n for name in order:\n keys_ord[name] = self[name]\n self._keys = keys_ord\n\n def check_unwanted(self, dims: List[str]):\n \"\"\"Check if keyring contains unwanted dimensions.\n\n :raises KeyError: Dimension is present in keyring but not `dims`.\n \"\"\"\n for c in self:\n if c not in dims:\n raise KeyError(f\"'{c}' dimension is unwanted in keyring.\")\n\n def make_full(self, dims: List[str], fill: Any = None):\n \"\"\"Add dimensions.\n\n :param dimensions: List of dimensions to add if not\n already present.\n :param fill: [opt] Value to set new keys to.\n \"\"\"\n for c in self:\n if c not in dims:\n log.warning(\"'%s' dimension in keyring is not in specified \"\n \"full list of dimensions, and might be unwanted.\", c)\n for c in dims:\n if c not in self:\n self[c] = fill\n\n def make_total(self, *dims: str):\n \"\"\"Fill missing keys by total slices.\n\n :param dims: [opt] Dimensions names to fill if missing.\n If not specified, all are selected.\n \"\"\"\n if not dims:\n dims = self.dims\n for dim, k in self.items():\n if dim in dims and k.type == 'none':\n k.set(slice(None, None))\n\n def make_single(self, *dims: str, idx: Union[Key, KeyLike] = 0):\n \"\"\"Fill missing keys by an index.\n\n :param dims: Dimensions names to fill if missing.\n If not specified, all are selected.\n :param idx: Index to set as value.\n \"\"\"\n if not dims:\n dims = self.dims\n for c, k in self.items():\n if c in dims and k.type == 'none':\n self[c] = idx\n\n def make_int_list(self, *dims: str):\n \"\"\"Turn integer values into lists.\n\n :param dims: [opt] Dimensions names to change if\n necessary. If not specified, all are\n selected.\n \"\"\"\n if not dims:\n dims = self.dims\n for c, k in self.items():\n if c in dims and k.type == 'int':\n self[c].make_int_list()\n\n def make_list_int(self, *dims: str):\n \"\"\"Turn lists of length one in integers.\n\n :param dims: Dimensions names to change if\n necessary. If not specified, all are\n selected.\n \"\"\"\n if not dims:\n dims = self.dims\n for c, k in self.items():\n if c in dims:\n k.make_list_int()\n\n def make_idx_var(self, variables: 'Variables'):\n \"\"\"Transform indices into variables names.\"\"\"\n if 'var' in self:\n self['var'].make_idx_var(variables)\n\n def make_var_idx(self, variables: 'Variables'):\n \"\"\"Transform variables names into indices.\"\"\"\n if 'var' in self:\n self['var'].make_var_idx(variables)\n\n def get_high_dim(self) -> List[str]:\n \"\"\"Returns coordinates of size higher than one.\"\"\"\n out = [c for c, k in self.items()\n if k.shape is None or k.shape > 1]\n return out\n\n def simplify(self):\n \"\"\"Simplify keys.\n\n Turn list into a slice if possible.\n \"\"\"\n for key in self.keys:\n key.simplify()\n\n def sort_keys(self, *dims: str):\n \"\"\"Sort keys.\n\n Remove redondant indices.\n Sort by indices.\n \"\"\"\n if dims is None:\n dims = self.dims\n for d in self.keys:\n d.sort()\n\n def __mul__(self, other: 'Keyring') -> 'Keyring':\n \"\"\"Subset keyring by another.\n\n If `B = A[self]`\n and `C = B[other]`\n then `C = A[self*other]`\n\n :returns: self*other\n \"\"\"\n res = Keyring()\n other_ = other.copy()\n other_.make_full(self.dims)\n other_.make_total()\n for name, key in self.items():\n res[name] = key * other_[name]\n return res\n\n def __add__(self, other: 'Keyring') -> 'Keyring':\n \"\"\"Expand keyring with another.\"\"\"\n res = self.copy()\n for d in other:\n if d in self:\n res[d] = self[d] + other[d]\n else:\n res[d] = other[d]\n return res\n\n def is_shape_equivalent(self, other: Union[Iterable[Optional[int]],\n 'Keyring']) -> bool:\n \"\"\"Compare keyrings shapes.\"\"\"\n if isinstance(other, type(self)):\n other = other.shape\n else:\n other = list(other)\n\n if len(self.shape) == len(other) == 0:\n out = True\n else:\n out = all([a is None\n or b is None\n or a == b\n for a, b in zip(self.shape, other)])\n return out\n\n def print(self) -> str:\n \"\"\"Return readable concise string representation.\"\"\"\n s = []\n for k in self.keys:\n if k.type == 'int':\n s.append(str(k.value))\n elif k.type == 'list':\n if len(k.value) <= 5:\n s.append(str(k.value))\n else:\n z = '[{}, {}, ..., {}, {}]'.format(*k.value[:2], *k.value[-2:])\n s.append(z)\n elif k.type == 'slice':\n z = []\n start, stop, step = k.value.start, k.value.stop, k.value.step\n if start is None:\n z.append('')\n else:\n z.append(str(start))\n if stop is None:\n z.append('')\n else:\n z.append(str(stop))\n if step is not None and step != 1:\n z.append(str(step))\n s.append(':'.join(z))\n return f\"[{', '.join(s)}]\"\n","sub_path":"src/tomate/keys/keyring.py","file_name":"keyring.py","file_ext":"py","file_size_in_byte":11239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"13964841","text":"import numpy as np\nimport pandas as pd\nimport math\n\ndef velocity(time_current,time_next,hit_x,hit_y,landing_x,landing_y):\n \n if type(time_current) == float:\n return('0')\n\n hhmm1 = time_current.split(':',2)\n if len(hhmm1) == 2:\n ms1 = int(hhmm1[0])*60*1000+float(hhmm1[1])*1000\n else:\n ms1 = int(hhmm1[0])*60*60*1000+int(hhmm1[1])*60*1000+float(hhmm1[2])*1000\n \n hhmm2 = time_next.split(':',2)\n if len(hhmm2) == 2:\n ms2 = int(hhmm2[0])*60*1000+float(hhmm2[1])*1000\n else:\n ms2 = int(hhmm2[0])*60*60*1000+int(hhmm2[1])*60*1000+float(hhmm2[2])*1000\n \n ms = abs(ms2-ms1)\n\n x_sqaure = pow(landing_x - hit_x,2)\n y_sqaure = pow(landing_y - hit_y,2)\n distance = pow(y_sqaure+x_sqaure,1/2)\n\n\n velocity = distance/70/1000/(ms/1000/60/60) # km/h\n\n return round(velocity,3)\n\ndef direction(diagonal_angle,hit_x,hit_y,hit_area,landing_x,landing_y,landing_area):\n\n if type(hit_area) == float:\n return('')\n if (hit_area[0] == 'C' or hit_area[0] == 'E') and \\\n (landing_area[0] == 'C' or landing_area[0] == 'E'):\n return 2\n if (landing_area[0] == 'B' or landing_area[0] == 'D') and \\\n (hit_area[0] == 'B' or hit_area[0] == 'D'):\n return 2\n if landing_y > hit_y:\n compare_y = 0\n else:\n compare_y = 935\n \n x1 = landing_x - hit_x\n x2 = 0\n y1 = landing_y - hit_y\n y2 = compare_y - hit_y\n\n dot = x1*x2+y1*y2\n distance1 = pow(x1*x1+y1*y1,1/2)\n distance2 = pow(x2*x2+y2*y2,1/2)\n\n cos_angle = abs(dot/(distance1*distance2))\n \n if cos_angle < math.cos(diagonal_angle/360*2*math.pi):\n return 2\n else:\n return 1\n\n\ndef ball_type_convertion(ball_type):\n if ball_type == '切球' or ball_type == '過渡切球':\n return 'cut'\n elif ball_type == '平球' or ball_type == '小平球' or ball_type == '後場抽平球':\n return 'drive'\n elif ball_type == '挑球' or ball_type == '防守回挑':\n return 'lob'\n elif ball_type == '長球' or ball_type == '發長球':\n return 'long'\n elif ball_type == '發小球' or ball_type == '放小球' or ball_type == '擋小球':\n return 'netplay'\n elif ball_type == '撲球':\n return 'rush'\n elif ball_type == '殺球':\n return 'smash'\n else:\n return 'error'\n\n\ndef hit_convertion_9(hit):\n if hit[0] == 'A':\n return '2',hit[1]\n elif hit[0] == 'B':\n return '3',hit[1]\n elif hit[0] == 'C':\n return '1',hit[1]\n elif hit[0] == 'D':\n return '4',hit[1]\n elif hit[0] == 'E':\n return '0',hit[1]\n else:\n return 'X'\n\ndef landing_convertion_9(landing):\n if landing[0] == 'A':\n return '2',landing[1]\n elif landing[0] == 'B':\n return '1',landing[1]\n elif landing[0] == 'C':\n return '3',landing[1]\n elif landing[0] == 'D':\n return '0',landing[1]\n elif landing[0] == 'E':\n return '4',landing[1]\n else:\n return 'X'\n \ndef hit_convertion(hit):\n if hit[0] == 'A':\n return '2',hit[1]\n elif hit[0] == 'B':\n return '3',hit[1]\n elif hit[0] == 'C':\n return '1',hit[1]\n elif hit[0] == 'D':\n return '4',hit[1]\n elif hit[0] == 'E':\n return '0',hit[1]\n elif hit[0] == 'F':\n return '5',hit[1]\n else:\n return 'X'\n\ndef landing_convertion(landing):\n if landing[0] == 'A':\n return '3',landing[1]\n elif landing[0] == 'B':\n return '2',landing[1]\n elif landing[0] == 'C':\n return '4',landing[1]\n elif landing[0] == 'D':\n return '1',landing[1]\n elif landing[0] == 'E':\n return '5',landing[1]\n elif landing[0] == 'F':\n return '0',landing[1]\n else:\n return 'X'\n\ndef map_reason(reason):\n if reason == 0:\n return '出界'\n elif reason == 1:\n return '落地'\n elif reason == 2:\n return '未回擊成功'\n else:\n return ''\ndef revese_map_reason(reason_name):\n if reason_name == '出界':\n return 0\n elif reason_name == '落地':\n return 1\n elif reason_name == '未回擊成功':\n return 2\n else:\n return ''\n\ndef another_player(player):\n if player == 'A':\n return 'B'\n elif player == 'B':\n return 'A'\n else:\n return ''\n\ndef who_first_blood(reason_name, winner):\n reason = revese_map_reason(reason_name)\n if reason == 0 or reason == 2:\n return another_player(winner)\n elif reason == 1:\n return winner","sub_path":"preprocessing/Code/test/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":4526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"532533677","text":"#!/usr/bin/env python3\nimport pickle\nimport os\nfrom google_auth_oauthlib.flow import Flow, InstalledAppFlow\nfrom googleapiclient.discovery import build\nfrom googleapiclient.http import MediaFileUpload, MediaIoBaseDownload\nfrom google.auth.transport.requests import Request\n\nimport base64\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\n\n\ndef Create_Service(client_secret_file, api_name, api_version, *scopes):\n #print(client_secret_file, api_name, api_version, scopes, sep='-')\n CLIENT_SECRET_FILE = client_secret_file\n API_SERVICE_NAME = api_name\n API_VERSION = api_version\n SCOPES = [scope for scope in scopes[0]]\n #print(SCOPES)\n\n cred = None\n\n pickle_file = f'token_{API_SERVICE_NAME}_{API_VERSION}.pickle'\n # print(pickle_file)\n\n if os.path.exists(pickle_file):\n with open(pickle_file, 'rb') as token:\n cred = pickle.load(token)\n\n if not cred or not cred.valid:\n if cred and cred.expired and cred.refresh_token:\n cred.refresh(Request())\n else:\n flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRET_FILE, SCOPES)\n cred = flow.run_local_server()\n\n with open(pickle_file, 'wb') as token:\n pickle.dump(cred, token)\n\n try:\n service = build(API_SERVICE_NAME, API_VERSION, credentials=cred)\n print(API_SERVICE_NAME, 'service created successfully')\n return service\n except Exception as e:\n print('Unable to connect.')\n print(e)\n return None\n\n\ndef convert_to_RFC_datetime(year=1900, month=1, day=1, hour=0, minute=0):\n dt = datetime.datetime(year, month, day, hour, minute, 0).isoformat() + 'Z'\n return dt\n\nCLIENT_SECRET_FILE = '/mnt/c/Users/User/credentials.json'\nAPI_NAME = 'gmail'\nAPI_VERSION = 'v1'\nSCOPES = ['https://mail.google.com/']\n\nservice = Create_Service(CLIENT_SECRET_FILE, API_NAME, API_VERSION, SCOPES)\n\nemailMsg = 'You won $100,000'\nmimeMessage = MIMEMultipart()\nmimeMessage['to'] = 'u1273400@hud.ac.uk'\nmimeMessage['subject'] = 'ESPNet'\nmimeMessage.attach(MIMEText(emailMsg, 'plain'))\nraw_string = base64.urlsafe_b64encode(mimeMessage.as_bytes()).decode()\n\nmessage = service.users().messages().send(userId='me', body={'raw': raw_string}).execute()\nprint(message)\n\n# from __future__ import print_function\n# import pickle\n# import os.path\n# from googleapiclient.discovery import build\n# from google_auth_oauthlib.flow import InstalledAppFlow\n# from google.auth.transport.requests import Request\n#\n# # If modifying these scopes, delete the file token.pickle.\n# SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']\n#\n#\n# def main():\n# \"\"\"Shows basic usage of the Gmail API.\n# Lists the user's Gmail labels.\n# \"\"\"\n# creds = None\n# # The file token.pickle stores the user's access and refresh tokens, and is\n# # created automatically when the authorization flow completes for the first\n# # time.\n# if os.path.exists('token.pickle'):\n# with open('token.pickle', 'rb') as token:\n# creds = pickle.load(token)\n# # If there are no (valid) credentials available, let the user log in.\n# if not creds or not creds.valid:\n# if creds and creds.expired and creds.refresh_token:\n# creds.refresh(Request())\n# else:\n# flow = InstalledAppFlow.from_client_secrets_file(\n# '/mnt/c/Users/User/credentials.json', SCOPES)\n# creds = flow.run_local_server(port=0)\n# # Save the credentials for the next run\n# with open('token.pickle', 'wb') as token:\n# pickle.dump(creds, token)\n#\n# service = build('gmail', 'v1', credentials=creds)\n#\n# # Call the Gmail API\n# results = service.users().labels().list(userId='me').execute()\n# labels = results.get('labels', [])\n#\n# if not labels:\n# print('No labels found.')\n# else:\n# print('Labels:')\n# for label in labels:\n# print(label['name'])\n#\n#\n# if __name__ == '__main__':\n# main()\n\n# json http post\n# body = {'channel': \"@jesusluvsu\",\n# 'username': 'espnet research',\n# 'text': 'test'\n# }\n# myurl = \"https://hooks.slack.com/services/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\"\n#\n# req = urllib.request.Request(myurl)\n# req.add_header('Content-Type', 'application/json; charset=utf-8')\n# jsondata = json.dumps(body)\n# jsondataasbytes = jsondata.encode('utf-8') # needs to be bytes\n# req.add_header('Content-Length', len(jsondataasbytes))\n# response = urllib.request.urlopen(req, jsondataasbytes)\n\n# # Import smtplib for the actual sending function\n# import smtplib\n#\n# # And imghdr to find the types of our images\n# import imghdr\n#\n# # Here are the email package modules we'll need\n# from email.message import EmailMessage\n#\n# root = 'exp/train_nodev_pytorch_train_mtlalpha1.0/'\n# pngfiles=['loss.png', 'cer.png']\n#\n# # Create the container email message.\n# msg = EmailMessage()\n# msg['Subject'] = 'ESPNET experiment'\n# # me == the sender's email address\n# # family = the list of all recipients' email addresses\n# msg['From'] = 'john.alamina@gmail.com'\n# msg['To'] = 'john.alamina@hud.ac.uk'\n# msg.preamble = 'You will not see this in a MIME-aware mail reader.\\n'\n#\n# # Open the files in binary mode. Use imghdr to figure out the\n# # MIME subtype for each specific image.\n# for file in pngfiles:\n# with open(f'{root}results/{file}', 'rb') as fp:\n# img_data = fp.read()\n# msg.add_attachment(img_data, maintype='image',\n# subtype=imghdr.what(None, img_data))\n#\n# # Send the email via our own SMTP server.\n# with smtplib.SMTP('localhost:1025') as s:\n# s.send_message(msg)\n\n# import yagmail\n# receiver = \"john.alamina@gmail.com\"\n# body = \"Hello there from Yagmail\"\n#\n# yag = yagmail.SMTP(\"john.alamina@gmail\", oauth2_file=\"/mnt/c/Users/User/credentials.json\")\n# yag.send(\n# to=receiver,\n# subject=\"Yagmail test with attachment\",\n# contents=body,\n# attachments=[f'{root}results/{file}' for file in pngfiles],\n# )\n#\n # curl = '''\n # curl -X POST --data-urlencode 'payload={\"channel\": \"@jesusluvsu\", \"username\": \"espnet research\", \"text\": \"'\"${m}\"'\"}' https://hooks.slack.com/services/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\n # '''\n # % json.dumps(x)\n # print(curl)\n\n # os.system('tail -n 2 exp/train_nodev_pytorch_train_mtlalpha1.0/train.log')\n #if c % (2 * 60) == 0:\n # os.system(\n # '''m=$(tail -n 2 exp/train_nodev_pytorch_train_mtlalpha1.0/train.log| gawk '{ gsub(/\"/,\"\\\\\\\"\") } 1');echo ${m};''' + curl)\n#\n#\n# def get_service():\n# \"\"\"Shows basic usage of the Gmail API.\n# Lists the user's Gmail labels.\n# \"\"\"\n# creds = None\n# # The file token.pickle stores the user's access and refresh tokens, and is\n# # created automatically when the authorization flow completes for the first\n# # time.\n# if os.path.exists('token.pickle'):\n# with open('token.pickle', 'rb') as token:\n# creds = pickle.load(token)\n# # If there are no (valid) credentials available, let the user log in.\n# if not creds or not creds.valid:\n# if creds and creds.expired and creds.refresh_token:\n# creds.refresh(Request())\n# else:\n# flow = InstalledAppFlow.from_client_secrets_file(\n# '/mnt/c/Users/User/credentials.json', SCOPES )\n# creds = flow.run_local_server(port=0)\n# # Save the credentials for the next run\n# with open('token.pickle', 'wb') as token:\n# pickle.dump(creds, token)\n#\n# return build('gmail', 'v1', credentials=creds)\n#\n#\n# SCOPES = ['https://www.googleapis.com/auth/gmail.send']","sub_path":"egs/an4/asr1s/local/gample.py","file_name":"gample.py","file_ext":"py","file_size_in_byte":7716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"263790710","text":"import unittest\nimport dummygraph\nfrom offsetbasedgraph import Graph, Block, Interval, Position, Translation, BlockCollection\n\n\nDEBUG = False\n\n\ndef simple_graph():\n blocks = {_id: block for _id, block in\n enumerate([10, 20, 30, 40])}\n adj_list = {0: [1], 1: [2], 2: [3], 0: [4], 4: [3]}\n return blocks, adj_list\n\n\ndef disjoint_graph():\n blocks = {_id: Block(block) for _id, block in\n enumerate([30, 40])}\n adj_list = {}\n return Graph(blocks, adj_list)\n\n\nclass TestGraph(unittest.TestCase):\n\n def assert_graph_equals(self, graph, blocks, adj_list):\n new_graph = Graph(blocks, adj_list)\n self.assertEqual(new_graph, graph)\n # self.assertEqual(graph.blocks, blocks)\n # self.assertEqual(graph.adj_list, adj_list)\n # self.assertEqual(graph.reverse_adj_list,\n # graph._get_reverse_edges(adj_list))\n\n def test_graph_equals(self):\n # Case 1\n graph1 = Graph({1: Block(10)}, {})\n graph2 = Graph({1: Block(10)}, {})\n self.assertEqual(graph1, graph2)\n\n # Case 2\n graph1 = Graph({1: Block(10), 2: Block(1)}, {})\n graph2 = Graph({1: Block(10)}, {})\n self.assertTrue(graph1 != graph2)\n\n # Case 3\n graph1 = Graph({1: Block(10), 2: Block(1)}, {1: []})\n graph2 = Graph({1: Block(10), 2: Block(1)}, {})\n self.assertEqual(graph1, graph2)\n\n # Case 4\n graph1 = Graph({1: Block(10), 2: Block(1)}, {1: [2]})\n graph2 = Graph({1: Block(10), 2: Block(1)}, {1: [2]})\n self.assertEqual(graph1, graph2)\n\n def test_init(self):\n blocks, adj_list = simple_graph()\n graph = Graph(blocks, adj_list)\n self.assert_graph_equals(graph, blocks, adj_list)\n\n def test_reverse_edges(self):\n adj_list = {1: [10, 20],\n 2: [100],\n 3: [100]}\n\n reverse_list = Graph._get_reverse_edges(adj_list)\n fasit = {10: [1], 20: [1], 100: [2, 3]}\n self.assertEqual(reverse_list, fasit)\n\n def _setup_merge(self):\n graph = disjoint_graph()\n interval_a = Interval(\n Position(0, 0),\n Position(0, 10), graph=graph)\n\n interval_b = Interval(\n Position(1, 0),\n Position(1, 10), graph=graph)\n\n return graph, interval_a, interval_b\n\n def _test_split(self):\n graph = dummygraph.get_simple_graph()\n splits = [5, 12]\n trans = graph._split_block(2, splits)\n \n # Test graph structure\n new_id = [b for b in graph.adj_list[1] if not b == 3][0]\n new_id2 = [b for b in graph.adj_list[new_id]][0]\n new_id3 = [b for b in graph.adj_list[new_id2]][0]\n\n new_blocks = {1: Block(10), new_id: Block(5),\n new_id2: Block(7), new_id3: Block(8),\n 3: Block(10), 4: Block(15)}\n\n new_adj_list = {1: [3, new_id], 3: [4],\n new_id: [new_id2],\n new_id2: [new_id3],\n new_id3: [4]}\n\n self.assert_graph_equals(graph, new_blocks, new_adj_list)\n\n # Test translation\n new_interval = Interval(Position(new_id, 0),\n Position(new_id3, 8),\n [new_id, new_id2, new_id3])\n old_intervals = [Interval(Position(2, 0), Position(2, 5)),\n Interval(Position(2, 5), Position(2, 12)),\n Interval(Position(2, 12), Position(2, 20))]\n\n true_trans = Translation(\n {2: [new_interval]},\n {_id: [interval] for _id, interval in\n zip([new_id, new_id2, new_id3], old_intervals)}\n )\n\n self.assertEqual(trans, true_trans)\n\n def _test_join(self):\n graph = dummygraph.get_mergable_graph()\n trans = graph._join_blocks([2, 3])\n\n # Test graph structure\n new_id = graph.adj_list[1][0]\n blocks = {1: Block(10), new_id: Block(20), 4: Block(15)}\n block_edges = {1: [new_id], new_id: [4]}\n self.assert_graph_equals(graph, blocks, block_edges)\n\n # Test translation\n new_interval = Interval(Position(new_id, 0),\n Position(new_id, 20))\n old_intervals = [Interval(Position(_id, 0),\n Position(_id, 20))\n for _id in (2, 3)]\n true_translation = Translation(\n {2: [new_interval],\n 3: [new_interval]},\n {new_id: old_intervals})\n\n self.assertEqual(\n true_translation,\n trans)\n\n def test_insulate_translation(self):\n graph, interval_a, interval_b = self._setup_merge()\n translation, _ = graph._get_inslulate_translation(\n [interval_a, interval_b])\n a_to_b = translation._a_to_b\n self.assertEqual(len(a_to_b), 2)\n i_first = a_to_b[0][0]\n new_ids = i_first.region_paths\n self.assertEqual(i_first, Interval(\n Position(new_ids[0], 0), Position(new_ids[1], 20)))\n i_last = a_to_b[1][0]\n new_ids = i_last.region_paths\n self.assertEqual(i_last, Interval(\n Position(new_ids[0], 0), Position(new_ids[1], 30)))\n\n def _test_insulated_translation(self):\n graph = dummygraph.get_insulated_graph()\n interval_a = Interval(Position(2, 0), Position(4, 10),\n [2, 3, 4], graph=graph)\n interval_b = Interval(Position(5, 0), Position(7, 10),\n [5, 6, 7], graph=graph)\n intervals = [interval_a, interval_b]\n trans, new_graph = graph._get_insulated_merge_transformation(intervals)\n # \n # graph, interval_a, interval_b = self._setup_merge()\n # translation, _ = graph._get_inslulate_translation(\n # [interval_a, interval_b])\n # a_to_b = translation._a_to_b\n # self.assertEqual(len(a_to_b), 2)\n # i_first = a_to_b[0][0]\n # new_ids = i_first.region_paths\n # self.assertEqual(i_first, Interval(\n # Position(new_ids[0], 0), Position(new_ids[1], 20)))\n # i_last = a_to_b[1][0]\n # new_ids = i_last.region_paths\n # self.assertEqual(i_last, Interval(\n # Position(new_ids[0], 0), Position(new_ids[1], 30)))\n\n def _test_merge_translation(self):\n # Not in use any more!\n graph, interval_a, interval_b = self._setup_merge()\n translation = graph.merge_intervals(\n interval_a,\n interval_b)\n A = 0\n B = 1\n a_first = translation._a_to_b[A][0].region_paths[0]\n a_last = translation._a_to_b[A][0].region_paths[1]\n b_first = translation._a_to_b[B][0].region_paths[0]\n b_last = translation._a_to_b[B][0].region_paths[1]\n\n # Sanity check on merge\n self.assertEqual(a_first, b_first)\n self.assertEqual(a_first.length() == interval_a.length())\n\n # Check that translation object is correct\n a_to_b = {\n A: Interval(Position(a_first, 0),\n Position(a_last, 20)),\n B: Interval(Position(b_first, 0),\n Position(b_last, 30))\n }\n b_to_a = {\n a_first: set(interval_a, interval_b),\n a_last: set(\n Interval(\n Position(A, 10),\n Position(A, 30)),\n Interval(\n Position(B, 10),\n Position(B, 40))\n )\n }\n self.assertEqual(\n Translation(a_to_b, b_to_a),\n translation)\n\n # Check graph\n blocks = {a_first: Block(10),\n a_last: Block(20),\n b_last: Block(30)\n }\n adj_list = {a_first: [a_last, b_last]}\n self.assert_graph_equals(\n graph, Graph(blocks, adj_list))\n\n def test_merge_translations2(self):\n graph = Graph({1: Block(3), 2: Block(2), 3: Block(2),\n 4: Block(3), 5: Block(1)},\n {1: [2, 5], 3: [4]} )\n #graph = Graph({1: Block(3), 2: Block(2), 3: Block(2),\n # 4: Block(3)},\n # {1: [2], 3: [4]})\n interval1 = Interval(1, 1, [1, 2], graph)\n interval2 = Interval(1, 2, [3, 4], graph)\n new_graph, trans = graph.merge([interval1, interval2])\n #print(trans)\n #print(new_graph)\n\n a = trans._a_to_b[1][0].region_paths\n b = trans._a_to_b[3][0].region_paths\n c = trans._a_to_b[2][0].region_paths\n d = trans._a_to_b[4][0].region_paths\n all_blocks = a+b+c+d+[5]\n blocks = {block_id: Block(1) for block_id in all_blocks}\n edges = {a[0]: [a[1]], b[0]: [b[1]], a[1]: [a[2]],\n a[2]: [c[0], 5], c[0]: [c[1], d[2]]}\n self.assert_graph_equals(new_graph, blocks, edges)\n\n def test_connect_positions(self):\n graph = dummygraph.get_disjoint_graph()\n pos_a = Position(1, 4)\n pos_b = Position(2, 10)\n n_g, trans = graph.connect_postitions(pos_a, pos_b)\n a, b = trans.translate(Interval(0, 10, [1])).region_paths\n c, d = trans.translate(Interval(0, 20, [2])).region_paths\n\n blocks = {a: Block(5), b: Block(5), c: Block(10), d: Block(10),\n 3: Block(30)}\n\n adj_list = {a: [b, d], c: [d]}\n t_g = Graph(blocks, adj_list)\n self.assertEqual(n_g, t_g)\n\n def _test_get_all_block_borders(self):\n blocks = {1: Block(20), 2: Block(20),\n 11: Block(20), 12: Block(20)}\n\n adj_list = {1: [2], 11: [12]}\n graph = Graph(blocks, adj_list)\n\n interval_a = Interval(Position(1, 10), Position(2, 11))\n interval_b = Interval(Position(11, 15), Position(12, 16))\n border_list = graph._get_all_block_borders(interval_a, interval_b)\n self.assertEqual(border_list, [5, 10, 21])\n\n def _test_split_blocks_at_starts_and_ends(self):\n graph = dummygraph.get_disjoint_graph()\n intervals = [Interval(Position(1, 0), Position(1, 5), graph=graph),\n Interval(Position(2, 5), Position(2, 10), graph=graph),\n Interval(Position(3, 25), Position(3, 30), graph=graph)]\n\n trans = graph._split_blocks_at_starts_and_ends(intervals)\n\n rps1 = trans.translate_rp(1).region_paths\n rps2 = trans.translate_rp(2).region_paths\n rps3 = trans.translate_rp(3).region_paths\n\n # Check that starts and ends have not been split\n self.assertEqual(len(rps1), 2)\n self.assertEqual(len(rps2), 3)\n self.assertEqual(len(rps3), 2)\n\n true_blocks = dict(zip(rps1, [Block(5), Block(5)]))\n true_blocks.update(dict(zip(rps2, [Block(5), Block(5), Block(10)])))\n true_blocks.update(dict(zip(rps3, [Block(25), Block(5)])))\n\n true_adjs = {rps1[0]: [rps1[1]],\n rps2[0]: [rps2[1]], rps2[1]: [rps2[2]],\n rps3[0]: [rps3[1]]}\n self.assert_graph_equals(graph, true_blocks, true_adjs)\n\n def test_merge_start_block(self):\n \"\"\"\n Special case where one interval starts at block\n :return:\n \"\"\"\n # Real case from grch38\n # graph = Graph({0: Block(185285), 1: Block(248956422), 2: Block(182439)}, {})\n # intervals = [Interval(Position(1, 144488705), Position(1, 144555943), [1], graph),\n # Interval(Position(0, 0), Position(0, 67238), [0], graph)]\n\n graph = Graph({0: Block(2), 1: Block(4)}, {})\n intervals = [Interval(Position(1, 1), Position(1, 2), [1], graph),\n Interval(Position(0, 0), Position(0, 1), [0], graph)]\n\n new_graph, trans = graph.merge(intervals)\n\n def test_merge_end_block(self):\n graph = Graph({0: Block(2), 1: Block(4)}, {})\n intervals = [Interval(Position(1, 1), Position(1, 2), [1], graph),\n Interval(Position(0, 1), Position(0, 2), [0], graph)]\n\n new_graph, trans = graph.merge(intervals)\n # print(\"test_merge_end_block_graph:\")\n # print(new_graph)\n # print(trans)\n\n def test_merge_two_end_block2(self):\n # print(\"test end block 2\")\n graph = Graph({8: Block(118047), 1: Block(182439), 3: Block(144488705), 12: Block(67238), 6: Block(104400479)},\n {3: [12], 12: [8, 6]})\n\n intervals = [Interval(Position(6, 117843), Position(6, 118838), [6], graph),\n Interval(Position(8, 117052), Position(8, 118047), [8], graph)]\n new_graph, trans = graph.merge(intervals)\n # print(new_graph)\n\n def test_connect_intervals(self):\n pass\n\n def test_from_file(self):\n pass\n\n def test_has_identical_structure(self):\n # Case 1\n g1 = Graph(\n {\n 1: Block(1),\n 2: Block(10)\n },\n {\n 1: [2]\n }\n )\n\n g2 = Graph(\n {\n 5: Block(10),\n 2: Block(1)\n },\n {\n 5: [2]\n }\n )\n\n self.assertTrue(g1.has_identical_structure(g2))\n\n # Case 2\n g1 = Graph(\n {\n 1: Block(1),\n 2: Block(1),\n 3: Block(1),\n 4: Block(1)\n },\n {\n 1: [2, 3],\n 3: [4],\n 2: [4]\n }\n )\n\n g2 = Graph(\n {\n 10: Block(2),\n 20: Block(2),\n 30: Block(2),\n 40: Block(2)\n },\n {\n 10: [20, 30],\n 30: [40],\n 20: [40]\n }\n )\n\n self.assertTrue(g1.has_identical_structure(g2))\n\n def test_find_critical_blocks(self):\n graph = dummygraph.get_realistic_graph()\n critical_blocks = graph.find_critical_blocks(0)\n self.assertEqual(critical_blocks, [0, 1, 5, 6])\n\n def _test_to_from_file(self):\n for graph in [dummygraph.get_simple_graph(),\n dummygraph.get_disjoint_graph()]:\n graph.to_file(\"test_graph\")\n\n graph2 = Graph.from_file(\"test_graph\")\n self.assertEqual(graph, graph2)\n\n def test_create_subgraph_from_intervals(self):\n graph = Graph(\n {\n 1: Block(10),\n 2: Block(10),\n 3: Block(10),\n 4: Block(10)\n },\n {\n 1: [2, 4],\n 2: [3],\n 4: [3]\n }\n )\n\n intervals = [\n Interval(8, 3, [1, 4, 3], graph),\n Interval(9, 5, [1, 2, 3], graph),\n ]\n print(graph.adj_list)\n subgraph, trans, start_pos = graph.create_subgraph_from_intervals(intervals, 2)\n print(subgraph.blocks)\n print(subgraph.adj_list)\n print(subgraph.reverse_adj_list)\n self.assertEqual(subgraph.blocks[subgraph.get_first_blocks()[0]].length(), 4)\n self.assertEqual(subgraph.blocks[subgraph.get_last_blocks()[0]].length(), 7)\n self.assertEqual(len(subgraph.blocks), 4)\n\n\n # Case 2\n graph = Graph(\n {\n 1: Block(10),\n 2: Block(10),\n 3: Block(10),\n 4: Block(10)\n },\n {\n 1: [2, 4],\n 2: [3],\n 4: [3]\n }\n )\n\n intervals = [\n Interval(8, 3, [1, 4], graph),\n Interval(5, 5, [1, 2], graph),\n ]\n\n subgraph, trans, start_pos = graph.create_subgraph_from_intervals(intervals, 2)\n self.assertEqual(subgraph.blocks[subgraph.get_first_blocks()[0]].length(), 7)\n self.assertEqual(subgraph.blocks[subgraph.get_last_blocks()[0]].length(), 2)\n self.assertEqual(len(subgraph.blocks), 4)\n\n\n def test_get_arbitrary_linear_graph(self):\n initial_graph = Graph(\n {\n 1: Block(10),\n 2: Block(10),\n 3: Block(10),\n 4: Block(10)\n },\n {\n 1: [2, 4],\n 2: [3],\n 4: [3]\n }\n )\n\n graph, trans = initial_graph.get_arbitrary_linear_graph()\n\n self.assertTrue(len(graph.blocks) == 1)\n self.assertTrue(len(graph.adj_list) == 0)\n self.assertTrue(list(graph.blocks.values())[0].length() == 30)\n\n # Case 2\n initial_graph = Graph(\n {\n 1: Block(10),\n 2: Block(10),\n 3: Block(10),\n 4: Block(10),\n 5: Block(10),\n 6: Block(5)\n },\n {\n 1: [2, 4],\n 2: [3],\n 4: [3],\n 5: [6]\n }\n )\n\n\n graph, trans = initial_graph.get_arbitrary_linear_graph()\n\n self.assertTrue(len(graph.blocks) == 2)\n self.assertTrue(len(graph.adj_list) == 0)\n sum_length = sum([b.length ()for b in graph.blocks.values()])\n self.assertEqual(sum_length, 45)\n\n def test_block_collection(self):\n blocks = BlockCollection({1: Block(10), 2: Block(12)})\n\n self.assertTrue(1 in blocks)\n self.assertTrue(2 in blocks)\n self.assertTrue(3 not in blocks)\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"tests/testGraph.py","file_name":"testGraph.py","file_ext":"py","file_size_in_byte":17492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"629558807","text":"#!/usr/bin/env python\n\n\"\"\"\nRegistration algorithms and utility functions\n\"\"\"\n\nfrom __future__ import print_function\nfrom pcl.boundaries import estimate_boundaries\nimport numpy as np\nimport logging\nfrom patty import conversions\nfrom patty.conversions import copy_registration, extract_mask\nfrom sklearn.decomposition import PCA\nfrom patty.segmentation import dbscan\nfrom matplotlib import path\nfrom patty.utils import BoundingBox\n\nlogging.basicConfig(level=logging.INFO)\n\ndef length_3d(pointcloud):\n xyz_array = np.asarray(pointcloud)\n return xyz_array.max(axis=0) - xyz_array.min(axis=0)\n\ndef downsample_voxel(pointcloud, voxel_size=0.01):\n ''' Downsample a pointcloud using a voxel grid filter.\n Arguments:\n pointcloud Original pointcloud\n voxel_size Grid spacing for the voxel grid\n Returns:\n filtered_pointcloud\n '''\n old_len = len(pointcloud)\n pc_filter = pointcloud.make_voxel_grid_filter()\n pc_filter.set_leaf_size(voxel_size, voxel_size, voxel_size)\n filtered_pointcloud = pc_filter.filter()\n new_len = len(filtered_pointcloud)\n decrease_percent = (old_len - new_len)*100 / old_len\n logging.info(\"number of points reduced from\", old_len, \"to\", new_len, \"(\", decrease_percent, \"pct. decrease)\")\n return filtered_pointcloud\n\ndef register_offset_scale_from_ref(pc, ref_array, ref_offset=np.zeros(3)):\n ''' Returns a 3d-offset and uniform scale value from footprint.\n The scale is immediately applied to the pointcloud, the offset is\n set to the patty_registration.conversions.RegisteredPointCloud'''\n ref_min = ref_array.min(axis=0)\n ref_max = ref_array.max(axis=0)\n ref_center = (ref_min + ref_max) / 2.0 + ref_offset\n\n pc_array = np.asarray(pc)\n pc_min = pc_array.min(axis=0)\n pc_max = pc_array.max(axis=0)\n \n pc_size = pc_max - pc_min\n ref_size = ref_max - ref_min\n \n # Take the footprint as the real offset, and correct the z-offset\n # The z-offset of the footprint will be ground level, the z-offset of the\n # pointcloud will include the monuments height\n pc_registration_scale = np.mean(ref_size[0:1]/pc_size[0:1])\n\n pc_array *= pc_registration_scale\n pc_min *= pc_registration_scale\n pc_max *= pc_registration_scale\n \n conversions.register(pc, offset=ref_center - (pc_min + pc_max) / 2.0, precision=pc.precision * pc_registration_scale)\n\n return pc.offset, pc_registration_scale\n\ndef get_pointcloud_boundaries(pointcloud, angle_threshold=0.1, search_radius=0.02, normal_search_radius=0.02):\n '''Find the boundary of a pointcloud.\n Arguments:\n pointcloud Input pointcloud\n angle_threshold=0.1 \n search_radius=0.02\n normal_radius=0.02\n Returns:\n a pointcloud\n '''\n boundary = estimate_boundaries(pointcloud, angle_threshold=angle_threshold, search_radius=search_radius, normal_search_radius=normal_search_radius)\n logging.info(\"sum\",np.sum(boundary))\n logging.info(\"len\",len(boundary))\n return extract_mask(pointcloud, boundary)\n\ndef principal_axes_rotation(data):\n '''Find the 3 princial axis of the pointcloud, and the rotation to align it to the x,y, and z axis.\n\n Arguments:\n data pointcloud\n Returns:\n transformation matrix\n '''\n pca = PCA(n_components=data.shape[1])\n pca.fit(data)\n transform = np.zeros((4,4))\n transform[:3,:3] = np.array(pca.components_)\n transform[3,3] = 1.0\n \n return np.matrix(transform)\n\ndef register_from_footprint(pc, footprint):\n '''Register a pointcloud by placing it in footprint. Applies dbscan first.\n Arguments:\n pc pointcloud\n footprint array of [x,y,z] describing the footprint\n Returns:\n the original pointcloud, but rotated/translated to the footprint\n '''\n logging.info(\"Finding largest cluster\")\n pc_main = dbscan.largest_dbscan_cluster(pc, .1, 250)\n \n logging.info(\"Detecting boundary\")\n boundary = get_pointcloud_boundaries(pc_main)\n \n logging.info(\"Finding rotation\")\n pc_transform = principal_axes_rotation(np.asarray(boundary))\n fp_transform = principal_axes_rotation(footprint)\n transform = np.linalg.inv(fp_transform) * pc_transform\n boundary.transform(transform)\n\n logging.info(\"Registering pointcloud to footprint\")\n registered_offset, registered_scale = register_offset_scale_from_ref(boundary, footprint)\n copy_registration(pc, boundary)\n \n # rotate and scale up\n transform[:3,:3] *= registered_scale\n pc.transform(transform)\n \n return pc\n\ndef register_from_reference(pc, pc_ref):\n '''Register a pointcloud by aligning it with a reference pointcloud. Applies dbscan first.\n Arguments:\n pc pointcloud\n footprint array of [x,y,z] describing the footprint\n Returns:\n the original pointcloud, but rotated/translated to the footprint\n '''\n logging.info(\"Finding largest cluster\")\n pc_main = dbscan.largest_dbscan_cluster(pc, .1, 250)\n \n logging.info(\"Finding rotation\")\n pc_transform = principal_axes_rotation(np.asarray(pc_main))\n ref_transform = principal_axes_rotation(np.asarray(pc_ref))\n transform = np.linalg.inv(ref_transform) * pc_transform\n pc_main.transform(transform)\n\n logging.info(\"Registering pointcloud to footprint\")\n registered_offset, registered_scale = register_offset_scale_from_ref(pc_main, np.asarray(pc_ref), pc_ref.offset)\n copy_registration(pc, pc_main)\n \n # rotate and scale up\n transform[:3,:3] *= registered_scale\n pc.transform(transform)\n \n return pc\n\ndef point_in_convex_polygon(points, polygon):\n ''' WARNING: Only works for convex polygons '''\n mask = np.ones(len(points),dtype=np.bool)\n for i in xrange(len(polygon)):\n v1 = polygon[i - 1] - polygon[i]\n v2 = points - polygon[i - 1]\n \n is_left = v1[0]*v2[:,1] - v1[1]*v2[:,0] >= 0\n mask = mask & is_left\n \n return mask\n\ndef point_in_polygon2d(points, polygon):\n p = path.Path(np.asarray(polygon)[:,:2])\n return np.array( [p.contains_point(point[:2]) for point in points], dtype=np.bool ) \n\ndef intersect_polgyon2d(pc, polygon):\n in_polygon = point_in_polygon2d(np.asarray(pc) + pc.offset, polygon)\n return extract_mask(pc, in_polygon)\n\ndef scale_points(polygon, factor):\n polygon = np.asarray(polygon,dtype=np.float64)\n offset = (polygon.max(axis=0) + polygon.min(axis=0)) / 2.0\n return ((polygon - offset) * factor) + offset\n\ndef center_boundingbox(pointcloud):\n conversions.register(pointcloud)\n pc_array = np.asarray(pointcloud)\n bb = BoundingBox(points=pc_array)\n pc_array -= bb.center\n pointcloud.offset += bb.center\n","sub_path":"patty/registration/registration.py","file_name":"registration.py","file_ext":"py","file_size_in_byte":6713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"322212222","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path(\"patrolman/\", views.output_patrolman, name='output_patrolman'),\n path(\"\", views.output_patrol_result, name='output_patrol_result'),\n path(\"createPatrol/\", views.create_patrol, name='create_patrol'),\n path(\"createWaterArea/\", views.createWaterArea, name='createWaterArea'),\n path(\"profile/\", views.output_profile, name='output_profile'),\n path(\"editprofile/\", views.editPatrolman, name='editprofile'),\n]","sub_path":"students/y2335/laboratory_works/Zhilina_Veronika/Final_work/see_police/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"168142449","text":"'''\n다음의 결과와 같이 이름과 나이를 입력 받아\n\n올해를 기준으로 100세가 되는 해를 표시하는 코드를 작성하십시오.\n'''\n\nname_input = input()\nage_input = int(input())\n\ndef when_be_100(name,age):\n this_year = 2018\n last_year = this_year + 100 - age\n print(\"%s(은)는 %d년에 100세가 될 것입니다.\" % (name,last_year))\n\nwhen_be_100(name_input,age_input)","sub_path":"PYTHON/파이썬_프로그래밍_기초_문제풀이/09/09-01.py","file_name":"09-01.py","file_ext":"py","file_size_in_byte":408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"144242448","text":"from organism import *\r\nimport pygame\r\n\r\nclass Human(Animal):\r\n __clock = 0\r\n\r\n def __init__(self, world, x, y):\r\n self.setStrength(5)\r\n self.setInitiative(4)\r\n self.img = pygame.image.load_basic('images/Human.bmp')\r\n self.setID(10)\r\n super(Human, self).__init__(world, x, y)\r\n\r\n def action(self):\r\n\r\n dir = self.world.humanMove\r\n nextX = self._x + dir[1]\r\n nextY = self._y + dir[0]\r\n if nextX >= 0 and nextY >= 0 and nextX < self.size[0] and nextY < self.size[1]:\r\n if self.world.tab[nextX][nextY] == None:\r\n self.world.tab[self._x][self._y] = None\r\n self.world.tab[nextX][nextY] = self\r\n self._x = nextX\r\n self._y = nextY\r\n else:\r\n self.world.tab[nextX][nextY].collision(self)\r\n\r\n @staticmethod\r\n def clock():\r\n if Human.__clock == 0:\r\n Human.__clock = 9\r\n\r\n @staticmethod\r\n def isActivePower():\r\n if Human.__clock > 4:\r\n return True\r\n else:\r\n return False\r\n\r\n @staticmethod\r\n def clockRound():\r\n if Human.__clock > 0:\r\n Human.__clock -= 1\r\n","sub_path":"Swiat/Human.py","file_name":"Human.py","file_ext":"py","file_size_in_byte":1202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"200789332","text":"import os\nimport sys\nimport logging\nlogging.basicConfig(level=logging.INFO)\n\nfrom telegram.ext import Updater, CommandHandler, MessageHandler, Filters\n\nimport app.basic as basic\nfrom app.poll import poll_handler\n\nupdater = None\n\n\ndef main():\n global updater\n\n token = os.environ[\"TELEGRAM\"]\n updater = Updater(token)\n\n dp = updater.dispatcher\n \n dp.add_handler(CommandHandler(\"start\", basic.start))\n dp.add_handler(CommandHandler(\"help\", basic.help_handler))\n\n dp.add_handler(poll_handler)\n dp.add_handler(MessageHandler(Filters.text, basic.msg_parser))\n\n\n dp.add_error_handler(basic.error)\n\n if len(sys.argv) > 1:\n if sys.argv[1] == \"local\":\n updater.start_polling()\n else:\n updater.start_webhook(listen=\"0.0.0.0\",\n port=int(os.environ[\"PORT\"]),\n url_path=token)\n updater.bot.set_webhook(\"https://telegram-mg-bot.herokuapp.com/\" + token)\n\n\n updater.idle()\n\n\nif __name__ == '__main__':\n main()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"377970368","text":"# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom tempest.api.aflo import base\nfrom tempest import config_aflo as config # noqa\nfrom tempest.lib import exceptions\n\nCONF = config.CONF\n\n\nclass GoodsAdminTest(base.BaseV1AfloAdminTest):\n \"\"\"Aflo Test Class by admin.\"\"\"\n\n @classmethod\n def resource_setup(cls):\n \"\"\"Setup Resources.\"\"\"\n super(GoodsAdminTest, cls).resource_setup()\n\n def test_goods(self):\n \"\"\"Test of \"Data Between Created to Deleted\".\"\"\"\n\n # create data\n field = {'goods_name': 'test_goods'}\n req, body = self.aflo_client.create_goods(field)\n\n goods_id = body['goods_id']\n\n self.assertTrue(goods_id is not None)\n\n try:\n\n # Get record\n resp, body = self.aflo_client.get_goods(goods_id)\n\n self.assertEqual(body['goods_id'], goods_id)\n self.assertEqual(body['goods_name'], 'test_goods')\n\n # Update record\n field = {'goods_name': 'test_goods_test'}\n req, body = self.aflo_client.update_goods(goods_id, field)\n\n print(body)\n self.assertEqual(body['goods_name'], 'test_goods_test')\n\n # Get record\n resp, body = self.aflo_client.get_goods(goods_id)\n self.assertEqual(body['goods_name'], 'test_goods_test')\n\n except Exception:\n if goods_id:\n self.aflo_client.delete_goods(goods_id)\n\n else:\n # Delete record\n self.aflo_client.delete_goods(goods_id)\n self.assertRaises(exceptions.NotFound,\n self.aflo_client.get_goods, goods_id)\n\n def test_get_goods_no_result(self):\n \"\"\"Test 'List search of goods.'\n Test of if you filtering irregular ticket type.\n \"\"\"\n resp, body = self.aflo_client.list_goods(\n \"region_id=samplexx-3e13-4284-a2f7-05b1b71ef40a\")\n\n self.assertTrue(len(body) == 0)\n","sub_path":"contrib/tempest/tempest/api/aflo/test_goods.py","file_name":"test_goods.py","file_ext":"py","file_size_in_byte":2453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"388657782","text":"import typing\nfrom json import dumps as json_dumps\nfrom urllib.parse import urlencode\n\nfrom .multipart import multipart_encode\n\nRequestData = typing.Union[dict, str, bytes, typing.AsyncIterator[bytes]]\n\nRequestFiles = typing.Dict[\n str,\n typing.Union[\n # file (or str)\n typing.Union[typing.IO[typing.AnyStr], typing.AnyStr],\n # (filename, file (or str))\n typing.Tuple[\n typing.Optional[str], typing.Union[typing.IO[typing.AnyStr], typing.AnyStr],\n ],\n # (filename, file (or str), content_type)\n typing.Tuple[\n typing.Optional[str],\n typing.Union[typing.IO[typing.AnyStr], typing.AnyStr],\n typing.Optional[str],\n ],\n ],\n]\n\n\nclass RequestContent:\n \"\"\"\n Base class for request content.\n Defaults to a \"no request body\" implementation.\n \"\"\"\n\n def get_headers(self) -> typing.Dict[str, str]:\n \"\"\"\n Return a dictionary of request headers that are implied by the encoding.\n \"\"\"\n return {}\n\n def can_replay(self) -> bool:\n \"\"\"\n Return `True` if `__aiter__` can be called multiple times.\n\n We need this in order to determine if we can re-issue a request body\n when we receive a redirect response.\n \"\"\"\n return True\n\n async def __aiter__(self) -> typing.AsyncIterator[bytes]:\n yield b\"\"\n\n async def aread(self) -> bytes:\n return b\"\".join([part async for part in self])\n\n\nclass BytesRequestContent(RequestContent):\n \"\"\"\n Request content encoded as plain bytes.\n \"\"\"\n\n def __init__(self, body: typing.Union[str, bytes]) -> None:\n self.body = body.encode(\"utf-8\") if isinstance(body, str) else body\n\n def get_headers(self) -> typing.Dict[str, str]:\n content_length = str(len(self.body))\n return {\"Content-Length\": content_length}\n\n async def __aiter__(self) -> typing.AsyncIterator[bytes]:\n yield self.body\n\n\nclass StreamingRequestContent(RequestContent):\n \"\"\"\n Request content encoded as plain bytes, using an async byte iterator.\n \"\"\"\n\n def __init__(self, aiterator: typing.AsyncIterator[bytes]) -> None:\n self.aiterator = aiterator\n\n def can_replay(self) -> bool:\n return False\n\n def get_headers(self) -> typing.Dict[str, str]:\n return {\"Transfer-Encoding\": \"chunked\"}\n\n async def __aiter__(self) -> typing.AsyncIterator[bytes]:\n async for part in self.aiterator:\n yield part\n\n\nclass JSONRequestContent(RequestContent):\n \"\"\"\n Request content encoded as JSON.\n \"\"\"\n\n def __init__(self, json: typing.Any) -> None:\n self.body = json_dumps(json).encode(\"utf-8\")\n\n def get_headers(self) -> typing.Dict[str, str]:\n content_length = str(len(self.body))\n content_type = \"application/json\"\n return {\"Content-Length\": content_length, \"Content-Type\": content_type}\n\n async def __aiter__(self) -> typing.AsyncIterator[bytes]:\n yield self.body\n\n\nclass URLEncodedRequestContent(RequestContent):\n \"\"\"\n Request content as URL encoded form data.\n \"\"\"\n\n def __init__(self, data: dict) -> None:\n self.body = urlencode(data, doseq=True).encode(\"utf-8\")\n\n def get_headers(self) -> typing.Dict[str, str]:\n content_length = str(len(self.body))\n content_type = \"application/x-www-form-urlencoded\"\n return {\"Content-Length\": content_length, \"Content-Type\": content_type}\n\n async def __aiter__(self) -> typing.AsyncIterator[bytes]:\n yield self.body\n\n\nclass MultipartRequestContent(RequestContent):\n \"\"\"\n Request content as multipart encoded form data.\n \"\"\"\n\n def __init__(self, data: dict, files: dict, boundary: bytes = None) -> None:\n self.body, self.content_type = multipart_encode(data, files, boundary)\n\n def get_headers(self) -> typing.Dict[str, str]:\n content_length = str(len(self.body))\n content_type = self.content_type\n return {\"Content-Length\": content_length, \"Content-Type\": content_type}\n\n async def __aiter__(self) -> typing.AsyncIterator[bytes]:\n yield self.body\n\n\ndef encode(\n data: RequestData = None,\n files: RequestFiles = None,\n json: typing.Any = None,\n boundary: bytes = None,\n) -> RequestContent:\n \"\"\"\n Handles encoding the given `data`, `files`, and `json`, returning\n a `RequestContent` implementation which provides a byte iterator onto\n the content, as well as `.is_rewindable()` and `.get_headers()` interfaces.\n\n The `boundary` argument is also included for reproducible test cases\n when working with multipart data.\n \"\"\"\n if data is None:\n if json is not None:\n return JSONRequestContent(json)\n elif files:\n return MultipartRequestContent({}, files, boundary=boundary)\n else:\n return RequestContent()\n elif isinstance(data, dict):\n if files is not None:\n return MultipartRequestContent(data, files, boundary=boundary)\n else:\n return URLEncodedRequestContent(data)\n elif isinstance(data, (str, bytes)):\n return BytesRequestContent(data)\n else:\n return StreamingRequestContent(data)\n","sub_path":"Entorno_STS_COMAP_CONTROL/Lib/site-packages/httpx/content.py","file_name":"content.py","file_ext":"py","file_size_in_byte":5208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"627688764","text":"#Author: Lzj\n#mail: harry_lee2683@outlook.com\nrent = 3000\n\ndef cost():\n utilities = int(input('请输入本月的水电费用'))\n food_cost = int(input('请输入本月的食材费用'))\n global variable_cost\n variable_cost = utilities + food_cost\n print('本月的变动成本费用是' + str(variable_cost))\n\ndef sum_cost():\n sum = rent + variable_cost\n print('本月的总成本是' + str(sum))\n\ncost()\nsum_cost()\ndef egg():\n global quantity\n quantity = 108\n\negg()\nprint(quantity)","sub_path":"Linux-Oldboy-practical/L4-Python/realproject/day6/f12.py","file_name":"f12.py","file_ext":"py","file_size_in_byte":510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"101126295","text":"import sys\nsys.path.append(\"..\")\nimport numpy as np\nimport sklearn.linear_model\n# import tick.hawkes as th\nimport copy\nfrom base import kernels\nimport quadprog\n\ndef fit(time_feature_list, T = 'None', beta = 1, kernel = 'exp', NonNeg = False):\n global dimensionality\n dimensionality = np.unique(time_feature_list['1dimension']).__len__()\n global f_dim\n f_dim = time_feature_list.shape[1] - 3\n time_list = []\n for i in np.arange(dimensionality):\n time_list.append(list(time_feature_list[time_feature_list['1dimension'] == i]['2timestamp']))\n\n def exp_lasting_time(time_list, T='None', beta=1, kernel='exp'):\n output = copy.deepcopy(time_list)\n if T == 'None':\n T = np.max(time_list)\n elif type(T) not in [int, float]:\n raise ValueError('T should be a number.')\n\n if kernel == 'exp':\n for seq in np.arange(time_list.__len__()):\n for timestamp in np.arange(time_list[seq].__len__()):\n output[seq][timestamp] = kernels.KernelExp((T - time_list[seq][timestamp]), beta) / beta\n return output\n\n def z_function(time_list, T='None', beta=1, kernel='exp'):\n exp_lasting_time_matrix = exp_lasting_time(time_list, T)\n dimensionality = time_list.__len__()\n output = np.zeros((dimensionality + 1, dimensionality + 1))\n\n if T == 'None':\n T = np.max(time_list)\n elif type(T) not in [int, float, np.ndarray, np.float64]:\n raise ValueError('T should be a number.')\n\n output[0, 0] = T\n for i in np.arange(dimensionality):\n for k in np.arange(exp_lasting_time_matrix[i].__len__()):\n output[0, i + 1] += (1. - exp_lasting_time_matrix[i][k])\n output[i + 1, 0] += (1. - exp_lasting_time_matrix[i][k])\n\n for i in np.arange(dimensionality):\n for j in np.arange(dimensionality):\n for k in np.arange(exp_lasting_time_matrix[i].__len__()):\n for k_prime in np.arange(exp_lasting_time_matrix[j].__len__()):\n lower_bound = np.abs(time_list[i][k] - time_list[j][k_prime])\n output[i + 1, j + 1] += beta * (np.exp(-beta * lower_bound) - exp_lasting_time_matrix[i][k] *\n exp_lasting_time_matrix[j][k_prime]) / 2.\n return output\n\n def y_function(time_list, T='None', beta=1, kernel='exp'):\n dimensionality = time_list.__len__()\n output = np.zeros((dimensionality + 1, dimensionality))\n\n for i in np.arange(dimensionality):\n # output[0, i] = np.sum(time_list[i])\n output[0, i] = time_list[i].__len__()\n for i in np.arange(dimensionality):\n for j in np.arange(dimensionality):\n for k in np.arange(time_list[i].__len__()):\n k_prime_length = sum([t_k > time_list[i][k] for t_k in time_list[j]])\n for k_prime in np.arange(k_prime_length) + (time_list[j].__len__() - k_prime_length):\n output[i + 1, j] += kernels.KernelExp(time_list[j][k_prime] - time_list[i][k])\n return output\n\n z_mat = z_function(time_list, T, beta, kernel)\n y_mat = y_function(time_list, T, beta, kernel)\n dimensiodnality = time_list.__len__()\n \n if NonNeg == False:\n try:\n out_mat = np.linalg.solve(z_mat, y_mat)\n except:\n out_mat = np.linalg.solve(z_mat+0.0001 * np.identity(z_mat.shape[0]), y_mat)\n return out_mat[0, :],out_mat[1:, :].T\n \n elif NonNeg == True:\n G = -np.identity(dimensiodnality+1)\n h = np.zeros(dimensiodnality+1)\n out_mat = np.zeros((dimensiodnality+1, dimensiodnality))\n \n for i in np.arange(dimensiodnality):\n sol = quadprog.solve_qp(z_mat, y_mat[:, i], -G, -h)\n # out_mat[:, i] = sol[0].reshape((1, dimensiodnality + 1))[0]\n out_mat[:, i] = sol[0]\n return out_mat[0, :], out_mat[1:, :].T\n else:\n raise ValueError('\\'NonNeg\\' is a boolean parameter')","sub_path":"learning/hp_estimate_ls.py","file_name":"hp_estimate_ls.py","file_ext":"py","file_size_in_byte":4103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"135274834","text":"import argparse, pickle, io\n\nfrom urllib import request\nfrom PIL import Image\n\nparser = argparse.ArgumentParser(description=\"Process parameters.\")\nparser.add_argument(\"--img_list\", nargs=1)\nparser.add_argument(\"--image_nr\", nargs=1)\nparser.add_argument(\"--path\", nargs=1)\na = parser.parse_args()\n\nwith open(a.img_list[0], 'rb') as fp:\n image_list = pickle.load(fp)\n\nimage_data = request.urlopen(image_list[int(a.image_nr[0])]).read()\n\ntpl_image = Image.open(io.BytesIO(image_data))\ntpl_image.save(a.path[0])\n","sub_path":"scripts/download_image.py","file_name":"download_image.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"627237078","text":"import os\nimport math\nimport time\nimport torch\nimport numpy as np\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport matplotlib.pyplot as plt\nfrom torchvision.ops import nms\nfrom PIL import Image,ImageDraw,ImageFont\n\ndef decodebox(regression,anchors,img):\n dtype = regression.dtype\n anchors = anchors.to(dtype)\n # 计算先验框的中心\n y_centers_a = (anchors[...,0] + anchors[...,2])/2\n x_centers_a = (anchors[..., 1] + anchors[..., 3]) / 2\n # 计算先验框的宽高\n ha = anchors[..., 2] - anchors[..., 0]\n wa = anchors[..., 3] - anchors[..., 1]\n\n # 计算调整后先验框的宽高 编码过程的反过程\n # 即计算预测框的宽高\n w = regression[...,3].exp() * wa\n h = regression[..., 2].exp() * ha\n # 计算调整后先验框的中心\n # 即计算预测框的中心\n y_centers = regression[...,0] * ha + y_centers_a\n x_centers = regression[...,1] * wa + x_centers_a\n\n # 预测框的左上角 右下角\n ymin = y_centers - h / 2.\n xmin = x_centers - w / 2.\n ymax = y_centers + h / 2.\n xmax = x_centers + w / 2.\n\n boxes = torch.stack([xmin,ymin,xmax,ymax],dim=2)\n\n _,_,height,width = np.shape(img)\n\n boxes[:, :, 0] = torch.clamp(boxes[:, :, 0], min=0)\n boxes[:, :, 1] = torch.clamp(boxes[:, :, 1], min=0)\n\n boxes[:, :, 2] = torch.clamp(boxes[:, :, 2], max=width - 1)\n boxes[:, :, 3] = torch.clamp(boxes[:, :, 3], max=height - 1)\n\n return boxes\n\ndef letterbox_image(image,size): # 填充灰边\n iw,ih = image.size\n w,h = size\n scale = min(w/iw,h/ih)\n nw = int(iw*scale)\n nh = int(ih*scale)\n\n image = image.resize((nw,nh),Image.BICUBIC)\n new_image = Image.new('RGB',size,(128,128,128))\n new_image.paste(image,((w-nw)//2,(h-nh)//2))\n return new_image\n\n\n# 调整框 调整框到原始图片大小 \ndef efficientdet_correct_boxes(top,left,bottom,right,input_shape,image_shape):\n new_shape = image_shape * np.min(input_shape/image_shape)\n offset = (input_shape - new_shape)/2./input_shape\n scale = input_shape/new_shape\n\n box_yx = np.concatenate(((top+bottom)/2,(left+right)/2),axis=-1)/input_shape\n box_hw = np.concatenate((bottom-top,right-left),axis=-1)/input_shape\n box_yx = (box_yx - offset) * scale\n box_hw *= scale\n\n box_mins = box_yx - (box_hw / 2.)\n box_maxes = box_yx + (box_hw / 2.)\n boxes = np.concatenate([\n box_mins[:, 0:1],\n box_mins[:, 1:2],\n box_maxes[:, 0:1],\n box_maxes[:, 1:2]\n ],axis=-1)\n\n boxes *= np.concatenate([image_shape,image_shape],axis=1)\n return boxes\n\ndef bbox_iou(box1,box2,x1y1x2y2=True):\n if not x1y1x2y2:\n b1_x1, b1_x2 = box1[:, 0] - box1[:, 2] / 2, box1[:, 0] + box1[:, 2] / 2\n b1_y1, b1_y2 = box1[:, 1] - box1[:, 3] / 2, box1[:, 1] + box1[:, 3] / 2\n b2_x1, b2_x2 = box2[:, 0] - box2[:, 2] / 2, box2[:, 0] + box2[:, 2] / 2\n b2_y1, b2_y2 = box2[:, 1] - box2[:, 3] / 2, box2[:, 1] + box2[:, 3] / 2\n else:\n b1_x1, b1_y1, b1_x2, b1_y2 = box1[:, 0], box1[:, 1], box1[:, 2], box1[:, 3]\n b2_x1, b2_y1, b2_x2, b2_y2 = box2[:, 0], box2[:, 1], box2[:, 2], box2[:, 3]\n \n inter_rec_x1 = torch.max(b1_x1,b2_x1)\n inter_rect_y1 = torch.max(b1_y1, b2_y1)\n inter_rect_x2 = torch.min(b1_x2, b2_x2)\n inter_rect_y2 = torch.min(b1_y2, b2_y2)\n\n inter_area = torch.clamp(inter_rect_x2-inter_rec_x1 + 1 ,min=0) * torch.clamp(inter_rect_y2 - inter_rect_y1 + 1, min=0)\n b1_area = (b1_x2-b1_x1+1) * (b1_y2-b1_y1+1)\n b2_area = (b2_x2 - b2_x1 + 1) * (b2_y2 - b2_y1 + 1)\n iou = inter_area/(b1_area + b2_area - inter_area + 1e-6)\n return iou\n\ndef non_max_suppression(prediction,num_classes,conf_thres=0.5,nums_thres=0.4):\n output = [None for _ in range(len(prediction))]\n for image_i ,image_pred in enumerate(prediction):\n # 获得种类及其置信度\n class_conf,class_pred = torch.max(image_pred[:,4:],1,keepdim=True)\n # 利用置信度进行第一轮筛选\n conf_mask = (class_conf>=conf_thres).squeeze()\n image_pred = image_pred[conf_mask]\n class_conf,class_pred = class_conf[conf_mask],class_pred[conf_mask]\n if not image_pred.size(0):\n continue\n # 获得的内容为(x1, y1, x2, y2, class_conf, class_pred)\n detections = torch.cat((image_pred[:,:4],class_conf.float,class_pred.float()),1)\n # 获得种类\n unique_labels = detections[:,-1].cpu().unique()\n if prediction.is_cuda:\n unique_labels = unique_labels.cuda()\n for c in unique_labels:\n # 获得某一类初步筛选后全部的预测结果\n detections_class = detections[detections[:,-1]==c]\n keep = nms(\n detections_class[:,:4],\n detections_class[:,4],\n nums_thres\n )\n max_detections = detections_class[keep]\n\n # 结果堆叠 单张图单个种类 有几个\n output[image_i] = max_detections if output[image_i] is None else torch.cat(\n (output[image_i], max_detections))\n \n return output\n\n\n\n\n","sub_path":"pytorch/EfficientDet/utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"482486825","text":"from google.appengine.api import urlfetch\n\nimport jinja2\nimport json\nimport os\nimport webapp2\n\n\njinja_environment = jinja2.Environment(loader=\n jinja2.FileSystemLoader(os.path.dirname(__file__)))\n\n\nclass MainHandler(webapp2.RequestHandler):\n\n def get(self):\n template = jinja_environment.get_template('templates/input.html')\n self.response.write(template.render())\n\n def post(self):\n template = jinja_environment.get_template('templates/output.html')\n query_text_value = self.request.get('query_text_field')\n query_text_value = query_text_value.replace(' ','+')\n url = \"http://api.giphy.com/v1/gifs/search?\"\n query = \"q=\" + query_text_value\n auth = \"&api_key=dc6zaTOxFJmzC&limit=10\"\n giphy_data_source = urlfetch.fetch(url+query+auth)\n giphy_json_content = giphy_data_source.content\n parsed_giphy_dictionary = json.loads(giphy_json_content)\n gif_images = parsed_giphy_dictionary['data'][0]['images']\n gif_url = gif_images['original']['url']\n response_dict = { 'gif_url': gif_url }\n self.response.write(template.render(response_dict))\n\n\napp = webapp2.WSGIApplication([\n ('/', MainHandler)\n], debug=True)\n\n","sub_path":"src/example-02/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"369845906","text":"# Author: Deanna Vickers\n# Defining the table structure for product type\n\nfrom safedelete.models import SafeDeleteModel\nfrom django.db import models\nfrom safedelete.models import SafeDeleteModel, SOFT_DELETE_CASCADE\n\nclass ProductType(SafeDeleteModel):\n\t_safedelete_policy = SOFT_DELETE_CASCADE\n\n\tcategory = models.CharField(max_length=100, default=\"\")\n\n\tclass Meta:\n\t\tdb_table = \"product_type\"\n\n\tdef __str__(self):\n\t\treturn self.category","sub_path":"bangazonAPI/api/models/product_type.py","file_name":"product_type.py","file_ext":"py","file_size_in_byte":438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"274427374","text":"# Adapted from https://github.com/meetshah1995/pytorch-semseg\nimport os\nimport json\nimport torch\nimport numpy as np\nimport scipy.misc as m\n\nfrom torch.utils import data\nimport torchvision.transforms.functional as tf\n\nfrom utils import recursive_glob, get_boundary_map, distance_transform\nfrom augmentation import *\n\nclass CityscapesSingleInstanceDataset(data.Dataset):\n \"\"\"cityscapesLoader\n https://www.cityscapes-dataset.com\n Data is derived from CityScapes, and can be downloaded from here:\n https://www.cityscapes-dataset.com/downloads/\n Many Thanks to @fvisin for the loader repo:\n https://github.com/fvisin/dataset_loaders/blob/master/dataset_loaders/images/cityscapes.py\n \"\"\"\n\n colors = [ # [ 0, 0, 0],\n [128, 64, 128],\n [244, 35, 232],\n [70, 70, 70],\n [102, 102, 156],\n [190, 153, 153],\n [153, 153, 153],\n [250, 170, 30],\n [220, 220, 0],\n [107, 142, 35],\n [152, 251, 152],\n [0, 130, 180],\n [220, 20, 60],\n [255, 0, 0],\n [0, 0, 142],\n [0, 0, 70],\n [0, 60, 100],\n [0, 80, 100],\n [0, 0, 230],\n [119, 11, 32],\n ]\n\n label_colours = dict(zip(range(19), colors))\n\n mean_rgb = {\n \"pascal\": [103.939, 116.779, 123.68],\n \"cityscapes\": [0.0, 0.0, 0.0],\n } # pascal mean for PSPNet and ICNet pre-trained model\n\n def __init__(\n self,\n root,\n split=\"train\",\n is_transform=False,\n img_size=(512, 1024),\n augmentations=None,\n train_transform=Compose([RandomHorizontallyFlip(0.5)]),\n scale_transform=Compose([Resize([224, 224])]),\n version=\"cityscapes\",\n out_dir=\"\"\n ):\n \"\"\"__init__\n :param root:\n :param split:\n :param is_transform:\n :param img_size:\n :param augmentations \n \"\"\"\n self.root = root\n self.split = split\n self.is_transform = is_transform\n self.augmentations = augmentations\n self.train_transform = train_transform\n self.scale_transform = scale_transform\n \n self.n_classes = 8 #19\n self.img_size = (\n img_size if isinstance(img_size, tuple) else (img_size, img_size)\n )\n \n self.images_base = os.path.join(self.root, \"leftImg8bit\", self.split)\n self.annotations_base = os.path.join(\n self.root, \"gtFine\", self.split\n )\n\n img_paths = recursive_glob(rootdir=self.images_base, suffix=\".png\")\n \n self.void_classes = [0, 1, 2, 3, 4, 5, 6, 9, 10, 14, 15, 16, 18, 29, 30, -1,7,\n 8,\n 11,\n 12,\n 13,\n 17,\n 19,\n 20,\n 21,\n 22,\n 23,]\n self.valid_classes = [\n 24,\n 25,\n 26,\n 27,\n 28,\n 31,\n 32,\n 33,\n ]\n self.class_names = [\n \"person\",\n \"rider\",\n \"car\",\n \"truck\",\n \"bus\",\n \"train\",\n \"motorcycle\",\n \"bicycle\",\n ]\n\n self.ignore_index = 250\n self.class_map = dict(zip(self.valid_classes, range(8)))\n\n self.img_paths, self.labels_coords, self.img_index_of_label, self.ins_ids = self._prepare_labels(img_paths, out_dir)\n \n if not self.img_paths:\n raise Exception(\n \"No files for split=[%s] found in %s\" % (split, self.images_base)\n )\n\n print(\"Found %d %s images\" % (len(self.img_paths), split))\n\n def load_dataset_info(self):\n info_dir = os.path.join(self.root, 'info.json')\n with open(info_dir) as f:\n info = json.load(f)\n return info\n \n def _prepare_labels(self, img_paths, out_dir):\n json_path = '{}/{}_cityscapes_single_instance_info.json'.format(out_dir, self.split)\n if not os.path.exists(json_path):\n print(\"No bbox info found. Preparing labels might take some time.\")\n labels_coords = []\n valid_img_paths = []\n img_index_of_label = []\n ins_ids = []\n for i, img_path in enumerate(img_paths):\n print('{}/{}'.format(i, len(img_paths)))\n img_path = img_path.rstrip()\n lbl_path = os.path.join(\n self.annotations_base,\n img_path.split(os.sep)[-2],\n os.path.basename(img_path)[:-15] + \"gtFine_labelIds.png\",\n )\n ins_path = os.path.join(\n self.annotations_base,\n img_path.split(os.sep)[-2],\n os.path.basename(img_path)[:-15] + \"gtFine_instanceIds.png\",\n )\n\n lbl = m.imread(lbl_path)\n lbl = self.encode_segmap(np.array(lbl, dtype=np.uint8))\n\n ins = m.imread(ins_path)\n ins = self.encode_insmap(np.array(ins, dtype=np.uint16), lbl)\n\n instances_coords = self._get_instances_coords(lbl, ins)\n if len(instances_coords) > 0:\n valid_img_paths += [img_path]\n labels_coords += [i[0] for i in instances_coords]\n img_index_of_label += [len(valid_img_paths) - 1] * len(instances_coords)\n ins_ids += [i[1] for i in instances_coords]\n with open(json_path, 'w') as f:\n json.dump({'valid_img_paths': valid_img_paths, 'labels_coords': labels_coords, 'img_index_of_label': img_index_of_label, 'ins_ids': ins_ids}, f)\n print('Saved bboxes to local.')\n else:\n with open(json_path) as f:\n json_file = json.load(f)\n valid_img_paths = json_file['valid_img_paths']\n labels_coords = json_file['labels_coords']\n img_index_of_label = json_file['img_index_of_label']\n ins_ids = json_file['ins_ids']\n \n return valid_img_paths, labels_coords, img_index_of_label, ins_ids\n \n def _get_instances_coords(self, lbl, ins):\n instances = np.unique(ins).tolist()\n instances = [i for i in instances if i != 0]\n \n instances_coords = []\n for ins_num in instances:\n x1, x2, y1, y2, ins_bmp = self.get_bbox(ins, ins_num)\n # filter out bbox with extreme sizes and irregular shapes\n area = np.sum(ins_bmp)\n if (area >= 100):\n instances_coords += [([x1, x2, y1, y2], ins_num)]\n# occupy_ratio = np.sum(ins_bmp) / ((x2 - x1) * (y2 - y1))\n \n# if (x2 - x1 >= 50 and y2 - y1 >= 50) and (x2 - x1 <= 1000 and y2 - y1 <= 1000) \\\n# and occupy_ratio > 0.25:\n# instances_coords += [([x1, x2, y1, y2], ins_num)]\n \n return instances_coords\n \n def __len__(self):\n \"\"\"__len__\"\"\"\n return len(self.labels_coords)\n\n def __getitem__(self, index):\n \"\"\"__getitem__\n :param index:\n \"\"\"\n img_path = self.img_paths[self.img_index_of_label[index]]\n \n img = m.imread(img_path)\n img = np.array(img, dtype=np.uint8)\n\n lbl_path = os.path.join(\n self.annotations_base,\n img_path.split(os.sep)[-2],\n os.path.basename(img_path)[:-15] + \"gtFine_labelIds.png\",\n )\n ins_path = os.path.join(\n self.annotations_base,\n img_path.split(os.sep)[-2],\n os.path.basename(img_path)[:-15] + \"gtFine_instanceIds.png\",\n )\n\n lbl = m.imread(lbl_path)\n lbl = self.encode_segmap(np.array(lbl, dtype=np.uint8))\n\n ins = m.imread(ins_path)\n ins = self.encode_insmap(np.array(ins, dtype=np.uint16), lbl)\n \n bbox = self.labels_coords[index]\n ins[ins != self.ins_ids[index]] = 0\n ins[ins == self.ins_ids[index]] = 1\n \n img, ins = self.crop_bbox(img, ins, bbox, random_crop = self.split=='train')\n \n img = Image.fromarray(img)\n ins = Image.fromarray(ins)\n if self.split == 'train':\n img, [ins] = self.train_transform(img, [ins])\n \n img, [ins] = self.scale_transform(img, [ins])\n \n ins = get_boundary_map(ins)\n \n img = tf.to_tensor(img).float()\n ins = (tf.to_tensor(ins).long().squeeze(0))\n \n return img, ins, bbox\n \n\n def decode_segmap(self, temp):\n r = temp.copy()\n g = temp.copy()\n b = temp.copy()\n for l in range(0, self.n_classes):\n r[temp == l] = self.label_colours[l][0]\n g[temp == l] = self.label_colours[l][1]\n b[temp == l] = self.label_colours[l][2]\n\n rgb = np.zeros((temp.shape[0], temp.shape[1], 3))\n rgb[:, :, 0] = r / 255.0\n rgb[:, :, 1] = g / 255.0\n rgb[:, :, 2] = b / 255.0\n return rgb\n\n def encode_segmap(self, mask):\n # Put all void classes to zero\n for _voidc in self.void_classes:\n mask[mask == _voidc] = self.ignore_index\n for _validc in self.valid_classes:\n mask[mask == _validc] = self.class_map[_validc]\n return mask\n \n def encode_insmap(self, ins, lbl):\n ins += 1\n ins[lbl == self.ignore_index] = 0\n instances = [i for i in np.sort(np.unique(ins)) if i != 0]\n \n for i in range(len(instances)):\n ins[ins == instances[i]] = i + 1\n return ins.astype(np.uint8)\n \n def crop_bbox(self, img, lbl, bbox, context_lo=0.1, context_hi=0.2, random_crop=True):\n # assumes imgs have the same size in the first two dimensions\n H, W, _ = img.shape\n x1, x2, y1, y2 = bbox\n \n cx = (x1+x2)/2\n cy = (y1+y2)/2\n if random_crop:\n factor = 1 + context_lo + np.random.random() * (context_hi - context_lo)\n else:\n factor = 1 + (context_lo + context_hi) / 2.\n w = (x2-x1)*factor\n h = (y2-y1)*factor\n l = max(w, h)\n x1, x2 = int(cx-l/2), int(cx+l/2)\n y1, y2 = int(cy-l/2), int(cy+l/2)\n x1, x2 = max(0, x1), min(x2, W)\n y1, y2 = max(0, y1), min(y2, H)\n \n patch_w = max(y2-y1, x2-x1)\n img_out = np.zeros((patch_w, patch_w, 3))\n lbl_out = np.zeros((patch_w, patch_w))\n \n img_out[:y2-y1, :x2-x1, :] = img[y1:y2,x1:x2,:]\n lbl_out[:y2-y1, :x2-x1] = lbl[y1:y2,x1:x2] \n return img_out.astype(np.uint8), lbl_out.astype(np.uint8)\n \n def get_bbox(self, ins, ins_id):\n # get instance bitmap\n ins_bmp = np.zeros_like(ins)\n ins_bmp[ins == ins_id] = 1\n row_sums = ins_bmp.sum(axis=0)\n col_sums = ins_bmp.sum(axis=1)\n col_occupied = row_sums.nonzero()\n row_occupied = col_sums.nonzero()\n x1 = int(np.min(col_occupied))\n x2 = int(np.max(col_occupied))\n y1 = int(np.min(row_occupied))\n y2 = int(np.max(row_occupied))\n area = (x2 - x1) * (y2 - y1)\n return x1, x2+1, y1, y2+1, ins_bmp\n ","sub_path":"cityscapes_single_instance.py","file_name":"cityscapes_single_instance.py","file_ext":"py","file_size_in_byte":11146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"16642336","text":"#pylint: disable=missing-docstring,invalid-name\n\nfrom app import models\nfrom app import utils\nfrom app.constants import STUDENT_ROLE, STAFF_ROLE, VALID_ROLES\n\nimport json\n\nSEED_OFFERING = \"cal/cs61a/sp15\"\n\ndef is_seeded():\n is_seed = models.Course.offering == SEED_OFFERING\n return bool(models.Course.query(is_seed).get())\n\ndef seed():\n import os\n import datetime\n import random\n from google.appengine.ext import ndb\n\n admin_user = models.User(\n email=[\"test@example.com\"],\n is_admin=True\n )\n admin_user.put()\n\n def make_seed_course(creator):\n return models.Course(\n display_name=\"CS 61A\",\n institution=\"UC Soumya\",\n offering=SEED_OFFERING,\n instructor=[creator.key])\n\n def make_future_assignment(course, creator, name):\n date = (datetime.datetime.now() + datetime.timedelta(days=365))\n with open('app/seed/hog_template.py') as fp:\n templates = {}\n templates['hog.py'] = fp.read()\n templates['hogq.scm'] = fp.read()\n\n return models.Assignment(\n name='cal/CS61A/sp15/proj1',\n display_name=\"Hog-\"+str(name),\n points=20,\n templates=json.dumps(templates),\n creator=creator.key,\n course=course.key,\n max_group_size=4,\n due_date=date,\n lock_date=date,\n url='cs61a.org/proj/hog',\n )\n\n # Will reject all scheme submissions\n def make_past_assignment(course, creator, name):\n date = (datetime.datetime.now() - datetime.timedelta(days=365))\n with open('app/seed/scheme_templates/scheme.py') as sc, \\\n open('app/seed/scheme_templates/scheme_reader.py') as sr, \\\n open('app/seed/scheme_templates/tests.scm') as tests, \\\n open('app/seed/scheme_templates/questions.scm') as quest:\n templates = {}\n templates['scheme.py'] = sc.read(),\n templates['scheme_reader.py'] = sr.read(),\n templates['tests.scm'] = tests.read(),\n templates['questsions.scm'] = quest.read(),\n\n return models.Assignment(\n name='cal/61A/fa14/proj4',\n points=20,\n display_name=\"Scheme-\"+str(name),\n templates=json.dumps(templates),\n course=course.key,\n creator=creator.key,\n max_group_size=4,\n due_date=date)\n\n def make_hw_assignment(course, creator, name):\n date = (datetime.datetime.now() + datetime.timedelta(days=2))\n with open('app/seed/scheme_templates/scheme.py') as sc:\n templates = {}\n templates['scheme.py'] = sc.read(),\n\n return models.Assignment(\n name='cal/CS61A/sp15/hw1',\n points=2,\n display_name=\"Homework 1-\"+str(name),\n templates=json.dumps(templates),\n course=course.key,\n creator=creator.key,\n max_group_size=4,\n due_date=date)\n\n def make_group(assign, members):\n return models.Group(\n member=[m.key for m in members],\n assignment=assign.key\n )\n\n def make_invited_group(assign, members):\n return models.Group(\n member=[members[0].key],\n invited=[members[1].key],\n assignment=assign.key\n )\n\n def random_date():\n days, seconds = random.randint(0, 12), random.randint(0, 86399)\n delta = datetime.timedelta(days=days, seconds=seconds)\n sdate = (datetime.datetime.now() - delta)\n\n def make_seed_backup(assignment, submitter, final=False):\n with open('app/seed/hog_modified.py') as fp:\n messages = {}\n messages['file_contents'] = {\n 'hog.py': fp.read(),\n 'hogq.scm': 'Blank Stuff',\n 'submit': final\n }\n\n\n messages = [models.Message(kind=kind, contents=contents)\n for kind, contents in messages.items()]\n\n backup = models.Backup(\n messages=messages,\n assignment=assignment.key,\n submitter=submitter.key,\n client_time=random_date())\n\n backup.put()\n return backup\n\n def make_seed_submission(assignment, submitter, final=False, grader=admin_user):\n backup = make_seed_backup(assignment, submitter, final)\n autograder_output = 'Point breakdown:\\n\\ttestName: 1.0/1\\n\\ttestName: 1.0/1\\n\\nScore:\\n\\tTotal: 2.0'\n score = models.Score(\n score=10,\n tag=\"Total\",\n message=autograder_output,\n grader=grader.key\n )\n score.put()\n return models.Submission(backup=backup.key, score=[score])\n\n\n def make_seed_scheme_submission(assignment, submitter, final=False):\n with open('app/seed/scheme.py') as sc, \\\n open('app/seed/scheme_reader.py') as sr, \\\n open('app/seed/tests.scm') as tests, \\\n open('app/seed/questions.scm') as quest:\n messages = {}\n messages['file_contents'] = {\n 'scheme.py': sc.read(),\n 'scheme_reader.py': sr.read(),\n 'tests.scm': tests.read(),\n 'questsions.scm': quest.read(),\n 'submit': final\n }\n\n messages = [models.Message(kind=kind, contents=contents)\n for kind, contents in messages.items()]\n backup = models.Backup(\n messages=messages,\n assignment=assignment.key,\n submitter=submitter.key,\n client_time=random_date())\n\n backup.put()\n return models.Submission(backup=backup.key)\n\n def make_version(current_version):\n return models.Version(\n name='ok',\n id='ok',\n base_url='https://github.com/Cal-CS-61A-Staff/ok-client/releases/download',\n versions=[current_version],\n current_version=current_version\n )\n\n\n def make_queue(assignment, submissions, asignee):\n queue = models.Queue(\n assignment=assignment.key,\n assigned_staff=[asignee.key],\n owner=asignee.key)\n queue = queue.put()\n for subm in submissions:\n backup = subm.backup.get()\n group = None\n if backup.submitter.get().get_group(assignment.key):\n group = backup.submitter.get().get_group(assignment.key).key\n fs = models.FinalSubmission(\n assignment=assignment.key,\n group=group,\n submission=subm.key,\n submitter=backup.submitter,\n queue=queue)\n fs.put()\n\n def make_final_with_group(subm, assign, submitter, group):\n fs = models.FinalSubmission(submission=subm.key,\n assignment=assign.key,\n submitter=submitter.key,\n group=group.key)\n fs.put()\n return fs\n\n def make_final(subm, assign, submitter):\n fs = models.FinalSubmission(submission=subm.key,\n assignment=assign.key,\n submitter=submitter.key)\n fs.put()\n return fs\n\n def score_seed_submission(final, score, msg, grader):\n \"\"\" Add composition score \"\"\"\n score = models.Score(\n tag='composition',\n score=score,\n message=msg,\n grader=grader.key)\n score.put()\n\n subm = final.submission.get()\n subm.score.append(score)\n subm.put()\n\n # Start putting things in the DB.\n c = admin_user # bad variable name in use by many parts of this script\n \n course = make_seed_course(admin_user)\n course.put()\n\n\n\n a = models.User(\n email=[\"dummy@admin.com\"],\n )\n a.put()\n models.Participant.add_role(a.key, course.key, STAFF_ROLE)\n\n students = []\n group_members = []\n staff = []\n\n for i in range(6):\n s = models.User(\n email=[\"partner\" + str(i) + \"@teamwork.com\"],\n )\n s.put()\n models.Participant.add_role(s.key, course.key, STUDENT_ROLE)\n group_members += [s]\n\n for i in range(9):\n s = models.User(\n email=[\"student\" + str(i) + \"@student.com\"],\n )\n s.put()\n models.Participant.add_role(s.key, course.key, STUDENT_ROLE)\n students += [s]\n\n for i in range(9):\n s = models.User(\n email=[\"grader\" + str(i) + \"@staff.com\"],\n )\n s.put()\n models.Participant.add_role(s.key, course.key, STAFF_ROLE)\n staff += [s]\n\n for i in range(9):\n forgetful_s = models.User(\n email=[\"forget\"+str(i)+\"@student.com\"],\n )\n forgetful_s.put()\n models.Participant.add_role(forgetful_s.key, course.key, STUDENT_ROLE)\n students += [forgetful_s]\n\n k = models.User(\n email=[\"dummy2@admin.com\"],\n )\n k.put()\n models.Participant.add_role(k.key, course.key, STAFF_ROLE)\n\n version = make_version('v1.3.0')\n version.put()\n version = make_version('v1.3.2')\n version.put()\n version = make_version('v1.3.15')\n version.put()\n\n # Put a few members on staff\n course.instructor.append(c.key)\n course.put()\n course.instructor.append(a.key)\n course.put()\n\n # Create a few assignments\n assignments = []\n for i in range(4):\n assignments += [\n make_future_assignment(course, c, i),\n make_past_assignment(course, c, i),\n make_hw_assignment(course, c, i)\n ]\n\n for assign in assignments:\n assign.put()\n # Create submissions\n subms = []\n\n # Group submission\n team1 = group_members[0:2]\n g1 = make_group(assign, team1)\n g1.put()\n\n\n team2 = group_members[2:4]\n g2 = make_invited_group(assign, team2)\n g2.put()\n\n team3 = group_members[4:6]\n g3 = make_group(assign, team3)\n g3.put()\n\n\n # Have each member in the group submit one\n for member in group_members:\n subm = make_seed_submission(assign, member)\n subm.put()\n\n # for member in group_members:\n # subm = make_seed_scheme_submission(assign2, member)\n # subm.put()\n\n group1_subm = make_seed_submission(assign, group_members[1])\n group1_subm.put()\n # Make team 1's submission final and score it.\n final = make_final_with_group(group1_subm, assign, group_members[1], g1)\n score_seed_submission(final, 2, \"Nice job, group 1!\", staff[8])\n subms.append(group1_subm)\n\n group3_subm = make_seed_submission(assign, group_members[5])\n group3_subm.put()\n # Make team 1's submission final and score it.\n final3 = make_final_with_group(group3_subm, assign, group_members[5], g3)\n score_seed_submission(final3, 1, \"Awesome job, group 3!\", staff[8])\n subms.append(group3_subm)\n\n # Make this one be a final submission though.\n # subm = make_seed_submission(assign, group_members[1], True)\n # subm.put()\n # subms.append(subm)\n\n # Create some Backups \n for s in students:\n for i in range(3):\n make_seed_backup(assign, s)\n\n\n # Now create indiviual submission, TODO: Enumerate instead of indexing\n for i in range(9):\n subm = make_seed_submission(assign, students[i])\n subm.put()\n #subms.append(subm)\n\n subm = make_seed_submission(assign, students[i], True)\n subm.put()\n subms.append(subm)\n\n # Make each individual submission final and score it.\n final = make_final(subm, assign, students[i])\n # Randomly assign composition so that some are ungraded:\n if i % 3 < 2:\n score_seed_submission(final, i % 3, \"Good job, student %s\" % str(i), staff[i])\n\n\n # Seed a queue. This should be auto-generated.\n make_queue(assign, subms[:len(subms)//2], c)\n make_queue(assign, subms[len(subms)//2:], k)\n\n utils.add_to_grading_queues(assign.key)\n","sub_path":"server/app/seed/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":12093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"428448120","text":"# 시작시간: 12시 12분\n# 문제를 해석한시간: 12시 38분\n# ~ 12시 50분\n# 시작: \n# 코딩시간:\n# 디버깅시간:\nimport sys\ninput = sys.stdin.readline\ngrid = list()\nDR = [0, -1, -1, -1, 0, 1, 1, 1]\nDC = [-1, -1, 0, 1, 1, 1, 0, -1]\n\ndef move_cloud(d, s, clouds, N):\n global grid\n new_clouds = dict()\n for x, y in list(clouds.keys()):\n first = (x + N + DR[d-1] * s) % N\n second = (y + N + DC[d-1] * s) % N\n new_clouds[(first, second)] = True\n grid[first][second] += 1\n return new_clouds\n\n\ndef copy_water(clouds, N):\n global grid\n for x, y in list(clouds.keys()):\n water_count = 0\n for dr, dc in zip([-1, -1, 1, 1], [-1, 1, -1, 1]):\n nx = x + dr\n ny = y + dc\n if 0 <= nx < N and 0 <= ny < N:\n if grid[nx][ny] > 0:\n water_count += 1\n grid[x][y] += water_count\n return clouds\n\n\ndef make_new_cloud(clouds, N):\n global grid\n new_clouds = dict()\n for i in range(N):\n for j in range(N):\n if grid[i][j] >= 2 and not clouds.get((i, j), False):\n new_clouds[(i, j)] = True\n grid[i][j] -= 2\n return new_clouds\n\n\ndef get_answer(N):\n global grid\n answer = 0\n for i in range(N):\n for j in range(N):\n answer += grid[i][j]\n return answer\n\n\ndef main():\n global grid\n grid = list()\n move = list()\n N, M = map(int, input().rstrip().split(\" \"))\n clouds = {(N-1, 0):True, (N-1, 1):True, (N-2, 0):True, (N-2, 1):True}\n\n for _ in range(N):\n grid.append(list(map(int, input().rstrip().split(\" \"))))\n for _ in range(M):\n d, s = tuple(map(int, input().rstrip().split(\" \")))\n clouds = move_cloud(d, s, clouds, N)\n clouds = copy_water(clouds, N)\n clouds = make_new_cloud(clouds, N)\n answer = get_answer(N)\n print(answer)\n\nif __name__ == \"__main__\":\n main()","sub_path":"soohyun/python/baekjoon/0429/21610_마법사상어와비바리기/1 copy.py","file_name":"1 copy.py","file_ext":"py","file_size_in_byte":1936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"121980964","text":"# Kelly Kelly\n# CTEC 121 / Winter 2019\n# Module 4 / Problem Set 5\n# Problem 1 (25 points)\n\n\"\"\"\nUsing the graphics library, draw a picture of the side view of a car. Make sure to include two tires, an area for windows and the roof. Include a front and rear bumper as well. Use all of the following types of objects and functions listed below:\n\n- Line\n- Circle\n- Rectangle\n- Polygon\n- setOutline\n- setFill\n\"\"\"\n# import graphics\nfrom graphics import *\n\n\ndef main():\n win = GraphWin(\"Vroom Vroom\", 800, 800)\n\n wheel = Circle(Point(225, 500), 100)\n wheel.setFill('black')\n wheel.draw(win)\n wheel2 = wheel.clone()\n wheel2.move(300, 0)\n wheel2.draw(win)\n rim = Circle(Point(225, 500), 25)\n rim.setFill(\"grey\")\n rim.setOutline(\"black\")\n rim.draw(win)\n frontRim = rim.clone()\n frontRim.move(300, 0)\n frontRim.draw(win)\n\n body2 = Rectangle(Point(340, 125), Point(520, 300))\n body2.setFill(\"blue\")\n body2.setOutline(\"blue\")\n body2.setWidth(4)\n body2.draw(win)\n body3 = Circle(Point(500, 275), 150)\n body3.setFill(\"blue\")\n body3.setOutline(\"blue\")\n body3.draw(win)\n body = Rectangle(Point(50, 300), Point(700, 500))\n body.setFill(\"blue\")\n body.setOutline(\"black\")\n body.setWidth(4)\n body.draw(win)\n door = Rectangle(Point(350, 310), Point(640, 490))\n door.setOutline(\"black\")\n door.setWidth(4)\n door.draw(win)\n doorHandle = Rectangle(Point(365, 340), Point(390, 355))\n doorHandle.setFill(\"grey\")\n doorHandle.draw(win)\n\n rear = Line(Point(340, 300), Point(340, 500))\n rear.setWidth(4)\n rear.draw(win)\n window = Rectangle(Point(350, 140), Point(520, 290))\n window.setFill(\"grey\")\n window.setOutline(\"black\")\n window.draw(win)\n frontWindow = Polygon(Point(530, 140), Point(\n 550, 140), Point(580, 160), Point(620, 200), Point(630, 220), Point(640, 250), Point(640, 290), Point(530, 290))\n frontWindow.setFill(\"grey\")\n frontWindow.setOutline(\"black\")\n frontWindow.draw(win)\n\n bumper = Rectangle(Point(660, 470), Point(705, 505))\n bumper.setFill(\"grey\")\n bumper.setOutline(\"black\")\n bumper.setWidth(4)\n bumper.draw(win)\n backBumper = bumper.clone()\n backBumper.move(-615, 0)\n backBumper.draw(win)\n\n road = Line(Point(0, 600), Point(800, 600))\n road.setWidth(5)\n road.draw(win)\n\n win.getMouse()\n\n\nmain()\n","sub_path":"problem-set-5-problem-1.py","file_name":"problem-set-5-problem-1.py","file_ext":"py","file_size_in_byte":2367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"176429281","text":"__author__ = 'zhy'\n\n\nclass Solution(object):\n @staticmethod\n def hIndex(citations):\n \"\"\"\n :type citations: List[int]\n :rtype: int\n \"\"\"\n L, R, length = 0, len(citations) - 1, len(citations)\n\n while L <= R:\n mid = L + R >> 1\n if length - mid > citations[mid]:\n L = mid + 1\n elif length - mid < citations[mid]:\n R = mid - 1\n else:\n return citations[mid]\n\n return length - L\n\n\ndef test():\n a = [[0, 0], [0], [1], [1, 2]]\n for i in a:\n print(Solution.hIndex(i))\n\n\nif __name__ == '__main__':\n test()\n","sub_path":"H-Index II.py","file_name":"H-Index II.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"378672082","text":"\"\"\"Options module.\"\"\"\n\n# This comment disables pylint's 'Invalid constant name' error for this module.\n# pylint: disable=C0103\n\n# third party\nimport click\n\n# local\nfrom click_annotvcf.constants import (\n CAVEMAN_TYPE,\n CUSTOM_TYPE,\n DEFAULT_PREFIX,\n GENERIC_TYPE,\n LOGGING_LEVELS,\n PINDEL_TYPE,\n RAW_TYPE,\n VARIANT_TYPE,\n )\n\ncosmic_reference = click.option(\n \"--cosmic_reference\", \"-r\",\n type=click.Path(\n exists=True, file_okay=False,\n dir_okay=True, readable=True,\n resolve_path=True),\n help=\"Directory containing a Cosmic vcf file per chromosome\"\n \"with tabix index file.\",\n required=True,\n )\n\ninput_file_name = click.option(\n \"--input_file_name\", \"-f\",\n type=click.Path(\n exists=True, file_okay=True,\n dir_okay=False, writable=False,\n readable=True, resolve_path=True),\n help=\"Gzipped, tab-delimited file.\",\n required=True,\n )\n\nref_file_name = click.option(\n \"--ref_file_name\", \"-r\",\n type=click.Path(\n exists=True, file_okay=True,\n dir_okay=False, writable=False,\n readable=True, resolve_path=True),\n help=\"Bed file (tab-delimited).\",\n required=True,\n )\n\noutput_file_name = click.option(\n \"--output_file_name\", \"-o\",\n type=click.Path(writable=True, resolve_path=True),\n help=\"Path to output path. Gzipped, tab-delimited.\",\n default=\"output.tsv.gz\",\n )\n\ninput_file_type = click.option(\n \"--input_file_type\", \"-t\",\n type=click.Choice([CAVEMAN_TYPE, PINDEL_TYPE, GENERIC_TYPE]),\n help=\"Data type. Default=%s\" % GENERIC_TYPE,\n default=None,\n )\n\noutput_file_format = click.option(\n \"--output_file_format\", \"-m\",\n type=click.Choice([RAW_TYPE, VARIANT_TYPE, CUSTOM_TYPE]),\n help=\"Output file type. Default=%s\" % RAW_TYPE,\n default=None,\n )\n\nnbases = click.option(\n \"--nbases\", \"-n\",\n type=click.INT,\n help=\"Extend regions by n bases. Default=0\",\n default=0,\n )\n\nloglevel = click.option(\n \"--loglevel\", \"-l\",\n type=click.Choice(LOGGING_LEVELS.keys()),\n help=\"Logger level.\",\n default=\"info\",\n )\n\nprefix = click.option(\n \"--prefix\", \"-p\",\n help=\"Prefix for fields in result header. Default='%s'\" % DEFAULT_PREFIX,\n default=DEFAULT_PREFIX,\n )\n\ncomparison_type = click.option(\n \"--comparison_type\", \"-c\",\n type=click.Choice([\"pos\", \"posmt\"]),\n help=\"Compare wrt: pos/posmt. Use `posmt` for SNPs and `pos` for indels.\",\n default=False,\n )\n\nnormal_tsv = click.option(\n \"--normal_tsv\", \"-tsv\",\n type=click.Path(\n exists=True, file_okay=True,\n dir_okay=False, writable=False,\n readable=True, resolve_path=True),\n help=\"Gzipped, tab-delimited file.\",\n multiple=True,\n required=True,\n)\n\nthreshold = click.option(\n \"--threshold\", \"-th\",\n type=click.INT,\n help=\"Base pairs threshold to annotate close variants with PON. Default=10\",\n default=10,\n)\n","sub_path":"click_annotvcf/options.py","file_name":"options.py","file_ext":"py","file_size_in_byte":2922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"519186425","text":"\"\"\" This python script checks if the BGP connection is working, and sends an snmp TRAP\nif the connection is broken.\n\"\"\"\nimport subprocess\nimport shlex\nimport re\n\n# Use socket and DNSpython to monitor the state of DNS \nimport socket\nimport dns.resolver\n\n\"\"\" CONSTANTS \"\"\"\n# GENERAL\nCFG_FILE_PATH = '/etc/scripts/trapnotifier.conf'\n\n# SNMPTRAP\nVERSION = '2c'\nCOMMUNITY = 'public' \nMONITOR_IPs = ['fe80::89e:b7ff:fe0d:3016', '::1'] # IPs of the monitoring servers\nUPTIME = '' # Let the agent set the uptime\n\n# DNS\nNAME_SERVERS = ['', '']\nTARGET = 'www.uclouvain.be'\n\n\n\n\"\"\" FUNCTIONS \"\"\"\n\ndef send_traps(oid, object_type, value_type, value):\n for monitor_ip in MONITOR_IPs:\n subprocess.call(['snmptrap', '-v', VERSION, '-c', COMMUNITY, monitor_ip, UPTIME, oid, object_type, value_type, value])\n\n# TEST DNS (ONLY MONITORING SERVERS?)\ndef check_dns(server_name):\n oid = '1.3.6.1.3.19997.0.0.0' # Experimental OID : SNMPv2-SMI::experimental.group9.notifications.prefix.dnsDownNotification\n object_type = '1.3.6.1.3.19997.0.1.0' # Experimental OID : SNMPv2-SMI::experimental.group9.notifications.objects.dnsDown\n value_type = 's'\n for nameServer in NAME_SERVERS:\n resolver = dns.resolver.Resolver()\n resolver.timeout = 5\n resolver.lifetime = 5\n resolver.nameservers=[nameServer]\n try:\n for rdata in resolver.query(TARGET, 'CNAME') :\n print(rdata.target)\n except dns.exception.DNSException as e:\n send_traps(oid, object_type, value_type, str(e))\n\n# TEST BGP (PYTHAGORE AND HALLES)\ndef check_bgp(server_name):\n oid = '1.3.6.1.3.19997.0.0.1' # Experimental OID : SNMPv2-SMI::experimental.group9.notifications.prefix.bgpErrorNotification\n object_type = '1.3.6.1.3.19997.0.1.1' # Experimental OID : SNMPv2-SMI::experimental.group9.notifications.objects.bgpError\n value_type = 's'\n # Test if BGP session is up\n p1 = subprocess.Popen(shlex.split('printf \"show protocols\\nquit\\n\"'), stdout=subprocess.PIPE)\n p2 = subprocess.Popen(shlex.split('birdc6 -s /tmp/'+server_name+'_bird6.ctl'), stdin=p1.stdout, stdout=subprocess.PIPE)\n out, err = p2.communicate()\n out = out.decode('utf-8')\n for l in out.splitlines()[5:-1]:\n protocol = l.split()\n if protocol[1].lower() == 'bgp':\n state = protocol[3].lower()\n info = protocol[5].lower()\n if state == 'up' :\n value = 'BGP - '+server_name+': protocol status -> '+state\n send_traps(oid, object_type, value_type, value)\n print(value)\n elif info != 'established':\n value = 'BGP - '+server_name+': BGP connection '+info\n send_traps(oid, object_type, value_type, value)\n print(value)\n print('BGP connection '+info)\n\n\n\n# TEST OSPF (EACH NODE MUST DO IT!)\ndef check_ospf(server_name):\n oid = '1.3.6.1.3.19997.0.0.2' # Experimental OID : SNMPv2-SMI::experimental.group9.notifications.prefix.ospfNeighbourUnavailableNotification\n object_type = '1.3.6.1.3.19997.0.1.2' # Experimental OID : SNMPv2-SMI::experimental.group9.notifications.objects.ospfNeighbourUnavailable\n value_type = 's'\n # Test if OSPF works\n p1 = subprocess.Popen(shlex.split('printf \"show ospf neighbors\\nquit\\n\"'), stdout=subprocess.PIPE)\n p2 = subprocess.Popen(shlex.split('birdc6 -s /tmp/'+server_name+'_bird6.ctl'), stdin=p1.stdout, stdout=subprocess.PIPE)\n out, err = p2.communicate()\n out = out.decode('utf-8')\n for l in out.splitlines()[5:-1]:\n neighbor = l.split()\n print(neighbor)\n neighbor_state = neighbor[2]\n neighbor_interface = neighbor[4]\n neighbor_ip = neighbor[5]\n ns = neighbor_state.split('/')[0].lower()\n if ns not in ['full', '2way']:\n value = 'OSPF - '+server_name+': neighbor @'+neighbor_ip+' '+ns\n send_traps(oid, object_type, value_type, value)\n print('Neighbor @'+neighbor_ip+' '+ns)\n else:\n print('Neighbor @'+neighbor_ip+' up!')\n # CHECK if number of neighbors == expected number ?\n\n\n# Read server name + execute functions\nwith open(CFG_FILE_PATH, 'r') as f:\n server_name = f.readline().rstrip('\\n')\n for line in f:\n globals()['check_'+line.rstrip('\\n')](server_name)\n","sub_path":"scripts/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":4334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"189618433","text":"# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\n\nimport contextlib\nimport io\nimport mock\nimport struct\nimport torch\n\nfrom detectron2.modeling import meta_arch\nfrom detectron2.structures import ImageList\n\nfrom .c10 import Caffe2Compatible\nfrom .patcher import ROIHeadsPatcher, patch_generalized_rcnn\nfrom .shared import alias, check_set_pb_arg, mock_torch_nn_functional_interpolate\n\n\ndef _cast_to_f32(f64):\n return struct.unpack(\"f\", struct.pack(\"f\", f64))[0]\n\n\ndef set_caffe2_compatible_tensor_mode(model, enable=True):\n def _fn(m):\n if isinstance(m, Caffe2Compatible):\n m.tensor_mode = enable\n\n model.apply(_fn)\n\n\ndef convert_batched_inputs_to_c2_format(batched_inputs, size_divisibility, device):\n \"\"\"\n batched_inputs is a list of dicts, each dict has fileds like image,\n height, width, image_id, etc ...\n # In D2, image is as 3D (C, H, W) tensor, all fields are not batched\n\n This function turn D2 format input to a tuple of Tensors\n \"\"\"\n\n assert all(isinstance(x, dict) for x in batched_inputs)\n assert all(x[\"image\"].dim() == 3 for x in batched_inputs)\n\n images = [x[\"image\"] for x in batched_inputs]\n images = ImageList.from_tensors(images, size_divisibility)\n\n im_info = []\n for input_per_image, image_size in zip(batched_inputs, images.image_sizes):\n target_height = input_per_image.get(\"height\", image_size[0])\n target_width = input_per_image.get(\"width\", image_size[1]) # noqa\n # NOTE: The scale inside im_info is kept as convention and for providing\n # post-processing information if further processing is needed. For\n # current Caffe2 model definitions that don't include post-processing inside\n # the model, this number is not used.\n # NOTE: There can be a slight difference between width and height\n # scales, using a single number can results in numerical difference\n # compared with D2's post-processing.\n scale = target_height / image_size[0]\n im_info.append([image_size[0], image_size[1], scale])\n im_info = torch.Tensor(im_info)\n\n return images.tensor.to(device), im_info.to(device)\n\n\ndef caffe2_preprocess_image(self, inputs):\n \"\"\"\n Override original preprocess_image, which is called inside the forward.\n Normalize, pad and batch the input images.\n \"\"\"\n data, im_info = inputs\n data = alias(data, \"data\")\n im_info = alias(im_info, \"im_info\")\n normalized_data = self.normalizer(data)\n normalized_data = alias(normalized_data, \"normalized_data\")\n\n # Pack (data, im_info) into ImageList which is recognized by self.inference.\n images = ImageList(tensor=normalized_data, image_sizes=im_info)\n\n return images\n\n\n@contextlib.contextmanager\ndef mock_preprocess_image(instance):\n with mock.patch.object(\n type(instance), \"preprocess_image\", autospec=True, side_effect=caffe2_preprocess_image\n ) as mocked_func:\n yield\n assert mocked_func.call_count > 0\n\n\nclass Caffe2GeneralizedRCNN(Caffe2Compatible, torch.nn.Module):\n def __init__(self, cfg, torch_model):\n \"\"\"\n Note: it modifies torch_model in-place.\n \"\"\"\n super(Caffe2GeneralizedRCNN, self).__init__()\n assert isinstance(torch_model, meta_arch.GeneralizedRCNN)\n self._wrapped_model = patch_generalized_rcnn(torch_model)\n self.eval()\n # self.tensor_mode = False\n set_caffe2_compatible_tensor_mode(self, True)\n\n self.roi_heads_patcher = ROIHeadsPatcher(cfg, self._wrapped_model.roi_heads)\n\n def get_tensors_input(self, batched_inputs):\n return convert_batched_inputs_to_c2_format(\n batched_inputs,\n self._wrapped_model.backbone.size_divisibility,\n self._wrapped_model.device,\n )\n\n def encode_additional_info(self, predict_net, init_net):\n size_divisibility = self._wrapped_model.backbone.size_divisibility\n check_set_pb_arg(predict_net, \"size_divisibility\", \"i\", size_divisibility)\n check_set_pb_arg(predict_net, \"meta_architecture\", \"s\", b\"GeneralizedRCNN\")\n # NOTE: maybe just encode the entire cfg.MODEL\n\n @mock_torch_nn_functional_interpolate()\n def forward(self, inputs):\n if not self.tensor_mode:\n return self._wrapped_model.inference(inputs)\n\n with mock_preprocess_image(self._wrapped_model):\n with self.roi_heads_patcher.mock_roi_heads(self.tensor_mode):\n results = self._wrapped_model.inference(inputs, do_postprocess=False)\n return tuple(results[0].flatten())\n\n\nclass Caffe2PanopticFPN(Caffe2Compatible, torch.nn.Module):\n def __init__(self, cfg, torch_model):\n super(Caffe2PanopticFPN, self).__init__()\n assert isinstance(torch_model, meta_arch.PanopticFPN)\n self._wrapped_model = patch_generalized_rcnn(torch_model)\n self.eval()\n set_caffe2_compatible_tensor_mode(self, True)\n\n self.roi_heads_patcher = ROIHeadsPatcher(cfg, self._wrapped_model.roi_heads)\n\n def get_tensors_input(self, batched_inputs):\n return convert_batched_inputs_to_c2_format(\n batched_inputs,\n self._wrapped_model.backbone.size_divisibility,\n self._wrapped_model.device,\n )\n\n def encode_additional_info(self, predict_net, init_net):\n size_divisibility = self._wrapped_model.backbone.size_divisibility\n check_set_pb_arg(predict_net, \"size_divisibility\", \"i\", size_divisibility)\n check_set_pb_arg(predict_net, \"meta_architecture\", \"s\", b\"PanopticFPN\")\n\n # Inference parameters:\n check_set_pb_arg(predict_net, \"combine_on\", \"i\", self._wrapped_model.combine_on)\n check_set_pb_arg(\n predict_net,\n \"combine_overlap_threshold\",\n \"f\",\n _cast_to_f32(self._wrapped_model.combine_overlap_threshold),\n )\n check_set_pb_arg(\n predict_net,\n \"combine_stuff_area_limit\",\n \"i\",\n self._wrapped_model.combine_stuff_area_limit,\n )\n check_set_pb_arg(\n predict_net,\n \"combine_instances_confidence_threshold\",\n \"f\",\n _cast_to_f32(self._wrapped_model.combine_instances_confidence_threshold),\n )\n\n @mock_torch_nn_functional_interpolate()\n def forward(self, inputs):\n \"\"\"\n Re-write the inference-only forward pass of PanopticFPN in c2 style\n \"\"\"\n assert self.tensor_mode\n\n images = caffe2_preprocess_image(self._wrapped_model, inputs)\n features = self._wrapped_model.backbone(images.tensor)\n\n gt_sem_seg = None\n sem_seg_results, _ = self._wrapped_model.sem_seg_head(features, gt_sem_seg)\n sem_seg_results = alias(sem_seg_results, \"sem_seg\")\n\n gt_instances = None\n proposals, _ = self._wrapped_model.proposal_generator(images, features, gt_instances)\n\n with self.roi_heads_patcher.mock_roi_heads(self.tensor_mode):\n detector_results, _ = self._wrapped_model.roi_heads(\n images, features, proposals, gt_instances\n )\n\n return tuple(detector_results[0].flatten()) + (sem_seg_results,)\n\n\nclass Caffe2RetinaNet(Caffe2Compatible, torch.nn.Module):\n def __init__(self, cfg, torch_model):\n super(Caffe2RetinaNet, self).__init__()\n assert isinstance(torch_model, meta_arch.RetinaNet)\n self._wrapped_model = torch_model\n self.eval()\n set_caffe2_compatible_tensor_mode(self, True)\n\n # serialize anchor_generator for future use\n self._serialized_anchor_generator = io.BytesIO()\n torch.save(self._wrapped_model.anchor_generator, self._serialized_anchor_generator)\n\n def get_tensors_input(self, batched_inputs):\n return convert_batched_inputs_to_c2_format(\n batched_inputs,\n self._wrapped_model.backbone.size_divisibility,\n self._wrapped_model.device,\n )\n\n def encode_additional_info(self, predict_net, init_net):\n size_divisibility = self._wrapped_model.backbone.size_divisibility\n check_set_pb_arg(predict_net, \"size_divisibility\", \"i\", size_divisibility)\n check_set_pb_arg(predict_net, \"meta_architecture\", \"s\", b\"RetinaNet\")\n\n # Inference parameters:\n check_set_pb_arg(\n predict_net, \"score_threshold\", \"f\", _cast_to_f32(self._wrapped_model.score_threshold)\n )\n check_set_pb_arg(predict_net, \"topk_candidates\", \"i\", self._wrapped_model.topk_candidates)\n check_set_pb_arg(\n predict_net, \"nms_threshold\", \"f\", _cast_to_f32(self._wrapped_model.nms_threshold)\n )\n check_set_pb_arg(\n predict_net,\n \"max_detections_per_image\",\n \"i\",\n self._wrapped_model.max_detections_per_image,\n )\n\n check_set_pb_arg(\n predict_net,\n \"bbox_reg_weights\",\n \"floats\",\n [_cast_to_f32(w) for w in self._wrapped_model.box2box_transform.weights],\n )\n self._encode_anchor_generator_cfg(predict_net)\n\n def _encode_anchor_generator_cfg(self, predict_net):\n # Ideally we can put anchor generating inside the model, then we don't\n # need to store this information.\n bytes = self._serialized_anchor_generator.getvalue()\n check_set_pb_arg(predict_net, \"serialized_anchor_generator\", \"s\", bytes)\n\n @mock_torch_nn_functional_interpolate()\n def forward(self, inputs):\n assert self.tensor_mode\n images = caffe2_preprocess_image(self._wrapped_model, inputs)\n\n # explicitly return the images sizes to avoid removing \"im_info\" by ONNX\n # since it's not used in the forward path\n return_tensors = [images.image_sizes]\n\n features = self._wrapped_model.backbone(images.tensor)\n features = [features[f] for f in self._wrapped_model.in_features]\n for i, feature_i in enumerate(features):\n features[i] = alias(feature_i, \"feature_{}\".format(i), is_backward=True)\n return_tensors.append(features[i])\n\n box_cls, box_delta = self._wrapped_model.head(features)\n for i, (box_cls_i, box_delta_i) in enumerate(zip(box_cls, box_delta)):\n return_tensors.append(alias(box_cls_i, \"box_cls_{}\".format(i)))\n return_tensors.append(alias(box_delta_i, \"box_delta_{}\".format(i)))\n\n return tuple(return_tensors)\n\n\nMETA_ARCH_CAFFE2_EXPORT_TYPE_MAP = {\n \"GeneralizedRCNN\": Caffe2GeneralizedRCNN,\n \"PanopticFPN\": Caffe2PanopticFPN,\n \"RetinaNet\": Caffe2RetinaNet,\n}\n","sub_path":"detectron2/export/caffe2_modeling.py","file_name":"caffe2_modeling.py","file_ext":"py","file_size_in_byte":10579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"99238090","text":"#BBN_LICENSE_START -- DO NOT MODIFY BETWEEN LICENSE_{START,END} Lines\n# Copyright (c) <2017,2018,2019,2020,2021>, \n# To be applied to the DCOMP/MAP Public Source Code Release dated 2018-04-19, with\n# the exception of the dcop implementation identified below (see notes).\n# \n# Dispersed Computing (DCOMP)\n# Mission-oriented Adaptive Placement of Task and Data (MAP) \n# \n# All rights reserved.\n# \n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n# \n# Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n# \n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n# IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n# TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n# PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n# TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n#BBN_LICENSE_END\n#!/usr/bin/env python3\n\n\"\"\"\nGraph the inferred demand information created by inferred_demand_to_csv.py.\n\nOutput to {output_dir}/inferred-demand/{ncp}-{service}={attr}.png\n\"\"\"\n\nimport warnings\nwith warnings.catch_warnings():\n import re\n import sys\n import argparse\n import os\n import logging\n import logging.config\n import json\n from pathlib import Path\n import map_utils\n import pandas as pd\n import matplotlib.pyplot as plt\n \nscript_dir=Path(__file__).parent.absolute()\n\ndef get_logger():\n return logging.getLogger(__name__)\n\n\ndef process_file(first_timestamp_ms, output, csv_file):\n ncp = csv_file.stem\n\n get_logger().debug(\"Processing %s ncp: %s\", csv_file, ncp)\n \n df = pd.read_csv(csv_file)\n df['minutes'] = (df['timestamp'] - first_timestamp_ms) / 1000 / 60\n df = df.sort_values(by=['minutes'])\n \n max_minutes = df['minutes'].max()\n services = df['service'].unique()\n source_regions = df['source region'].unique()\n attributes = df['attribute'].unique()\n\n xdata = df['minutes'].unique()\n for service in sorted(services):\n get_logger().debug(\"Service: %s\", service)\n for attr in attributes:\n get_logger().debug(\"attribute: %s\", attr)\n \n fig, ax = map_utils.subplots()\n ax.set_title(f\"Inferred demand for {service} and {attr} on {ncp}\")\n ax.set_xlabel('time (minutes)')\n ax.set_xlim(left=0, right=max_minutes)\n\n ydata = list()\n labels = list()\n for source_region in sorted(source_regions):\n get_logger().debug(\"source region: %s\", source_region)\n \n plot_data = df.loc[ (df['service'] == service) & (df['source region'] == source_region) & (df['attribute'] == attr)]\n label = source_region\n time_data = pd.Series(plot_data['value'].values, index=plot_data['minutes']).to_dict()\n yfilled = map_utils.fill_missing_times(xdata, time_data)\n \n get_logger().debug(\"yseries len: %d\", len(yfilled))\n ydata.append(yfilled)\n labels.append(label)\n\n get_logger().debug(\"xdata len: %d\", len(xdata))\n get_logger().debug(\"ydata len: %d\", len(ydata))\n ax.stackplot(xdata, ydata, labels=labels)\n handles, labels = ax.get_legend_handles_labels()\n lgd = ax.legend(handles, labels, bbox_to_anchor=(1.04, 1), loc=\"upper left\")\n\n output_name = output / f\"{ncp}-{service}-{attr}.png\"\n fig.savefig(output_name.as_posix(), format='png', bbox_extra_artists=(lgd,), bbox_inches='tight')\n plt.close(fig)\n \n \n \n\ndef main_method(args):\n with open(args.first_timestamp_file) as f:\n ts_str = f.readline().strip()\n first_timestamp = map_utils.log_timestamp_to_datetime(ts_str)\n first_timestamp_ms = first_timestamp.timestamp() * 1000\n get_logger().info(\"Simulation started at %s -> %d\", first_timestamp, first_timestamp_ms)\n \n output = Path(args.output) / 'inferred-demand'\n if not output.exists():\n get_logger().error(\"%s does not exist and is required to read the CSV files\", output)\n\n\n for csv_file in output.glob('*.csv'):\n process_file(first_timestamp_ms, output, csv_file)\n\n\ndef main(argv=None):\n if argv is None:\n argv = sys.argv[1:]\n\n class ArgumentParserWithDefaults(argparse.ArgumentParser):\n '''\n From https://stackoverflow.com/questions/12151306/argparse-way-to-include-default-values-in-help\n '''\n def add_argument(self, *args, help=None, default=None, **kwargs):\n if help is not None:\n kwargs['help'] = help\n if default is not None and args[0] != '-h':\n kwargs['default'] = default\n if help is not None:\n kwargs['help'] += ' (default: {})'.format(default)\n super().add_argument(*args, **kwargs)\n \n parser = ArgumentParserWithDefaults(formatter_class=argparse.RawTextHelpFormatter)\n parser.add_argument(\"-l\", \"--logconfig\", dest=\"logconfig\", help=\"logging configuration (default: logging.json)\", default='logging.json')\n parser.add_argument(\"--debug\", dest=\"debug\", help=\"Enable interactive debugger on error\", action='store_true')\n parser.add_argument(\"-o\", \"--output\", dest=\"output\", help=\"Output directory (Required)\", required=True)\n parser.add_argument(\"--first-timestamp-file\", dest=\"first_timestamp_file\", help=\"Path to file containing the log timestamp that the simulation started\", required=True)\n\n args = parser.parse_args(argv)\n\n map_utils.setup_logging(default_path=args.logconfig)\n if 'multiprocessing' in sys.modules:\n import multiprocessing_logging\n multiprocessing_logging.install_mp_handler()\n\n if args.debug:\n import pdb, traceback\n try:\n return main_method(args)\n except:\n extype, value, tb = sys.exc_info()\n traceback.print_exc()\n pdb.post_mortem(tb) \n else:\n return main_method(args)\n \n \nif __name__ == \"__main__\":\n sys.exit(main())\n","sub_path":"src/MAP-ChartGeneration/scripts/graph_inferred_demand.py","file_name":"graph_inferred_demand.py","file_ext":"py","file_size_in_byte":6936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"402867102","text":"from node_classes import Node_X\n\n\nclass BinarySearchTree_X(object):\n\n def __init__(self, root):\n self.root = root\n\n def check_ri(self, current=-1):\n\n \"\"\"\n Checks representation invariance.\n Prints error_message if it is violated\n \"\"\"\n if current == -1:\n current = self.root\n\n if not current:\n return True\n\n # Initialize to True\n representation_invariant = True\n\n # Check left subtree\n representation_invariant = (\n self.check_ri(current.left_child) or\n representation_invariant)\n\n # Check current node\n print(current.data, end =\" \")\n if current.left_child:\n if current.data <= current.left_child.data:\n error_message = (\n \"Representation invariance failed at left child of %s\" %\n str(current.data))\n # raise Exception(error_message)\n print(error_message)\n representation_invariant = False\n if current.right_child:\n if current.data >= current.right_child.data:\n error_message = (\n \"Representation invariance failed at right child of %s\" %\n str(current.data))\n # raise Exception(error_message)\n print(error_message)\n representation_invariant = False\n\n # Check right subtree\n representation_invariant = (\n self.check_ri(current.right_child) or\n representation_invariant)\n\n return representation_invariant\n\n def insert(self, data, current=-1):\n if current == -1:\n current = self.root\n\n if not current:\n try:\n self.root = Node_X(data, parent=None)\n except Exception as error:\n print(\"ERROR: %s\" % str(error))\n return False\n return True\n\n if data < current.data:\n if not current.left_child:\n try:\n current.left_child = Node_X(data, current)\n except Exception as error:\n print(\"ERROR: %s\" % str(error))\n return False\n return True\n else:\n self.insert(data, current.left_child)\n elif data > current.data:\n if not current.right_child:\n try:\n current.right_child = Node_X(data, current)\n except Exception as error:\n print(\"ERROR: %s\" % str(error))\n return False\n else:\n self.insert(data, current.right_child)\n else:\n return False\n\n def traverse_inorder(self, current=-1):\n if current == -1:\n current = self.root\n\n if not current:\n return\n\n self.traverse_inorder(current.left_child)\n print(current.data, end =\" \")\n self.traverse_inorder(current.right_child)\n\n def find(self, value, current=-1):\n if current == -1:\n current = self.root\n\n # Base case 1\n if not current:\n return None\n\n # Base case 2\n if current.data == value:\n print(\"Found \" + str(value))\n return current\n\n if value > current.data:\n return self.find(value, current.right_child)\n if value < current.data:\n return self.find(value, current.left_child)\n\n def find_min(self, current=-1):\n if current == -1:\n current = self.root\n\n if not current:\n return None\n\n if not current.left_child:\n return current\n\n return self.find_min(current.left_child)\n\n def find_max(self, current=-1):\n if current == -1:\n current = self.root\n\n if not current:\n return None\n\n if not current.right_child:\n return current\n\n return self.find_max(current.right_child)\n\n def next_larger(self, current=-1):\n if current == -1:\n current = self.root\n\n if not current:\n return None\n\n if current.right_child:\n # Has a right subtree\n return self.find_min(current.right_child)\n else:\n # Does not have a right subtree\n temp = current\n while True:\n if not temp.parent:\n # temp has reached root with no right subtree there\n # - current is the largest\n return None\n\n if temp is temp.parent.right_child:\n temp = temp.parent\n else:\n return temp.parent\n\n def next_smaller(self, current=-1):\n if current == -1:\n current = self.root\n\n if not current:\n return None\n\n if current.left_child:\n # Has a left subtree\n return self.find_max(current.left_child)\n else:\n # Does not have a left subtree\n temp = current\n while True:\n if not temp.parent:\n # temp has reached root & there is no left subtree for root\n # - current is the smallest node\n return None\n\n if temp is temp.parent.left_child:\n temp = temp.parent\n else:\n return temp.parent\n\n def delete(self, target_node):\n if not target_node:\n return False\n\n parent_node = target_node.parent\n\n # Case 1: No children\n if (not target_node.left_child) and (not target_node.right_child):\n if target_node is parent_node.left_child:\n parent_node.left_child = None\n if target_node is parent_node.right_child:\n parent_node.right_child = None\n target_node = None\n return True\n\n # Case 2: Has one subtree\n if target_node.left_child and not target_node.right_child:\n child_subtree_root = target_node.left_child\n child_subtree_root.parent = parent_node\n if target_node is parent_node.left_child:\n parent_node.left_child = child_subtree_root\n else:\n parent_node.right_child = child_subtree_root\n target_node = None\n return True\n\n if target_node.right_child and not target_node.left_child:\n child_subtree_root = target_node.right_child\n child_subtree_root.parent = parent_node\n if target_node is parent_node.left_child:\n parent_node.left_child = child_subtree_root\n else:\n parent_node.right_child = child_subtree_root\n target_node = None\n return True\n\n # Case 3: Has left as well as right subtrees\n if target_node.right_child and target_node.left_child:\n next_larger_node = self.next_larger(target_node)\n target_node.data = next_larger_node.data\n return self.delete(next_larger_node)\n\n\ndef main():\n my_bst = BinarySearchTree_X(None)\n\n \"\"\"\n for data in [1, 9, 6, 7, 2, 3, 4, 8]:\n my_bst.insert(data)\n \"\"\"\n \"\"\"\n print(\"\\nIn-order:\")\n my_bst.traverse_inorder()\n print(\"\")\n \"\"\"\n for data in [10, 4, 5, 6, 7]:\n my_bst.insert(data)\n\n print(\"\\nRep invariant: %s\" % str(my_bst.check_ri()))\n print(\"\")\n\n for data in [1, 9 ,5, 6, 7, 2, 3, 4, 8, 0, 5]:\n print(\"Find %s: %s\" % (str(data), my_bst.find(data)))\n\n print(\"\\nMinimum value: \" + str((my_bst.find_min()).data))\n print(\"\\nMaximum value: \" + str((my_bst.find_max()).data))\n\n print(\"\")\n for data in [7, 10, 6]:\n node = my_bst.find(data)\n if not node:\n print(\"Not found: \" + str(data))\n continue\n next_larger_node = my_bst.next_larger(node)\n if not next_larger_node:\n print(\"No next larger for: \" + str(data))\n continue\n print(\"Next larger of %s: %s\" %\n (str(data), str((next_larger_node).data)))\n\n\n for data in [7, 10, 6]:\n node = my_bst.find(data)\n if not node:\n print(\"Not found: \" + str(data))\n continue\n next_smaller_node = my_bst.next_smaller(node)\n if not next_larger_node:\n print(\"No next smaller for: \" + str(data))\n continue\n print(\"Next smaller of %s: %s\" %\n (str(data), str((next_smaller_node).data)))\n\n print(\"=\" * 100)\n my_bst_2 = BinarySearchTree_X(None)\n for data in [5, 4, 10, 8, 7, 20, 15, 30]:\n my_bst_2.insert(data)\n my_bst_2.traverse_inorder()\n print(\"\")\n print(my_bst_2.delete(my_bst_2.find(5)))\n my_bst_2.traverse_inorder()\n print(\"\")\n print(my_bst_2.delete(my_bst_2.find(4)))\n my_bst_2.traverse_inorder()\n print(\"\")\n print(my_bst_2.delete(my_bst_2.find(8)))\n my_bst_2.traverse_inorder()\n print(\"\")\n print(my_bst_2.delete(my_bst_2.find(20)))\n my_bst_2.traverse_inorder()\n print(\"\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Trees/BinarySearchTree/bst_2.py","file_name":"bst_2.py","file_ext":"py","file_size_in_byte":9135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"546688298","text":"\n# coding: utf-8\n\n# In[1]:\n\n\nimport gym\nimport time\nimport numpy as np\nimport matplotlib.pyplot as plt \nimport imageio\nimport os\n\n\n# In[2]:\n\n\nacro = gym.make('Acrobot-v1') # make acrobot\nacro.reset() # reset state\n\n\n# In[3]:\n\n\ndef get_action_current_egreedy(q_values_for_state,epsilon):\n \n if np.random.rand() < epsilon:\n action = np.random.choice(4)\n else:\n action = np.argmax(q_values_for_state)\n return action, 1,0\n\n\n# In[4]:\n\n\ndef evaluation(env, Q_table, state_t_discrete, epsilon, scaling_array, step_current_bound = 300, num_itr = 5):\n total_step_current = 0\n total_reward_current = 0\n itr = 0\n while(itr= (episode_cnt - print_count):\n render_list.append(acro_object.render(mode='rgb_array'))\n \n # choose action at time t based on e-greedy algorithm\n\n if int(counter_dir) % time_cluster == 0:\n if np.random.random() < 1 - epsilon:\n action_t = np.argmax(q_matrix[state_t_discrete[0], state_t_discrete[1], state_t_discrete[2], state_t_discrete[3]]) \n else:\n action_t = np.random.randint(0, acro_object.action_space.n)\n \n # get next state, next reward, done\n state_next, reward_next, done, _ = acro_object.step(action_t) \n \n# theta_1 = np.arctan(state_next[1]/state_next[0])\n# theta_2 = np.arctan(state_next[3]/state_next[2])\n\n# state_next_radians = np.array([theta_1,theta_2,state_next[4],state_next[5]]) \n \n # discretize state_next\n state_next_discrete = discretize_state(acro_object, state_next,scaling_array)\n \n # update q matrix for final state\n if done:\n q_matrix[ state_t_discrete[0], state_t_discrete[1], state_t_discrete[2], state_t_discrete[3], action_t] = reward_next\n \n # if not done, update q matrix for current state\n else:\n temporal_difference = lr*(1-(episode/episode_cnt)**2)*(reward_next + \n gamma*np.amax(q_matrix[state_next_discrete[0],\\\n state_next_discrete[1],\\\n state_next_discrete[2],\\\n state_next_discrete[3]])\\\n -\\\n q_matrix[ state_t_discrete[0],\\\n state_t_discrete[1],\\\n state_t_discrete[2],\\\n state_t_discrete[3],action_t])\n \n q_matrix[ state_t_discrete[0], state_t_discrete[1], state_t_discrete[2], state_t_discrete[3],action_t] += temporal_difference\n \n # update state and reward\n state_t_discrete = state_next_discrete\n episode_reward +=reward_next\n counter_dir += 1\n# print(\"STATE\", state_t)\n \n \n # apply epsilon reduction\n if epsilon > epsilon_floor:\n epsilon -= epsilon_reduction_factor\n \n # add reward to eposide list\n reward_list.append(episode_reward)\n \n if (episode+1) % 50 == 0:\n epsilon_module = 0.0\n evaluation_iterations.append(evaluation(acro_object, q_matrix, state_t_discrete, epsilon_module*(1-episode/episode_cnt),scaling_array)) \n \n if (episode+1) % 100 == 0:\n ave_reward = np.mean(reward_list)\n rewards_average_list.append(ave_reward)\n reward_list = []\n \n if (episode+1) % 1000 == 0: \n print('Average Reward for Episode {} : {}'.format(episode+1, ave_reward))\n \n acro_object.close() \n \n directory = 'acro_gifs/'\n\n if not os.path.exists(directory):\n os.makedirs(directory)\n \n if len(render_list) >0:\n imageio.mimsave(directory+str(lr)+str(time.time())+'.gif', render_list, fps=30)\n return rewards_average_list,render_list,evaluation_iterations\n\n\n# In[7]:\n\n\n# Run Q-learning algorithm\n\nlr_list = np.arange(.1,.2,.02)\nepsilon_floors = np.arange(0.0,.51,.125)\n\n\ngamma = 0.9\nepsilon = 1\nrender_cnt = 1\n\ntime_cluster = 1\nepisody_cnt = 10000\n\nfor min_epsilon in epsilon_floors:\n \n rewards_lr = []\n renders_lr = []\n evaluation_lr = []\n \n for lr in lr_list:\n rewards,render_list,evaluation_interations = q_learning(acro, lr, gamma,epsilon, min_epsilon, episody_cnt,render_cnt,time_cluster)\n rewards_lr.append(rewards)\n renders_lr.append(render_list)\n evaluation_lr.append(evaluation_interations)\n \n directory = 'acro_exploration_rewards/'\n\n if not os.path.exists(directory):\n os.makedirs(directory)\n\n # generate plot \n fig1 = plt.figure(figsize=(15,15))\n for i,j in enumerate(lr_list):\n plt.plot(100*(np.arange(len(rewards_lr[i])) + 1), rewards_lr[i],label=str(j),alpha=(i+1)/len(lr_list))\n plt.legend(title=\"Gamma = \"+str(gamma)+\"\\nEpsilon Initial (Exploration) = \"+str(epsilon)+\"\\nEpsilon Minimum = \"+str(min_epsilon)+\"\\n Learning Rates:\")\n plt.title(\"Average Reward vs Episode (Exploration Mode)\", size = 30)\n plt.xlabel(\"Episode Number\",size =30)\n plt.ylabel(\"Mean Reward\",size =30)\n plt.savefig(directory+\"rewards\"+str(time.time())+\".jpg\")\n plt.show()\n plt.close()\n\n directory = 'acro_evaluation_rewards/'\n\n if not os.path.exists(directory):\n os.makedirs(directory)\n\n\n # generate plot \n fig1 = plt.figure(figsize=(15,15))\n for i,j in enumerate(lr_list):\n plt.plot(100*(np.arange(len(evaluation_lr[i])) + 1), np.asarray(evaluation_lr[i])[:,1],label=str(j),alpha=(i+1)/len(lr_list))\n\n plt.legend(title=\"Time Cluster Size\"+str(time_cluster)+\"\\nGamma = \"+str(gamma)+\"\\nEpsilon Initial (Exploration) = \"+str(epsilon)+\"\\nEpsilon Minimum = \"+str(min_epsilon)+\"\\n Learning Rates:\")\n plt.title(\"Average Reward vs Episode (Evaluation Mode)\", size = 30)\n plt.xlabel(\"Episode Number\",size =30)\n plt.ylabel(\"Mean Reward\",size =30)\n\n plt.savefig(directory+\"rewards\"+str(time.time())+\".jpg\")\n plt.show()\n plt.close() \n\n","sub_path":"acrobot_Q_learning.py","file_name":"acrobot_Q_learning.py","file_ext":"py","file_size_in_byte":10453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"586368456","text":"# Brittni Watkins\n# 37996950\n# 10 February 2019\n# CSE 8935\n# Assignment 3\n# GISMO and Search\n# Python Client\n\nimport socket\n\nHOST = 'localhost'\nPORT = 8088\n\nclient = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nclient.connect((HOST, PORT))\nmessage = \"Hello there from Python\"\nmessageBytes = message.encode('utf-8')\nclient.sendall(messageBytes)\nresponse = client.recv(1024)\nclient.close()\n\nprint('Data from server: %s' %response.decode())\n","sub_path":"Python/Sockets/simple_server_client.py","file_name":"simple_server_client.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"523906249","text":"#!usr/bin/env python3.6\n\nfrom urllib.request import urlopen as uReq\nfrom bs4 import BeautifulSoup as soup\n\nmy_url='http://www.bbc.co.uk/sport/football/scores-fixtures'\n\nuClient = uReq(my_url)\npage_html=uClient.read()\nuClient.close()\npage_soup = soup(page_html,\"html.parser\")\n\nli=page_soup.findAll(\"li\",{\"class\":\"gs-u-pb-\"})\n\nmatches_list=[]\nfor match in li:\n col=match.findAll(\"span\",{\"class\":\"gs-u-display-none\"})\n matchDict={\"home\":col[0].text,\"away\":col[1].text}\n matches_list.append(matchDict)\n\nprint(matches_list)","sub_path":"bs.py","file_name":"bs.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"159649524","text":"#!/usr/bin/python3\n\"\"\"\nCreate Internet gateway, Dhcp options and attach to a vpc\n\"\"\"\n\nimport argparse\nimport awsops\n\ndef select_vpc(vpc_ids):\n \"\"\"\n Selected a vpc id chosen by user\n :param vpc_ids: [String] of vpcids\n :return: String id of the vpc selected\n \"\"\"\n print(\"Select vpc to act on:\")\n for vpc_id in vpc_ids:\n print(vpc_id)\n id_selected = input(\"Enter id: \")\n return id_selected\n\n\ndef args_parser():\n \"\"\" validate arguments and return them \"\"\"\n parser = argparse.ArgumentParser(add_help=True, description=\"VPC Arguments\")\n parser.add_argument(\"--region\", \"-r\", help=\"Get target region\",\n required=True)\n return parser.parse_args()\n\n\ndef main():\n args = args_parser()\n vpc_ids = []\n aws = awsops.awsOperations(args.region)\n respone_vpcs = aws.describe_vpcs()\n for vpc in respone_vpcs['Vpcs']:\n vpc_ids.append(vpc['VpcId'])\n vpc_id = select_vpc(vpc_ids)\n response_igw = aws.create_internet_gateway()\n igw_id = response_igw['InternetGateway']['InternetGatewayId']\n aws.attach_internet_gateway(vpc_id, igw_id)\n response_create_dhcp_options = aws.create_dhcp_options()\n dhcp_options_id = response_create_dhcp_options['DhcpOptions']['DhcpOptionsId']\n aws.associate_dhcp_options(vpc_id, dhcp_options_id)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"session-1/igateway/internetgw.py","file_name":"internetgw.py","file_ext":"py","file_size_in_byte":1358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"349824602","text":"# 9.14. The Accumulator Pattern with Strings¶\n'''\nCombining the in operator with string concatenation using + and the accumulator\npattern, we can write a function that removes all the vowels from a string.\nThe idea is to start with a string and iterate over each character, checking\nto see if the character is a vowel. As we process the characters, we will build\nup a new string consisting of only the nonvowel characters.\nTo do this, we use the accumulator pattern.\n\nRemember that the accumulator pattern allows us to keep a “running total”.\nWith strings, we are not accumulating a numeric total.\nInstead we are accumulating characters onto a string.\n'''\n\ndef removeVowels(s):\n vowels = \"aeiouAEIOU\"\n sWithoutVowels = \"\"\n for eachChar in s:\n if eachChar not in vowels:\n sWithoutVowels = sWithoutVowels + eachChar\n return sWithoutVowels\n\nprint(removeVowels(\"compsci\"))\nprint(removeVowels(\"aAbEefIijOopUus\"))\n\n","sub_path":"9_strings/9.14.accumlator_pattern_in_strings.py","file_name":"9.14.accumlator_pattern_in_strings.py","file_ext":"py","file_size_in_byte":944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"236254350","text":"#encoding:utf-8\r\nfrom os import path\r\nimport multiprocessing\r\nfrom pathlib import Path\r\n\"\"\"Note:\r\n\r\n\"\"\"\r\nBASE_DIR = Path('pybert')\r\n\r\nconfigs = {\r\n\r\n 'task':'multi label',\r\n 'data':{\r\n 'raw_data_path': BASE_DIR / 'dataset/raw/train.csv', # \r\n 'train_file_path': BASE_DIR / 'dataset/processed/train.tsv',\r\n 'valid_file_path': BASE_DIR / 'dataset/processed/valid.tsv',\r\n 'test_file_path': BASE_DIR / 'dataset/raw/test.csv'\r\n },\r\n 'output':{\r\n 'log_dir': BASE_DIR / 'output/log', # \r\n 'writer_dir': BASE_DIR / \"output/TSboard\",# \r\n 'figure_dir': BASE_DIR / \"output/figure\", # \r\n 'checkpoint_dir': BASE_DIR / \"output/checkpoints\",# \r\n 'cache_dir': BASE_DIR / 'model/',\r\n 'result': BASE_DIR / \"output/result\",\r\n },\r\n 'pretrained':{\r\n \"bert\":{\r\n 'vocab_path': BASE_DIR / 'model/pretrain/uncased_L-12_H-768_A-12/vocab.txt',\r\n 'tf_checkpoint_path': BASE_DIR / 'model/pretrain/uncased_L-12_H-768_A-12/bert_model.ckpt',\r\n 'bert_config_file': BASE_DIR / 'model/pretrain/uncased_L-12_H-768_A-12/bert_config.json',\r\n 'pytorch_model_path': BASE_DIR / 'model/pretrain/pytorch_pretrain/pytorch_model.bin',\r\n 'bert_model_dir': BASE_DIR / 'model/pretrain/pytorch_pretrain',\r\n },\r\n 'embedding':{}\r\n },\r\n 'train':{\r\n 'valid_size': 0.2,\r\n 'max_seq_len': 256,\r\n 'do_lower_case':True,\r\n 'batch_size': 4,#24, # how many samples to process at once\r\n 'epochs': 2, # number of epochs to train\r\n 'start_epoch': 1,\r\n 'warmup_proportion': 0.1,# Proportion of training to perform linear learning rate warmup for. E.g., 0.1 = 10%% of training.\r\n 'gradient_accumulation_steps': 1,# Number of updates steps to accumulate before performing a backward/update pass.\r\n 'learning_rate': 2e-5,\r\n 'n_gpu': [0], # \r\n 'num_workers': multiprocessing.cpu_count(), # \r\n 'weight_decay': 1e-5,\r\n 'seed':2018,\r\n 'resume':False,\r\n },\r\n 'predict':{\r\n 'batch_size':400,\r\n 'amount_of_target_labels': 6\r\n },\r\n 'callbacks':{\r\n 'lr_patience': 5, # number of epochs with no improvement after which learning rate will be reduced.\r\n 'mode': 'min', # one of {min, max}\r\n 'monitor': 'valid_loss', # \r\n 'early_patience': 20, # early_stopping\r\n 'save_best_only': True, # SAVE ONLY CHECKPOINT OF EPOCH WITH THE LOWEST LOSS\r\n 'save_checkpoint_freq': 10 # THIS ONLY APPLIES WHEN SAVE_BEST_ONLY = FALSE\r\n },\r\n 'loss_metrics':{\r\n #ATTENTION - THIS IS NOT YET IMPLEMENTED - TO CHANGE LOSS FUNCTION, GO TO train_bert_multi_label.py, look under TRAIN_CONFIGS\r\n # Loss Functions Currently Available:\r\n # Binary_Cross_Entropy - BC\r\n\r\n\r\n\r\n # 'loss_criterion': 'Binary_Cross_Entropy'\r\n },\r\n\r\n\r\n 'label2id' : { # FOR MULTILABEL, ORDERED LABELS GO HERE\r\n \"toxic\": 0,\r\n \"severe_toxic\": 1,\r\n \"obscene\": 2,\r\n \"threat\": 3,\r\n \"insult\": 4,\r\n \"identity_hate\": 5\r\n },\r\n 'model':{\r\n 'arch':'bert'\r\n }\r\n}","sub_path":"BERT-PYTORCH-ENV/pybert/config/basic_config.py","file_name":"basic_config.py","file_ext":"py","file_size_in_byte":3155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"554280213","text":"def main():\n n = int(input('Digite o valor de N: '))\n\n i = 1\n q = 0\n resultado = 0\n while i <= n:\n if i%2 != 0:\n fracao = i/(n-q)\n resultado = fracao + resultado\n \n else:\n fracao = (n-q)/i\n resultado = resultado - fracao\n\n i += 1\n q += 1\n \n print(f'o resultado da somatoria das frações ate {n}: {resultado:.2f}')\n \n\nmain()","sub_path":"Fabio03 - For/fabio03_q19_valor_de_s.py","file_name":"fabio03_q19_valor_de_s.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"120529653","text":"#!/usr/bin/env python\n__author__ = 'chriswhsu'\n\nimport datetime\nimport ConfigParser\nimport os\nimport logging\nimport threading\nfrom time import sleep\nimport uuid\nimport pytz\nimport numpy\nfrom cassandra.cluster import Cluster\nfrom multiprocessing.pool import ThreadPool\n\n\nlog = logging.getLogger()\nlog.setLevel('INFO')\nhandler = logging.StreamHandler()\nhandler.setFormatter(logging.Formatter(\"%(asctime)s [%(levelname)s] %(name)s: %(message)s\"))\nlog.addHandler(handler)\n\nConfig = ConfigParser.ConfigParser()\n\n# look for config file in same directory as executable .py file.\nConfig.read(os.path.join(os.path.abspath(os.path.dirname(__file__)), '../sense.cnf'))\n\nKEYSPACE = Config.get(\"Cassandra\", \"Keyspace\")\n\n\ndef runquery_async(session, prepared, myuuid, utcdate):\n\n future = session.execute_async(prepared.bind([myuuid, utcdate]))\n\n log.info(\"start\")\n\n def log_results(rows):\n log.info('We got %s rows' % len(rows))\n\n power = [row.actpower for row in rows]\n\n log.info(\"Min Power: %d\" % numpy.min(power))\n log.info(\"Max Power: %d\" % numpy.max(power))\n log.info(\"Mean Power: %d\" % numpy.mean(power))\n log.info(\"done\")\n\n def log_error(exc):\n log.error(\"Operation failed: %s\", exc)\n\n future.add_callbacks(log_results, log_error)\n\n\ndef runquery(session, prepared, myuuid, utcdate):\n future = session.execute_async(prepared.bind([myuuid, utcdate]))\n\n rows = future.result()\n\n log.info(\"start\")\n\n log.info('We got %s rows' % len(rows))\n\n power = [row.actpower for row in rows]\n\n log.info(\"Min Power: %d\" % numpy.min(power))\n log.info(\"Max Power: %d\" % numpy.max(power))\n log.info(\"Mean Power: %d\" % numpy.mean(power))\n log.info(\"--------\")\n\n\ndef main():\n cluster = Cluster([Config.get(\"Cassandra\", \"Cluster\")], port=Config.getint(\"Cassandra\", \"Port\"))\n\n utc = pytz.utc\n\n utc_date = datetime.datetime(2013, 10, 13, 0, 0, 0, 0, utc)\n\n mylist = {'10000000-0000-0000-0000-00000000094e', '10000001-0000-0000-0000-0000000008b8',\n '10000002-0000-0000-0000-0000000008b9', '10000003-0000-0000-0000-0000000008ba',\n '10000004-0000-0000-0000-0000000008d4', '10000005-0000-0000-0000-0000000008d8'}\n\n session = cluster.connect()\n\n log.info(\"setting keyspace...\")\n session.set_keyspace(KEYSPACE)\n\n query = (\"SELECT actpower FROM data where device_id = ? and day in (?)\")\n prepared = session.prepare(query)\n\n threads = []\n\n for myuuid in mylist:\n\n #runquery(session, prepared, uuid.UUID(myuuid), utc_date)\n t = threading.Thread(target=runquery, args=(session, prepared, uuid.UUID(myuuid), utc_date))\n t.start()\n threads.append(t)\n #runquery_async(session, prepared, uuid.UUID(myuuid), utc_date)\n log.info(\"done spawning threads\")\n\n #sleep(10)\n for t in range(len(threads)):\n threads[t].join()\n\n log.info(\"done waiting for execution\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"crest/sense/misc/threadRead.py","file_name":"threadRead.py","file_ext":"py","file_size_in_byte":2956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"130249942","text":"# Description: This file contains the options for the youtube-dl module.\nydl_opts = {\n \"format\": \"bestaudio/best\",\n \"postprocessors\": [\n {\n \"key\": \"FFmpegExtractAudio\",\n \"preferredcodec\": \"mp3\",\n \"preferredquality\": \"192\",\n },\n ],\n \"ignoreerrors\": True,\n \"quiet\": False,\n \"sleep_interval\": 2,\n}\n","sub_path":"src/options.py","file_name":"options.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"328585624","text":"# -*- coding: utf-8 -*-\nfrom __future__ import print_function\nimport sys\nimport socket\nimport requests\nfrom pyformance.reporters.reporter import Reporter\nfrom . import delta\n\nif sys.version_info[0] > 2:\n from urllib.parse import urlparse\nelse:\n from urlparse import urlparse\n\n\nclass WavefrontReporter(Reporter):\n \"\"\"\n Base reporter for reporting data in Wavefront format.\n \"\"\"\n\n def __init__(self, source=\"wavefront-pyformance\", registry=None, reporting_interval=10, clock=None, prefix=\"\", tags={}):\n super(WavefrontReporter, self).__init__(registry=registry,\n reporting_interval=reporting_interval,\n clock=clock)\n self.source = source\n self.prefix = prefix\n tags = tags or {}\n self.tagStr = ' '.join(['\\\"%s\\\"=\\\"%s\\\"' % (k,v) for (k,v) in tags.items()])\n\n def report_now(self, registry=None, timestamp=None):\n raise NotImplementedError('use WavefrontProxyReporter or WavefrontDirectReporter')\n\n def _collect_metrics(self, registry, timestamp=None):\n metrics = registry.dump_metrics()\n metrics_data = []\n for key in metrics.keys():\n is_delta = delta.is_delta_counter(key, registry)\n for value_key in metrics[key].keys():\n if is_delta:\n registry.counter(key).dec(metrics[key][value_key]) # decrement delta counter\n metric_name = self._get_metric_name(self.prefix, key, value_key, is_delta=is_delta)\n metric_line = self._get_metric_line(metric_name, metrics[key][value_key], timestamp)\n metrics_data.append(metric_line)\n return metrics_data\n\n def _get_metric_line(self, name, value, timestamp):\n if timestamp:\n return \"%s %s %s source=\\\"%s\\\" %s\" % (name, value, timestamp, self.source, self.tagStr)\n else:\n return \"%s %s source=\\\"%s\\\" %s\" % (name, value, self.source, self.tagStr)\n\n def _get_metric_name(self, prefix, name, value_key, is_delta=False):\n return delta.get_delta_name(prefix, name, value_key) if is_delta else \"%s%s.%s\" % (prefix, name, value_key)\n\n\nclass WavefrontProxyReporter(WavefrontReporter):\n \"\"\"\n This reporter requires a host and port to report data to a Wavefront proxy.\n \"\"\"\n\n def __init__(self, host, port=2878, source=\"wavefront-pyformance\", registry=None, reporting_interval=10, clock=None,\n prefix=\"proxy.\", tags={}):\n super(WavefrontProxyReporter, self).__init__(source=source,\n registry=registry,\n reporting_interval=reporting_interval,\n clock=clock,\n prefix=prefix,\n tags=tags)\n self.host = host\n self.port = port\n self.socket_factory = socket.socket\n self.proxy_socket = None\n\n def report_now(self, registry=None, timestamp=None):\n timestamp = timestamp or int(round(self.clock.time()))\n metrics = self._collect_metrics(registry or self.registry, timestamp)\n if metrics:\n self._report_points(metrics)\n\n def stop(self):\n super(WavefrontProxyReporter, self).stop()\n if self.proxy_socket:\n self.proxy_socket.close()\n\n def _report_points(self, metrics, reconnect=True):\n try:\n if not self.proxy_socket:\n self._connect()\n for line in metrics:\n self.proxy_socket.send(line.encode('utf-8') + \"\\n\")\n except socket.error as e:\n if reconnect:\n self.proxy_socket = None\n self._report_points(metrics, reconnect=False)\n else:\n print(\"error reporting to wavefront proxy:\", e, file=sys.stderr)\n except Exception as e:\n print(\"error reporting to wavefront proxy:\", e, file=sys.stderr)\n\n def _connect(self):\n self.proxy_socket = self.socket_factory(socket.AF_INET, socket.SOCK_STREAM)\n self.proxy_socket.connect((self.host, self.port))\n\n\nclass WavefrontDirectReporter(WavefrontReporter):\n \"\"\"\n This reporter requires a server and a token to report data directly to a Wavefront server.\n \"\"\"\n\n def __init__(self, server, token, source=\"wavefront-pyformance\", registry=None, reporting_interval=10, clock=None,\n prefix=\"direct.\", tags={}):\n super(WavefrontDirectReporter, self).__init__(source=source,\n registry=registry,\n reporting_interval=reporting_interval,\n clock=clock,\n prefix=prefix,\n tags=tags)\n self.server = self._validate_url(server)\n self.token = token\n self.batch_size = 10000\n self.headers = {'Content-Type': 'text/plain',\n 'Authorization': 'Bearer ' + token}\n self.params = {'f': 'graphite_v2'}\n\n def _validate_url(self, server):\n parsed_url = urlparse(server)\n if not all([parsed_url.scheme, parsed_url.netloc]):\n raise ValueError(\"invalid server url\")\n return server\n\n def report_now(self, registry=None, timestamp=None):\n metrics = self._collect_metrics(registry or self.registry)\n if metrics:\n # limit to batch_size per api call\n chunks = self._get_chunks(metrics, self.batch_size)\n for chunk in chunks:\n metrics_str = u'\\n'.join(chunk).encode('utf-8')\n self._report_points(metrics_str)\n\n def _get_chunks(self, metrics, chunk_size):\n \"\"\"\n returns a lazy list generator\n \"\"\"\n for i in range(0, len(metrics), chunk_size):\n yield metrics[i:i+chunk_size]\n\n def _report_points(self, points):\n try:\n r = requests.post(self.server+'/report', params=self.params, headers=self.headers, data=points)\n r.raise_for_status()\n except Exception as e:\n print(e, file=sys.stderr)\n\n\n","sub_path":"wavefront_pyformance/wavefront_pyformance/wavefront_reporter.py","file_name":"wavefront_reporter.py","file_ext":"py","file_size_in_byte":6358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"474932577","text":"#!/usr/bin/python\n\n\"\"\"\nvocab.py: Vocabulary Generation\n\nUsage:\n vocab.py --snli-corpus= --sts-corpus= [options]\n\nOptions:\n -h --help show this screen.\n --snli-corpus= snli corpus\n --sts-corpus= sts corpus\n --freq-cutoff= frequency cutoff [default: 1]\n --save-vocab-to= save vocab object [default: vocab.pickle]\n\"\"\"\n\nfrom docopt import docopt\nfrom collections import Counter\nfrom itertools import chain\nimport pickle\nimport torch\n\nfrom utils import read_corpus\nfrom utils import pad_sents\n\nclass Vocab(object):\n \"\"\"\n structure of the vocabulary\n \"\"\"\n def __init__(self, word2id=None):\n \"\"\"\n @param word2id (dict): dictionary mapping words->indices\n \"\"\"\n self.pad_tok = '' #Pad Token\n self.unk_tok = '' #Unknown Token\n self.start_tok = '' #Start Token\n self.eos_tok = '' #End of sentence Token\n if word2id:\n self.word2id = word2id\n else:\n self.word2id = dict()\n self.word2id[self.pad_tok] = 0 \n self.word2id[self.unk_tok] = 1\n self.word2id[self.start_tok] = 2\n self.word2id[self.eos_tok] = 3\n\n self.pad_id = self.word2id[self.pad_tok]\n self.unk_id = self.word2id[self.unk_tok]\n self.start_id = self.word2id[self.start_tok]\n self.eos_id = self.word2id[self.eos_tok]\n\n self.id2word = {v: k for k, v in self.word2id.items()}\n\n def __getitem__(self, word):\n return self.word2id.get(word, self.unk_id)\n\n def __len__(self):\n return len(self.word2id)\n\n def id2word(self, w_id):\n return self.id2word[w_id]\n\n def add(self, word):\n if word not in self.word2id:\n w_id = self.word2id[word] = len(self)\n self.id2word[w_id] = word\n return w_id\n else:\n return self[word]\n\n def words2indices(self, sents):\n if type(sents[0]) == str:\n return [self[w] for w in sents]\n else:\n return [[self[w] for w in s] for s in sents]\n\n def indices2words(self, w_ids):\n return [self.id2word[w_id] for w_id in w_ids]\n\n def sents2Tensor(self, sents, device):\n \"\"\"\n Convert list of sent to tensor by padding required sents\n @param sents (list[list[str]]): batch of sents in reverse sorted order\n @return torch.t(out_tensor) (torch.tensor (max_sent_len, batch_size))\n \"\"\"\n word_ids = self.words2indices(sents)\n sents_padded = pad_sents(word_ids, self[''])\n out_tensor = torch.tensor(sents_padded, dtype=torch.long, device=device)\n return torch.t(out_tensor) #transpose since batch_first=False in our model\n\n def save(self, file_path):\n \"\"\"\n save the vocab to a json file\n @param file_path (str): /path/file to save the vocab\n \"\"\"\n pickle.dump(self.word2id, open(file_path, 'wb'))\n\n @staticmethod\n def build(corpus, freq_cutoff):\n \"\"\"\n create Vocab object for the words in the corpus\n @param corpus (list[list[str]]): list of sentences\n @param freq_cutoff (int): min frequency cutoff\n @return vocab (Vocab): Vocab class obj\n \"\"\"\n vocab = Vocab()\n word_freq = Counter(chain(*corpus))\n vocab_words = [w for w, v in word_freq.items() if v >= freq_cutoff]\n top_vocab_words = sorted(vocab_words, key=lambda w: word_freq[w], reverse=True)\n for word in top_vocab_words:\n vocab.add(word)\n return vocab\n\n @staticmethod\n def load(file_path):\n \"\"\"\n load vocabulary from the json dump\n @param file_path (str): /path/file for vocab build on corpus\n @return Vocab class obj loaded from this file_path\n \"\"\"\n word2id = pickle.load(open(file_path, 'rb'))\n return Vocab(word2id)\n\nif __name__ == \"__main__\":\n args = docopt(__doc__)\n\n snli_sents = read_corpus(args['--snli-corpus'])\n sts_sents = read_corpus(args['--sts-corpus'])\n train_sents = snli_sents\n train_sents.extend(sts_sents)\n vocab = Vocab.build(train_sents, int(args['--freq-cutoff']))\n vocab.save(args['--save-vocab-to'])\n","sub_path":"src/vocab.py","file_name":"vocab.py","file_ext":"py","file_size_in_byte":4268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"541807067","text":"import pandas as pd\nfrom sklearn.model_selection import train_test_split\n\nimport numpy as np\n\n#Read data file\n#https://www.kaggle.com/mlg-ulb/creditcardfraud/version/3\ndata = pd.read_csv('creditcard.csv')\n\n#Seperate data from target\n#\tLast column of data is currently the target (class = 1 for fraudulant transaction 0 for normal transaction)\ncol_labels=[]\nfor col_label in data.columns:\n\tcol_labels.append(col_label)\n#print(col_labels)\ntarget_col_label=col_labels[len(col_labels)-1]\ncol_labels=col_labels[1:len(col_labels)-1]\ntarget=data[target_col_label]\ndata=data[col_labels]\n#print(data.head(n=40))\n#print(target.head(n=40))\n\ndata_train, data_test, target_train, target_test = train_test_split(data,target, test_size = 0.30, random_state = 10)\n\n\n#Naive-Bayes Estimator\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.metrics import auc\nfrom sklearn.metrics import accuracy_score\ngnb = GaussianNB()\npred = gnb.fit(data_train, target_train).predict(data_test)\n\nnum_false_pos=0\nnum_false_neg=0\nnum_fraud_cases=0\ncaught_frauds=0\nnum_of_pred=len(pred)\nfor i in range(0,num_of_pred):\n#\tprint(target_test[i])\n\tif pred[i]==0 and target_test.iloc[i]==1:\n\t\tnum_false_neg+=1\n\telif pred[i]==1 and target_test.iloc[i]==0:\n\t\tnum_false_pos+=1\n\tif target_test.iloc[i]==1:\n\t\tnum_fraud_cases+=1\n\t\tif pred[i]==1:\n\t\t\tcaught_frauds+=1\nprint(\"*** Naive-Bayes Estimater Results ***\")\nprint(\"Length of target data \"+str(target_test.shape[0]))\nprint(\"Number of predictions made: \"+str(num_of_pred))\nprint(\"Number of frauds committed: \"+str(num_fraud_cases))\nprint(\"Number of frauds caught: \"+str(caught_frauds))\nprint(\"Number of false positives: \"+str(num_false_pos))\nprint(\"Number of false negatives: \"+str(num_false_neg))\nprint(\"Naive-Bayes accuracy : \",accuracy_score(target_test, pred, normalize = True))\n#print(\"Naive-Bayes AUC : \",auc(target_test, pred))\n\n#LinearSVC\nfrom sklearn.svm import LinearSVC\n#create an object of type LinearSVC\n#Got convergence warning without having dual=False. max_iter default is 1000\nsvc_model = LinearSVC(random_state=0, dual=False)\n#train the algorithm on training data and predict using the testing data\npred = svc_model.fit(data_train, target_train).predict(data_test)\n\nnum_false_pos=0\nnum_false_neg=0\nnum_fraud_cases=0\ncaught_frauds=0\nnum_of_pred=len(pred)\nfor i in range(0,num_of_pred):\n#\tprint(target_test[i])\n\tif pred[i]==0 and target_test.iloc[i]==1:\n\t\tnum_false_neg+=1\n\telif pred[i]==1 and target_test.iloc[i]==0:\n\t\tnum_false_pos+=1\n\tif target_test.iloc[i]==1:\n\t\tnum_fraud_cases+=1\n\t\tif pred[i]==1:\n\t\t\tcaught_frauds+=1\nprint(\"*** LinearSVC Results ***\")\nprint(\"Length of target data \"+str(target_test.shape[0]))\nprint(\"Number of predictions made: \"+str(num_of_pred))\nprint(\"Number of frauds committed: \"+str(num_fraud_cases))\nprint(\"Number of frauds caught: \"+str(caught_frauds))\nprint(\"Number of false positives: \"+str(num_false_pos))\nprint(\"Number of false negatives: \"+str(num_false_neg))\nprint(\"LinearSVC accuracy : \",accuracy_score(target_test, pred, normalize = True))\n\n\n#K-Neighbors Classifier\nfrom sklearn.neighbors import KNeighborsClassifier\n#create object of the lassifier\nneigh = KNeighborsClassifier(n_neighbors=3, p=1)\n#Train the algorithm\nneigh.fit(data_train, target_train)\n# predict the response\npred = neigh.predict(data_test)\nnum_false_pos=0\nnum_false_neg=0\nnum_fraud_cases=0\ncaught_frauds=0\nnum_of_pred=len(pred)\nfor i in range(0,num_of_pred):\n#\tprint(target_test[i])\n\tif pred[i]==0 and target_test.iloc[i]==1:\n\t\tnum_false_neg+=1\n\telif pred[i]==1 and target_test.iloc[i]==0:\n\t\tnum_false_pos+=1\n\tif target_test.iloc[i]==1:\n\t\tnum_fraud_cases+=1\n\t\tif pred[i]==1:\n\t\t\tcaught_frauds+=1\nprint(\"*** K-Neighbors Classifier Results ***\")\nprint(\"Length of target data \"+str(target_test.shape[0]))\nprint(\"Number of predictions made: \"+str(num_of_pred))\nprint(\"Number of frauds committed: \"+str(num_fraud_cases))\nprint(\"Number of frauds caught: \"+str(caught_frauds))\nprint(\"Number of false positives: \"+str(num_false_pos))\nprint(\"Number of false negatives: \"+str(num_false_neg))\nprint(\"K-Neighbors Classifier accuracy : \",accuracy_score(target_test, pred, normalize = True))\n","sub_path":"Scikit-learn_credit_card_fraud/ml_credit_card_fraud_no_time.py","file_name":"ml_credit_card_fraud_no_time.py","file_ext":"py","file_size_in_byte":4134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"519145689","text":"'''\nReader for LSP output xdr files (.p4's)\n\n'''\nimport xdrlib as xdr;\nimport numpy as np;\nfrom misc import test;\n#get basic dtypes\ndef get_int(file,N=1,forcearray=False):\n ret=np.fromfile(file,dtype='>i4',count=N);\n if N==1 and not forcearray:\n return ret[0];\n return ret;\n\ndef get_float(file,N=1,forcearray=False):\n ret=np.fromfile(file,dtype='>f4',count=N);\n if N==1 and not forcearray:\n return ret[0];\n return ret;\n\ndef get_str(file):\n l1 = get_int(file);\n l2 = get_int(file);\n if l1 != l2:\n print(\"warning, string prefixes are not equal...\");\n print(\"{}!={}\".format(l1,l2));\n size=l1;\n if l1%4:\n size+=4-l1%4;\n return xdr.Unpacker(file.read(size)).unpack_fstring(l1);\n\ndef get_list(file,fmt):\n '''makes a list out of the fmt from the LspOutput f using the format\n i for int\n f for float\n d for double\n s for string'''\n out=[]\n for i in fmt:\n if i == 'i':\n out.append(get_int(file));\n elif i == 'f' or i == 'd':\n out.append(get_float(file));\n elif i == 's':\n out.append(get_str(file));\n else:\n raise ValueError(\"Unexpected flag '{}'\".format(i));\n return out;\ndef get_dict(file,fmt,keys):\n return dict(\n zip(keys, get_list(file,fmt))\n );\n\ndef get_header(file,**kw):\n '''gets the header for the .p4 file, note that this\n Advanced the file position to the end of the header.\n \n Returns the size of the header, and the size of the header,\n if the header keyword is true.\n '''\n if type(file) == str:\n #if called with a filename, recall with opened file.\n with open(file,'r') as f:\n return get_header(f,**kw);\n if test(kw, \"size\"):\n size = file.tell();\n header = get_dict(\n file,'iiss',\n ['dump_type','dversion', 'title','revision']);\n if header['dump_type'] == 2 or header['dump_type'] == 3:\n #this is a fields file or a scalars file.\n d = get_dict(file,'fii',['timestamp','geometry','domains']);\n header.update(d);\n #reading quantities\n n = get_int(file);\n names=[get_str(file) for i in range(n)];\n units=[get_str(file) for i in range(n)];\n header['quantities'] = zip(names,units);\n elif header['dump_type'] == 6:\n #this is a particle movie file\n d = get_dict(file,\n 'iiii',\n ['geometry','sflagsx','sflagsy','sflagsz']);\n header.update(d);\n #reading params\n n = get_int(file);\n flags=[bool(get_int(file)) for i in range(n)];\n units=[get_str(file) for i in range(n)];\n labels=['q','x','y','z','ux','uy','uz','E'];\n if n == 8:\n pass;\n elif n == 7:\n labels = labels[:-1];\n elif n == 11:\n labels+=['xi','yi','zi'];\n else:\n raise NotImplementedError('Not implemented for these number of parameters:{}.'.format(n));\n header['params'] = [\n (label,unit) for (label,unit,flag) in zip(labels,units,flags) if flag\n ];\n elif header['dump_type'] == 10:\n #this is a particle extraction file:\n header['geometry'] = get_int(file);\n #reading quantities\n n = get_int(file);\n header['quantities'] = [get_str(file) for i in range(n)];\n else:\n raise ValueError('Unknown dump_type: {}'.format(header['dump_type']));\n if test(kw,'size'):\n return header, file.tell()-size;\n return header;\n\ndef read_flds(file, header, var, vprint, vector=True,remove_edges=False):\n '''\n Read a flds file. Do not call directly\n '''\n if vector:\n size=3;\n readin = set();\n for i in var:#we assume none of the fields end in x\n if i[-1] == 'x' or i[-1] == 'y' or i[-1] == 'z':\n readin.add(i[:-1]);\n else:\n readin.add(i);\n else:\n size=1;\n readin = set(var);\n doms = [];\n qs = [i[0] for i in header['quantities']];\n for i in range(header['domains']):\n iR, jR, kR = get_int(file, N=3);\n #getting grid parameters (real coordinates)\n nI = get_int(file); Ip = get_float(file,N=nI, forcearray=True);\n nJ = get_int(file); Jp = get_float(file,N=nJ, forcearray=True);\n nK = get_int(file); Kp = get_float(file,N=nK, forcearray=True);\n nAll = nI*nJ*nK;\n vprint('reading domain with dimensions {}x{}x{}={}.'.format(nI,nJ,nK,nAll));\n d={}\n d['xs'], d['ys'], d['zs'] = Ip, Jp, Kp;\n #d['x'], d['y'], d['z'] = np.vstack(np.meshgrid(Ip,Jp,Kp,indexing='ij')).reshape(3,-1);\n d['z'], d['y'], d['x'] = np.meshgrid(Kp,Jp,Ip,indexing='ij')\n d['z'], d['y'], d['x'] = d['z'].ravel(), d['y'].ravel(), d['x'].ravel();\n for quantity in qs:\n if quantity not in readin:\n vprint('skipping {}'.format(quantity));\n file.seek(nAll*4*size,1);\n else:\n vprint('reading {}'.format(quantity));\n d[quantity] = get_float(file,N=nAll*size);\n if size==3:\n data=d[quantity].reshape(nAll,3).T;\n d[quantity+'x'],d[quantity+'y'],d[quantity+'z']= data;\n del data, d[quantity];\n doms.append(d);\n if remove_edges:\n vprint(\"removing edges\");\n dims = ['xs','ys','zs'];\n readqs = [k for k in doms[0].keys()\n if k not in dims ] if len(doms) > 0 else None;\n mins = [ min([d[l].min() for d in doms])\n for l in dims ];\n def cutdom(d):\n ldim = [len(d[l]) for l in dims];\n cuts = [ np.isclose(d[l][0], smin)\n for l,smin in zip(dims,mins) ];\n cuts[:] = [None if i else 1\n for i in cuts];\n for quantity in readqs:\n d[quantity]=d[quantity].reshape((ldim[2],ldim[1],ldim[0]));\n d[quantity]=d[quantity][cuts[2]:,cuts[1]:,cuts[0]:].ravel();\n for l,cut in zip(dims,cuts):\n d[l] = d[l][cut:];\n return d;\n doms[:] = [cutdom(d) for d in doms];\n vprint('Stringing domains together.');\n out = { k : np.concatenate([d[k] for d in doms]) for k in doms[0] };\n vprint('Converting to little-endian');\n for k in out:\n out[k] = out[k].astype('f4');\n return out;\n\ndef iseof(file):\n c = file.tell();\n file.read(1);\n if file.tell() == c:\n return True;\n file.seek(c);\n \ndef read_movie(file, header):\n params,_ = zip(*header['params']);\n nparams = len(params);\n pbytes = (nparams+1)*4;\n frames=[];\n pos0 = file.tell(); \n while not iseof(file):\n d=get_dict(file, 'fii',['t','step','pnum']);\n d['pos']=file.tell();\n file.seek(d['pnum']*pbytes,1);\n frames.append(d);\n for i,d in enumerate(frames):\n N = d['pnum'];\n lt=[('ip','>i4')]+zip(params,['>f4']*nparams);\n file.seek(d['pos']);\n arr=np.fromfile(file,dtype=np.dtype(lt),count=N);\n frames[i].update({'data':arr});\n del frames[i]['pos'];\n return frames;\n\ndef read_pext(file, header):\n nparams = len(header['quantities']);\n params = ['t','q','x','y','z','ux','uy','uz'];\n if nparams == 9:\n params+=['E'];\n elif nparams == 11:\n params+=['xi','yi','zi'];\n elif nparams == 12:\n params+=['E','xi','yi','zi'];\n #it's just floats here on out\n dt = list(zip(params, ['>f4']*len(params)));\n out = np.fromfile(file,dtype=dt,count=-1);\n return out;\n\ndef read(fname,**kw):\n '''\n Reads an lsp output file and returns a raw dump of data,\n sectioned into quantities either as an dictionary or a typed numpy array.\n\n Parameters:\n -----------\n\n fname -- filename of thing to read\n \n Keyword Arguments:\n ------------------\n\n vprint -- Verbose printer. Used in scripts\n override -- (type, start) => A tuple of a dump type and a place to start\n in the passed file, useful to attempting to read semicorrupted\n files.\n\n flds/sclr Specific Arguments:\n -----------------------------\n var -- list of quantities to be read. For fields, this can consist\n of strings that include vector components, e.g., 'Ex'. If \n None (default), read all quantities.\n remove_edges -- If set to truthy, then remove the edges from domains before\n concatenation.\n '''\n with open(fname,'rb') as file:\n if test(kw,'override'):\n dump, start = kw['override'];\n file.seek(start);\n header = {'dump_type': dump};\n if not test(kw, 'var') and 2 <= header['dump_type'] <= 3 :\n raise ValueError(\"If you want to force to read as a scalar, you need to supply the quantities\")\n else:\n header = get_header(file);\n \n vprint = kw['vprint'] if test(kw, 'vprint') else lambda s: None;\n if 2 <= header['dump_type'] <= 3 :\n if not test(kw, 'var'):\n var=[i[0] for i in header['quantities']];\n else:\n var=kw['var'];\n if test(kw, 'remove_edges'):\n remove_edges=True;\n else:\n remove_edges=False;\n readers = {\n 2: lambda: read_flds(file,header,var, vprint, remove_edges=remove_edges),\n 3: lambda: read_sclr(file,header,var, vprint, remove_edges=remove_edges),\n 6: lambda: read_movie(file, header),\n 10:lambda: read_pext(file,header)\n };\n \n try:\n d = readers[header['dump_type']]();\n except KeyError:\n d = None;\n raise NotImplementedError(\"Other file types not implemented yet!\");\n return d;\n","sub_path":"lspreader.py","file_name":"lspreader.py","file_ext":"py","file_size_in_byte":9874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"478459245","text":"# This file contains python variables that configure Lamson for email processing.\nimport logging\nimport os\nos.environ['DJANGO_SETTINGS_MODULE'] = 'webapp.settings'\n\n# You may add additional parameters such as `username' and `password' if your\n# relay server requires authentication, `starttls' (boolean) or `ssl' (boolean)\n# for secure connections.\nrelay_config = {'host': 'localhost', 'port': 1025}\n\nreceiver_config = {'host': '0.0.0.0', 'port': 25}\n\nhandlers = ['app.handlers.talking']\n\n\nrouter_defaults = {\n 'host': 'mr\\\\.quibbl\\\\.es',\n 'answer_id' : '[0-9]+',\n 'snip_id' : '[0-9]+',\n 'conv_id' : '[0-9]+',\n}\n\ntemplate_config = {'dir': 'app', 'module': 'templates'}\n\n# the config/boot.py will turn these values into variables set in settings\n","sub_path":"prod/email/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"242352338","text":"#!/usr/bin/env python\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf\nfrom tensorflow.examples.tutorials.mnist import input_data\nfrom tensorflow.examples.tutorials.mnist import mnist\n\nFLAGS = tf.app.flags.FLAGS\ntf.app.flags.DEFINE_string('input_data_dir', '../mnist',\n \"\"\"Data where MNIST data is stored\"\"\")\ntf.app.flags.DEFINE_float('learning_rate', 1e-3,\n \"\"\"Initial learning rate\"\"\")\ntf.app.flags.DEFINE_integer('batch_size', 32,\n \"\"\"Number of images in a batch\"\"\")\ntf.app.flags.DEFINE_integer('n_hidden', 300,\n \"\"\"Number of hidden units\"\"\")\ntf.app.flags.DEFINE_integer('max_iter', 10000,\n \"\"\"Maximum number of training iterations\"\"\")\ntf.app.flags.DEFINE_string('run', 'run1',\n \"\"\"Subdirectory name for log files\"\"\")\nN_CLASSES = 10\n\n\ndef conv_network(batch_size):\n images = tf.placeholder(tf.float32, shape=(batch_size,\n mnist.IMAGE_PIXELS),\n name='images')\n labels = tf.placeholder(tf.int32, shape=(batch_size), name='labels')\n is_training = tf.placeholder(tf.bool, shape=(), name='is_training')\n input_layer = tf.reshape(images, [-1, 28, 28, 1])\n conv1 = tf.layers.conv2d(inputs=input_layer,\n filters=32,\n kernel_size=[5, 5],\n padding=\"same\",\n activation=tf.nn.relu)\n\n pool1 = tf.layers.max_pooling2d(inputs=conv1, pool_size=[2, 2], strides=2)\n conv2 = tf.layers.conv2d(inputs=pool1,\n filters=64,\n kernel_size=[5, 5],\n padding=\"same\",\n activation=tf.nn.relu)\n pool2 = tf.layers.max_pooling2d(inputs=conv2, pool_size=[2, 2], strides=2)\n pool2_flat = tf.reshape(pool2, [-1, 7 * 7 * 64])\n dense = tf.layers.dense(inputs=pool2_flat, units=1024, activation=tf.nn.relu)\n dropout = tf.layers.dropout(\n inputs=dense, rate=0.4, training=is_training)\n logits = tf.layers.dense(inputs=dropout, units=10)\n with tf.name_scope('loss'):\n labels = tf.to_int64(labels)\n cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(\n labels=labels, logits=logits, name='xentropy')\n loss = tf.reduce_mean(cross_entropy, name='xentropy_mean')\n tf.summary.scalar('loss', loss)\n with tf.name_scope('accuracy'):\n correct = tf.nn.in_top_k(logits, labels, 1)\n n_correct = tf.to_float(tf.reduce_sum(tf.cast(correct, tf.int32)))\n accuracy = n_correct*100.0/tf.to_float(batch_size)\n tf.summary.scalar('accuracy', accuracy)\n return images, labels, is_training, logits, loss, accuracy\n\n\ndef main(argv=None):\n modelpath = \"/tmp/model.ckpt\"\n \n data_sets = input_data.read_data_sets(FLAGS.input_data_dir)\n g1 = tf.Graph()\n with g1.as_default():\n images, labels, is_training, logits, loss, acc = conv_network(\n FLAGS.batch_size)\n optimizer = tf.train.AdamOptimizer(FLAGS.learning_rate)\n global_step = tf.Variable(0, name='global_step', trainable=False)\n train_op = optimizer.minimize(loss, global_step=global_step)\n init = tf.global_variables_initializer()\n with tf.variable_scope('conv2d') as scope:\n scope.reuse_variables()\n kernel = tf.get_variable('kernel')\n k_min = tf.reduce_min(kernel)\n k_max = tf.reduce_max(kernel)\n I0 = (kernel - k_min) / (k_max - k_min)\n tf.summary.image('filters', tf.transpose(I0, [3, 0, 1, 2]),\n max_outputs=32)\n summary = tf.summary.merge_all()\n \n saver = tf.train.Saver() # included Saver\n \n sess = tf.Session()\n summary_writer = tf.summary.FileWriter('./logs/' + FLAGS.run,\n sess.graph) \n \n sess.run(init)\n\n for it in xrange(FLAGS.max_iter):\n image_b, label_b = data_sets.train.next_batch(FLAGS.batch_size)\n _, lv, av = sess.run([train_op, loss, acc],\n feed_dict={images: image_b,\n labels: label_b,\n is_training: True})\n if (it % 50 == 0):\n summary_str = sess.run(summary, feed_dict={images: image_b,\n labels: label_b,\n is_training: True})\n summary_writer.add_summary(summary_str, it)\n summary_writer.flush()\n if (it % 500 == 0):\n msg = 'Iteration {:5d}: loss is {:7.4f}, accuracy is {:6.2f}%'\n print(msg.format(it, lv, av))\n print('Training completed')\n \n save_path = saver.save(sess, modelpath) # Save parameters to disk\n print(\"Model saved in file: %s\" % save_path)\n \n g2 = tf.Graph()\n with g2.as_default():\n images, labels, is_training, logits, loss, acc = conv_network(\n FLAGS.batch_size)\n optimizer = tf.train.AdamOptimizer(FLAGS.learning_rate)\n global_step = tf.Variable(0, name='global_step', trainable=False)\n train_op = optimizer.minimize(loss, global_step=global_step)\n init = tf.global_variables_initializer()\n with tf.variable_scope('conv2d') as scope:\n scope.reuse_variables()\n kernel = tf.get_variable('kernel')\n k_min = tf.reduce_min(kernel)\n k_max = tf.reduce_max(kernel)\n I0 = (kernel - k_min) / (k_max - k_min)\n tf.summary.image('filters', tf.transpose(I0, [3, 0, 1, 2]),\n max_outputs=32)\n summary = tf.summary.merge_all()\n \n summary_writer = tf.summary.FileWriter('./logs/' + FLAGS.run,\n sess.graph)\n sess2 = tf.Session()\n sess2.run(init) \n saver = tf.train.Saver() # included Saver\n saver.restore(sess2, modelpath)\n\n \n \n \n avg_accuracy = 0.0\n n_evals = data_sets.test.num_examples // FLAGS.batch_size\n for i in xrange(n_evals):\n image_b, label_b = data_sets.test.next_batch(FLAGS.batch_size)\n _, lv, av = sess2.run([train_op, loss, acc],\n feed_dict={images: image_b,\n labels: label_b,\n is_training: False})\n avg_accuracy += av\n avg_accuracy /= n_evals\n print('Test accuracy is {:.2f}%'.format(avg_accuracy))\n\n\n \n\nif __name__ == '__main__':\n tf.app.run()\n","sub_path":"mnist_nn.py","file_name":"mnist_nn.py","file_ext":"py","file_size_in_byte":7014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"117969059","text":"from telegram.ext import Updater, MessageHandler, Filters\nfrom telegram.ext import CallbackContext, CommandHandler\nfrom telegram import ReplyKeyboardMarkup\nimport time\nimport random\n\nTOKEN = '1626176954:AAFdiHbSGPA8td6gFYQx_XI-Wb6pEwJAWcs'\n\nstart_keyboard = [['/dice', '/timer']]\nstart_markup = ReplyKeyboardMarkup(start_keyboard, one_time_keyboard=True)\n\nclose_keyboard = [['/close']]\nclose_markup = ReplyKeyboardMarkup(close_keyboard, one_time_keyboard=True)\n\n\ndef draw_one_dice():\n return str(random.randint(1, 6))\n\n\ndef draw_two_dices():\n return f\"{random.randint(1, 6)}, {random.randint(1, 6)}\"\n\n\ndef draw_big_dice():\n return str(random.randint(1, 20))\n\n\ntime_dict = {'30 секунд': 3, '1 минута': 60, '5 минут': 300}\ndice_dict = {'Кинуть один шестигранный кубик': draw_one_dice,\n 'Кинуть 2 шестигранных кубика одновременно': draw_two_dices,\n 'Кинуть 20-гранный кубик': draw_big_dice}\n\ndice_keyboard = list(dice_dict.keys())\ndice_keyboard.append('Вернуться назад')\ndice_keyboard = list(map(lambda x: [x], dice_keyboard))\ndice_markup = ReplyKeyboardMarkup(dice_keyboard, one_time_keyboard=False)\n\ntimer_keyboard = list(time_dict.keys())\ntimer_keyboard.append('Вернуться назад')\ntimer_keyboard = list(map(lambda x: [x], timer_keyboard))\ntimer_markup = ReplyKeyboardMarkup(timer_keyboard, one_time_keyboard=False)\n\n\ndef remove_job_if_exists(name, context):\n current_jobs = context.job_queue.get_jobs_by_name(name)\n if not current_jobs:\n return False\n for job in current_jobs:\n job.schedule_removal()\n return True\n\n\ndef start(update, context):\n update.message.reply_text(\n \"Я JustBot. Чем сегодня займётесь?\",\n reply_markup=start_markup\n )\n\n\ndef timer(update, context):\n update.message.reply_text(\n \"Хотите засечь время?\",\n reply_markup=timer_markup\n )\n\n\ndef dice(update, context):\n update.message.reply_text(\n \"Хотите кинуть кубик?\",\n reply_markup=dice_markup\n )\n\n\ndef close(update, context):\n chat_id = update.message.chat_id\n job_removed = remove_job_if_exists(\n str(chat_id),\n context\n )\n update.message.reply_text(\n \"Таймер сброшен. Хотите засечь время?\" if job_removed else 'Таймер не запущен.',\n reply_markup=timer_markup\n )\n\n\ndef set_my_timer(update, context, number, msg):\n chat_id = update.message.chat_id\n try:\n due = number\n if due < 0:\n update.message.reply_text(\n 'Извините, не умеем возвращаться в прошлое')\n return\n job_removed = remove_job_if_exists(\n str(chat_id),\n context\n )\n context.job_queue.run_once(\n task,\n due,\n context={'chat_id': chat_id, 'due': msg},\n name=str(chat_id)\n )\n text = f'Засек {msg}.'\n if job_removed:\n text += ' Старая задача удалена.'\n update.message.reply_text(text, reply_markup=close_markup)\n\n except (IndexError, ValueError):\n update.message.reply_text('Ошибка.')\n\n\ndef task(context):\n job = context.job\n context.bot.send_message(job.context['chat_id'], text=f'{job.context[\"due\"]} истекло')\n\n\ndef echo(update, context):\n text = update.message.text\n if text == 'Вернуться назад':\n start(update, context)\n return\n func = dice_dict.get(text)\n if func:\n update.message.reply_text(func())\n return\n number = time_dict.get(text)\n if number:\n set_my_timer(update, context, number, text)\n return\n update.message.reply_text(f'Я получил сообщение {text}')\n\n\ndef main():\n updater = Updater(TOKEN, use_context=True)\n dp = updater.dispatcher\n\n text_handler = MessageHandler(Filters.text, echo)\n dp.add_handler(CommandHandler(\"start\", start))\n dp.add_handler(CommandHandler(\"dice\", dice))\n dp.add_handler(CommandHandler(\"timer\", timer))\n dp.add_handler(CommandHandler(\"close\", close))\n\n dp.add_handler(text_handler)\n\n updater.start_polling()\n updater.idle()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"533846209","text":"from culqipy.resource import (\n Token,\n Charge,\n Plan,\n Subscription,\n Refund,\n Iins,\n Card,\n Event,\n Customer,\n Transfer,\n)\nfrom culqipy.utils import Util\n\n# Configuration variables.\nAPI_TOKEN = 'https://secure.culqi.com/v2'\nAPI_URL = \"https://api.culqi.com/v2\"\npublic_key = None\nsecret_key = None\n","sub_path":"culqipy/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"336567581","text":"#!/usr/bin/python3\n\"\"\"\nLists all City objects from the database hbtn_0e_101_usa\nArguments:\n mysql_usr - username to connect the mySQL\n mysql psw - password to connect the mySQL\n db_name - Name of the database\n\"\"\"\n\n\nfrom sys import argv\nfrom relationship_state import Base, State\nfrom relationship_city import City\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy import create_engine\n\nif __name__ == \"__main__\":\n mysql_usr = argv[1]\n mysql_pswd = argv[2]\n db_name = argv[3]\n\n engine = create_engine('mysql+mysqldb://{}:{}@localhost:3306/{}'\n .format(mysql_usr, mysql_pswd, db_name),\n pool_pre_ping=True)\n Base.metadata.create_all(engine)\n Session = sessionmaker(bind=engine)\n session = Session()\n my_cities = session.query(City).order_by(City.id)\n for city in my_cities:\n print(\"{}: {} -> {}\".format(city.id, city.name, city.state.name))\n","sub_path":"0x0F-python-object_relational_mapping/102-relationship_cities_states_list.py","file_name":"102-relationship_cities_states_list.py","file_ext":"py","file_size_in_byte":940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"510769667","text":"from django.urls import path\nfrom . import views\n\n\n\nurlpatterns = [\n path('', views.PodcastDetailView.as_view(), name=\"podcast_index\"),\n path('inspect_xml', views.InspectXML.as_view(), name='xml_form'),\n path('inspect_url', views.InspectURL.as_view(), name='url_form'),\n path('submit', views.RSSFormSubmit.as_view(), name='submit_form'),\n path('get_episodes', views.EpisodeList.as_view(), name = 'episodeList'),\n path('search', views.SearchPodcasts.as_view(), name='search'),\n path('get_popular', views.PopularPodcasts.as_view(), name='popular'),\n path('get_categories', views.GetCategories.as_view(), name='get_categories'),\n path('podcast_by_genre',views.PodcastByGenre.as_view(), name='podcast_by_genre'),\n path('episode_detail/',views.EpisodeDetailView.as_view(), name='episode_detail' )\n]","sub_path":"podcasts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"283248916","text":"import json\r\n\r\ndata = []\r\ndata2 = []\r\ndata3 = []\r\ncount2 = []\r\nctr = 0\r\nstr1 = ''\r\ndata2flag = 0\r\nwith open('yelp_academic_dataset_review.json') as f:\r\n for line in f:\r\n data = json.loads(line)\r\n str1 = data['business_id']\r\n for i in range(0, len(data2) - 1):\r\n if data2[i] == str1:\r\n count2[i] += 1\r\n data2flag = 1\r\n if 0 == data2flag:\r\n data2.append(str1)\r\n count2.append(1)\r\n data2flag = 0\r\nf.close()\r\nprint(len(data2))\r\ntarget = open('business_reviews.txt', 'w')\r\nfor i in range(0, len(data2) - 1):\r\n target.write(data2[i])\r\n target.write(\"\\t\")\r\n target.write(str(count2[i]))\r\n target.write(\"\\n\")\r\ntarget.close()\r\n","sub_path":"python/readjson.py","file_name":"readjson.py","file_ext":"py","file_size_in_byte":731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"349523301","text":"import random\r\nosnavateli=('Ларри Пейдж','Сергей Брин')\r\nosnavatel=random.randint(0,1)\r\nrand=osnavateli[osnavatel]\r\nochki=100\r\nprint(\"Я загадал одного из оснавателей Google(а также желание о том,чтобы получить...не скажу, а то не сбудется)\")\r\notvet=0\r\nwhile (otvet)!=(rand):\r\n\totvet=input(\"Введите имя одного из основателей:\")\r\n\tif (otvet)!=(rand):\r\n\t\tprint (\"Вы не угадали. Попробуйте снова.\")\r\n\t\tochki/=2\r\n\telif (otvet)==(rand):\r\n\t\tprint (\"Вы угадали.\")\r\n\t\tprint (\"Ваши баллы:\"+str(ochki))\r\n\t\tbreak\r\n\r\ninput(\"Нажмите Enter для выхода.\")\r\n","sub_path":"PMIa/2014/Demoshenkov_G_G/8.py","file_name":"8.py","file_ext":"py","file_size_in_byte":726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"179040464","text":"\"\"\"\nText bucket trainer script\nProject RGR104\nCopyRight (C) 2016 StarColon Projects.\n\"\"\"\n\nimport sys\nfrom termcolor import colored\nfrom pprint import pprint\nfrom pyrgr import pyrgr as RGR\n\n# Prepare arguments\n\nisVerbose = True if 'v' in sys.argv else False\n\ndef get_train_path():\n\treturn './data/train/*.csv'\n\ndef get_test_path():\n\treturn './data/test/*.csv'\n\ndef get_pattern_path():\n\treturn './model/pattern'\n\nif __name__ == '__main__':\n\tprint(colored('••••••••••••••••••','cyan'))\n\tprint(colored(' RGR104 Trainer ','cyan'))\n\tprint(colored('••••••••••••••••••','cyan'))\n\n\tprint(colored('ꁘꁘꁘꁘ---- Loading training data','cyan'))\n\ttrain_data = RGR.load_train_sets(get_train_path(), RGR.vectorize, isVerbose=isVerbose)\n\n\tprint(colored('ꁘꁘꁘꁘ---- Generating sentence pattern tree','cyan'))\n\ttree = RGR.generate_pattern_tree(train_data,isVerbose=isVerbose)\n\tRGR.visualize_pattern_tree(tree)\n\t###RGR.print_pattern_tree(tree)\n\n\tprint(colored('ꁘꁘꁘꁘ---- Analyzing the generated tree','cyan'))\n\tRGR.analyze_pattern_tree(tree)\n\n\tprint(colored('ꁘꁘꁘꁘ---- Saving sentence pattern tree', 'cyan'))\n\tRGR.save_pattern_tree(tree,get_pattern_path())\n\n\tprint(colored('ꁘꁘꁘꁘ---- Testing the pattern tree','cyan'))\n\tprint('Self validation...')\n\tvalidation_train = RGR.examine_test_set(tree, get_train_path(), isVerbose=isVerbose)\n\tprint('Cross validation...')\t\n\tvalidation_test = RGR.examine_test_set(tree, get_test_path(), isVerbose=isVerbose)\n\n\tprint(colored('ꁘꁘꁘꁘ---- Finishing jobs','cyan'))\n\tpass","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":1597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"261955527","text":"__author__ = 'Andreas Iakobou'\n__version__ = '2.0.0'\n\nimport os\nfrom datetime import date\nfrom datetime import timedelta\nimport shutil\nimport openpyxl\nfrom .calweek import calweek\nfrom .planning import planning\nfrom .read_data import read_eBas\nfrom .copyxlsx import copyx\nfrom .writexlsx import prepare_excel\n\n\n\ndef wochenplanung(PrüffeldVar = '', yearVar = 0, KWVar=0, fileVar=''):\n\t\n\t#In Version 2.0 for GUI, the steps for creating file and KW are no longer required but are kept if Wochenplanung is run as __main__ \n\tif yearVar == 0:\n\t\tP = input('Prüffeld: ')\n\t\tif P in ['e', 'E', 'eetz', 'EETZ']:\n\t\t\tPrüffeld = 'EETZ'\n\t\telse:\n\t\t\tPrüffeld = 'UPZ'\n\t\t\n\t\twhile True:\n\t\t\tKWstr = input('Bitte KW eingeben: ')\n\t\t\tyearstr = input('Jahr eingeben: ')\n\t\t\t\n\t\t\ttry:\n\t\t\t\tassert len(yearstr) == 4\n\t\t\t\tKW = int(KWstr)\n\t\t\t\tyear = int(yearstr)\n\t\t\t\tbreak\n\t\t\texcept AssertionError as e:\n\t\t\t\te.args += ('Ungültige Jahreszahl', yearstr)\n\t\t\t\traise\n\t\t\texcept:\n\t\t\t\tprint('Falsches Format bei KW oder Jahr')\n\t\t\n\t\twhile True:\n\t\t\tfilename = input('Dateiname eingeben: ')\n\t\t\tfile = r'..\\{}'.format(filename)\n\t\t\tif os.path.isfile(file):\n\t\t\t\tbreak\n\t\t\telse:\n\t\t\t\tprint('Datei nicht gefunden. Erneut eingeben.\\n')\n\telse:\n\t\tPrüffeld = PrüffeldVar.get()\n\t\tyear = yearVar.get()\n\t\tKW = KWVar.get()\n\t\tfile = fileVar\n\t\n\t#Copy Excel Template and create new File\n\tfname = copyx(Prüffeld,KW)\n\t\n\t# Get Monday for current CW\n\tmonday = date.fromisocalendar(year, KW, 1)\n\n\t# Open workbook\n\tworkbook = openpyxl.load_workbook(fname)\n\tsheet = workbook.active\n\t\n\t# Update Excel with current date\n\tprepare_excel(monday, workbook, sheet, Prüffeld, KW, year)\n\n\t# Read the AKF data from eBas Export\n\takfs = read_eBas(file, Prüffeld)\n\n\t#Call planning function\n\tplanning(workbook, sheet, monday, akfs, Prüffeld)\n\n\tworkbook.save(fname)\n\tworkbook.close()\n\tshutil.move(fname, \"..\\{}\".format(fname))\n\n\t\nif __name__ == '__main__':\n wochenplanung()\n\n\n","sub_path":"app/files/wochenplanung.py","file_name":"wochenplanung.py","file_ext":"py","file_size_in_byte":1906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"65468564","text":"import logging\n\nfrom django.test import TestCase\n\nfrom eth_account import Account\nfrom hexbytes import HexBytes\n\nfrom ..multi_send import MultiSendOperation, MultiSendTx\nfrom .safe_test_case import SafeTestCaseMixin\n\nlogger = logging.getLogger(__name__)\n\n\nclass TestMultiSend(SafeTestCaseMixin, TestCase):\n def test_multi_send_tx_from_bytes(self):\n operation = MultiSendOperation.DELEGATE_CALL\n address = Account.create().address\n value = 876\n data = HexBytes('0x123456789a')\n multi_send_tx = MultiSendTx(operation, address, value, data)\n new_multi_send_tx = MultiSendTx.from_bytes(multi_send_tx.encoded_data)\n\n self.assertEqual(new_multi_send_tx, multi_send_tx)\n self.assertEqual(new_multi_send_tx.operation, operation)\n self.assertEqual(new_multi_send_tx.address, address)\n self.assertEqual(new_multi_send_tx.value, value)\n self.assertEqual(new_multi_send_tx.data, data)\n","sub_path":"gnosis/safe/tests/test_multi_send.py","file_name":"test_multi_send.py","file_ext":"py","file_size_in_byte":953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"323960838","text":"import json\nfrom datetime import datetime\nimport dateutil.parser as dparser\nimport matplotlib.pyplot as plt\n\nimport csv\n\n# Remove duplicates\ndef remove_dup_list_dic(test_list):\n # remove duplicates\n # seen = set()\n # new_filter_cleaned_data = []\n # for each in filter_cleaned_data:\n # tup = tuple(each.items())\n # if tup not in seen:\n # seen.add(tup)\n # new_filter_cleaned_data.append(each)\n res_list = [] \n for i in range(len(test_list)): \n if test_list[i] not in test_list[i + 1:]: \n res_list.append(test_list[i])\n\n return res_list\n\ndef export_csv(filter_cleaned_data,csv_file):\n \n final_data = remove_dup_list_dic(filter_cleaned_data)\n \n # csv_columns = ['platform','key','name', 'rating', 'user_numbers', 'creator', 'last_updated', 'reviews']\n csv_columns = ['platform', 'id', 'key','name', 'rating', 'user_numbers', 'creator', 'last_updated']\n\n with open(csv_file, 'w') as csvfile:\n writer = csv.DictWriter(csvfile, fieldnames=csv_columns)\n writer.writeheader()\n for data in final_data:\n writer.writerow(data)\n\ndef processing(input_file):\n data = []\n last_seven_months = [0, 0, 0, 0, 0, 0, 0]\n\n with open(input_file) as json_file:\n data_dict = json.load(json_file)\n\n # Removing duplicates\n clean_data = remove_dup_list_dic(data_dict)\n\n\n for p in clean_data:\n\n date_type = dparser.parse(p[\"last_updated\"],fuzzy=True)\n # 2020\n if (date_type.year == 2020):\n data.append(p)\n # Jan\n if (date_type.month == 1):\n last_seven_months[0] = last_seven_months[0] + 1\n # Feb\n elif (date_type.month == 2):\n last_seven_months[1] = last_seven_months[1] + 1\n # Mar\n elif (date_type.month == 3):\n last_seven_months[2] = last_seven_months[2] + 1\n # April\n elif (date_type.month == 4):\n last_seven_months[3] = last_seven_months[3] + 1\n # May\n elif (date_type.month == 5):\n last_seven_months[4] = last_seven_months[4] + 1\n # June\n elif (date_type.month == 6):\n last_seven_months[5] = last_seven_months[5] + 1\n # July\n elif (date_type.month == 7):\n last_seven_months[6] = last_seven_months[6] + 1\n \n # for total in last_seven_months:\n # print(total)\n\n y_units = last_seven_months\n\n result = [y_units, data]\n return result\n\n\n\n\nx_units = [1, 2, 3, 4, 5, 6, 7]\n# y_1 = processing(\"cleaned_data.json\")\n\ny_1 = processing(\"chrome_cleaned_data.json\")\n# export csv\n# export_csv(y_1[1],\"cleaned_seven_months_data.csv\")\nexport_csv(y_1[1],\"cleaned_seven_months_data_chrome.csv\")\n\n\n# y_2 = processing(\"combined.json\")\ny_2 = processing(\"chrome_ext_data.json\")\n\n\nf = plt.figure(1)\n# two figure\n# fig, (ax1, ax2) = plt.subplots(1, 2)\n\nplt.subplot(211)\n\nmonths_label = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'July']\n\nplt.bar(x_units, y_1[0], tick_label=months_label,\n width=0.8, color=['red', 'green', 'blue', 'orange', 'purple', 'brown', 'pink'])\n # print(date_type.year)\n# plt.xlabel('Last 7 months')\n# plt.ylabel('The number of \"potentially malicious\" browser extensions')\nplt.title('Cleaning up')\n# plt.suptitle('Comparision between before (left) and after (right) cleaning up ')\nplt.subplot(212)\nplt.bar(x_units, y_2[0], tick_label=months_label,\n width=0.8, color=['red', 'green', 'blue', 'orange', 'purple', 'brown', 'pink'])\nplt.title('without cleaning up')\n# plt.suptitle('Comparision between before (left) and after (right) cleaning up ')\n\n# plt.suptitle('Comparision between before (left) and after (right) cleaning up ')\n\n# ax1.plot(x_units, y_units)\nplt.show()\n # print(data_dict[0])\n","sub_path":"data_analysis/removes_and_plotting.py","file_name":"removes_and_plotting.py","file_ext":"py","file_size_in_byte":3982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"445796452","text":"import io\nimport os\nfrom google.cloud import vision\n\nos.environ[\"GOOGLE_APPLICATION_CREDENTIALS\"] = \"emapped-8b4be6305e9a.json\"\n\nclient = vision.ImageAnnotatorClient()\nfile_name = os.path.abspath('image.jpeg')\n\nwith io.open(file_name, 'rb') as image_file:\n content = image_file.read()\n\nimage = vision.Image(content=content)\n\n# Performs label detection on the image file\nresponse = client.label_detection(image=image)\nlabels = response.label_annotations\n\ntags = []\nfor label in labels:\n tags.append(str(label.description))\n\nprint(tags)\n\n# Performs face detection on the image file\nresponse = client.face_detection(image=image)\nfaces = response.face_annotations\n\nlikelihood_name = ('UNKNOWN', 'VERY_UNLIKELY', 'UNLIKELY', 'POSSIBLE', 'LIKELY', 'VERY_LIKELY')\n\nmoods = []\n\nfor face in faces:\n\tmood = []\n\tmood.append('Joy')\n\tmood.append(likelihood_name.index(likelihood_name[face.joy_likelihood]))\n\tmoods.append(mood)\n\n\tmood = []\n\tmood.append('Sorrow')\n\tmood.append(likelihood_name.index(likelihood_name[face.sorrow_likelihood]))\n\tmoods.append(mood)\n\n\tmood = []\n\tmood.append('Anger')\n\tmood.append(likelihood_name.index(likelihood_name[face.anger_likelihood]))\n\tmoods.append(mood)\n\n\tmood = []\n\tmood.append('Surprise')\n\tmood.append(likelihood_name.index(likelihood_name[face.surprise_likelihood]))\n\tmoods.append(mood)\n\nprint(moods)\n\n","sub_path":"vision.py","file_name":"vision.py","file_ext":"py","file_size_in_byte":1333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"441286292","text":"import pandas as pd\nimport collections\n\nimport sklearn.model_selection\n\n\nclass Split:\n\n def __init__(self, splitting: collections.namedtuple):\n \"\"\"\n\n :param splitting: A collection of named parameters, and their values, for\n the sklearn.model_selection.train_test_split() function\n \"\"\"\n\n self.splitting = splitting\n\n def exc(self, data: pd.DataFrame, target: list, strata: list) -> (pd.DataFrame, pd.DataFrame):\n \"\"\"\n\n :param data:\n :param target:\n :param strata:\n :return:\n \"\"\"\n\n x_train, x_test, y_train, y_test = sklearn.model_selection.train_test_split(\n data.drop(columns=target),\n data[target],\n test_size=self.splitting.test_size,\n random_state=self.splitting.random_state,\n stratify=data[strata])\n\n training = pd.concat((x_train.reset_index(drop=True), y_train.reset_index(drop=True)), axis=1,\n ignore_index=False)\n testing = pd.concat((x_test.reset_index(drop=True), y_test.reset_index(drop=True)), axis=1,\n ignore_index=False)\n\n return training, testing\n","sub_path":"beans/functions/split.py","file_name":"split.py","file_ext":"py","file_size_in_byte":1202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"215566477","text":"\"\"\"created sentmail table\n\nRevision ID: 157ae5e82dcb\nRevises: da5ef4256d98\nCreate Date: 2019-03-29 18:27:59.846874\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '157ae5e82dcb'\ndown_revision = 'da5ef4256d98'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('sentmails',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('email_user', sa.String(length=64), nullable=True),\n sa.Column('subject', sa.String(length=200), nullable=True),\n sa.Column('body', sa.String(length=2000), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_index(op.f('ix_sentmails_email_user'), 'sentmails', ['email_user'], unique=False)\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_index(op.f('ix_sentmails_email_user'), table_name='sentmails')\n op.drop_table('sentmails')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/157ae5e82dcb_created_sentmail_table.py","file_name":"157ae5e82dcb_created_sentmail_table.py","file_ext":"py","file_size_in_byte":1062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"12103556","text":"from via import app\nimport json\nfrom models import Link, db\n\n\ndef build_result(json_data=None, message=None, return_code=None):\n data = {}\n if json_data is not None:\n data['json'] = json_data\n if message is not None:\n data['message'] = message\n if return_code is not None:\n data['return_code'] = return_code\n return data\n\n\ndef add_link(link_url, short_url=None):\n if link_url is None:\n return build_result(message='\"link_url\" is missing', return_code=400)\n if len(link_url) > 550:\n return build_result(message='\"link_url\" length is greater then 550 characters', return_code=400)\n if short_url == \"\":\n short_url = None\n\n link = Link(link_url, short_url)\n db.session.add(link)\n db.session.commit()\n return build_result(link.as_dict(), return_code=201)\n\n\ndef modify_link(link_id, link_url=None, short_url=None):\n link = Link.query.get(link_id)\n if link is None:\n return build_result({}, return_code=404)\n if link_url:\n link.link_url = link_url\n if short_url:\n exists = Link.query.filter_by(short_url=short_url).first() is not None\n if exists:\n return build_result(message=\"'short_url' is already in use\", return_code=400)\n link.is_custom_url = link.short_url != short_url\n link.short_url = short_url\n # We are choosing to ignore changes to the is_custom_url column instead of returning an error\n\n db.session.commit()\n return build_result(link.as_dict(), return_code=200)\n\n\ndef delete_link(link_id):\n link = Link.query.get(link_id)\n if link is None:\n return build_result({}, return_code=404)\n db.session.delete(link)\n db.session.commit()\n return build_result({ 'id': link.id }, return_code=202)\n\n\ndef get_link(link_id=None, link_hash=None):\n if link_id is not None:\n link = Link.query.get(link_id)\n elif link_hash is not None:\n link = Link.query.filter_by(short_url=link_hash).first()\n else:\n return build_result({}, return_code=404)\n\n if link is None:\n return build_result({}, return_code=404)\n return build_result(link.as_dict())\n\n\ndef get_all_links():\n links = Link.query.all()\n data = {}\n data['num_results'] = len(links)\n link_list = []\n for link in links:\n link_list.append(link.as_dict())\n data['objects'] = link_list\n return build_result(data, return_code=200)\n","sub_path":"via/links_db.py","file_name":"links_db.py","file_ext":"py","file_size_in_byte":2410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"223283590","text":"from selenium import webdriver\nfrom bs4 import BeautifulSoup\nimport time\n\n\ndriver = webdriver.Chrome(executable_path=r\"D:\\Softwares\\chromedriver_win32\\chromedriver.exe\")\ndriver.get('https://djmag.com/top100djs')\n\n\nartists = []\n\ncontent = driver.page_source\nsoup = BeautifulSoup(content, 'html.parser')\nfor a in soup.findAll('div', attrs={'class': 'top100dj-name'}):\n artist = a.find('a')\n artists.append(artist.text)\n\nprint(*artists, sep='\\n')\n","sub_path":"SCRAPING/DJ_Mag_100.py","file_name":"DJ_Mag_100.py","file_ext":"py","file_size_in_byte":450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"466723058","text":"# -*- coding: utf-8 -*-\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nl = 0.5\nr = 1.5\nlw = 3\nx = np.linspace(l, r, 1000)\nf = lambda x: np.sin(x)\ny = f(x)\nplt.plot(x, y, color='black', linewidth=lw)\n# plt.text(1.05, 0.9, '$f(x)$')\n\n# secant\nb = (f(r) - f(l)) / (r - l)\ny = f(l) + b * (x - l)\nplt.plot(x, y, color='blue', linestyle=\"dotted\", linewidth=lw)\n# plt.text(1.4, 0.92, '$s$')\n\n# tangent\nf1 = lambda x: np.cos(x)\ny = f(l) + f1(l) * (x - l)\nplt.plot(x, y, color='orange', linestyle=\"dashed\", linewidth=lw)\n# plt.text(0.55, 0.9, '$t_l$')\n\ny = f(r) + f1(r) * (x - r)\nplt.plot(x, y, color='red', linestyle='dashed', linewidth=lw)\n# plt.text(1.4, 1.3, '$t_r$')\n\nplt.axes().get_xaxis().set_ticklabels([])\nplt.axes().get_yaxis().set_ticklabels([])\nplt.xlim(l, r)\nplt.savefig(\"tangent_secant_concave.pdf\", bbox_inches=\"tight\")\n","sub_path":"scripts/secant_tangent_concave.py","file_name":"secant_tangent_concave.py","file_ext":"py","file_size_in_byte":832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"255622662","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Sep 18 14:07:47 2020\r\n\r\n@author: Администратор\r\n\"\"\"\r\n\r\nimport numpy\r\n\r\n# y = w1x1+w2x2+w3x3*w4x4+w5x5\r\n\r\n\r\ndef cal_pop_fitness(equation_inputs, pop):\r\n fitness = list()\r\n for row in pop:\r\n pairs = [a * b for a, b in zip(row, equation_inputs)]\r\n funcResult = pairs[0] + pairs[1] + pairs[2] * pairs[3] + pairs[4]\r\n fitness.append(funcResult)\r\n return fitness\r\n\r\n\r\ndef select_mating_pool(pop, fitness, num_parents):\r\n # Selecting the best individuals in the current\r\n # generation as parents for producing the\r\n # offspring of the next generation.\r\n pop_shape = pop.shape[1]\r\n parents = numpy.empty((num_parents, pop_shape))\r\n for parent_num in range(num_parents):\r\n max_fitness_idx = numpy.where(fitness == numpy.max(fitness))\r\n max_fitness_idx = max_fitness_idx[0][0]\r\n parents[parent_num, :] = pop[max_fitness_idx, :]\r\n fitness[max_fitness_idx] = -99999999999\r\n return parents\r\n\r\n\r\ndef crossover(parents, offspring_size):\r\n offspring = numpy.empty(offspring_size)\r\n # The point at which crossover takes place between two parents. Usually it is at the center.\r\n parent1_idx = 0\r\n parent2_idx = 1\r\n for k in range(offspring_size[0]):\r\n crossover_point = numpy.random.randint(0,4)\r\n offspring[k, 0:crossover_point] = parents[parent1_idx, 0:crossover_point]\r\n offspring[k, crossover_point:] = parents[parent2_idx, crossover_point:]\r\n return offspring\r\n\r\n\r\ndef mutation(offspring_crossover):\r\n # Mutation changes a single gene in each offspring randomly.\r\n for idx in range(offspring_crossover.shape[0]):\r\n # The random value to be added to the gene.\r\n random_value = numpy.random.uniform(-4.0, 4.0, 1)\r\n offspring_crossover[idx, numpy.random.randint(0, 4)] = (\r\n offspring_crossover[idx, numpy.random.randint(0, 4)] + random_value\r\n )\r\n return offspring_crossover\r\n","sub_path":"Tasks/lab1_2/ga2.py","file_name":"ga2.py","file_ext":"py","file_size_in_byte":1987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"108258840","text":"# Copyright 2017 Mycroft AI, 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 mycroft.util\nfrom adapt.intent import IntentBuilder\nfrom mycroft.skills.core import MycroftSkill\nfrom mycroft.version import CORE_VERSION_STR\n\n\nclass VersionCheckerSkill(MycroftSkill):\n def __init__(self):\n super(VersionCheckerSkill, self).__init__(\"VersionCheckerSkill\")\n\n def initialize(self):\n intent = IntentBuilder('CheckVersion').require('Check') \\\n .require('Version').build()\n self.register_intent(intent, self.check_version)\n\n intent = IntentBuilder('CheckPlatformBuild').require('Check') \\\n .require('PlatformBuild')\n self.register_intent(intent, self.check_platform_build)\n\n def check_version(self, message):\n # Report the version of mycroft-core software\n self.enclosure.deactivate_mouth_events()\n self.enclosure.mouth_text(CORE_VERSION_STR)\n\n self.speak_dialog('version', data={'version': CORE_VERSION_STR})\n\n # NOTE: intentionally sticking with this deprecated API instead\n # of mycroft.audio.wait_while_speaking() so that this skill\n # works on 0.8.15+\n mycroft.util.wait_while_speaking()\n self.enclosure.activate_mouth_events()\n\n def check_platform_build(self, message):\n if 'platform_build' in self.config_core['enclosure']:\n # Report the platform build (aka firmware version)\n build = self.config_core['enclosure']['platform_build']\n self.enclosure.deactivate_mouth_events()\n self.enclosure.mouth_text(build)\n\n self.speak_dialog('platform.build', data={'build': build})\n\n mycroft.util.wait_while_speaking()\n self.enclosure.activate_mouth_events()\n else:\n self.speak_dialog('platform.build.none')\n\n def stop(self):\n pass\n\n\ndef create_skill():\n return VersionCheckerSkill()\n","sub_path":"__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"398412536","text":"import time\nimport urllib2\n\nfrom bs4 import BeautifulSoup\n\n\ndef get_specs(url):\n try:\n html_text = urllib2.urlopen(url).read()\n except urllib2.HTTPError:\n return \"specs not available\"\n\n soup = BeautifulSoup(html_text, 'html.parser')\n specs = soup.find_all('div', {'class': 'spec-details'})\n\n all_specs = list()\n [all_specs.append(spec.encode('utf-8')) for spec in specs]\n\n return ' '.join(all_specs)\n\n\ndef get_quick_specs(url):\n try:\n html_text = urllib2.urlopen(url).read()\n except urllib2.HTTPError:\n return \"quick specs not available\"\n\n soup = BeautifulSoup(html_text, 'html.parser')\n quick_specs = soup.find('p', {'class': 'specs'})\n\n # replace a tag with b make it bold\n bold = soup.new_tag('b')\n bold.string = quick_specs.a.text\n quick_specs.a.insert_before(bold)\n\n # remove a tags\n quick_specs.a.extract()\n\n return str(quick_specs)\n\n\ndef get_image_for_item(url):\n try:\n html_text = urllib2.urlopen(url).read()\n except urllib2.HTTPError:\n return \"image not available\"\n\n soup = BeautifulSoup(html_text, 'html.parser')\n image = soup.find('a', {'class': 'sku-image'})\n\n a = image['href']\n\n return 'http:'+a\n\n\nclass Model(object):\n db = None\n data_collection_name = None\n items_collection_name = None\n results_limit = 10\n\n def __init__(self, config, db):\n self.db = db\n self.data_collection_name = config['data_collection']\n self.items_collection_name = config['items_collection']\n self.specs_collection_name = config['specs_collection']\n self.config = config\n\n def add_new_item(self, item):\n for store in item['stores']:\n rec = {\n 'item_name': item['item_name'],\n }\n rec.update(store)\n self.db.mongodb[self.items_collection_name].insert(rec)\n\n if store['store_name'] == 'skroutz':\n skroutz_site_url = store['url']\n specs = {\n 'item_name': item['item_name'],\n 'specs': get_specs(skroutz_site_url),\n 'quick_specs': get_quick_specs(skroutz_site_url),\n 'image': get_image_for_item(skroutz_site_url)\n }\n self.db.mongodb[self.specs_collection_name].insert(specs)\n\n # specs = {\n # 'item_name': item['item_name'],\n # 'specs': get_specs('http://www.gsmarena.com/microsoft_lumia_950-7262.php')\n # }\n # self.db.mongodb['specs'].insert(specs)\n\n from price_crawler import PriceCrawler\n pc = PriceCrawler(self.config, self, item['item_name'])\n rec = {\n 'timestamp': time.time(),\n 'item_name': item['item_name'],\n }\n\n try:\n rec.update(pc.get_store_price(store['store_name']))\n self.add_record(rec)\n except TypeError:\n pass # no price for store\n\n def add_record(self, record):\n self.db.mongodb[self.data_collection_name].insert(record)\n\n def get_all(self):\n return self.db.mongodb[self.data_collection_name].find()\n\n def get_all_items(self):\n return self.db.mongodb[self.items_collection_name]\\\n .distinct('item_name')\n\n def get_all_stores(self):\n return self.db.mongodb[self.items_collection_name]\\\n .distinct('store_name')\n\n def get_all_for_store(self, store):\n mongo_filter = {\n 'store_name': store,\n }\n mongo_projection = {\n 'store_name': 1,\n 'item_name': 1,\n 'timestamp': 1,\n 'price': 1,\n '_id': 0\n }\n\n result = self.db.mongodb[self.data_collection_name]\\\n .find(mongo_filter, mongo_projection)\\\n .sort([('timestamp', -1)])\\\n .limit(self.results_limit)\n\n return_list = list(result)\n return_list.reverse()\n return return_list\n\n def get_item_for_all_stores(self, item):\n mongo_filter = {\n 'item_name': item,\n }\n mongo_projection = {\n 'store_name': 1,\n 'item_name': 1,\n 'timestamp': 1,\n 'price': 1,\n '_id': 0\n }\n\n result = self.db.mongodb[self.data_collection_name]\\\n .find(mongo_filter, mongo_projection)\\\n .sort([('timestamp', -1)])\\\n .limit(self.results_limit)\n\n return_list = list(result)\n return_list.reverse()\n return return_list\n\n def get_item_for_store(self, item, store):\n mongo_filter = {\n 'store_name': store,\n 'item_name': item\n }\n mongo_projection = {\n 'price': 1,\n '_id': 0\n }\n\n result = self.db.mongodb[self.data_collection_name]\\\n .find(mongo_filter, mongo_projection)\\\n .sort([('timestamp', -1)])\\\n .limit(self.results_limit)\n\n return_list = list(result)\n return_list.reverse()\n return return_list\n\n def get_timestamps_for_item(self, item):\n mongo_filter = {\n 'item_name': item,\n 'store_name': 'skroutz',\n }\n mongo_projection = {\n 'timestamp': 1,\n '_id': 0\n }\n return_list = list()\n mongo_response = self.db.mongodb[self.data_collection_name]\\\n .find(mongo_filter, mongo_projection)\\\n .sort([('timestamp', -1)])\\\n .limit(self.results_limit)\n\n for item in mongo_response:\n return_list.append(item['timestamp'])\n\n return_list.reverse()\n return return_list\n\n def get_url_for_item(self, item, store):\n\n mongo_filter = {\n 'item_name': item,\n 'store_name': store,\n }\n mongo_projection = {\n 'url': 1,\n '_id': 0\n }\n\n return self.db.mongodb[self.items_collection_name]\\\n .find(mongo_filter, mongo_projection).next()\n\n def get_stores_for_item(self, item):\n mongo_filter = {\n 'item_name': item\n }\n mongo_projection = {\n 'store_name': 1,\n '_id': 0\n }\n\n result = self.db.mongodb[self.items_collection_name]\\\n .find(mongo_filter, mongo_projection)\n\n return_list = list()\n\n for item in result:\n return_list.append(item['store_name'])\n\n return return_list\n\n def maintenance(self):\n now = time.time()\n delta = self.config['keep_data_for']\n delete_from = now - delta\n\n mongo_filter = {\n 'timestamp': {'$lte': delete_from}\n }\n\n result = self.db.mongodb[self.data_collection_name]\\\n .delete_many(mongo_filter)\n\n return \"deleted {} records\".format(result)\n\n def get_specs(self, item):\n mongo_filter = {\n 'item_name': item,\n }\n mongo_projection = {\n 'specs': 1,\n '_id': 0\n }\n\n try:\n res = self.db.mongodb[self.specs_collection_name]\\\n .find(mongo_filter, mongo_projection).next()\n\n return res['specs']\n except Exception:\n return \"specs not available\"\n\n def get_quick_specs(self, item):\n mongo_filter = {\n 'item_name': item,\n }\n mongo_projection = {\n 'quick_specs': 1,\n '_id': 0\n }\n\n try:\n res = self.db.mongodb[self.specs_collection_name]\\\n .find(mongo_filter, mongo_projection).next()\n\n return res['quick_specs']\n except Exception:\n return \"quick specs not available\"\n\n def get_image(self, item):\n mongo_filter = {\n 'item_name': item,\n }\n mongo_projection = {\n 'image': 1,\n '_id': 0\n }\n\n try:\n res = self.db.mongodb[self.specs_collection_name]\\\n .find(mongo_filter, mongo_projection).next()\n\n return res['image']\n except Exception:\n return \"quick specs not available\"\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":8201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"482442061","text":"# -*- coding: utf-8 -*-\n# @Time : 2018/9/4 2:34 PM\n# @Author : ZHAOBOWEN467@pingan.com.cn\n# @File : modelEvaluator.py\n# @Software: PyCharm\n# @desc:\n\nimport numpy as np\nfrom sklearn.metrics import f1_score, precision_score, recall_score\n\n\nclass Evaluator(object):\n \"\"\" 模型评估\n Attributes:\n model: 待评估的模型\n \"\"\"\n\n def __init__(self,model):\n self.model = model\n\n def basicEvaluator(self,feed_dict,test_label):\n \"\"\" 模型测试集的acc,f1,recall\n\n Args:\n feed_dict: evaluate数据的自变量\n test_label: evaluate数据标签\n Return:\n \"\"\"\n\n test_probs = self.model.predict(feed_dict)\n test_pred = np.argmax(test_probs, axis=1)\n\n f1 = f1_score(test_pred, test_label)\n r1 = recall_score(test_pred, test_label)\n acc = precision_score(test_pred, test_label)\n\n print('f1:{first} ****** precision:{second} ******recall:{third}'.format(first=f1, second=acc, third=r1))\n","sub_path":"src/util/modelEvaluator.py","file_name":"modelEvaluator.py","file_ext":"py","file_size_in_byte":1000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"147081295","text":"# -*- coding: utf-8 -*-\n# RFC 2822 - style email validation for Python\n# (c) 2012 Syrus Akbary \n# Extended from (c) 2011 Noel Bush \n# for support of mx and user check\n# This code is made available to you under the GNU LGPL v3.\n#\n# This module provides a single method, valid_email_address(),\n# which returns True or False to indicate whether a given address\n# is valid according to the 'addr-spec' part of the specification\n# given in RFC 2822. Ideally, we would like to find this\n# in some other library, already thoroughly tested and well-\n# maintained. The standard Python library email.utils\n# contains a parse_addr() function, but it is not sufficient\n# to detect many malformed addresses.\n#\n# This implementation aims to be faithful to the RFC, with the\n# exception of a circular definition (see comments below), and\n# with the omission of the pattern components marked as \"obsolete\".\n\nimport re\nimport smtplib\n\ntry:\n import DNS\n ServerError = DNS.ServerError\nexcept:\n DNS = None\n\n class ServerError(Exception):\n pass\n# All we are really doing is comparing the input string to one\n# gigantic regular expression. But building that regexp, and\n# ensuring its correctness, is made much easier by assembling it\n# from the \"tokens\" defined by the RFC. Each of these tokens is\n# tested in the accompanying unit test file.\n#\n# The section of RFC 2822 from which each pattern component is\n# derived is given in an accompanying comment.\n#\n# (To make things simple, every string below is given as 'raw',\n# even when it's not strictly necessary. This way we don't forget\n# when it is necessary.)\n#\nWSP = r'[ \\t]'\nCRLF = r'(?:\\r\\n)'\nNO_WS_CTL = r'\\x01-\\x08\\x0b\\x0c\\x0f-\\x1f\\x7f'\nQUOTED_PAIR = r'(?:\\\\.)'\nFWS = r'(?:(?:{0}*{1})?{0}+)'.format(WSP, CRLF)\nCTEXT = r'[{0}\\x21-\\x27\\x2a-\\x5b\\x5d-\\x7e]'.format(NO_WS_CTL)\nCCONTENT = r'(?:{0}|{1})'.format(CTEXT, QUOTED_PAIR)\nCOMMENT = r'\\((?:{0}?{1})*{0}?\\)'.format(FWS, CCONTENT)\nCFWS = r'(?:{0}?{1})*(?:{0}?{1}|{0})'.format(FWS, COMMENT)\nATEXT = r'[\\w!#$%&\\'\\*\\+\\-/=\\?\\^`\\{\\|\\}~]'\nATOM = r'{0}?{1}+{0}?'.format(CFWS, ATEXT)\nDOT_ATOM_TEXT = r'{0}+(?:\\.{0}+)*'.format(ATEXT)\nDOT_ATOM = r'{0}?{1}{0}?'.format(CFWS, DOT_ATOM_TEXT)\nQTEXT = r'[{0}\\x21\\x23-\\x5b\\x5d-\\x7e]'.format(NO_WS_CTL)\nQCONTENT = r'(?:{0}|{1})'.format(QTEXT, QUOTED_PAIR)\nQUOTED_STRING = r'{0}?\"(?:{1}?{2})*{1}?\"{0}?'.format(CFWS, FWS, QCONTENT)\nLOCAL_PART = r'(?:{0}|{1})'.format(DOT_ATOM, QUOTED_STRING)\nDTEXT = r'[{0}\\x21-\\x5a\\x5e-\\x7e]'.format(NO_WS_CTL)\nDCONTENT = r'(?:{0}|{1})'.format(DTEXT, QUOTED_PAIR)\nDOMAIN_LITERAL = r'{0}?\\[(?:{1}?{2})*{1}?\\]{0}?'.format(CFWS, FWS, DCONTENT)\nDOMAIN = r'(?:{0}|{1})'.format(DOT_ATOM, DOMAIN_LITERAL)\nADDR_SPEC = r'{0}@{1}'.format(LOCAL_PART, DOMAIN)\nVALID_ADDRESS_REGEXP = '^' + ADDR_SPEC + '$'\n\n\ndef validate_email(email, check_mx=False, verify=False):\n \"\"\"Indicate whether the given string is a valid email address\n according to the 'addr-spec' portion of RFC 2822 (see section\n 3.4.1). Parts of the spec that are marked obsolete are *not*\n included in this test, and certain arcane constructions that\n depend on circular definitions in the spec may not pass, but in\n general this should correctly identify any email address likely\n to be in use as of 2011.\"\"\"\n try:\n assert re.match(VALID_ADDRESS_REGEXP, email) is not None\n check_mx |= verify\n if check_mx:\n if not DNS:\n raise Exception('For check the mx records or check if the '\n 'email exists you must have installed pyDNS '\n 'python package')\n DNS.DiscoverNameServers()\n hostname = email[email.find('@') + 1:]\n mx_hosts = DNS.mxlookup(hostname)\n for mx in mx_hosts:\n try:\n smtp = smtplib.SMTP()\n smtp.connect(mx[1])\n if not verify:\n return True\n status, _ = smtp.helo()\n if status != 250:\n continue\n smtp.mail('')\n status, _ = smtp.rcpt(email)\n if status != 250:\n return False\n break\n # Server not permits verify user\n except smtplib.SMTPServerDisconnected:\n break\n except smtplib.SMTPConnectError:\n continue\n except (AssertionError, ServerError):\n return False\n return True\n","sub_path":"base_partner_merge/validate_email.py","file_name":"validate_email.py","file_ext":"py","file_size_in_byte":4573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"198303413","text":"#!/usr/bin/python\n\n\"\"\"\nhtml_writer.py - Construct HTML pages\n\n\"\"\"\n\nimport datetime\nimport os\nimport types\nimport numpy as np\nimport xml.dom.minidom\nimport codecs\n\ndef _mkdir(newdir):\n \"\"\"works the way a good mkdir should :)\n - already exists, silently complete\n - regular file in the way, raise an exception\n - parent directory(ies) does not exist, make them as well\n \"\"\"\n if os.path.isdir(newdir):\n pass\n elif os.path.isfile(newdir):\n raise OSError(\"a file with the same name as the desired \" \\\n \"dir, '%s', already exists.\" % newdir)\n else:\n head, tail = os.path.split(newdir)\n if head and not os.path.isdir(head):\n _mkdir(head)\n if tail:\n os.mkdir(newdir)\n \nclass BaseHtmlWriter:\n def __init__(self):\n self.div_counter = 0\n pass\n\n def relative_to_full_path(self, relpath):\n raise Exception(\"class not implemented\")\n\n def write(self, s):\n raise Exception(\"class not implemented\")\n\n def write_header(self):\n self.write('\\n')\n self.write('\\n')\n self.write('\\n')\n self.write('\\n')\n self.write('\\n\\n')\n \n now = datetime.datetime.now()\n self.write('
Written at %s
' % now)\n \n def write_js(self, path):\n if os.path.exists(path + '/expandCollapse.js'):\n return\n fp = open(path + '/expandCollapse.js', 'w')\n fp.write(\"\"\"function toggleMe(a){\n var e=document.getElementById(a);\n if(!e)return true;\n if(e.style.display==\"none\"){\n e.style.display=\"block\"\n } else {\n e.style.display=\"none\"\n }\n return true;\n}\n\"\"\")\n fp.close()\n \n def write_ol(self, l):\n self.write(\"
    \\n\")\n for mem in l:\n self.write(\"
  1. %s
  2. \\n\" % str(mem))\n self.write(\"
\\n\")\n \n def write_ul(self, l):\n self.write(\"
    \\n\")\n for mem in l:\n self.write(\"
  • %s
  • \\n\" % str(mem))\n self.write(\"
\\n\")\n \n def write_table(self, rowdicts, headers=None, border=1, decimal=None):\n \"\"\"\n In order to print the row number, use the title '#' in headers and\n write_table() will automatically fill that column with the row numbers.\n \"\"\"\n def to_string(x, decimal=None):\n if type(x) == types.StringType:\n return x\n\n if type(x) in (types.IntType, np.int16, np.int32, np.int64):\n return '%d' % x\n\n if type(x) in (types.FloatType, np.float32, np.float64):\n if np.isnan(x):\n return 'N/A'\n if decimal is not None:\n return eval(\"'%%.%df' %% x\" % decimal)\n return \"%g\" % x\n \n return str(x)\n \n if not headers:\n headers = set()\n for rowdict in rowdicts:\n for key in rowdict.keys():\n headers.add(to_string(key))\n headers = sorted(headers)\n \n self.write('\\n' % border)\n self.write('\\n')\n for i, rowdict in enumerate(rowdicts):\n rowdict['#'] = '%d' % i\n values = [to_string(rowdict.get(key, \"\"), decimal) for key in headers]\n self.write('\\n')\n self.write(\"
' + ''.join(headers) + '
' + ''.join(values) + '
\\n\")\n \n def table_start(self, border=1):\n self.write('\\n' % border)\n\n def table_writerow(self, values):\n self.write('\\n')\n \n def table_end(self):\n self.write(\"
' + ''.join(values) + '
\\n\")\n \n def insert_toggle(self, div_id=None, start_here=False, label='Show'):\n if not div_id:\n div_id = \"DIV%05d\" % self.div_counter\n self.div_counter += 1\n elif type(div_id) != types.StringType:\n raise ValueError(\"HTML div ID must be a string\")\n self.write('\\n'\n % (div_id, label))\n if start_here:\n self.div_start(div_id)\n return div_id\n \n def div_start(self, div_id):\n self.write('
' % div_id)\n \n def div_end(self):\n self.write('
\\n')\n \n def embed_img(self, fig_fname, alternative_string=\"\"):\n self.write('')\n \n def embed_svg(self, fig_fname, width=320, height=240, name=''):\n self.write('
' % name)\n self.extract_svg_from_file(fig_fname, width=width, height=height)\n self.write('')\n\n #self.write(''\n # % (fig_fname, width, height, name))\n \n def embed_matplotlib_figure(self, fig, width=None, height=None, name=None):\n \"\"\"\n Adds a matplotlib figure into the HTML as an inline SVG\n \n Arguments:\n fig - a matplotlib Figure object\n width - the desired width of the figure in pixels\n height - the desired height of the figure in pixels\n name - if not None, the SVG will be written to a file with that name will\n be linked to from the inline figure\n \"\"\"\n if name:\n svg_filename = self.relative_to_full_path(name + '.svg')\n self.write('' % name)\n else:\n svg_filename = '.svg'\n \n width = width or (fig.get_figwidth() * fig.get_dpi())\n height = height or (fig.get_figheight() * fig.get_dpi())\n \n fig.savefig(svg_filename, format='svg')\n self.extract_svg_from_file(svg_filename, width=width, height=height)\n \n if name:\n self.write('')\n else:\n os.remove(svg_filename)\n\n def embed_dot_inline(self, Gdot, width=320, height=240, name=None):\n \"\"\"\n Converts the DOT graph to an SVG DOM and uses the inline SVG option to \n add it directly into the HTML (without creating a separate SVG file).\n \"\"\"\n if name:\n svg_filename = self.relative_to_full_path(name + '.svg')\n self.write('' % name)\n else:\n svg_filename = '.svg'\n\n Gdot.write(svg_filename, prog='dot', format='svg')\n self.extract_svg_from_file(svg_filename, width=width, height=height)\n if name:\n self.write('')\n else:\n os.remove(svg_filename)\n\n def embed_dot(self, Gdot, name, width=320, height=240):\n \"\"\"\n Converts the DOT graph to an SVG DOM and uses the inline SVG option to \n add it directly into the HTML (without creating a separate SVG file).\n \"\"\"\n svg_filename = self.relative_to_full_path(name + '.svg')\n Gdot.write(svg_filename, prog='dot', format='svg')\n self.embed_svg(svg_filename, width=width, height=height, name=name)\n\n def extract_svg_from_xmldom(self, dom, width=320, height=240):\n svg = dom.getElementsByTagName(\"svg\")[0]\n svg.setAttribute('width', '%dpt' % width)\n svg.setAttribute('height', '%dpt' % height)\n self.write(svg.toxml())\n \n def extract_svg_from_file(self, fname, width=320, height=240):\n xmldom = xml.dom.minidom.parse(fname)\n self.extract_svg_from_xmldom(xmldom, width, height)\n \n def branch(self, relative_path, link_text=None):\n \"\"\"\n Branches the HTML file by creating a new HTML and adding a link to it with the desired text\n \"\"\"\n if (link_text == None):\n link_text = relative_path\n \n self.write(\"\" + link_text + \"\")\n return HtmlWriter(os.path.join(self.filepath, relative_path + \".html\"))\n \n def close(self):\n self.write(\"\\n\\n\")\n\nclass NullHtmlWriter(BaseHtmlWriter):\n def __init__(self):\n BaseHtmlWriter.__init__(self)\n self.filename = None\n \n def write(self, s):\n pass\n \n def relative_to_full_path(self, relpath):\n pass\n\n\nclass HtmlWriter(BaseHtmlWriter):\n \n def __init__(self, filename, force_path_creation=True, flush_always=True):\n BaseHtmlWriter.__init__(self)\n self.filename = filename\n self.filepath = os.path.dirname(filename)\n self.flush_always = flush_always\n if (not os.path.exists(self.filepath)):\n if (force_path_creation and not os.path.exists(self.filepath)):\n _mkdir(self.filepath)\n else:\n raise Exception(\"cannot write to HTML file %s since the directory doesn't exist\" % filename)\n \n self.file = codecs.open(self.filename, \"w\", encoding='utf_8')\n self.write_header()\n self.write_js(self.filepath)\n \n def relative_to_full_path(self, relpath):\n return self.filepath + \"/\" + relpath\n\n def write(self, s):\n if (self.file == None):\n raise Exception(\"cannot write to this HTML since it is already closed\")\n self.file.write(s)\n if (self.flush_always):\n self.file.flush()\n \n def __del__(self):\n if self.file:\n self.close()\n \n def close(self):\n BaseHtmlWriter.close(self)\n self.file.flush()\n self.file.close()\n self.file = None\n\ndef test():\n html_write = HtmlWriter(\"../res/test.html\")\n html_write.write(\"

hello world

\\n\")\n\nif __name__ == '__main__':\n test()\n","sub_path":"scripts/html_writer.py","file_name":"html_writer.py","file_ext":"py","file_size_in_byte":10104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"223090679","text":"from plexcomingsoon import PlexComingSoon, logger\nimport schedule\nimport time\n\ninstance = PlexComingSoon()\nlogger.info(\"Starting script, scheduled every %d minutes\" % (instance.interval))\ninstance.run()\nschedule.every(instance.interval).minutes.do(instance.run)\nwhile 1:\n\tschedule.run_pending()\n\ttime.sleep(1)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"557399944","text":"from flask import Flask,request,redirect,url_for,session,flash,render_template\nimport database\nimport ChatBot_Utility as bot\nimport ChatBot_Inference as engine \n#import ChatBot_Train as Trainer\nfrom passlib.hash import sha256_crypt\nfrom werkzeug.utils import secure_filename # secured file upload\nfrom datetime import datetime\nimport gmaps\nfrom ipywidgets.embed import embed_minimal_html\napp=Flask(__name__)\napp.secret_key='QwErTY9934@123'\ngmaps.configure(api_key='API_KEY_GOES_HERE')\n@app.route('/')\ndef HomePage():\n\treturn render_template('index.html')\n@app.route('/register')\ndef register():\n\treturn render_template('register.html')\t\n@app.route('/login')\ndef login():\n\treturn render_template('login.html')\n@app.route('/registerBack',methods=['POST'])\ndef registerBack():\n\tregistrar=database.Registration()\n\tif request.method=='POST':\n\t\tuserId=request.form['userId']\n\t\tpassword=sha256_crypt.encrypt(request.form['password'])\n\t\temail=request.form['email']\n\t\tprofilePic=request.files['profilePic']\n\t\tfileName=userId + secure_filename(profilePic.filename)\n\t\tprofilePic.save('static/PROFILE_PIC/'+fileName)\n\telse:\n\t\tflash(\"Unsupported method of registration! Please use the registration tab instead.\",'alert alert-danger')\n\t\treturn redirect(url_for(\"HomePage\"))\n\tprofilePath='static/PROFILE_PIC/'+fileName\n\tres=registrar.registerUser(userId,password,email,profilePath)\n\tprint(res)\n\tif res==True:\n\t\t# as we advance, incorporate functionality of OTP verification as well.\n\t\tflash(\"You are successfully registered! verification link has been sent to your registered E-mail.\",'alert alert-success') \n\t\treturn redirect(url_for('login'))\n\telse:\n\t\tflash(\"User with provided data already exists! \",'alert alert-danger')\n\t\treturn redirect(url_for('register'))\n\n@app.route('/loginBack',methods=['POST'])\ndef loginBack():\n\tauthenticator=database.AuthLogin()\n\tif request.method=='POST':\n\t\tuserId=request.form['userId']\n\t\tpassword=request.form['password']\n\telse:\n\t\tflash(\"Unsupported method of login! Please use the login tab instead.\",'alert alert-danger')\n\t\treturn redirect(url_for(\"HomePage\"))\n\tstatus,res,msg,category=authenticator.checkCredentials(userId,password)\n\tflash(msg,category)\n\tif status==True:\n\t\tsession['username']=res[0][0]\n\t\tsession['email']=res[0][2]\n\t\tsession['profilePic']=res[0][3]\n\t\tsession['type']=res[0][6]\n\t\tsession['userId']=res[0][4]\n\t\treturn redirect(url_for('HomePage'))\n\telse:\n\t\treturn redirect(url_for('login'))\n\n@app.route('/logout')\ndef logout():\n\tflash('You are successfully logged out!','alert alert-success')\n\tsession.pop('username',None)\n\tsession.pop('email',None)\n\tsession.pop('profilePic',None)\n\treturn redirect(url_for('HomePage'))\n@app.route('/aboutus')\ndef aboutus():\n\treturn render_template('aboutus.html')\n\n\n@app.route('/contactus')\ndef contactus():\n\treturn render_template('contactus.html')\n@app.route('/admin')\ndef admin():\n\treturn render_template('admin.html')\n@app.route('/messenger')\ndef messenger():\n\treturn render_template('messenger.html')\n@app.route('/settings')\ndef settings():\n\treturn render_template('settings.html')\n\n@app.route('/ventures')\ndef ventures():\n\treturn render_template('ventures.html')\n\n@app.route('/activate')\ndef activate():\n\totp = request.args.get('otp')\n\tuserId=request.args.get('userId')\n\totpVal=database.otpValidator()\n\tif otpVal.validate(otp,userId)==True:\n\t\tflash(\"Congratulations! Your account has been activated. Try logging in.\",'alert alert-success')\n\t\treturn redirect(url_for('login'))\n\telse:\n\t\tflash(\"OTP verification Failed! Try again later.\",'alert alert-danger')\n\t\treturn redirect(url_for('HomePage'))\t\t\n@app.route('/chat_post',methods=['GET'])\ndef chat_post():\n\tchat=database.chat()\n\tdata={\"inputs\" : []}\n\tif request.method=='GET':\n\t\tdata[\"inputs\"].append({\"in\" : request.args.get('msg'),\"userID\" : session['userId'],\"action\" : \"\"})\n\t\tuid=session[\"userId\"]\n\t\twith open(f\"{uid}.json\",'w') as file:\n\t\t\tbot.json.dump(data,file)\n\t\tnow=datetime.now()\n\t\tts=now.strftime(\"%d/%m/%Y %H:%M:%S\")\n\t\tmsg=request.args.get('msg')\n\t\tchat.post(0,session['userId'],msg,0,ts)\n\t\tengine.respond(f\"{uid}.json\") # it will make inference and create response.json file.\n\t\twith open(f\"{uid}.json\",'r') as file:\n\t\t\tdata=bot.json.load(file)\n\t\tnow=datetime.now()\n\t\tts=now.strftime(\"%d/%m/%Y %H:%M:%S\")\n\t\tchat.post(session['userId'],0,data['responses'][0],0,ts)\n\t\tif len(data['action'][0])>0:\n\t\t\t# perform recommendation and plot the recommendation on the map.\n\t\t\t# https://medium.com/future-vision/google-maps-in-python-part-2-393f96196eaf\n\t\t\tcsv_hndl=database.csv_handler()\n\t\t\tres=csv_hndl.getRecommendation(session['latitude'],session['longitude'])\n\t\t\tnow=datetime.now()\n\t\t\tts=now.strftime(\"%d/%m/%Y %H:%M:%S\")\n\t\t\tchat.post(session['userId'],0,res,0,ts)\n@app.route('/chat_fetch',methods=['GET'])\ndef chat_fetch():\n\tchat=database.chat()\n\tif request.method=='GET':\n\t\tuid=session[\"userId\"]\n\t\tresponse=''\n\t\tres=chat.get(uid)\n\t\tfor i in res:\n\t\t\tif i[0]==uid:\n\t\t\t\tresponse+='
'+i[2]+'
'+i[4]+'

' \n\t\t\telif i[1]==uid:\n\t\t\t\tresponse+='
'+i[2]+'
'+i[4]+'

'\n\t\treturn response\n\t\t\n@app.route('/storePosition',methods=['GET'])\ndef storePosition():\n\tif request.method=='GET':\n\t\tsession['latitude']=request.args.get('lat')\n\t\tsession['longitude']=request.args.get('longi')\t\n\t\t\n\n@app.route('/map',methods=['GET'])\ndef map():\n\tif request.method=='GET':\n\t\tmyLoc=(float(session['latitude']),float(session['longitude']))\n\t\thospital=(float(request.args.get('lat')),float(request.args.get('lng')))\n\t\tfig = gmaps.figure()\n\t\tlayer = gmaps.directions.Directions(myLoc, hospital,mode='car')\n\t\tfig.add_layer(layer)\n\t\tuid=session['userId']\n\t\tname=f\"{uid}.html\"\n\t\tembed_minimal_html(\"templates/\"+name, views=[fig])\n\t\treturn render_template(name)\n\n@app.route('/add_venture',methods=['GET'])\ndef add_venture():\n\tif request.method=='GET':\n\t\tname=request.args.get(\"name\")\n\t\tloc=request.args.get(\"loc\")\n\t\tstt=request.args.get(\"state\")\n\t\tdist=request.args.get(\"dist\")\n\t\tpin=request.args.get(\"pin\")\n\t\tlat=request.args.get(\"lat\")\n\t\tlng=request.args.get(\"lng\")\n\t\tcsv_hndl=database.csv_handler()\n\t\tstat=csv_hndl.append_csv([loc,name,stt,dist,pin,lat,lng])\n\t\t#if stat:\n\t\t#\tflash(\"Congratulations! a new venture has been added.\",'alert alert-success')\n\t\t#else: \n\t\t#\tflash(\"Alas! the data already exists\",'alert alert-danger')\n\t#else:\n\t\t#flash(\"Unsupported method of venture management!\",'alert alert-danger')\n\n@app.route('/del_venture',methods=['GET'])\ndef del_venture():\n\tif request.method=='GET':\n\t\tname=request.args.get(\"name\")\n\t\tloc=request.args.get(\"loc\")\n\t\tstt=request.args.get(\"state\")\n\t\tdist=request.args.get(\"dist\")\n\t\tpin=request.args.get(\"pin\")\n\t\tlat=request.args.get(\"lat\")\n\t\tlng=request.args.get(\"lng\")\n\t\tcsv_hndl=database.csv_handler()\n\t\tstat=csv_hndl.delete_csv([loc,name,stt,dist,pin,lat,lng])\n\t\t#if stat:\n\t\t#\tflash(\"Congratulations! the venture data has been deleted.\",'alert alert-success')\n\t\t#else: \n\t\t#\tflash(\"Alas! the data does not exist exists\",'alert alert-danger')\n\t#else:\n\t\t#flash(\"Unsupported method of venture management!\",'alert alert-danger')\n\n@app.route('/user_fetch',methods=['GET'])\ndef user_fetch():\n\tif request.method=='GET':\n\t\tuser_data_fetcher=database.user_data()\n\t\tres=user_data_fetcher.getUserData()\n\t\tresponse=''\n\t\tresponse+='
'\n\t\tresponse+=''\n\t\tresponse+=''\n\t\tresponse+=''\n\t\tresponse+=''\n\t\tresponse+=''\n\t\tresponse+=''\n\t\tresponse+=''\n\t\tif len(res)!=0:\n\t\t\tfor i in res:\n\t\t\t\tresponse+=f\"\"\n\t\t\t\tresponse+=''\n\t\t\t\tif int(i[4])==1:\n\t\t\t\t\tresponse+=''\n\t\t\t\telse:\n\t\t\t\t\tresponse+=''\n\t\treturn response\n\t\t\t\n@app.route('/activate_user',methods=['GET'])\ndef activate_user():\n\tif request.method=='GET':\t\n\t\tuid=request.args.get('userId')\n\t\tact_handler=database.activation_handler()\n\t\tstat=act_handler.activate(uid)\n\t\t#if stat:\n\t\t#\tflash(\"Congratulations! the user has been activated.\",'alert alert-success')\n\t\t#else:\n\t\t#\tflash(\"Faced some issue while updaing the status\",'alert alert-danger')\t\n\t\n@app.route('/deactivate_user',methods=['GET'])\ndef deactivate_user():\n\tif request.method=='GET':\n\t\tuid=request.args.get('userId')\n\t\tact_handler=database.activation_handler()\n\t\tstat=act_handler.deactivate(uid)\n\t\t#if stat:\n\t\t#\tflash(\"Congratulations! the user has been deactivated.\",'alert alert-success')\n\t\t#else:\n\t\t#\tflash(\"Faced some issue while updaing the status\",'alert alert-danger')\t\n\n@app.route('/intents_fetch',methods=['GET'])\ndef intents_fetch():\n\tif request.method=='GET':\n\t\tresponse=''\n\t\twith open('intents.json','r') as file:\n\t\t\tdata=bot.json.load(file)\n\t\tresponse+='
User IdUser NameUser MailUser Profile pictureAction
{i[0]}{i[1]}{i[2]}
'\n\t\tfor i in data['intents']:\n\t\t\tintents=i.keys()\n\t\t\tfor j in intents:\n\t\t\t\tresponse+=f\"\"\n\t\t\tresponse+=''\n\t\t\tbreak\n\t\tfor intents in data['intents']:\n\t\t\tresponse+=''\n\t\t\tfor header in intents.keys():\n\t\t\t\ttemp=intents[header]\n\t\t\t\tresponse+=''\n\t\t\tresponse+=''\n\t\tresponse+='
{j}
'\n\t\t\t\tif type(temp)==type([]):\n\t\t\t\t\tfor i in temp:\n\t\t\t\t\t\tresponse+=str(i)+', '\n\t\t\t\telse:\n\t\t\t\t\tresponse+=str(temp)\n\t\t\t\t\t\n\t\t\t\tresponse+='
'\n\t\t#response+='
'\n\t\t#for i in data['intents']:\n\t\t#\tintents=i.keys()\n\t\t#\tfor j in intents:\n\t\t#\t\tresponse+=f\"\"\n\t\t#\tresponse+=''\n\t\t#\tresponse+=''\n\t\t#\tbreak\t\t\n\t\t#response+=''\n\t\t#response+=''\n\t\t#response+=''\n\t\t#response+=''\n\t\t#response+=''\n\t\t#response+=''\n\t\t#response+=''\n\t\t#response+='
{j}Action
'\n\t\treturn response\n\n@app.route('/add_intent',methods=['GET'])\ndef add_intent():\n\tif request.method=='GET':\n\t\ttag=request.args.get(\"tag\")\n\t\tpat=request.args.get(\"pattern\")\n\t\tres=request.args.get(\"responses\")\n\t\tact=request.args.get(\"action\")\n\t\tcxt=request.args.get(\"context\")\n\t\twith open('intents.json','r') as file:\n\t\t\tdata=bot.json.load(file)\n\t\tnew_data={\"tag\" : tag,\"pattern\" : list(pat),\"responses\" : list(res),\"action\" : act,\"context_set\" : cxt}\n\t\tdata['intents'].append(new_data)\n\t\twith open('intents.json','w') as file:\n\t\t\tbot.json.dump(data,file)\n\t\tif bot.os.path.exists('model.h5'):\n\t\t\tbot.os.remove('model.h5')\n\t\tTrainer.train()\n\t\t\t\n@app.route('/change_credit',methods=['GET'])\ndef change_credit():\n\tif request.method=='GET':\n\t\tval=request.args.get(\"value\")\n\t\tmode=request.args.get(\"mode\")\n\t\tuserId=session['userId']\n\t\tif mode==\"1\":\n\t\t\t# change password.\n\t\t\tregistrar=database.Registration()\n\t\t\tregistrar.updateProfile(sha256_crypt.encrypt(val),mode,userId)\n\n\t\telif mode==\"2\":\n\t\t\t# change username.\n\t\t\tregistrar=database.Registration()\n\t\t\tregistrar.updateProfile(val,mode,userId)\n\t\t\t\n@app.route('/changeProfPic',methods=['POST'])\ndef changeProfPic():\n\tif request.method=='POST':\n\t\t# change profile pic.\n\t\tprofilePic=request.files['profpic']\t\n\t\tfileName=session['profilePic']\n\t\tprofilePic.save(fileName)\n\t\treturn redirect(url_for('HomePage'))\n\n@app.route('/vents_fetch',methods=['GET'])\ndef vents_fetch():\n\tif request.method=='GET':\n\t\tcsv_hndl=database.csv_handler()\n\t\tres=csv_hndl.getData()\n\t\tpattern=request.args.get('pattern')\n\t\ttemp=[]\n\t\tresponse=''\n\t\tresponse+=''\n\t\tresponse+=''\n\t\tif pattern!='EMPTY':\n\t\t\tfor i in res:\n\t\t\t\tflag=0\n\t\t\t\tfor j in i:\n\t\t\t\t\tif str(pattern).lower() in str(j).lower():\n\t\t\t\t\t\tflag=1\n\t\t\t\t\t\tbreak\n\t\t\t\tif flag==1:\n\t\t\t\t\ttemp.append(i)\n\t\telse:\n\t\t\ttemp=res\n\t\tif len(temp)>0:\n\t\t\tfor i in temp:\n\t\t\t\tresponse+=f\"\"\n\t\tresponse+='
NameLocationDistrictStateZIP code
{i[1]}{i[0]}{i[3]}{i[2]}{i[4]}
'\n\t\treturn response\t\t\t\t\t\t\n\t\t\t\t\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":12440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"437786119","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nReegis geometry tools.\n\nSPDX-FileCopyrightText: 2016-2021 Uwe Krien \n\nSPDX-License-Identifier: MIT\n\"\"\"\n__copyright__ = \"Uwe Krien \"\n__license__ = \"MIT\"\n\n__all__ = [\"deflex_geo\", \"divide_off_and_onshore\"]\n\nimport os\nfrom collections import namedtuple\n\nfrom deflex import config as cfg\n\ntry:\n import geopandas as gpd\nexcept ImportError:\n gpd = None\n\n\ndef deflex_geo(rmap):\n \"\"\"\n Fetch default deflex geometries as a named tuple with the following fields:\n * polygons\n * lines\n * labels\n * line_labels\n\n Note that some fields might be None for some region sets.\n\n Parameters\n ----------\n rmap : str\n Name of the deflex map. Possible values are: de01, de02, de17, de21,\n de22\n\n Returns\n -------\n namedtuple\n\n Examples\n --------\n >>> de02 = deflex_geo(\"de02\")\n >>> list(de02.polygons.index)\n ['DE01', 'DE02']\n >>> p = de02.labels.loc[\"DE01\"].geometry\n >>> p.x, p.y\n (10.0, 51.6)\n >>> de02.lines.index\n Index(['DE01-DE02'], dtype='object', name='name')\n >>> de02.line_labels.iloc[0]\n gid 246\n rotation -42\n geometry POINT (7.61 53.78)\n Name: DE01-DE02, dtype: object\n >>> de01 = deflex_geo(\"de01\")\n >>> print(de01.lines)\n None\n \"\"\"\n geo = namedtuple(\n \"geometry\", [\"polygons\", \"lines\", \"labels\", \"line_labels\"]\n )\n polygons = deflex_regions(rmap, rtype=\"polygons\")\n labels = deflex_regions(rmap, rtype=\"labels\")\n lines = deflex_power_lines(rmap, rtype=\"lines\")\n line_labels = deflex_power_lines(rmap, rtype=\"labels\")\n return geo(\n polygons=polygons, labels=labels, lines=lines, line_labels=line_labels\n )\n\n\ndef deflex_regions(rmap=None, rtype=\"polygons\"):\n \"\"\"\n Get the geometries of deflex example regions.\n\n Parameters\n ----------\n rmap : str\n Name of the deflex map.\n rtype : str\n Type of the deflex map ('polygon', 'labels').\n\n Returns\n -------\n GeoDataFrame\n\n Examples\n --------\n >>> my_regions=deflex_regions('de17')\n >>> len(my_regions)\n 17\n >>> my_regions.geometry.iloc[0].geom_type\n 'MultiPolygon'\n >>> l=deflex_regions('de21', 'labels').loc['DE04', 'geometry']\n >>> l.geom_type\n 'Point'\n >>> l.x\n 13.2\n >>> l.y\n 51.1\n >>> deflex_regions(rmap=\"de22\").name\n 'de22'\n >>> list(deflex_regions('de02').index)\n ['DE01', 'DE02']\n >>> print(deflex_regions(\"de05\"))\n None\n \"\"\"\n name = os.path.join(\n os.path.dirname(__file__),\n \"data\",\n \"geometries\",\n cfg.get(\"geometry\", \"deflex_polygon\").format(\n suffix=\".geojson\", map=rmap, type=rtype\n ),\n )\n\n if os.path.isfile(name):\n regions = gpd.read_file(name)\n regions.set_index(\"region\", inplace=True)\n regions.name = rmap\n else:\n regions = None\n\n return regions\n\n\ndef deflex_power_lines(rmap=None, rtype=\"lines\"):\n \"\"\"\n Get the geometries of deflex example power lines.\n\n Parameters\n ----------\n rmap : str\n Name of the deflex powerline map.\n rtype : str\n Type of the deflex powerline map ('lines', 'labels').\n\n Returns\n -------\n\n Examples\n --------\n >>> my_lines=deflex_power_lines('de17')\n >>> my_lines.geometry.iloc[0].geom_type\n 'LineString'\n >>> len(my_lines)\n 31\n >>> deflex_power_lines('de02').index[0]\n 'DE01-DE02'\n >>> deflex_power_lines(rmap=\"de21\").name\n 'de21'\n >>> print(deflex_regions(\"de05\"))\n None\n \"\"\"\n name = os.path.join(\n os.path.dirname(__file__),\n \"data\",\n \"geometries\",\n cfg.get(\"geometry\", \"powerlines\").format(\n map=rmap, type=rtype, suffix=\".geojson\"\n ),\n )\n if os.path.isfile(name):\n lines = gpd.read_file(name)\n lines.set_index(\"name\", inplace=True)\n lines.name = rmap\n else:\n lines = None\n\n return lines\n\n\ndef divide_off_and_onshore(regions):\n \"\"\"\n Sort regions into onshore and offshore regions (Germany).\n\n A namedtuple with two list\n of regions ids will be returned. Fetch the `onshore` and `offshore`\n attribute of the named tuple to get the list.\n\n Parameters\n ----------\n regions : GeoDataFrame\n A region set with the region id in the index.\n\n Returns\n -------\n namedtuple\n\n Examples\n --------\n >>> reg=deflex_regions('de02')\n >>> divide_off_and_onshore(reg).onshore\n ['DE01']\n >>> reg=deflex_regions('de21')\n >>> divide_off_and_onshore(reg).offshore\n ['DE19', 'DE20', 'DE21']\n \"\"\"\n region_type = namedtuple(\"RegionType\", \"offshore onshore\")\n regions_centroid = regions.copy()\n regions_centroid.geometry = regions_centroid.to_crs(\n epsg=25832\n ).centroid.to_crs(epsg=\"4326\")\n\n germany_onshore = gpd.read_file(\n os.path.join(\n os.path.dirname(__file__),\n \"data\",\n \"geometries\",\n cfg.get(\"geometry\", \"germany_polygon\"),\n )\n )\n\n gdf = gpd.sjoin(\n regions_centroid, germany_onshore, how=\"left\", predicate=\"within\"\n )\n\n onshore = list(gdf.loc[~gdf.gid.isnull()].index)\n offshore = list(gdf.loc[gdf.gid.isnull()].index)\n\n return region_type(offshore=offshore, onshore=onshore)\n","sub_path":"src/deflex/geometries.py","file_name":"geometries.py","file_ext":"py","file_size_in_byte":5353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"44103578","text":"import random\r\n\r\n##the students in the class\r\n##the most popular names in 2020\r\nstudents = \\\r\n[\"Oliver\",\\\r\n\"Liam\",\\\r\n\"Ethan\",\\\r\n\"Aiden\",\\\r\n\"Gabriel\",\\\r\n\"Caleb\",\\\r\n\"Elijah\",\\\r\n\"Theodore\",\\\r\n\"Declan\",\\\r\n\"Owen\",\\\r\n\"Elijah\",\\\r\n\"Charlotte\",\\\r\n\"Ava\",\\\r\n\"Amelia\",\\\r\n\"Olivia\",\\\r\n\"Aurora\",\\\r\n\"Violet\",\\\r\n\"Luna\",\\\r\n\"Hazel\",\\\r\n\"Cloe\",\\\r\n\"Aria\"\r\n ]\r\n\r\n##needed to build the test results\r\ntest_results = []\r\nanswers = ['a', 'b', 'c', 'd'] \r\nnum_questions = 3 ##You may change the number for testing, a smaller number\r\n ##will made testing the correctness of your code easier\r\n\r\n##this code will build a dictionary of length 20 of \r\n##key - student name\r\n##value - a list of num_questions length of randomly selected\r\n##values from the list answers above\r\nfor student in students:\r\n result = []\r\n for i in range(num_questions):\r\n result.append(random.choice(answers))\r\n test = {}\r\n test[student] = result\r\n test_results.append(test)\r\nprint(\"Raw Data: \")\r\nprint(test_results)\r\nvisited = [False]*len(test_results)\r\nprint(\"Names and Answers of Each Student\")\r\nfor i in range(0,len(test_results)):\r\n for key,value in test_results[i].items():\r\n print(key,value)\r\nprint(\"Names and Answers of Students Who Copied\")\r\nfor i in range(0,len(test_results)):\r\n for key,value in test_results[i].items():\r\n for j in range(0,len(test_results)):\r\n for key2,value2 in test_results[j].items():\r\n if value == value2 and visited[j] == False and key != key2:\r\n print(key,value,\"copied\",key2,value2)\r\n visited[j] = True; \r\n","sub_path":"Assignment 6/PS6_Part1.py","file_name":"PS6_Part1.py","file_ext":"py","file_size_in_byte":1597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"328030323","text":"\"\"\"\nExtract only sentences from the body of Hillary Clinton's released emails.\nUses @honnibal's spacy NLP package which uses dependency parse to segment sentences.\nLower-cased and tokenized (including punctuation).\nEach line should be a sentence.\n\nFirst download the 'output' by unzipping the following in the home directory.\n https://www.kaggle.com/c/hillary-clinton-emails/data\n\nCode to:\n https://github.com/benhamner/hillary-clinton-emails\n\nExample:\n python scripts/clean.py\n\"\"\"\nfrom __future__ import print_function\n\nimport re\nimport pandas as pd\ndf = pd.read_csv('output/Emails.csv')\n\nfrom spacy.en import English\nprint('Loading spacy model..')\nnlp = English(load_vectors=False)\n\nSTOPSYMBOLS = {'<', '>'}\n\nWORDS_META = {'re:', 'case', 'no.', 'doc no', 'from', 'for:', 'fw:', 'h:', 'to:', 'subject:', 'date:', 'prom:'}\nWORDS_DAY = {'sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'}\nWORDS_MONTH = {'january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'}\n\npattern_email = re.compile(r\"[\\w]+@[\\.\\w]+\")\npattern_date = re.compile(r\"\\d+/\\d+/\\d+\")\npattern_time = re.compile(r\"[0-2]?[0-9]:[0-6][0-9]\")\n\nis_email = lambda x: sum([i.like_email for i in x]) > 0\nis_url = lambda x: sum([i.like_url for i in x]) > 0\nis_oov = lambda x: sum([i.cluster == 0 for i in x]) > 1\nis_short = lambda x: len(x) <= 3\nis_gibberish = lambda x: sum([i.is_digit == i.is_alpha for i in x]) > 1\n\nreplace_whitespace = lambda x: re.sub(r'\\s+', ' ', x)\n\ndupes = set()\ncounter = 0\n\nif __name__ == '__main__':\n print('Number of emails:', df.shape[0])\n\n with open('sentences.txt', 'w') as f:\n for email in df['ExtractedBodyText']:\n # remove nan\n if type(email) != str:\n continue\n \n # emails are sometimes broken up into \n email_filtered = []\n for line in email.split('\\n'):\n tokens = line.lower().split()\n if tokens[0] in WORDS_META:\n continue\n \n lexemes = [nlp.vocab[unicode(i, errors='ignore')] for i in tokens]\n if lexemes[0].is_digit == lexemes[0].is_alpha:\n continue\n \n if is_short(tokens):\n continue\n if is_oov(lexemes):\n continue\n if is_email(lexemes):\n continue\n if is_url(lexemes):\n continue\n # if is_gibberish(lexemes):\n # continue\n \n # else\n email_filtered.append(line)\n \n email = ' '.join(email_filtered)\n for sent in nlp(unicode(email, errors='ignore')).sents:\n if is_short(sent):\n continue\n \n tokens = [i.lower_ for i in sent]\n sentence = ' '.join(tokens)\n if sentence in dupes:\n continue\n else:\n dupes.add(sentence)\n counter += 1\n f.write(sentence)\n f.write('\\n')\n\n print('Number of extracted sentences:', counter)\n print('Saved extracted sentences to:', 'sentences.txt')\n\n","sub_path":"scripts/clean.py","file_name":"clean.py","file_ext":"py","file_size_in_byte":3278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"89127930","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 ('website', '0006_auto_20180509_1722'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='profile',\n name='iwanttohelp',\n field=models.BooleanField(default=False, verbose_name='I want to help'),\n ),\n ]\n","sub_path":"idetra/website/migrations/0007_auto_20180509_1743.py","file_name":"0007_auto_20180509_1743.py","file_ext":"py","file_size_in_byte":442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"564138148","text":"#coding=utf-8\r\nfrom selenium import webdriver\r\nimport time\r\nimport os\r\n'''\r\nos_filepath = os.path.dirname(__file__)\r\nproject_path = os.path.dirname(os_filepath)\r\nproject_path = project_path.replace(\"\\\\\",\"/\")\r\nprint(project_path)\r\n'''\r\n\r\ndriver = webdriver.Chrome()\r\n\r\ndriver.get(\"http://apitest.gfs100.cn/iboss/login.aspx\")\r\ndriver.find_element_by_id(\"txtUserName\")\r\ndriver.maximize_window()\r\ntime.sleep(0.5)\r\ndriver.get_screenshot_as_file\\\r\n(r\"../test_report/error_screenshot/登录页3.png\")\r\n#.send_keys(\"School035\")\r\n#driver.find_element_by_id(\"txtPassword\").send_keys(\"123456\")\r\n#driver.find_element_by_id(\"btnSubmit\").click()\r\n","sub_path":"Selenium Automation Test/base/test_base.py","file_name":"test_base.py","file_ext":"py","file_size_in_byte":634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"19739779","text":"from linkedin_scraper import Person, Experience, Education\nfrom linkedin_scraper.functions import time_divide\nfrom parsel import Selector\nfrom selenium.common.exceptions import TimeoutException\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.ui import WebDriverWait\n\nfrom scraper.interface.util import map_from_search\n\n\nclass Candidate(Person):\n def __init__(self, linkedin_url=None, name=None, experiences=[], educations=[], driver=None, get=True, scrape=True):\n super().__init__(linkedin_url, name, experiences, educations, driver, get, scrape)\n\n def get_connections(self, limit=None):\n driver = self.driver\n # topcard_view_all_connections\n # /search/results/people/\n # find_element_by_xpath(\"//a[contains(@href, '/search/results/people/')]\").text\n driver.find_element_by_xpath(\"//a[contains(@href, '/search/results/people/')]\").click()\n\n return map_from_search(driver,\n wait_time=10,\n fn=lambda res: Candidate.parse_candidate_from_search_result(self.driver, res),\n limit=limit)\n\n @staticmethod\n def parse_candidate_from_search_result(driver, search_result):\n try:\n result_link = search_result.find_element_by_class_name(\"search-result__result-link\")\n result_name = search_result.find_elements_by_class_name(\"search-result__result-link\")[1]\n\n candidate = Candidate(linkedin_url=(result_link.get_attribute(\"href\")),\n name=result_name.text.encode('utf-8').strip(),\n driver=driver,\n get=False,\n scrape=False)\n\n position_title = search_result.find_element_by_xpath('.//span[@dir=\"ltr\"]')\n candidate.add_experience(Experience(position_title=position_title.text))\n return candidate\n except:\n return None\n\n def scrape_logged_in(self, close_on_complete=True):\n driver = self.driver\n _ = WebDriverWait(driver, 3).until(EC.presence_of_element_located((By.CLASS_NAME, \"pv-top-card-v3\")))\n root = driver.find_element_by_class_name(\"pv-top-card-v3\")\n self.name = str(root.find_elements_by_xpath(\"//section/div/div/div/*/li\")[0].text.strip())\n\n driver.execute_script(\"window.scrollTo(0, Math.ceil(document.body.scrollHeight/2));\")\n\n try:\n _ = WebDriverWait(driver, 3).until(EC.presence_of_element_located((By.ID, \"experience-section\")))\n\n # get experience\n exp = driver.find_element_by_id(\"experience-section\")\n for position in exp.find_elements_by_class_name(\"pv-position-entity\"):\n position_title = position.find_element_by_tag_name(\"h3\").text.strip()\n selector = Selector(text=driver.page_source)\n company_xpath = '//*[starts-with(@class, \"text-align-left ml2 t-14 t-black t-bold full-width lt-line-clamp lt-line-clamp--multi-line ember-view\")]/text()'\n company = (selector.xpath(company_xpath).extract_first())\n\n try:\n times = position.find_element_by_class_name(\"pv-entity__date-range\").text.strip()\n times = \"\\n\".join(times.split(\"\\n\")[1:])\n from_date, to_date, duration = time_divide(times)\n except:\n from_date, to_date, duration = (\"Unknown\", \"Unknown\", \"Unknown\")\n try:\n location = position.find_element_by_class_name(\"pv-entity__location\").text.strip()\n except:\n location = None\n experience = Experience(position_title=position_title, from_date=from_date, to_date=to_date, duration=duration,\n location=location)\n experience.institution_name = company\n self.add_experience(experience)\n except TimeoutException:\n print(\"No experience...\")\n\n driver.execute_script(\"window.scrollTo(0, Math.ceil(document.body.scrollHeight/1.5));\")\n\n try:\n _ = WebDriverWait(driver, 3).until(EC.presence_of_element_located((By.ID, \"education-section\")))\n\n # get education\n edu = driver.find_element_by_id(\"education-section\")\n for school in edu.find_elements_by_class_name(\"pv-education-entity\"):\n university = school.find_element_by_class_name(\"pv-entity__school-name\").text.strip()\n degree = \"Unknown Degree\"\n try:\n degree = school.find_element_by_class_name(\"pv-entity__degree-name\").text.strip()\n times = school.find_element_by_class_name(\"pv-entity__dates\").text.strip()\n from_date, to_date, duration = time_divide(times)\n except:\n from_date, to_date = (\"Unknown\", \"Unknown\")\n education = Education(from_date=from_date, to_date=to_date, degree=degree)\n education.institution_name = university\n self.add_education(education)\n\n except TimeoutException:\n print(\"No education...\")\n\n if close_on_complete:\n driver.close()\n\n def scrape_not_logged_in(self, close_on_complete=True, retry_limit=10):\n driver = self.driver\n retry_times = 0\n while self.is_signed_in() and retry_times <= retry_limit:\n page = driver.get(self.linkedin_url)\n retry_times = retry_times + 1\n\n # get name\n self.name = str(driver.find_element_by_id(\"name\").text.strip())\n\n # get experience\n exp = driver.find_element_by_id(\"experience\")\n for position in exp.find_elements_by_class_name(\"position\"):\n position_title = position.find_element_by_class_name(\"item-title\").text.strip()\n company = position.find_element_by_class_name(\"item-subtitle\").text.strip()\n\n try:\n times = position.find_element_by_class_name(\"date-range\").text.strip()\n from_date, to_date, duration = time_divide(times)\n except:\n from_date, to_date, duration = (None, None, None)\n\n try:\n location = position.find_element_by_class_name(\"location\").text.strip()\n except:\n location = None\n experience = Experience(position_title=position_title,\n from_date=from_date,\n to_date=to_date,\n duration=duration,\n location=location)\n experience.institution_name = company\n self.add_experience(experience)\n\n # get education\n edu = driver.find_element_by_id(\"education\")\n for school in edu.find_elements_by_class_name(\"school\"):\n university = school.find_element_by_class_name(\"item-title\").text.strip()\n degree = school.find_element_by_class_name(\"original\").text.strip()\n try:\n times = school.find_element_by_class_name(\"date-range\").text.strip()\n from_date, to_date, duration = time_divide(times)\n except:\n from_date, to_date = (None, None)\n education = Education(from_date=from_date, to_date=to_date, degree=degree)\n education.institution_name = university\n self.add_education(education)\n\n # get\n if close_on_complete:\n driver.close()\n","sub_path":"web/scraper/interface/candidate.py","file_name":"candidate.py","file_ext":"py","file_size_in_byte":6927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"299918853","text":"#批量梗概目录下的文件名称 \n\nimport os\nfrom multiprocessing import Pool\n\ndef shorten(n):\n os.rename(n, n[0:-5])\nbase = '/media/zzx/DATA1/segmentation/'\n\n\nif __name__ == \"__main__\":\n types = ['ApplyEyeMakeup','ApplyLipstick','Archery','BabyCrawling','BalanceBeam','BandMarching','BaseballPitch','Basketball','BasketballDunk',\n'BenchPress','Biking','Billiards','BlowDryHair','BlowingCandles','BodyWeightSquats','Bowling','BoxingPunchingBag','BoxingSpeedBag','BreastStroke','BrushingTeeth',\n'CleanAndJerk','CliffDiving','CricketBowling','CricketShot','CuttingInKitchen','Diving','Drumming','Fencing','FieldHockeyPenalty','FloorGymnastics','FrisbeeCatch',\n'FrontCrawl','GolfSwing','Haircut','Hammering','HammerThrow','HandstandPushups','HandstandWalking','HeadMassage','HighJump','HorseRace','HorseRiding','HulaHoop',\n'IceDancing','JavelinThrow','JugglingBalls','JumpingJack','JumpRope','Kayaking','Knitting','LongJump','Lunges','MilitaryParade','Mixing','MoppingFloor','Nunchucks',\n'ParallelBars','PizzaTossing','PlayingCello','PlayingDaf','PlayingDhol','PlayingFlute','PlayingGuitar','PlayingPiano']\n for t in types:\n dir_type = base +t +'/'\n names = os.listdir(dir_type)\n\n for i in range(len(names)):\n names[i] = dir_type+names[i]\n\n p = Pool(8)\n p.map(shorten, names)\n p.close()\n p.join()\n\n","sub_path":"fyp/change.py","file_name":"change.py","file_ext":"py","file_size_in_byte":1329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"305721670","text":"import glob, os\n\nderiv_path = '/projects/niblab/bids_projects/Experiments/Bevel/derivatives'\nfmriprep_path = '/projects/niblab/bids_projects/Experiments/Bevel/fmriprep'\n\nqa_dict = {}\nanats = []\nruns = []\nonsets_miss =[]\nrests = []\n\nqa_dict[\"SUBJECT_COUNT\"] = len(glob.glob(os.path.join(deriv_path,\"sub-*\")))\nderiv_dir = glob.glob(os.path.join(deriv_path, \"sub-*\"))\nfmriprep_dir = glob.glob(os.path.join(fmriprep_path, \"sub-*\"))\nderiv_subs = []\nfmriprep_subs = []\n\nfor sub_dir in deriv_dir:\n sub_id = sub_dir.split(\"/\")[-1]\n deriv_subs.append(sub_id)\nfor sub_dir in fmriprep_dir:\n\n sub_id = sub_dir.split(\"/\")[-1]\n fmriprep_subs.append(sub_id)\n#missing = [i for i in deriv_subs if i not in fmriprep_subs] \n\nfor sub_dir in deriv_dir:\n sub_id = sub_dir.split(\"/\")[-1]\n anat_file = glob.glob(os.path.join(sub_dir, \"anat/*\"))\n if not anat_file:\n if sub_id not in qa_dict:\n qa_dict[sub_id] = {}\n qa_dict[sub_id] = {\"ANAT\": \"missing\"}\n anats.append(sub_id)\n #else:\n # for _file in anat_file:\n # print(_file.split(\"/\")[-1])\n run = glob.glob(os.path.join(sub_dir, \"func/*run*preproc_brain.nii.gz\"))\n if not run:\n if sub_id not in qa_dict:\n qa_dict[sub_id] = {}\n qa_dict[sub_id][\"FUNCS\"] = \"missing\"\n runs.append(sub_id)\n elif len(run) != 4:\n if sub_id not in qa_dict:\n qa_dict[sub_id] = {}\n qa_dict[sub_id][\"FUNCS\"] = []\n runs.append(sub_id)\n for _file in run:\n run_ = _file.split(\"/\")[-1].split(\"_\")[2]\n qa_dict[sub_id][\"FUNCS\"].append(run_)\n else:\n pass\n rest = glob.glob(os.path.join(sub_dir, \"func/*rest*preproc_brain.nii.gz\"))\n if not rest:\n if sub_id not in qa_dict:\n qa_dict[sub_id] = {}\n qa_dict[sub_id][\"RESTS\"] = \"missing\"\n rests.append(sub_id)\n onsets = glob.glob(os.path.join(sub_dir, \"func/onsets/*.txt\"))\n if not onsets:\n if sub_id not in qa_dict:\n qa_dict[sub_id] = {}\n qa_dict[sub_id][\"ONSETS\"] = \"missing\"\n onsets_miss.append(sub_id)\n motion1 = glob.glob(os.path.join(sub_dir, \"func/motion_assessment/*brain_confound.txt\"))\n motion2 =glob.glob(os.path.join(sub_dir, \"func/motion_assessment/motion_parameters/*.txt\"))\n if not motion1:\n if sub_id not in qa_dict:\n qa_dict[sub_id] = {}\n qa_dict[sub_id][\"CONFOUNDS\"] = \"missing\"\n if not motion2:\n if sub_id not in qa_dict:\n qa_dict[sub_id] = {}\n qa_dict[sub_id][\"MOTION_PARAMS\"] = \"missing\"\n","sub_path":"preprocessing/extra_preprocessing/derivatives/qa.py","file_name":"qa.py","file_ext":"py","file_size_in_byte":2568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"285529867","text":"import numpy as np\nimport math\nimport time\n\n######################################################################\n# Take slice from the volume\n######################################################################\ndef take_one_slice(index_, weight_, volume_, pixel_num_):\n # Convert the index of the 3D diffraction volume to 1D\n volume_num_1d_ = volume_.shape[0]\n convertion_factor = np.array([volume_num_1d_*volume_num_1d_,volume_num_1d_,1],dtype = int)\n \n index_2d_ = np.reshape(index_, [pixel_num_, 8, 3])\n index_2d_ = np.matmul(index_2d_, convertion_factor)\n #index_2d_ = index_2d_.astype(np.int32)\n \n volume_1d_ = np.reshape(volume_, volume_num_1d_**3)\n weight_2d_ = np.reshape(weight_,[pixel_num_, 8])\n \n # Expand the data to merge\n data_to_merge_ = volume_1d_[index_2d_]\n \n # Merge the data\n data_merge_ = np.sum(np.multiply(weight_2d_,data_to_merge_),axis=1)\n \n return data_merge_.reshape(index_.shape[:3])\n\ndef take_n_slice(detector_, volume_, voxel_length_, orientations_ ):\n \n # Preprocess\n volume_num_1d = volume_.shape[0]\n pattern_shape_ = detector_.pixel_rms.shape\n number_ = orientations_.shape[0]\n pixel_position_ = detector_.pixel_position_reciprocal.copy()\n \n # Create variable to hold the slices\n slices_ = np.zeros((number_, pattern_shape_[0], pattern_shape_[1], pattern_shape_[2]))\n \n tic = time.time()\n for l in range(number_):\n # construct the rotation matrix\n rotmat_ = quaternion2rot3D(orientations_[l,:])\n # rotate the pixels in the reciprocal space. Notice that at this time, the pixel position is in 3D\n pixel_position_ = rotate_pixels_in_reciprocal_space(rotmat_, pixel_position_)\n # calculate the index and weight in 3D\n index_ ,weight_ = get_weight_in_reciprocal_space(pixel_position_, voxel_length_, volume_num_1d)\n # get one slice\n slices_[l,:,:,:] = take_one_slice(index_, weight_, volume_ , detector_.pix_num_total)\n \n toc = time.time()\n print(\"Finishing constructing %d patterns in %f seconds\"%(number_, toc-tic))\n \n return slices_\n\ndef take_n_random_slices(detector_, volume_, voxel_length_, number_ ):\n \n # Preprocess\n volume_num_1d = volume_.shape[0]\n pattern_shape_ = detector_.pixel_rms.shape\n pixel_position_ = detector_.pixel_position_reciprocal.copy()\n \n # Create variable to hold the slices\n slices_ = np.zeros((number_, pattern_shape_[0], pattern_shape_[1], pattern_shape_[2]))\n \n tic = time.time()\n for l in range(number_):\n # construct the rotation matrix\n rotmat_ = quaternion2rot3D(getRandomRotation('x'))\n # rotate the pixels in the reciprocal space. Notice that at this time, the pixel position is in 3D\n pixel_position_new = rotate_pixels_in_reciprocal_space(rotmat_, pixel_position_)\n # calculate the index and weight in 3D\n index_ ,weight_ = get_weight_in_reciprocal_space(pixel_position_new, voxel_length_, volume_num_1d)\n # get one slice\n slices_[l,:,:,:] = take_one_slice(index_, weight_, volume_, detector_.pix_num_total)\n \n toc = time.time()\n print(\"Finishing constructing %d patterns in %f seconds\"%(number_, toc-tic))\n \n return slices_\n\n\n######################################################################\n# The following functions are utilized to get corrections\n######################################################################\ndef reshape_pixels_position_arrays_to_1d(array):\n \n array_1d = np.reshape(array, [np.prod(array.shape[:-1]),3])\n return array_1d\n\ndef _reciprocal_space_pixel_position(pixel_center, wave_vector, polarization):\n \n ## reshape the array into a 1d position array\n pixel_center_1d = reshape_pixels_position_arrays_to_1d(pixel_center)\n \n ## Calculate the reciprocal position of each pixel\n wave_vector_norm = np.sqrt(np.sum(np.square(wave_vector)))\n wave_vector_direction = wave_vector/ wave_vector_norm\n \n pixel_center_norm = np.sqrt(np.sum(np.square(pixel_center_1d),axis=1))\n pixel_center_direction = pixel_center_1d / pixel_center_norm[:,np.newaxis]\n \n pixel_position_reciprocal_1d = wave_vector_norm*(pixel_center_direction - wave_vector_direction)\n \n ## restore the pixels shape\n pixel_position_reciprocal = np.reshape(pixel_position_reciprocal_1d, pixel_center.shape)\n \n return pixel_position_reciprocal\n\ndef _polarization_correction(pixel_center, wave_vector, polarization):\n \n ## reshape the array into a 1d position array\n pixel_center_1d = reshape_pixels_position_arrays_to_1d(pixel_center)\n \n #print pixel_center_1d.shape\n \n pixel_center_norm = np.sqrt(np.sum(np.square(pixel_center_1d),axis=1))\n pixel_center_direction = pixel_center_1d / pixel_center_norm[:,np.newaxis]\n \n ## Calculate the polarization correction\n polarization_norm = np.sqrt(np.sum(np.square(polarization)))\n polarization_direction = polarization/polarization_norm\n\n \n polarization_correction_1d = np.sum(np.square(np.cross(pixel_center_direction, polarization_direction)),axis=1)\n \n #print polarization_correction_1d.shape\n \n polarization_correction = np.reshape(polarization_correction_1d, pixel_center.shape[0:-1])\n \n return polarization_correction\n \ndef _geometry_correction(pixel_center, orientation):\n \n ## reshape the array into a 1d position array\n pixel_center_1d = reshape_pixels_position_arrays_to_1d(pixel_center)\n distance = pixel_center_1d[0,2]\n pixel_center_norm = np.sqrt(np.sum(np.square(pixel_center_1d),axis=1))\n pixel_center_direction = pixel_center_1d / pixel_center_norm[:,np.newaxis]\n \n ## Calculate the solid angle correction\n orientation_norm = np.sqrt(np.sum(np.square(orientation)))\n orientation_normalized = orientation/orientation_norm\n \n ## The correction induced by the orientation\n geometry_correction_1d = np.abs(np.dot(pixel_center_direction, orientation_normalized))\n ## The correction induced by the distance\n distance_correction = np.square(distance/pixel_center_norm)\n geometry_correction_1d = np.multiply(geometry_correction_1d, distance_correction)\n \n geometry_correction = np.reshape(geometry_correction_1d, pixel_center.shape[0:-1])\n \n return geometry_correction\n \ndef reciprocal_space_pixel_position_and_correction(pixel_center, wave_vector, polarization, orientation):\n\n pixel_position_reciprocal = _reciprocal_space_pixel_position(pixel_center, wave_vector, polarization)\n pixel_position_reciprocal_norm = np.sqrt(np.sum(np.square(pixel_position_reciprocal),axis=-1))*( 1e-10/2. )\n \n polarization_correction = _polarization_correction(pixel_center, wave_vector, polarization)\n geometry_correction = _geometry_correction(pixel_center, orientation)\n \n return pixel_position_reciprocal, pixel_position_reciprocal_norm, polarization_correction, geometry_correction\n\n######################################################################\n# The following functions are utilized to get reciprocal space grid mesh\n######################################################################\n\ndef get_reciprocal_mesh(voxel_num_1d, voxel_length):\n \n voxel_half_num_1d = (voxel_num_1d-1)/2\n \n x_meshgrid = (np.array(range(voxel_num_1d)) - voxel_half_num_1d)*voxel_length\n reciprocal_mesh_stack = np.meshgrid(x_meshgrid, x_meshgrid, x_meshgrid ) \n\n reciprocal_mesh= np.zeros((voxel_num_1d, voxel_num_1d, voxel_num_1d, 3))\n for l in range(3):\n reciprocal_mesh[:,:,:,l] = reciprocal_mesh_stack[l][:,:,:]\n \n return reciprocal_mesh \n \ndef get_weight_in_reciprocal_space(pixel_position_reciprocal, voxel_length, voxel_num_1d):\n \n ##convert_to_voxel_unit \n pixel_position_reciprocal_voxel = pixel_position_reciprocal / voxel_length\n voxel_half_num_1d = int(voxel_num_1d/2)\n \n ## Get the indexes of the eight nearest points.\n num_panel, num_x, num_y, _ = pixel_position_reciprocal.shape\n _indexes = np.zeros((num_panel, num_x, num_y, 2 ,3))\n for l in range(3):\n _indexes[:,:,:,0,l] = (np.floor(pixel_position_reciprocal_voxel[:,:,:,l])\n + voxel_half_num_1d).astype('int')\n _indexes[:,:,:,1,l] = (np.floor(pixel_position_reciprocal_voxel[:,:,:,l])\n + voxel_half_num_1d +1).astype('int')\n \n indexes = np.zeros((num_panel,num_x, num_y, 8, 3))\n for l in range(2):\n for m in range(2):\n for n in range(2):\n indexes[:,:,:, l*4+m*2+n,0] = _indexes[:,:,:,l,0] \n indexes[:,:,:, l*4+m*2+n,1] = _indexes[:,:,:,m,1] \n indexes[:,:,:, l*4+m*2+n,2] = _indexes[:,:,:,n,2] \n \n del _indexes\n \n difference = indexes - pixel_position_reciprocal_voxel[:,:,:, np.newaxis, :]\n distance = np.sqrt(np.sum(np.square(difference),axis=-1))\n \n del difference\n \n summation = np.sum(distance,axis=-1)\n weight = distance/summation[:,:,:,np.newaxis]\n \n return indexes.astype(np.int), weight\n\n######################################################################\n# The following functions are utilized to assemble the images\n######################################################################\n\ndef assemble_image_from_index_and_panel(image_stack, index):\n # get boundary\n index_max_x = np.max(index[:,:,:,0])\n index_max_y = np.max(index[:,:,:,1])\n # set holder\n image = np.zeros((index_max_x, index_max_y))\n # loop through the panels\n for l in range(index.shape[0]):\n image[index[l,:,:,:]] = image_stack[l,:,:]\n \n return image\n\ndef batch_assemble_image_from_index_and_panel(image_stack, index):\n pass\n\n######################################################################\n# The following functions are utilized to rotate the pixels in reciprocal space\n######################################################################\n\ndef rotate_pixels_in_reciprocal_space(rot_mat, pixels_position):\n pixels_position_1d = reshape_pixels_position_arrays_to_1d(pixels_position)\n pixels_position_1d = pixels_position_1d.dot(rot_mat)\n return np.reshape(pixels_position_1d, pixels_position.shape)\n\n\n######################################################################\n# Some trivial geometry calculations\n######################################################################\n\ndef corrCoeff(X, Y):\n x = X.reshape(-1)\n y = Y.reshape(-1)\n x -= np.mean(x)\n y -= np.mean(y)\n return np.dot(x, y) / np.sqrt(np.dot(x, x)*np.dot(y, y))\n\n\n# Converters between different descriptions of 3D rotation.\ndef angleAxis2rot3D(axis, theta):\n \"\"\"\n Convert rotation with angle theta around a certain axis to a rotation matrix in 3D.\n \"\"\"\n if len(axis) is not 3:\n raise ValueError('Number of axis element must be 3!')\n axis = axis.astype(float)\n axis /= np.linalg.norm(axis)\n a = axis[0]\n b = axis[1]\n c = axis[2]\n cosTheta = np.cos(theta)\n bracket = 1 - cosTheta\n aBracket = a * bracket\n bBracket = b * bracket\n cBracket = c * bracket\n sinTheta = np.sin(theta)\n aSinTheta = a * sinTheta\n bSinTheta = b * sinTheta\n cSinTheta = c * sinTheta\n rot3D = np.array([[a*aBracket+cosTheta, a*bBracket-cSinTheta, a*cBracket+bSinTheta],\n [b*aBracket+cSinTheta, b*bBracket+cosTheta, b*cBracket-aSinTheta],\n [c*aBracket-bSinTheta, c*bBracket+aSinTheta, c*cBracket+cosTheta]])\n return rot3D\n\n\ndef euler2rot3D(psi, theta, phi):\n \"\"\"\n Convert rotation with euler angle (psi, theta, phi) to a rotation matrix in 3D.\n \"\"\"\n Rphi = np.array([[np.cos(phi), np.sin(phi), 0],\n [-np.sin(phi), np.cos(phi), 0],\n [0, 0, 1]])\n Rtheta = np.array([[np.cos(theta), 0, -np.sin(theta)],\n [0, 1, 0],\n [np.sin(theta), 0, np.cos(theta)]])\n Rpsi = np.array([[np.cos(psi), np.sin(psi), 0],\n [-np.sin(psi), np.cos(psi), 0],\n [0, 0, 1]])\n return np.dot(Rpsi, np.dot(Rtheta, Rphi))\n\n\ndef euler2quaternion(psi, theta, phi):\n \"\"\"\n Convert rotation with euler angle (psi, theta, phi) to quaternion description.\n \"\"\"\n if abs(psi) == 0 and abs(theta) == 0 and abs(phi) == 0:\n quaternion = np.array([1., 0., 0., 0.])\n else:\n R = euler2rot3D(psi, theta, phi)\n W = np.array([R[1, 2]-R[2, 1], R[2, 0]-R[0, 2], R[0, 1]-R[1, 0]])\n if W[0] >= 0:\n W /= np.linalg.norm(W)\n else:\n W /= np.linalg.norm(W) * -1\n theta = np.arccos(0.5 * (np.trace(R) - 1))\n CCisTheta = corrCoeff(R, angleAxis2rot3D(W, theta))\n CCisNegTheta = corrCoeff(R, angleAxis2rot3D(W, -theta))\n if CCisNegTheta > CCisTheta:\n theta = -theta\n quaternion = np.array([np.cos(theta/2.), np.sin(theta/2.)*W[0], np.sin(theta/2.)*W[1], np.sin(theta/2.)*W[2]])\n if quaternion[0] < 0:\n quaternion *= -1\n return quaternion\n\n\ndef quaternion2AngleAxis(quaternion):\n \"\"\"\n Convert quaternion to a right hand rotation theta about certain axis.\n \"\"\"\n HA = np.arccos(quaternion[0])\n theta = 2 * HA\n if theta < np.finfo(float).eps:\n theta = 0\n axis = np.array([1, 0, 0])\n else:\n axis = quaternion[[1, 2, 3]] / np.sin(HA)\n return theta, axis\n\n\ndef quaternion2rot3D(quaternion):\n \"\"\"\n Convert quaternion to a rotation matrix in 3D.\n Use zyz convention after Heymann (2005)\n \"\"\"\n theta, axis = quaternion2AngleAxis(quaternion)\n return angleAxis2rot3D(axis, theta)\n\n\n# Functions to generate rotations for different cases: uniform(1d), uniform(3d), random.\ndef pointsOn1Sphere(numPts, rotationAxis):\n \"\"\"\n Given number of points and axis of rotation, distribute evenly on the surface of a 1-sphere (circle).\n \"\"\"\n points = np.zeros((numPts, 4))\n incAng = 360. / numPts\n myAng = 0\n if rotationAxis == 'y':\n for i in range(numPts):\n points[i, :] = euler2quaternion(0, myAng * np.pi / 180, 0)\n myAng += incAng\n elif rotationAxis == 'z':\n for i in range(numPts):\n points[i, :] = euler2quaternion(0, 0, myAng * np.pi / 180)\n myAng += incAng\n return points\n\n\ndef pointsOn4Sphere(numPts):\n \"\"\"\n Given number of points, distribute evenly on hyper surface of a 4-sphere.\n \"\"\"\n points = np.zeros((2*numPts, 4))\n N = 4\n surfaceArea = N * np.pi ** (N/2) / (N/2) # for even N\n delta = np.exp(np.log(surfaceArea / numPts) / 3)\n Iter = 0\n ind = 0\n maxIter = 1000\n while ind != numPts and Iter < maxIter:\n ind = 0\n deltaW1 = delta\n w1 = 0.5 * deltaW1\n while w1 < np.pi:\n q0 = np.cos(w1)\n deltaW2 = deltaW1 / np.sin(w1)\n w2 = 0.5 * deltaW2\n while w2 < np.pi:\n q1 = np.sin(w1) * np.cos(w2)\n deltaW3 = deltaW2 / np.sin(w2)\n w3 = 0.5 * deltaW3\n while w3 < 2 * np.pi:\n q2 = np.sin(w1) * np.sin(w2) * np.cos(w3)\n q3 = np.sin(w1) * np.sin(w2) * np.sin(w3)\n points[ind, :] = np.array([q0, q1, q2, q3])\n ind += 1\n w3 += deltaW3\n w2 += deltaW2\n w1 += deltaW1\n delta *= np.exp(np.log(float(ind) / numPts) / 3)\n Iter += 1\n return points[0:numPts, :]\n\n\ndef getRandomRotation(rotationAxis):\n \"\"\"\n Generate random rotation.\n \"\"\"\n if rotationAxis == 'y':\n u = np.random.random() * 2 * np.pi # random angle between [0, 2pi]\n return euler2quaternion(0, u, 0)\n else:\n u = np.random.rand(3) # uniform random distribution in the [0,1] interval\n # generate uniform random quaternion on SO(3)\n return np.array([np.sqrt(1-u[0]) * np.sin(2*np.pi*u[1]), np.sqrt(1-u[0]) * np.cos(2*np.pi*u[1]),\n np.sqrt(u[0]) * np.sin(2*np.pi*u[2]), np.sqrt(u[0]) * np.cos(2*np.pi*u[2])])\n\n######################################################################\n# Obsolete\n######################################################################\n\n'''\ndef rotation_matrix(axis, theta):\n \"\"\"\n Return the rotation matrix associated with counterclockwise rotation about\n the given axis by theta radians.\n \"\"\"\n axis = np.asarray(axis)\n axis = axis/math.sqrt(np.dot(axis, axis))\n a = math.cos(theta/2.0)\n b, c, d = -axis*math.sin(theta/2.0)\n aa, bb, cc, dd = a*a, b*b, c*c, d*d\n bc, ad, ac, ab, bd, cd = b*c, a*d, a*c, a*b, b*d, c*d\n return np.array([[aa+bb-cc-dd, 2*(bc+ad), 2*(bd-ac)],\n [2*(bc-ad), aa+cc-bb-dd, 2*(cd+ab)],\n [2*(bd+ac), 2*(cd-ab), aa+dd-bb-cc]])\n \n \ndef convert_to_poisson(dp):\n \"\"\"\n Add poisson noise to a certain diffraction pattern dp.\n \"\"\"\n return np.random.poisson(dp)\n\n\n'''\n\n\n\n","sub_path":"pysingfel/geometry.py","file_name":"geometry.py","file_ext":"py","file_size_in_byte":17044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"264482762","text":"# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n\n# http://www.apache.org/licenses/LICENSE-2.0.html\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 yaml\nfrom pyspark import SparkContext\nfrom pyspark.sql import HiveContext\nfrom pyspark.sql.functions import lit, col, udf, array, mean\nfrom pyspark.sql.types import FloatType, StringType, StructType, StructField, ArrayType, MapType\nimport argparse\nfrom pyspark.sql.functions import udf\nimport time\nimport math\n\n'''\nspark-submit --executor-memory 16G --driver-memory 24G --num-executors 16 --executor-cores 5 --master yarn --conf spark.driver.maxResultSize=8g distance_table_list.py config.yml\n'''\n\n\ndef euclidean(l1):\n def _euclidean(l2):\n list = []\n for item in l1:\n similarity = 1 - (math.sqrt(sum([(item[i]-l2[i]) ** 2 for i in range(len(item))]))/math.sqrt(len(item)))\n list.append(similarity)\n return list\n return _euclidean\n\n\ndef dot(l1):\n def _dot(l2):\n list = []\n for item in l1:\n similarity = sum([item[i]*l2[i] for i in range(len(item))])\n list.append(similarity)\n return list\n return _dot\n\n\ndef ux(l1):\n if alg == \"euclidean\":\n _udf_similarity = udf(euclidean(l1), ArrayType(FloatType()))\n if alg ==\"dot\":\n _udf_similarity = udf(dot(l1), ArrayType(FloatType()))\n return _udf_similarity\n\n\n\ndef l(d):\n s = [value for key, value in d.items()]\n return s\nudf_tolist = udf(l, ArrayType(FloatType()))\n\ndef top_n(l):\n #### top 10\n n = 10\n l.sort()\n return l[-n:]\nudf_top_n = udf(top_n, ArrayType(FloatType()))\n\ndef _top_n(l1, l2):\n n = 10\n l = sorted(l1+l2)\n return l[-n:]\n\n_udf_top_n = udf(_top_n, ArrayType(FloatType()))\n\ndef _mean(l):\n ave = sum(l)/len(l)\n return ave\nudf_mean = udf(_mean, FloatType())\n\ndef run(hive_context, cfg):\n\n ## load dataframes\n lookalike_score_table_norm = cfg['output']['score_norm_table']\n keywords_table = cfg[\"input\"][\"keywords_table\"]\n seeduser_table = cfg[\"input\"][\"seeduser_table\"]\n lookalike_similarity_table = cfg[\"output\"][\"similarity_table\"]\n\n command = \"SELECT * FROM {}\"\n df = hive_context.sql(command.format(lookalike_score_table_norm))\n df_keywords = hive_context.sql(command.format(keywords_table))\n df_seed_user = hive_context.sql(command.format(seeduser_table))\n\n\n #### creating a tuple of did and kws for seed users\n if alg == \"dot\":\n df = df.withColumn('kws_norm_list', udf_tolist(col('kws_norm')))\n if alg == \"euclidean\":\n df = df.withColumn('kws_norm_list', udf_tolist(col('kws')))\n df_seed_user = df_seed_user.join(df.select('did','kws_norm_list'), on=['did'], how='left')\n seed_user_list = df_seed_user.select('did', 'kws_norm_list').collect()\n\n## batch 1 : 0-100 801 seed\n batch_length = 800\n c = 0\n #### i=0, c=0 , batched_user=[0,200], top_10\n total_c = len(seed_user_list)\n df = df.withColumn('top_10', array(lit(0.0)))\n while total_c > 0 :\n len_tobe_p = min(batch_length,total_c)\n total_c-= len_tobe_p\n batched_user = [item[1] for item in seed_user_list[c: c+len_tobe_p]]\n df = df.withColumn(\"similarity_list\",ux(batched_user)(col('kws_norm_list')))\n df = df.withColumn(\"top_10\", _udf_top_n(col(\"similarity_list\"),col(\"top_10\")))\n c+=len_tobe_p\n\n df = df.withColumn(\"mean_score\",udf_mean(col(\"top_10\")))\n df.write.option(\"header\", \"true\").option(\n \"encoding\", \"UTF-8\").mode(\"overwrite\").format('hive').saveAsTable(lookalike_similarity_table)\n extended_did = df.sort(col('mean_score').desc()).select('did', 'mean_score')\n\n\n\nif __name__ == \"__main__\":\n start = time.time()\n parser = argparse.ArgumentParser(description=\" \")\n parser.add_argument('config_file')\n args = parser.parse_args()\n with open(args.config_file, 'r') as yml_file:\n cfg = yaml.safe_load(yml_file)\n\n sc = SparkContext.getOrCreate()\n sc.setLogLevel('WARN')\n hive_context = HiveContext(sc)\n\n ## select similarity algorithm\n alg = cfg[\"input\"][\"alg\"]\n run(hive_context=hive_context, cfg=cfg)\n sc.stop()\n end = time.time()\n print('Runtime of the program is:', (end - start))\n","sub_path":"Model/lookalike-model/lookalike_model/application/legacy_files/distance_table_list.py","file_name":"distance_table_list.py","file_ext":"py","file_size_in_byte":4862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"351527291","text":"\n\n#calss header\nclass _SETTLEMENT():\n\tdef __init__(self,): \n\t\tself.name = \"SETTLEMENT\"\n\t\tself.definitions = [u'an official agreement that finishes an argument: ', u'an arrangement to end a disagreement involving a law having been broken, without taking it to a law court, or an amount of money paid as part of such an arrangement: ', u'a place where people come to live or the process of settling in such a place: ', u'the action of paying money to someone: ', u'the process of the slow sinking of a building or the ground']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_settlement.py","file_name":"_settlement.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"429968938","text":"# -*- coding: utf-8 -*-\n# Time: 2019/6/8 13:02\n# Author: laugc\n# Email: hahalgc@gmail.com\n# File: py74_turtle_1.py\n\nfrom turtle import *\n\n\"\"\"\n海龟绘图\n\"\"\"\n\nt = Turtle()\n\n# 设置笔刷宽度\nt.width(4)\n# 前进\nt.forward(200)\n# 右转 90 度\nt.right(90)\n\n# 笔刷颜色\nt.pencolor('red')\nt.forward(100)\nt.right(90)\n\nt.pencolor('green')\nt.forward(200)\nt.right(90)\n\nt.pencolor('blue')\nt.forward(100)\nt.right(90)\n\n# 调用 done() 使得窗口等待被关闭,否则将立刻关闭窗口\ndone()\n","sub_path":"graphic_interface/py74_turtle_1.py","file_name":"py74_turtle_1.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"4392669","text":"import socket\n\n# 创建udp套接字\nudp_socket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)\n# 准备接收方数据地址\ndest_addr = ('192.168.0.103',8080) # 注意 是元组,ip是字符串,端口是数字\n\n# 从键盘获取数据\nsend_data = input(\"请输入您要发送的数据:\")\n# 发送数据到指定的电脑\nudp_socket.sendto(send_data.encode('gbk'),dest_addr)\n# 关闭套接字\n\n# 等待对方发送数据并接受\nrecv_data = udp_socket.recvfrom(1024) # 1024表示本次接收的最大字节数\n\n# 6. 显示对方发送的数据\n# 接收到的数据recv_data是一个元组\n# 第1个元素是对方发送的数据\n# 第2个元素是对方的ip和端口\nprint(recv_data[0].decode(\"gbk\"))\nprint(recv_data[1])\nudp_socket.close()","sub_path":"网络基础/UDP/it_02_UDP发送多条数据.py","file_name":"it_02_UDP发送多条数据.py","file_ext":"py","file_size_in_byte":746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"522784963","text":"import os, socket, datetime\nfrom lxml import etree, objectify\n\n#------------------------------------------------------------\n# This class is for coloring purposes\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#---------------------------------------------------------\n#function: parse_xml\n#arguments:\n# - xml_file: path with name of the xml file to read\n#return values:\n# - xml: content of the xml file\n#---------------------------------------------------------\ndef parse_xml(xml_file):\n with open(xml_file) as file:\n xml = file.read()\n return xml\n\n#---------------------------------------------------------\n#function: set_xml\n#arguments:\n# - command: complete string input of the terminal\n#return values:\n# - xmlfile: path with name of the xmlfile to read -\n# send empty if file does not exists\n#---------------------------------------------------------\ndef set_xml(command):\n parts = command.split()\n if len(parts) < 2:\n print(\"Pass path to the xml-file as an argument\")\n return \"\"\n xmlfile = parts[1]\n if os.path.exists(xmlfile):\n check_alive(xmlfile)\n print (bcolors.OKGREEN+xmlfile+ \" is set as xml-file\"+ bcolors.ENDC) \n return xmlfile\n else:\n print(\"Xml file not found\")\n return \"\"\n#---------------------------------------------------------\n#function: lset_xml\n#arguments:\n# - command: complete string input of the terminal\n#return values:\n# - xmlfile: path with name of the xmlfile to read -\n# send empty if file does not exists\n# Note: Same as set_xml but without checking reachability\n#---------------------------------------------------------\ndef l_set_xml(command):\n parts = command.split()\n if len(parts) < 2:\n print(\"Pass path to the xml-file as an argument\")\n return \"\"\n xmlfile = parts[1]\n if os.path.exists(xmlfile):\n print(xmlfile + \" was set as xml-file\")\n return xmlfile\n else:\n print(\"Xml file not found\")\n return \"\"\n#---------------------------------------------------------\n#function: create_log\n#arguments:\n# - path: string with path of the logfile\n#---------------------------------------------------------\ndef create_log(path):\n global logfile\n logfile = open(path,'a',0)\n\n#---------------------------------------------------------\n#function: log\n#arguments:\n# - message: string with message to write to logfile\n#---------------------------------------------------------\ndef log(message):\n print(message)\n logfile.write(message+'\\n')\n\n#---------------------------------------------------------\n#function: get_logfiles\n#arguments:\n# - sockets: array of sockets to get logfiles from\n#---------------------------------------------------------\ndef get_logfiles(sockets):\n if sockets != -1:\n #get timestamp\n time = datetime.datetime.now()\n timestamp = str(time.day)+\"_\"+str(time.month)+\"_\"+str(time.hour)+\"_\"+str(time.minute)+\"_\"+str(time.second)\n #create new folder\n os.system(\"mkdir logfiles/\"+timestamp)\n daemonpath = \"/home/asn/asn_daemon/logfiles/*\"\n for soc in sockets:\n ip = soc.getpeername()[0]\n id = ip.split(\".\")[-1]\n id_folder = \"pi_\"+str(id)\n os.system(\"mkdir logfiles/\"+timestamp+\"/\"+id_folder)\n os.system(\"scp -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o LogLevel=error asn@\"+str(ip)+\":\"+daemonpath+\" logfiles/\"+timestamp+\"/\"+id_folder+\"/\")\n print(\"all logs transferred\")\n else:\n print(\"Sockets not connected yet\")\n\ndef check_alive(xmlfile):\n # parse xml to get pi-ids\n target_pi_id = []\n root_as_string = parse_xml(xmlfile)\n root = objectify.fromstring(root_as_string)\n nodes = []\n for element in root.getchildren():\n nodes.append(etree.tostring(element))\n\n # add every pi-id to list\n for node in nodes:\n target_pi_id.append(objectify.fromstring(node).get(\"pi_id\"))\n\n for id in target_pi_id:\n try:\n int(id)\n errCode = 0\n errCode = os.system(\"ssh -t -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o LogLevel=error asn@10.1.1.\"+id+\" 'sudo systemctl restart asn_daemon 1>/dev/null 2>/dev/null'\")\n if errCode != 0:\n print (bcolors.WARNING + \"Warning - Please check the reachability and make sure that daemon is running\\\\ or try the killproccess command\"+ bcolors.ENDC) \n \n except Exception:\n errCode = os.system(\"ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o LogLevel=error -t asn@\"+id+\" 'sudo systemctl restart asn_daemon 1>/dev/null 2>/dev/null'\")\n if errCode != 0:\n print (bcolors.WARNING + \"Warning - Please check the reachability and make sure that daemon is running\\n or try the killproccess command\"+ bcolors.ENDC) \n","sub_path":"asn_server/bin/xml_and_log.py","file_name":"xml_and_log.py","file_ext":"py","file_size_in_byte":5053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"124749902","text":"#############################################################################\n# https://www.hackerrank.com/challenges/equal-stacks/problem\n# Equal Stacks\n\ndef equalStacks(h1, h2, h3):\n sum_1 = sum(h1)\n sum_2 = sum(h2)\n sum_3 = sum(h3)\n last_1 = 0\n last_2 = 0\n last_3 = 0\n\n while not (sum_1 == sum_2 and sum_1 == sum_3):\n if sum_1 >= sum_2 and sum_1 >= sum_3:\n sum_1 -= h1[last_1]\n last_1 += 1\n elif sum_2 >= sum_1 and sum_2 >= sum_3:\n sum_2 -= h2[last_2]\n last_2 += 1\n elif sum_3 >= sum_1 and sum_3 >= sum_1:\n sum_3 -= h3[last_3]\n last_3 += 1\n\n return sum_1\n\nh1 = [3, 2, 1, 1, 1]\nh2 = [4, 3, 2]\nh3 = [1, 1, 4, 1]\n\nh1 = [1, 1, 1, 1, 2]\nh2 = [3, 7]\nh3 = [1, 3, 1]\n\n# print(equalStacks(h1, h2, h3))\n\n#############################################################################\n# https://www.hackerrank.com/challenges/maximum-element/problem\n# Maximum Element\n\n#!/bin/python3\n\n\nimport os\nfrom collections import deque\n\n#\ndef naximumElement(n, queries):\n stack_deque = deque()\n max_stack = deque()\n curr_max = 0\n result = []\n for q in queries:\n if q[0] == 1:\n stack_deque.append(q[1])\n curr_max = max(curr_max, q[1])\n max_stack.append(curr_max)\n elif q[0] == 2:\n stack_deque.pop()\n max_stack.pop()\n if max_stack:\n curr_max = max_stack[-1]\n else:\n curr_max = 0\n else:\n result.append(curr_max)\n return result\n\n\n# if __name__ == '__main__':\n# fptr = open(os.environ['OUTPUT_PATH'], 'w')\n#\n# n = int(input())\n#\n# queries = []\n#\n# for _ in range(n):\n# queries.append(list(map(int, input().rstrip().split())))\n#\n# result = naximumElement(n, queries)\n#\n# fptr.write('\\n'.join(map(str, result)))\n# fptr.write('\\n')\n#\n# fptr.close()\n\nqueries = [\n [1, 97],\n [2],\n [1, 20],\n [2],\n [1, 26],\n [1, 20],\n [2],\n [3],\n [1, 91],\n [3]\n]\n\n# print(naximumElement(n, queries))\n\n#############################################################################","sub_path":"HackerRank/DataStructures_Stacks.py","file_name":"DataStructures_Stacks.py","file_ext":"py","file_size_in_byte":2167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"241705291","text":"from libs.module import *\nfrom libs.uds import *\nfrom libs.frag import *\nimport json\nimport re\nimport collections\nimport ast\n\n\nclass mod_stat(CANModule):\n name = \"Service discovery and statistic\"\n\n help = \"\"\"\n \n This module doing statistic for found CAN messages, putting into STDOUT or file (text/csv).\n Good to see anomalies, behaviour and discovery new IDs\n \n Init parameters: NONE\n \n \"\"\"\n\n _bodyList = None\n _logFile = False\n ISOList = None\n UDSList = None\n id = 3\n _active = True\n version = 1.0\n\n def get_status(self):\n return \"Current status: \" + str(self._active) + \"\\nSniffed frames: \" + str(len(self.all_frames))+\"\\nDiff mode: \" + str(self._diff) +\\\n \"\\nSniffed in Diff mode: \" + str(len(self.all_diff_frames))\n\n def do_init(self, params):\n self.all_frames = []\n self.all_diff_frames = []\n self.meta_data = {}\n self._bodyList = collections.OrderedDict()\n self._diff = False\n\n self.shift = params.get('uds_shift', 8)\n\n if 'meta_file' in params:\n self.dprint(1, self.do_load_meta(params['meta_file']))\n\n self._cmdList['p'] = [\"Print current table\", 0, \"\", self.do_print, True]\n self._cmdList['a'] = [\"Analyses of captured traffic\", 1, \"\", self.do_anal, True]\n self._cmdList['D'] = [\"Enable/Disable Diff mode\", 0, \"\", self.enable_diff, True]\n self._cmdList['I'] = [\"Print Diff frames\", 1, \" [COUNT filter (default none, put number)] \", self.print_diff, False]\n self._cmdList['N'] = [\"Print Diff frames (new ID only)\", 1, \"[COUNT filter (default none, put number)]\", self.print_diff_id, False]\n self._cmdList['Y'] = [\"Dump Diff in replay format\", 1, \" \", self.print_dump_diff, False]\n self._cmdList['c'] = [\"Clean table, remove alerts\", 0, \"\", self.do_clean, True]\n self._cmdList['i'] = [\"Meta-data: add description for frames\", 1, \", , \", self.do_add_meta_descr_data, True]\n self._cmdList['l'] = [\"Load meta-data\", 1, \"\", self.do_load_meta, True]\n self._cmdList['z'] = [\"Save meta-data\", 1, \"\", self.do_save_meta, True]\n self._cmdList['r'] = [\"Dump ALL in replay format\", 1, \" \", self.do_dump_replay, True]\n self._cmdList['d'] = [\"Dump STAT in CSV format\", 1, \" \", self.do_dump_csv, True]\n\n def do_add_meta_descr_data(self, input_params):\n try:\n fid, body, descr = input_params.split(',')\n if fid.strip().find('0x') == 0:\n num_fid = int(fid, 16)\n else:\n num_fid = int(fid)\n if 'description' not in self.meta_data:\n self.meta_data['description'] = {}\n\n self.meta_data['description'][(num_fid, body.strip().upper())] = descr\n\n return \"Description data has been added\"\n except Exception as e:\n return \"Description data META error: \" + str(e)\n\n def get_meta_descr(self, fid, msg):\n descrs = self.meta_data.get('description', {})\n for (key, body) in list(descrs.keys()):\n if fid == key:\n if(re.match(body, self.get_hex(msg), re.IGNORECASE)):\n return str(descrs[(key, body)])\n return \" \"\n\n\n def do_load_meta(self, filename):\n try:\n data = \"\"\n with open(filename.strip(), \"r\") as ins:\n for line in ins:\n data += line\n self.meta_data = ast.literal_eval(data)\n\n except Exception as e:\n return \"Can't load META: \" + str(e)\n return \"Loaded META from \" + filename\n\n def do_save_meta(self, filename):\n try:\n _file = open(filename.strip(), 'w')\n _file.write(str(self.meta_data))\n _file.close()\n except Exception as e:\n return \"Can't save META: \" + str(e)\n return \"Saved META to \" + filename\n\n # Detect ASCII data\n @staticmethod\n def ret_ascii(text_array):\n return_str = \"\"\n for byte in text_array:\n if 31 < byte < 127:\n return_str += chr(byte)\n else:\n return_str += '.'\n return return_str\n\n # Detect ASCII data\n @staticmethod\n def is_ascii(text_array):\n bool_ascii = False\n ascii_cnt = 0\n pre_byte = False\n\n for byte in text_array:\n if 31 < byte < 127:\n if pre_byte:\n ascii_cnt += 1\n if ascii_cnt > 1:\n bool_ascii = True\n break\n else:\n pre_byte = True\n else:\n pre_byte = False\n ascii_cnt = 0\n\n if ascii_cnt > 5:\n bool_ascii = True\n\n return bool_ascii\n\n @staticmethod\n def create_short_table(input_frames):\n _bodyList = collections.OrderedDict()\n for can_msg in input_frames:\n if can_msg.CANFrame.frame_id not in _bodyList:\n _bodyList[can_msg.CANFrame.frame_id] = collections.OrderedDict()\n _bodyList[can_msg.CANFrame.frame_id][(\n can_msg.CANFrame.frame_length,\n can_msg.CANFrame.frame_raw_data,\n can_msg.bus,\n can_msg.CANFrame.frame_ext)\n ] = 1\n else:\n if (can_msg.CANFrame.frame_length,\n can_msg.CANFrame.frame_raw_data,\n can_msg.bus,\n can_msg.CANFrame.frame_ext) not in _bodyList[can_msg.CANFrame.frame_id]:\n _bodyList[can_msg.CANFrame.frame_id][(\n can_msg.CANFrame.frame_length,\n can_msg.CANFrame.frame_raw_data,\n can_msg.bus,\n can_msg.CANFrame.frame_ext)\n ] = 1\n else:\n _bodyList[can_msg.CANFrame.frame_id][(\n can_msg.CANFrame.frame_length,\n can_msg.CANFrame.frame_raw_data,\n can_msg.bus,\n can_msg.CANFrame.frame_ext)\n ] += 1\n return _bodyList\n\n def find_iso_tp(self):\n message_iso = {}\n iso_list = []\n for can_msg in self.all_frames:\n if can_msg.CANFrame.frame_id not in message_iso:\n message_iso[can_msg.CANFrame.frame_id] = ISOTPMessage(can_msg.CANFrame.frame_id)\n\n if 1 < can_msg.CANFrame.frame_length:\n ret = message_iso[can_msg.CANFrame.frame_id].add_can(can_msg.CANFrame)\n if ret < 0:\n del message_iso[can_msg.CANFrame.frame_id]\n elif ret == 1:\n iso_list.append(message_iso[can_msg.CANFrame.frame_id])\n del message_iso[can_msg.CANFrame.frame_id]\n else:\n del message_iso[can_msg.CANFrame.frame_id]\n return iso_list\n\n def find_uds(self, iso_list):\n uds_list = UDSMessage(self.shift)\n for message_iso in iso_list:\n uds_list.handle_message(message_iso)\n return uds_list\n\n def find_frags(self):\n frg_list = collections.OrderedDict()\n for can_msg in self.all_frames:\n index_bytes = self.meta_data.get(can_msg.CANFrame.frame_id, {}).get('id_index', None)\n if can_msg.CANFrame.frame_id not in frg_list:\n frg_list[can_msg.CANFrame.frame_id] = FragmentedCAN()\n\n if index_bytes: # We have META data\n idx1, idx2, strt = index_bytes.strip().split('-')\n idx1 = int(idx1)\n idx2 = int(idx2)\n strt = int(strt)\n frg_list[can_msg.CANFrame.frame_id].add_can_meta(can_msg.CANFrame, idx1, idx2, strt)\n\n return frg_list\n\n def find_loops(self):\n frg_list = collections.OrderedDict()\n for fid, lst in self._bodyList.items():\n frg_list[fid] = FragmentedCAN()\n for (lenX, msg, bus, mod), cnt in lst.items():\n frg_list[fid].add_can_loop(CANMessage.init_data(fid, lenX, msg))\n\n return frg_list\n\n def do_anal(self, format = \"ALL\"):\n if self._diff:\n self.enable_diff()\n\n self._bodyList = self.create_short_table(self.all_frames)\n iso_tp_list = self.find_iso_tp()\n uds_list = self.find_uds(iso_tp_list)\n frag_list = self.find_frags()\n loops_list = self.find_loops()\n ret_str = \"\"\n\n format.upper()\n\n _iso_tbl = collections.OrderedDict()\n for msg in iso_tp_list:\n if msg.message_id not in _iso_tbl:\n _iso_tbl[msg.message_id] = collections.OrderedDict()\n _iso_tbl[msg.message_id][(msg.message_length, bytes(msg.message_data))] = 1\n else:\n if (msg.message_length, bytes(msg.message_data)) in _iso_tbl[msg.message_id]:\n _iso_tbl[msg.message_id][(msg.message_length, bytes(msg.message_data))] += 1\n else:\n _iso_tbl[msg.message_id][(msg.message_length, bytes(msg.message_data))] = 1\n\n if format.strip() not in [\"ISO\",\"FRAG\"]:\n # Print out UDS\n ret_str += \"UDS Detected:\\n\\n\"\n for fid, services in uds_list.sessions.items():\n for service, body in services.items():\n text = \" (N/A) \"\n if service in UDSMessage.services_base:\n for sub in UDSMessage.services_base[service]:\n if list(sub.keys())[0] == body['sub'] or None:\n text = \" (\" + list(sub.values())[0] + \") \"\n if text == \" (N/A) \":\n text = \" (\" + list(UDSMessage.services_base[service][0].values())[0] + \") \"\n if body['status'] == 1:\n data = body['response']['data']\n data_ascii = \"\\n\"\n if self.is_ascii(body['response']['data']):\n data_ascii = \"\\n\\t\\tASCII: \" + self.ret_ascii(data)+\"\\n\"\n ret_str += \"\\n\\tID: \" + hex(fid) + \" Service: \" + str(hex(service)) + \" Sub: \" + (str(\n hex(body['sub'])) if body['sub'] else \"None\") + text + \"\\n\\t\\tResponse: \" + self.get_hex(bytes(data)) + data_ascii\n elif body['status'] == 2:\n ret_str += \"\\n\\tID: \" + hex(fid) + \" Service: \" + str(hex(service)) + \" Sub: \" + (str(\n hex(body['sub'])) if body['sub'] else \"None\") + text + \"\\n\\t\\tError: \" + body['response']['error']\n\n if format.strip() not in [\"ISO\", \"UDS\"]:\n # Print detected loops\n ret_str += \"\\n\\nDe-Fragmented frames (using loop-based detection):\\n\"\n local_temp = {}\n for fid, data in loops_list.items():\n data.clean_build_loop()\n for message in data.messages:\n if (fid, bytes(message['message_data'])) not in local_temp:\n ret_str += \"\\n\\tID \" + hex(fid) + \" and length \" + str(message['message_length']) + \"\\n\"\n ret_str += \"\\t\\tData: \" + self.get_hex(bytes(message['message_data']))\n if self.is_ascii(message['message_data']):\n ret_str += \"\\n\\t\\tASCII: \" + self.ret_ascii(bytes(message['message_data'])) + \"\\n\\n\"\n local_temp[(fid, bytes(message['message_data']))] = None\n\n if format.strip() not in [\"UDS\",\"FRAG\"]:\n # Print out ISOTP messages\n ret_str += \"\\nISO TP Messages:\\n\\n\"\n for fid, lst in _iso_tbl.items():\n ret_str += \"\\tID: \" + hex(fid) + \"\\n\"\n for (lenX, msg), cnt in lst.items():\n ret_str += \"\\t\\tDATA: \" + self.get_hex(msg)\n if self.is_ascii(msg):\n ret_str += \"\\n\\t\\tASCII: \" + self.ret_ascii(msg)\n ret_str += \"\\n\"\n\n return ret_str\n\n def print_dump_diff(self, name):\n table1 = self.create_short_table(self.all_frames)\n try:\n _name = open(name.strip(), 'w')\n for can_msg in self.all_diff_frames:\n if can_msg.CANFrame.frame_id not in list(table1.keys()):\n _name.write(str(can_msg.CANFrame.frame_id) + \":\" + str(can_msg.CANFrame.frame_length) + \":\" + self.get_hex(can_msg.CANFrame.frame_raw_data) + \"\\n\")\n else:\n neq = True\n for (len2, msg, bus, mod), cnt in table1[can_msg.CANFrame.frame_id].items():\n if msg == can_msg.CANFrame.frame_raw_data:\n neq = False\n if neq:\n _name.write(hex(can_msg.CANFrame.frame_id) + \":\" + str(can_msg.CANFrame.frame_length) + \":\" + self.get_hex(can_msg.CANFrame.frame_raw_data) + \"\\n\")\n _name.close()\n except Exception as e:\n self.dprint(2, \"can't open log\")\n return str(e)\n return \"Saved into \" + name.strip()\n\n def do_dump_replay(self, name):\n\n try:\n _name = open(name.strip(), 'w')\n for can_msg in self.all_frames:\n _name.write(hex(can_msg.CANFrame.frame_id) + \":\" + str(can_msg.CANFrame.frame_length) + \":\" + self.get_hex(can_msg.CANFrame.frame_raw_data) + \"\\n\")\n _name.close()\n except Exception as e:\n self.dprint(2, \"can't open log\")\n return str(e)\n return \"Saved into \" + name.strip()\n\n\n def do_dump_csv(self, name):\n self._bodyList = self.create_short_table(self.all_frames)\n try:\n _name = open(name.strip(), 'w')\n _name.write(\"BUS,ID,LENGTH,MESSAGE,ASCII,COMMENT,COUNT\\n\")\n for fid, lst in self._bodyList.items():\n for (len, msg, bus, mod), cnt in lst.items():\n if self.is_ascii(msg):\n data_ascii = '\"' + self.ret_ascii(msg) + '\"'\n else:\n data_ascii = \"\"\n _name.write(\n str(bus) + \",\" + hex(fid) + \",\" + str(len) + \",\" + self.get_hex(msg) + ',' + data_ascii + ',' +\\\n \"\\\"\" + self.get_meta_descr(fid, msg) + \"\\\"\" + ',' + str(cnt) + \"\\n\"\n )\n except Exception as e:\n self.dprint(2, \"can't open log\")\n return str(e)\n return \"Saved into \" + name.strip()\n\n def print_diff(self, count = 0):\n return self.print_diff_orig(0, int(count))\n\n def print_diff_id(self, count = 0):\n return self.print_diff_orig(1, int(count))\n\n def print_diff_orig(self, mode = 0, count = 0):\n if not self._diff:\n return \"Error: Diff mode disabled...\"\n table1 = self.create_short_table(self.all_frames)\n table2 = self.create_short_table(self.all_diff_frames)\n table = \"\"\n rows = [['BUS', 'ID', 'LENGTH', 'MESSAGE', 'ASCII', 'DESCR', 'COUNT']]\n for fid2, lst2 in table2.items():\n if fid2 not in list(table1.keys()):\n\n for (lenX, msg, bus, mod), cnt in lst2.items():\n if self.is_ascii(msg):\n data_ascii = self.ret_ascii(msg)\n else:\n data_ascii = \" \"\n if count == 0 or count == cnt:\n rows.append([str(bus),hex(fid2), str(lenX), self.get_hex(msg), data_ascii, self.get_meta_descr(fid2, msg), str(cnt)])\n elif mode == 0:\n for (lenX, msg, bus, mod), cnt in lst2.items():\n\n if (lenX, msg, bus, mod) not in table1[fid2]:\n if self.is_ascii(msg):\n data_ascii = self.ret_ascii(msg)\n else:\n data_ascii = \" \"\n if count == 0 or count == cnt:\n rows.append([str(bus),hex(fid2), str(lenX), self.get_hex(msg), data_ascii, self.get_meta_descr(fid2, msg), str(cnt)])\n\n cols = list(zip(*rows))\n col_widths = [max(len(value) for value in col) for col in cols]\n format_table = ' '.join(['%%-%ds' % width for width in col_widths ])\n for row in rows:\n table += format_table % tuple(row) + \"\\n\"\n table += \"\\n\"\n return table\n\n def enable_diff(self):\n if self._diff:\n self.all_frames += self.all_diff_frames\n self.all_diff_frames = []\n #self._cmdList['p'][4] = True\n self._cmdList['a'][4] = True\n self._cmdList['r'][4] = True\n self._cmdList['d'][4] = True\n self._cmdList['I'][4] = False\n self._cmdList['N'][4] = False\n self._cmdList['Y'][4] = False\n else:\n #self._cmdList['p'][4] = False\n self._cmdList['a'][4] = False\n self._cmdList['r'][4] = False\n self._cmdList['d'][4] = False\n self._cmdList['I'][4] = True\n self._cmdList['N'][4] = True\n self._cmdList['Y'][4] = True\n self._diff = not self._diff\n return \"Diff mode: \"+str(self._diff)\n\n\n def do_print(self):\n self._bodyList = self.create_short_table(self.all_frames)\n table = \"\\n\"\n rows = [['BUS', 'ID', 'LENGTH', 'MESSAGE', 'ASCII', 'DESCR', 'COUNT']]\n # http://stackoverflow.com/questions/3685195/line-up-columns-of-numbers-print-output-in-table-format\n for fid, lst in self._bodyList.items():\n for (lenX, msg, bus, mod), cnt in lst.items():\n if self.is_ascii(msg):\n data_ascii = self.ret_ascii(msg)\n else:\n data_ascii = \" \"\n rows.append([str(bus),hex(fid), str(lenX), self.get_hex(msg), data_ascii, self.get_meta_descr(fid, msg), str(cnt)])\n\n cols = list(zip(*rows))\n col_widths = [ max(len(value) for value in col) for col in cols ]\n format_table = ' '.join(['%%-%ds' % width for width in col_widths ])\n for row in rows:\n table += format_table % tuple(row) + \"\\n\"\n table += \"\"\n return table\n\n def do_clean(self):\n self.all_frames = []\n self.all_diff_frames = []\n self._diff = False\n self._cmdList['a'][4] = True\n self._cmdList['r'][4] = True\n self._cmdList['d'][4] = True\n self._cmdList['I'][4] = False\n self._cmdList['N'][4] = False\n self._cmdList['Y'][4] = False\n return \"Buffers cleaned!\"\n\n # Effect (could be fuzz operation, sniff, filter or whatever)\n def do_effect(self, can_msg, args):\n if can_msg.CANData:\n if not self._diff:\n self.all_frames.append(can_msg)\n else:\n self.all_diff_frames.append(can_msg)\n\n return can_msg\n","sub_path":"modules/mod_stat.py","file_name":"mod_stat.py","file_ext":"py","file_size_in_byte":19054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"242501299","text":"import EbModule\nfrom EbTablesModule import EbTable, PointerTableEntry\nfrom EbDataBlocks import DataBlock\nfrom modules.Table import ValuedIntTableEntry\nfrom modules.Progress import updateProgress\n\nimport yaml\nfrom re import sub\n\nclass Door:\n # Types: Switch, Rope/Ladder, Door, Escalator, Stairway, Object, Person\n _TYPE_NAMES = [\"switch\", \"rope/ladder\", \"door\", \"escalator\", \"stairway\",\n \"object\", \"person\"]\n def readFromRom(self, rom, addr):\n self._y = rom[addr]\n self._x = rom[addr+1]\n self._type = rom[addr+2]\n ptr = rom.readMulti(addr+3, 2)\n if self._type == 1: # Rope/Ladder\n self._isRope = (ptr == 0x8000)\n elif (self._type == 3) or (self._type == 4): # Escalator and Stairs\n if ptr == 0x8000:\n stairDir = 4\n else:\n stairDir = ptr / 0x100\n self._stairDir = ValuedIntTableEntry(None, None,\n [\"NW\", \"NE\", \"SW\", \"SE\", \"Nowhere\"])\n self._stairDir.setVal(stairDir)\n elif self._type == 2: # Door\n ptr |= 0xF0000\n #self._destTextPtr = rom.readMulti(ptr, 4)\n self._destTextPtr = PointerTableEntry(None, 4)\n self._destTextPtr.setVal(rom.readMulti(ptr, 4))\n if ((self._destTextPtr.val() != 0) and \n ((self._destTextPtr.val() < 0xc00000)\n or (self._destTextPtr.val() > 0xffffff))):\n raise ValueError(\"Invalid Door\")\n self._destFlag = rom.readMulti(ptr+4, 2)\n self._destY = rom[ptr+6]\n self._destY |= (rom[ptr+7] & 0x3f) << 8\n #self._destDir = (rom[ptr+7] & 0xc0) >> 6\n self._destDir = ValuedIntTableEntry(None, None,\n [\"Down\", \"Up\", \"Right\", \"Left\"])\n self._destDir.setVal((rom[ptr+7] & 0xc0) >> 6)\n self._destX = rom.readMulti(ptr+8, 2)\n self._destStyle = rom[ptr+10]\n elif self._type == 0: # Switch\n ptr |= 0xF0000\n self._destFlag = rom.readMulti(ptr, 2)\n #self._destTextPtr = rom.readMulti(ptr+2, 4)\n self._destTextPtr = PointerTableEntry(None, 4)\n self._destTextPtr.setVal(rom.readMulti(ptr+2, 4))\n if ((self._destTextPtr.val() != 0) and \n ((self._destTextPtr.val() < 0xc00000)\n or (self._destTextPtr.val() > 0xffffff))):\n raise ValueError(\"Invalid Switch\")\n elif (self._type == 5) or (self._type == 6): # Object and Person\n ptr |= 0xF0000\n #self._destTextPtr = rom.readmulti(ptr, 4)\n self._destTextPtr = PointerTableEntry(None, 4)\n self._destTextPtr.setVal(rom.readMulti(ptr, 4))\n else:\n raise ValueError(\"Unknown type \" + str(self._type))\n def getTypeAsString(self):\n if self._type == 1:\n if self._isRope:\n return \"rope\"\n else:\n return \"ladder\"\n else:\n return Door._TYPE_NAMES[self._type]\n def setTypeFromString(self, str):\n str = str.lower()\n if str == \"rope\":\n self._type = 1\n self._isRope = True\n elif str == \"ladder\":\n self._type = 1\n self._isRope = False\n else:\n self._type = Door._TYPE_NAMES.index(str)\n def dump(self):\n out = { \"X\": self._x,\n \"Y\": self._y,\n \"Type\": self.getTypeAsString() }\n if (self._type == 3) or (self._type == 4): # Stairs/Escalator\n out[\"Direction\"] = self._stairDir.dump()\n elif self._type == 2: # Door\n out[\"Text Pointer\"] = self._destTextPtr.dump()\n out[\"Event Flag\"] = self._destFlag\n out[\"Destination X\"] = self._destX\n out[\"Destination Y\"] = self._destY\n out[\"Direction\"] = self._destDir.dump()\n out[\"Style\"] = self._destStyle\n elif self._type == 0: # Switch\n out[\"Text Pointer\"] = self._destTextPtr.dump()\n out[\"Event Flag\"] = self._destFlag\n elif (self._type == 5) or (self._type == 6):\n out[\"Text Pointer\"] = self._destTextPtr.dump()\n return out\n def load(self, input):\n self._x = input[\"X\"]\n self._y = input[\"Y\"]\n self.setTypeFromString(input[\"Type\"])\n if (self._type == 3) or (self._type == 4): # Stairs/Escalator\n self._stairDir = ValuedIntTableEntry(None, None,\n [\"NW\", \"NE\", \"SW\", \"SE\", \"Nowhere\"])\n self._stairDir.load(input[\"Direction\"])\n elif self._type == 2: # Door\n self._destTextPtr = PointerTableEntry(None, 4)\n self._destTextPtr.load(input[\"Text Pointer\"])\n self._destFlag = input[\"Event Flag\"]\n self._destX = input[\"Destination X\"]\n self._destY = input[\"Destination Y\"]\n self._destDir = ValuedIntTableEntry(None, None,\n [\"Down\", \"Up\", \"Right\", \"Left\"])\n self._destDir.load(input[\"Direction\"])\n self._destStyle = input[\"Style\"]\n elif self._type == 0: # Switch\n self._destTextPtr = PointerTableEntry(None, 4)\n self._destTextPtr.load(input[\"Text Pointer\"])\n self._destFlag = input[\"Event Flag\"]\n elif (self._type == 5) or (self._type == 6):\n self._destTextPtr = PointerTableEntry(None, 4)\n self._destTextPtr.load(input[\"Text Pointer\"])\n def writeToRom(self, rom, addr, destWriteLoc, destRangeEnd, destLocs):\n rom[addr] = self._y\n rom[addr+1] = self._x\n rom[addr+2] = self._type\n if self._type == 1: # Rope/Ladder\n rom[addr+3] = 0\n rom[addr+4] = (0x80 if self._isRope else 0)\n return 0\n elif (self._type == 3) or (self._type == 4): # Escalator and Stairs\n rom[addr+3] = 0\n rom[addr+4] = (0x80 if (self._stairDir.val() == 4) else\n self._stairDir.val())\n return 0\n elif self._type == 2: # Door\n with DataBlock(11) as destBlock:\n # Write data to block\n destTextPtr = self._destTextPtr.val()\n destBlock[0] = destTextPtr & 0xff\n destBlock[1] = (destTextPtr>>8) & 0xff\n destBlock[2] = (destTextPtr>>16) & 0xff\n destBlock[3] = (destTextPtr>>24) & 0xff\n destBlock[4] = self._destFlag & 0xff\n destBlock[5] = (self._destFlag >> 8) & 0xff\n destBlock[6] = self._destY & 0xff\n destBlock[7] = (self._destY >> 8) | (self._destDir.val() << 6)\n destBlock[8] = self._destX & 0xff\n destBlock[9] = self._destX >> 8\n destBlock[10] = self._destStyle\n # Check for any pre-existing matching destinations\n destHash = destBlock.hash()\n try:\n destAddr = destLocs[destHash]\n rom[addr+3] = destAddr & 0xff\n rom[addr+4] = destAddr >> 8\n return 0\n except KeyError:\n # Need to write a new destination\n if (destWriteLoc + 11) > destRangeEnd:\n # TODO Error, not enough space\n raise RunetimeError(\"Not enough door destination space\")\n destBlock.writeToRom(rom, destWriteLoc)\n destLocs[destHash] = destWriteLoc & 0xffff\n rom[addr+3] = destWriteLoc & 0xff\n rom[addr+4] = (destWriteLoc >> 8) & 0xff\n return 11\n elif self._type == 0: # Switch\n with DataBlock(6) as destBlock:\n # Write the data to block\n destBlock[0] = self._destFlag & 0xff\n destBlock[1] = self._destFlag >> 8\n destTextPtr = self._destTextPtr.val()\n destBlock[2] = destTextPtr & 0xff\n destBlock[3] = (destTextPtr>>8) & 0xff\n destBlock[4] = (destTextPtr>>16) & 0xff\n destBlock[5] = (destTextPtr>>24) & 0xff\n # Check for any pre-existing matching destinations\n destHash = destBlock.hash()\n try:\n destAddr = destLocs[destHash]\n rom[addr+3] = destAddr & 0xff\n rom[addr+4] = destAddr >> 8\n return 0\n except KeyError:\n # Need to write a new destination\n if (destWriteLoc + 6) > destRangeEnd:\n # TODO Error, not enough space\n raise RunetimeError(\"Not enough door destination space\")\n destBlock.writeToRom(rom, destWriteLoc)\n destLocs[destHash] = destWriteLoc & 0xffff\n rom[addr+3] = destWriteLoc & 0xff\n rom[addr+4] = (destWriteLoc >> 8) & 0xff\n return 6\n elif (self._type == 5) or (self._type == 6): # Switch\n with DataBlock(4) as destBlock:\n # Write the data to block\n destTextPtr = self._destTextPtr.val()\n destBlock[0] = destTextPtr & 0xff\n destBlock[1] = (destTextPtr>>8) & 0xff\n destBlock[2] = (destTextPtr>>16) & 0xff\n destBlock[3] = (destTextPtr>>24) & 0xff\n # Check for any pre-existing matching destinations\n destHash = destBlock.hash()\n try:\n destAddr = destLocs[destHash]\n rom[addr+3] = destAddr & 0xff\n rom[addr+4] = destAddr >> 8\n return 0\n except KeyError:\n # Need to write a new destination\n if (destWriteLoc + 4) > destRangeEnd:\n # TODO Error, not enough space\n raise RunetimeError(\"Not enough door destination space\")\n destBlock.writeToRom(rom, destWriteLoc)\n destLocs[destHash] = destWriteLoc & 0xffff\n rom[addr+3] = destWriteLoc & 0xff\n rom[addr+4] = (destWriteLoc >> 8) & 0xff\n return 4\n\nclass DoorModule(EbModule.EbModule):\n _name = \"Doors\"\n def __init__(self):\n self._ptrTbl = EbTable(0xD00000)\n self._entries = [ ]\n def readFromRom(self, rom):\n self._ptrTbl.readFromRom(rom)\n updateProgress(5)\n pct = 45.0/(40*32)\n for i in range(self._ptrTbl.height()):\n loc = EbModule.toRegAddr(self._ptrTbl[i,0].val())\n entry = [ ]\n numDoors = rom.readMulti(loc, 2)\n loc += 2\n for j in range(numDoors):\n d = Door()\n try:\n d.readFromRom(rom, loc)\n except ValueError:\n # Invalid door entry. Some entries in EB are invalid.\n # When we encounter one, just assume we've reached the end\n # of this entry.\n break\n entry.append(d)\n loc += 5\n self._entries.append(entry)\n i += 1\n updateProgress(pct)\n def writeToProject(self, resourceOpener):\n out = dict()\n x = y = 0\n rowOut = dict()\n pct = 45.0/(40*32)\n for entry in self._entries:\n if not entry:\n rowOut[x%32] = None\n else:\n rowOut[x%32] = map(lambda z: z.dump(), entry)\n if (x % 32) == 31:\n # Start new row\n out[y] = rowOut\n x = 0\n y += 1\n rowOut = dict()\n else:\n x += 1\n updateProgress(pct)\n with resourceOpener(\"map_doors\", \"yml\") as f:\n s = yaml.dump(out, default_flow_style=False, Dumper=yaml.CSafeDumper)\n s = sub(\"Event Flag: (\\d+)\",\n lambda i: \"Event Flag: \" + hex(int(i.group(0)[12:])), s)\n f.write(s)\n updateProgress(5)\n def readFromProject(self, resourceOpener):\n self._entries = []\n pct = 45.0/(40*32)\n with resourceOpener(\"map_doors\", \"yml\") as f:\n updateProgress(5)\n input = yaml.load(f, Loader=yaml.CSafeLoader)\n for y in input:\n row = input[y]\n for x in row:\n if row[x] == None:\n self._entries.append(None)\n else:\n entry = []\n for door in row[x]:\n d = Door()\n d.load(door)\n entry.append(d)\n self._entries.append(entry)\n updateProgress(pct)\n def writeToRom(self, rom):\n self._ptrTbl.clear(32*40)\n destWriteLoc = 0xF0000\n destRangeEnd = 0xF58EE # TODO Is this correct? Can we go more?\n destLocs = dict()\n emptyEntryPtr = EbModule.toSnesAddr(rom.writeToFree([0, 0]))\n pct = 45.0/(40*32)\n i=0\n for entry in self._entries:\n if (entry == None) or (not entry):\n self._ptrTbl[i,0].setVal(emptyEntryPtr)\n else:\n entryLen = len(entry)\n writeLoc = rom.getFreeLoc(2 + entryLen*5)\n self._ptrTbl[i,0].setVal(EbModule.toSnesAddr(writeLoc))\n rom[writeLoc] = entryLen & 0xff\n rom[writeLoc+1] = entryLen >> 8\n writeLoc += 2\n for door in entry:\n destWriteLoc += door.writeToRom(rom, writeLoc, destWriteLoc,\n destRangeEnd, destLocs)\n writeLoc += 5\n i += 1\n updateProgress(pct)\n self._ptrTbl.writeToRom(rom)\n # Mark any remaining space as free\n if destWriteLoc < destRangeEnd:\n rom.addFreeRanges([(destWriteLoc, destRangeEnd)])\n updateProgress(5)\n","sub_path":"modules/eb/DoorModule.py","file_name":"DoorModule.py","file_ext":"py","file_size_in_byte":14122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"590228286","text":"tags = []\r\ndivs = []\r\nn1 = open(\"ahkEDIT.txt\")\r\nn1 = n1.read()\r\nn2 = n1.split(\"\")\r\n\r\nfor n in n2:\r\n if n.count(\"\") > 0:\r\n divs.append(n)\r\n n2.remove(n)\r\n elif n.count(\" 0:\r\n divs.append(n)\r\n n2.remove(n)\r\n elif n.count(\"en-note\") > 0:\r\n divs.append(n)\r\n n2.remove(n)\r\n elif n.count(\"\") > 0:\r\n x = len(n) - 6\r\n n = n[0:x]\r\n tags.append(n)\r\n\r\ndef virtue(seq):\r\n seen = set()\r\n seen_add = seen.add\r\n return [ x for x in seq if not (x in seen or seen_add(x))]\r\n\r\nptags = virtue(tags)\r\n\r\nptags = list(ptags)\r\n\r\noutput_tags = open(\"output.txt\", \"w\")\r\n\r\nfor i in ptags:\r\n output_tags.write(i + '\\n')\r\noutput_tags.close()\r\n","sub_path":"drills/tag_extractor.py","file_name":"tag_extractor.py","file_ext":"py","file_size_in_byte":728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"7044556","text":"'''\r\nTask: Delete alternate elements of the given list, starting from index 0,\r\n print the list after each traversal.\r\n\r\nExample: given list -> [1,2,3,4,5]\r\n o/p: [2, 4]\r\n [4]\r\n []\r\n\r\n'''\r\n\r\nnums = [3, 5, 2, 9, 101, 333, 4]\r\n\r\ndef fn(l) :\r\n for i in l:\r\n if l.index(i)%2==0:\r\n l[l.index(i)]=''\r\n for i in l:\r\n if i=='':\r\n del l[l.index(i)]\r\n print(l)\r\n if l != [] :\r\n fn(l)\r\n\r\nfn(nums)","sub_path":"ListOps/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"465463899","text":"import json\nimport inspect\nimport threading\nfrom django.conf.urls import url\nfrom django.shortcuts import render\nfrom django.http import JsonResponse\nfrom django.conf import settings\nfrom django.utils.functional import SimpleLazyObject\nfrom django.middleware.csrf import get_token\nfrom zencore.utils.debug import get_exception_stack\n\n\nclass Fault(Exception):\n def __init__(self, code, message):\n self.code = code\n self.message = message\n\n def __repr__(self):\n return \"\"\"({}, \"{}\")\"\"\".format(self.code, self.message)\n\n\nclass Middleware(object):\n def __init__(self, get_response):\n self.get_response = get_response\n\n def __call__(self, request, payload, manager, caller=None):\n raise NotImplementedError()\n\n\nclass Service(object):\n \"\"\"服务基础类。\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n self.data = threading.local()\n\n def __call__(self, environment, request, manager, caller=None):\n \"\"\"\n :param environment: object 根据不同的运行环境而不同。Django实现接口下,为HttpRequest对象。\n :param request: dict Jsonrpc2请求报文\n :param manager: object 服务管理器的引用\n :param caller: object 调用者\n \"\"\"\n self.data.environment = environment\n self.data.request = request\n self.data.manager = manager\n self.data.caller = caller\n try:\n return self.serve(**request.get(\"params\", {}))\n except TypeError as error:\n message = str(error)\n if \"unexpected keyword argument\" in message or \"required positional argument\" in message:\n raise Fault(-32602, \"Invalid method parameter(s): \" + message)\n raise error\n\n @property\n def signature(self):\n return inspect.getargspec(self.serve)\n\n def serve(self, **params):\n raise Fault(-32000, \"NotImplementedError\")\n\n\nclass ServiceManager(object):\n \"\"\"服务管理类。\n \"\"\"\n def __init__(self, name=\"default\"):\n self.name = name\n self.services = {}\n self.middlewares = []\n self.post_register_callbacks = []\n self.post_unregister_callbacks = []\n\n def register_middleware(self, middleware):\n self.middlewares.append(middleware)\n\n def register(self, name, service):\n self.services[name] = service\n for callback in self.post_register_callbacks:\n callback(name, service, self)\n\n def unregister(self, name):\n del self.services[name]\n for callback in self.post_unregister_callbacks:\n callback(name, self)\n\n def get_service(self, name):\n return self.services[name]\n\n def has_service(self, name):\n return name in self.services\n\n def get_response(self, method):\n service = self.get_service(method)\n for middleware in self.middlewares:\n service = middleware(service)\n return service\n\n def post_register(self, callback):\n self.post_register_callbacks.append(callback)\n for name, service in self.services.items():\n callback(name, service, self)\n\n def post_unregister(self, callback):\n self.post_unregister_callbacks.append(callback)\n \n\ndefault_service_manager = SimpleLazyObject(lambda: ServiceManager())\n\n\nclass DjangoServiceSite(object):\n\n def __init__(self, service_manager, name=None):\n self.service_manager = service_manager\n self.name = name or self.service_manager.name\n\n @property\n def urls(self):\n return [\n url('^get_csrftoken/$', self.get_csrftoken, name=\"jsonrpc2.\"+self.name+\".get_csrftoken\"),\n url('^tester/$', self.tester, name=\"jsonrpc2.\"+self.name+\".tester\"),\n url('^$', self.handler, name=\"jsonrpc2.\"+self.name)\n ]\n\n def get_csrftoken(self, request):\n token = get_token(request)\n return JsonResponse({\n \"jsonrpc\": \"2.0\",\n \"result\": {\n \"name\": settings.CSRF_COOKIE_NAME,\n \"csrftoken\": token,\n }\n })\n \n def tester(self, request):\n services = []\n for name, service in self.service_manager.services.items():\n doc = service.__doc__\n if doc:\n lines = [line for line in doc.splitlines() if line.strip()]\n else:\n lines = []\n title = len(lines) and lines[0] or \"\"\n services.append({\n \"name\": name,\n \"doc\": service.__doc__,\n \"title\": title,\n })\n return render(request, \"jsonrpc2/tester.html\", {\n \"manager\": self,\n \"services\": services,\n })\n\n def handler(self, request):\n data = self.get_response_data(request)\n return self.make_http_response(data)\n handler.csrf_exempt = True\n\n def get_response_data(self, request):\n try:\n payload = self.payload_decode(request)\n except Exception as error:\n message = str(error)\n return {\n \"jsonrpc\": \"2.0\",\n \"error\": {\n \"code\": -32700,\n \"message\": \"Invalid JSON was received by the server: \" + message,\n }\n }\n if isinstance(payload, list):\n data = []\n for item in payload:\n data.append(self.get_service_data(request, item))\n return data\n if isinstance(payload, dict):\n return self.get_service_data(request, payload)\n return {\n \"jsonrpc\": \"2.0\",\n \"error\": {\n \"code\": -32600,\n \"message\": \"The JSON sent is not a valid Request object.\",\n }\n }\n\n def get_service_data(self, request, payload):\n method = payload.get(\"method\")\n id = payload.get(\"id\")\n response = {\"jsonrpc\": \"2.0\"}\n if id:\n response[\"id\"] = id\n if not method or not self.service_manager.has_service(method):\n response[\"error\"] = {\n \"code\": -32601,\n \"message\": \"The method does not exist / is not available.\",\n }\n return response\n try:\n result = self.service_manager.get_response(method)(request, payload, self.service_manager)\n response[\"result\"] = result\n except Fault as error:\n response[\"error\"] = {\n \"code\": error.code,\n \"message\": error.message,\n }\n except Exception as error:\n error_message = \"Internal JSON-RPC error\"\n if settings.DEBUG:\n error_message += \": \" + get_exception_stack()\n else:\n error_message += \".\"\n response[\"error\"] = {\n \"code\": -32603,\n \"message\": error_message,\n }\n return response\n\n @classmethod\n def payload_decode(cls, request):\n return json.loads(request.read())\n\n @classmethod\n def get_payload_encoding(cls, request):\n return request.META.get(\"Content-Encoding\", \"utf-8\")\n\n def make_http_response(self, data):\n return JsonResponse(data)\n\n\n\nclass CeleryApplicationManager(object):\n\n def __init__(self, application):\n self.application = application\n\n def connect(self, manager):\n manager.post_register(self.post_register)\n manager.post_unregister(self.post_unregister)\n\n def post_register(self, name, service, service_manager=None):\n @self.application.task(name=name)\n def wrapper(**kwargs):\n return service(self.application, kwargs, service_manager, self)\n\n def post_unregister(self, name, service_manager=None):\n pass\n\n","sub_path":"src/zencore/jsonrpc2/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":7744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"539540517","text":"import math\n\nimport numpy as np\nfrom kivy.clock import Clock\nfrom kivy.core.window import Window\nfrom kivy.graphics import Rectangle, Color\nfrom kivy.uix.behaviors import ButtonBehavior\nfrom kivy.uix.widget import Widget\n\n\nclass Blackboard(ButtonBehavior, Widget):\n part = None\n rectangles = None\n\n force_v = {}\n force_h = {}\n perma_force_v = {}\n perma_force_h = {}\n\n support_v = {}\n support_h = {}\n perma_support_v = {}\n perma_support_h = {}\n\n force_size = 5\n support_size = 5\n\n element_size = 30\n xPos = None\n yPos = None\n refresh = None\n pressed = None\n go_right = True\n go_up = True\n mouse_pos_last_press = None\n\n def update_grid(self, *args):\n element_size = self.element_size\n with self.canvas:\n self.canvas.clear()\n\n # drawing the rectangles\n for i in range(0, self.xPos):\n for j in range(0, self.yPos):\n Color(self.rectangles[i, j, 0], self.rectangles[i, j, 1], self.rectangles[i, j, 2])\n Rectangle(pos=(i * element_size, j * element_size), size=(element_size - 1, element_size - 1))\n\n force_size = self.force_size\n Color(1, 0, 0)\n self.update_constraints(force_size, self.force_v, self.force_h, self.perma_force_v, self.perma_force_h)\n\n support_size = self.support_size\n Color(0, 1, 0)\n self.update_constraints(support_size, self.support_v, self.support_h, self.perma_support_v,\n self.perma_support_h)\n\n def update_constraints(self, constraint_size, temp_v, temp_h, perma_v, perma_h):\n\n # drawing permanent vertical constraints\n length = len(perma_v)\n listofkeys = perma_v.keys()\n if length != 0:\n for i in range(length):\n x = listofkeys[i][0]\n y = listofkeys[i][1]\n Rectangle(pos=(\n (x * self.element_size) - (constraint_size / 2), (y * self.element_size) - (constraint_size / 2)),\n size=(constraint_size, self.element_size - 1))\n\n # drawing permanent horizontal constraints\n length = len(perma_h)\n listofkeys = perma_h.keys()\n if length != 0:\n for i in range(length):\n x = listofkeys[i][0]\n y = listofkeys[i][1]\n Rectangle(pos=(\n (x * self.element_size) - (constraint_size / 2), (y * self.element_size) - (constraint_size / 2)),\n size=(self.element_size - 1, constraint_size))\n\n # drawing vertical constraints\n length = len(temp_v)\n listofkeys = temp_v.keys()\n if length != 0:\n for j in range(length):\n if temp_v[listofkeys[0]][2] == 0 or temp_v[listofkeys[j]][2] <= length:\n temp_v[listofkeys[j]][2] = length + 1\n for i in range(length):\n y = listofkeys[i]\n x = temp_v[y][1]\n Rectangle(pos=(\n (x * self.element_size) - (constraint_size / 2), (y * self.element_size) - (constraint_size / 2)),\n size=(constraint_size, self.element_size - 1))\n if self.go_right:\n if self.rectangles[x, y, 1] != 0:\n if self.pressed.is_triggered == 0:\n val = temp_v[y]\n if (x + 1) < self.xPos:\n temp_v[y][1] = val[1] + 1\n else:\n del temp_v[y]\n else:\n perma_v[(x, y)] = temp_v[y][0] / temp_v[y][2]\n del temp_v[y]\n else:\n if self.rectangles[x - 1, y, 1] != 0:\n if self.pressed.is_triggered == 0:\n val = temp_v[y]\n if (x - 1) >= 0:\n temp_v[y][1] = val[1] - 1\n else:\n del temp_v[y]\n else:\n perma_v[(x, y)] = temp_v[y][0] / temp_v[y][2]\n del temp_v[y]\n\n # drawing horizontal constraints\n length = len(temp_h)\n listofkeys = temp_h.keys()\n\n if length != 0:\n for j in range(length):\n if temp_h[listofkeys[j]][2] == 0 or temp_h[listofkeys[j]][2] <= length:\n temp_h[listofkeys[j]][2] = length + 1\n for i in range(length):\n x = listofkeys[i]\n y = temp_h[x][1]\n Rectangle(pos=(\n (x * self.element_size) - (constraint_size / 2), (y * self.element_size) - (constraint_size / 2)),\n size=(self.element_size - 1, constraint_size))\n if self.go_up:\n if self.rectangles[x, y, 1] != 0:\n if self.pressed.is_triggered == 0:\n val = temp_h[x]\n if (y + 1) < self.xPos:\n temp_h[x][1] = val[1] + 1\n else:\n del temp_h[x]\n else:\n perma_h[(x, y)] = temp_h[x][0] / temp_h[x][2]\n del temp_h[x]\n else:\n if self.rectangles[x, y - 1, 1] != 0:\n if self.pressed.is_triggered == 0:\n val = temp_h[x]\n if (y - 1) >= 0:\n temp_h[x][1] = val[1] - 1\n else:\n del temp_h[x]\n else:\n perma_h[(x, y)] = temp_h[x][0] / temp_h[x][2]\n del temp_h[x]\n pass\n\n def select_rec(self, *args):\n pos = Window.mouse_pos\n if self.mouse_pos_last_press is None:\n self.mouse_pos_last_press = pos\n x = int(math.floor(pos[0] / self.element_size))\n y = int(math.floor(pos[1] / self.element_size))\n if self.parent.parent.ids.tbutPart.state == 'down':\n # taking inputs for rectangles/part body\n self.rectangles[x, y, :] = [0, 0, 1]\n elif self.parent.parent.ids.tbutForceV.state == 'down':\n # taking inputs for vertical forces\n if self.rectangles[x, y, 1] != 0:\n self.force_v[y] = [45, x, 0] # Enter value of Force\n elif self.parent.parent.ids.tbutForceH.state == 'down':\n # taking inputs for horizontal forces\n if self.rectangles[x, y, 1] != 0:\n self.force_h[x] = [45, y, 0] # Enter value of Force\n elif self.parent.parent.ids.tbutSupportV.state == 'down':\n # taking inputs for vertical supports\n if self.rectangles[x, y, 1] != 0:\n self.support_v[y] = [0, x, 0]\n elif self.parent.parent.ids.tbutSupportH.state == 'down':\n # taking inputs for horizontal supports\n if self.rectangles[x, y, 1] != 0:\n self.support_h[x] = [0, y, 0]\n\n self.pressed = Clock.schedule_once(self.select_rec, 0.001)\n\n def stop_press(self):\n pos = Window.mouse_pos\n if pos[0] - self.mouse_pos_last_press[0] >= 0:\n self.go_right = True\n else:\n self.go_right = False\n\n if pos[1] - self.mouse_pos_last_press[1] >= 0:\n self.go_up = True\n else:\n self.go_up = False\n\n self.mouse_pos_last_press = None\n Clock.unschedule(self.pressed)\n\n def load(self):\n ele_size = np.shape(self.part.ele)\n for i in range(ele_size[0]):\n pos = self.part.nodes[int(self.part.ele[i, 0]) - 1, :]\n self.rectangles[int(pos[0]), int(pos[1]), :] = [0, 0, 1]\n","sub_path":"gui/Blackboard.py","file_name":"Blackboard.py","file_ext":"py","file_size_in_byte":7918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"578201781","text":"\nimport csv\n\nfrom eval import Eval\nfrom team_state import TeamState\nfrom stadium import Stadium\nfrom common import BlaseballStatistics as Stats\nfrom common import ForbiddenKnowledge as FK\nfrom common import AdditiveTypes, BloodType, PlayerBuff, Team, Weather\n\n\ndefault_stadium = Stadium(\n \"team_id\",\n \"stadium_id\",\n \"stadium_name\",\n 0.5,\n 0.5,\n 0.5,\n 0.5,\n 0.5,\n 0.5,\n 0.5,\n [],\n)\n\nbatter_file = \"../season_sim/eval/batters.csv\"\npitcher_file = \"../season_sim/eval/pitchers-sibr.csv\"\n\nlineup = {}\nrotation = {}\nstlats = {}\nbuffs = {}\nnames = {}\ngame_stats = {}\n\nwith open(batter_file) as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=',')\n line_count = 1\n for row in csv_reader:\n name = row[0]\n buo = row[1]\n div = row[2]\n mar = row[3]\n mox = row[4]\n mus = row[5]\n thw = row[6]\n trg = row[7]\n bth = row[8]\n con = row[9]\n grf = row[10]\n ind = row[11]\n lsr = row[12]\n prs = row[13]\n cin = row[14]\n pth = row[15]\n lineup[line_count] = name\n names[name] = name\n buffs[name] = {}\n game_stats[name] = {}\n stlats[name] = {\n FK.BUOYANCY: float(buo),\n FK.DIVINITY: float(div),\n FK.MARTYRDOM: float(mar),\n FK.MOXIE: float(mox),\n FK.MUSCLITUDE: float(mus),\n FK.THWACKABILITY: float(thw),\n FK.TRAGICNESS: float(trg),\n FK.BASE_THIRST: float(bth),\n FK.CONTINUATION: float(con),\n FK.GROUND_FRICTION: float(grf),\n FK.INDULGENCE: float(ind),\n FK.LASERLIKENESS: float(lsr),\n FK.PRESSURIZATION: float(prs),\n FK.CINNAMON: float(cin),\n FK.PATHETICISM: float(pth),\n FK.ANTICAPITALISM: 0.773526430988913,\n FK.CHASINESS: 0.826184892943561,\n FK.OMNISCIENCE: 0.7901157143783870,\n FK.TENACIOUSNESS: 0.8133712472630720,\n FK.WATCHFULNESS: 0.7665729800544850,\n FK.VIBES: 0.5,\n }\n line_count = line_count + 1\n\nwith open(pitcher_file) as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=',')\n line_count = 1\n for row in csv_reader:\n #print(f'row={row}')\n name = row[0]\n col = row[1]\n ovp = row[2]\n rth = row[3]\n ssp = row[4]\n sup = row[5]\n uth = row[6]\n prs = row[7]\n cin = row[8]\n buo = row[9]\n rotation[line_count] = name\n names[name] = name\n buffs[name] = {}\n stlats[name] = {\n FK.BUOYANCY: float(buo),\n FK.COLDNESS: float(col),\n FK.OVERPOWERMENT: float(ovp),\n FK.RUTHLESSNESS: float(rth),\n FK.SHAKESPEARIANISM: float(ssp),\n FK.SUPPRESSION: float(sup),\n FK.UNTHWACKABILITY: float(uth),\n FK.PRESSURIZATION: float(prs),\n FK.CINNAMON: float(cin),\n FK.ANTICAPITALISM: 0.773526430988913,\n FK.CHASINESS: 0.826184892943561,\n FK.OMNISCIENCE: 0.7901157143783870,\n FK.TENACIOUSNESS: 0.8133712472630720,\n FK.WATCHFULNESS: 0.7665729800544850,\n FK.VIBES: 0.5,\n }\n line_count = line_count + 1\n\nhome_team = TeamState(\n team_id=\"pitcher-eval\",\n season=1,\n day=1,\n stadium=default_stadium,\n weather=Weather.ECLIPSE,\n is_home=True,\n num_bases=4,\n balls_for_walk=4,\n strikes_for_out=3,\n outs_for_inning=3,\n lineup=lineup,\n rotation=rotation,\n starting_pitcher=rotation[1],\n cur_pitcher_pos=1,\n stlats=stlats,\n buffs=buffs,\n game_stats={},\n segmented_stats={},\n blood={},\n player_names=names,\n cur_batter_pos=1,\n )\n\naway_team = TeamState(\n team_id=\"batter-eval\",\n season=1,\n day=1,\n stadium=default_stadium,\n weather=Weather.ECLIPSE,\n is_home=False,\n num_bases=4,\n balls_for_walk=4,\n strikes_for_out=3,\n outs_for_inning=3,\n lineup=lineup,\n rotation=rotation,\n starting_pitcher=rotation[1],\n cur_pitcher_pos=1,\n stlats=stlats,\n buffs=buffs,\n game_stats={},\n segmented_stats={},\n blood={},\n player_names=names,\n cur_batter_pos=1,\n )\n\neval = Eval(\n home_team,\n away_team,\n 3,\n 4,\n)\n\neval.simulate_game()\n\nprint('name,walks_per_batter,outs_per_batter,strikeouts_per_batter,hits_per_batter,doubles_per_batter,triples_per_batter,hr_per_batter')\nfor key in home_team.game_stats:\n batters_faced = home_team.game_stats[key][Stats.PITCHER_BATTERS_FACED]\n walks_per_batter = home_team.game_stats[key][Stats.PITCHER_WALKS] / batters_faced\n outs = home_team.game_stats[key][Stats.PITCHER_STRIKEOUTS] + home_team.game_stats[key][Stats.PITCHER_FLYOUTS] + \\\n home_team.game_stats[key][Stats.PITCHER_GROUNDOUTS]\n outs_per_batter = outs / batters_faced\n k_per_batter = home_team.game_stats[key][Stats.PITCHER_STRIKEOUTS] / batters_faced\n hits_per_batter = home_team.game_stats[key][Stats.PITCHER_HITS_ALLOWED] / batters_faced\n doubles_per_batter = home_team.game_stats[key][Stats.PITCHER_DOUBLE_ALLOWED] / batters_faced\n triples_per_batter = home_team.game_stats[key][Stats.PITCHER_TRIPLE_ALLOWED] / batters_faced\n hr_per_batter = home_team.game_stats[key][Stats.PITCHER_HRS_ALLOWED] / batters_faced\n print(f'{key},{walks_per_batter},{outs_per_batter},{k_per_batter},{hits_per_batter},{doubles_per_batter},{triples_per_batter},{hr_per_batter}')\n ##print(f'Summary for {key}')\n ##print(f'\\twalks per batter = {home_team.game_stats[key][Stats.PITCHER_WALKS] / batters_faced}')\n ##print(f'\\touts per batter = {outs / batters_faced}')\n ##print(f'\\t\\tstrikeouts per batter = {home_team.game_stats[key][Stats.PITCHER_STRIKEOUTS] / batters_faced}')\n ##print(f'\\thits per batter = {home_team.game_stats[key][Stats.PITCHER_HITS_ALLOWED] / batters_faced}')\n ##print(f'\\t\\tdouble per batter = {home_team.game_stats[key][Stats.PITCHER_DOUBLE_ALLOWED] / batters_faced}')\n ##print(f'\\t\\ttriple per batter = {home_team.game_stats[key][Stats.PITCHER_TRIPLE_ALLOWED] / batters_faced}')\n ##print(f'\\t\\thome runs per batter = {home_team.game_stats[key][Stats.PITCHER_HRS_ALLOWED] / batters_faced}')\n ##print('')\n\n\n","sub_path":"src/run_eval.py","file_name":"run_eval.py","file_ext":"py","file_size_in_byte":6624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"66177136","text":"import logging\nimport io\n\nimport os\nfrom django.conf import settings\nfrom django.core.servers.basehttp import FileWrapper\nfrom django.core.urlresolvers import reverse\nfrom django.db import transaction\nfrom django.http import HttpResponseRedirect, HttpResponse, Http404\nfrom django.views.generic import TemplateView, ListView, DeleteView, View, DetailView, UpdateView\nfrom django.contrib import messages\nfrom django.core.exceptions import ValidationError, ObjectDoesNotExist\nfrom django.views.generic.edit import FormView\nfrom django.shortcuts import get_object_or_404\nimport chardet\nfrom carddirector.cd_api.constants import card_submission_modes\nfrom carddirector.cd_api.services import send_card_application_submission_non_txn_to_tps\n\nfrom carddirector.cd_app_upload.constants import db_constants, kyc_result_status_choices\nfrom carddirector.cd_app_upload import services, repos, utils, forms, session_handler, batch_update_handler\nfrom carddirector.cd_app_upload.constants import upload_file_type\nfrom carddirector.cd_app_upload.exceptions import AppUploadValidationError, KycFileNotFoundError\nfrom carddirector.cd_kyc_connector.services import submit_kyc_checks\nfrom carddirector.cd_main.views import SearchFormListView, DownloadableSearchFormListView\nfrom carddirector.cd_master.constants import kyc_check_status_constants\nfrom carddirector.cd_utils import string_utils, fis_utils, file_utils\nfrom carddirector.cd_utils.json_utils import JSONResponse, response_mimetype\nfrom carddirector.cd_app_upload.models import CardApplicationImportKycFile, CardAppImportLine, CardApplicationKycCheckLog, \\\n CardApplicationKycCheck, CardAppImportLineForKycResult\nfrom carddirector.cd_app_upload.forms import ApplicationFileUploadForm, AppUploadKycFilesSearchForm,\\\n FisBatchQueueSearchForm\nfrom carddirector.cd_main.utils import sorted_nicely\nfrom carddirector.cd_app_upload import exceptions as app_upload_exceptions\nfrom carddirector.cd_app_upload.repos import find_card_app_import_file_by_id, \\\n get_card_application_import_line_by_kyc_check_id\nfrom carddirector.cd_api.forms import SubmitQGenKYCCallbackForm\nfrom carddirector.cd_kyc_connector.qgen import create_mock_qgen_response, \\\n generate_doc_return_dom,\\\n generate_address_line2_for_qgen_xml\nfrom carddirector.tps_protobuf.utils import is_mq_timeout_tps_response\nfrom carddirector.cd_generic import forms as generic_forms\nfrom carddirector.cd_kyc_connector.entities import ApplicantKYCInfo,\\\n ApplicantAddress\nfrom carddirector.cd_kyc_connector import entities\nfrom carddirector.cd_api.utils import Namespace\nfrom carddirector.cd_main.signals import user_card_application_upload,\\\n user_card_application_upload_kyc_file, user_card_application_delete_kyc_file,\\\n user_card_application_submit_kyc_check, user_card_application_modify,\\\n user_card_application_issue\nfrom carddirector.cd_main.constants import user_actions\nfrom carddirector.cd_app_upload import csv_model\nfrom carddirector.cd_app_upload.csv_app_upload_services import AppUploadCsvImportService\nfrom carddirector.cd_utils.csv_upload.views import FileUploadView\n\n\nlogger = logging.getLogger(__name__)\n\n \nclass ApplicationFileUploadView(FileUploadView):\n form_class = ApplicationFileUploadForm\n csv_service_class = AppUploadCsvImportService\n template_name = 'carddirector/cd_app_upload/app_file_upload.html'\n \n csv_model_map = {\n upload_file_type.WEBBLACK_SUCCESS_EXPORT : csv_model.WebBlackApplicationFileModel,\n upload_file_type.CLIENT_REQUEST_INTERNAL_FILE : csv_model.ClientFileCardApplicationFileModel,\n upload_file_type.SDD_FILE : csv_model.SDDFileModel\n }\n \n def save_file(self, filename, uploaded_file, records, user, **kwargs):\n saved_file = FileUploadView.save_file(self, filename, uploaded_file, records, user, **kwargs)\n message = u'File \\'%s\\' has been uploaded successfully: %s card load(s) imported.' % (unicode(filename), unicode(len(records)))\n user_card_application_upload.send(\n sender=self.__class__, \n request=self.request, \n user=self.request.user, \n user_action_name=user_actions.CARD_APPLICATION__UPLOAD, \n details=message\n )\n return saved_file\n \n def get_csv_model(self):\n return self.csv_model_map[self.request.POST['type']]\n \n def get_extra_parameters_for_services(self):\n extra_params = {}\n extra_params['application_type'] = self.request.POST['type']\n return extra_params\n \n def get_success_url(self):\n app_type = self.request.POST['type']\n if app_type == upload_file_type.SDD_FILE:\n return reverse('carddirector.cd_app_upload.views.app_file_list')\n else:\n messages.add_message(self.request, messages.INFO, 'Step 2: Upload KYC')\n app_file = services.find_card_application_import_file(self.filename)\n return reverse('carddirector.cd_app_upload.views.kyc_batch_upload', args=[app_file.id])\n \n\n\nclass KycBatchUploadView(TemplateView):\n template_name = 'carddirector/cd_app_upload/kyc_batch_upload.html'\n\n def get_context_data(self, **kwargs):\n context = super(KycBatchUploadView, self).get_context_data(**kwargs)\n app_file_id = self.kwargs['app_file_id']\n card_app_import_file = repos.find_card_app_import_file_by_id(app_file_id)\n\n if card_app_import_file.import_type.name == db_constants.IMPORT_FILE_TYPE_SDD_FILE:\n raise Http404()\n\n context[\"app_file_id\"] = app_file_id\n context[\"card_app_import_file\"] = card_app_import_file\n\n image_names = services.get_all_image_files_under_import_file(card_app_import_file)\n context[\"file_ext\"] = utils.get_allowed_upload_file_extensions_array()\n context[\"image_names\"] = utils.convert_to_js_array(image_names)\n\n return context\n\n def post(self, request, *args, **kwargs):\n pp_or_poa_filename = \"N/A\"\n try:\n app_file_id = self.kwargs['app_file_id']\n file = request.FILES.get('file', None)\n pp_or_poa_filename = file.name\n\n import_file = repos.find_card_app_import_file_by_id(app_file_id)\n\n #application file\n import_filename = import_file.original_filename\n kyc_filename = file.name\n services.validate_upload_kyc_against_application(import_filename, kyc_filename)\n services.validate_upload_kyc_file_type(file)\n\n application = repos.find_card_app_import_line_by_pp_or_poa(import_filename, pp_or_poa_filename)\n\n # im = thumbnail_utils.get_thumbnail(full_path, '100x100', crop='center', quality=99)\n kyc_file = repos.create_card_app_import_kyc_file(application, pp_or_poa_filename, file)\n user_card_application_upload_kyc_file.send(\n sender=self.__class__, \n request=request, \n user=request.user, \n user_action_name=user_actions.CARD_APPLICATION__UPLOAD_KYC_FILE, \n details='Uploaded KYC file \"{kyc_file.original_filename}\"[id={kyc_file.pk}] for application id={app.pk}'\n .format(kyc_file=kyc_file, app=application),\n )\n str_url = reverse('carddirector.cd_app_upload.views.kyc_file_download', args=[kyc_file.id])\n\n data = [{'name': pp_or_poa_filename, 'url': str_url,\n # 'thumbnail_url': im.url\n }]\n except ValidationError as ex:\n msg = str(ex)\n if len(ex.messages)==1:\n msg = ex.messages[0]\n data = [{'name': pp_or_poa_filename, 'error': msg}]\n except AppUploadValidationError as ex:\n data = [{'name': pp_or_poa_filename, 'error': str(ex)}]\n except Exception:\n logger.exception(\"Internal Server Error\")\n data = [{'name': pp_or_poa_filename, 'error': 'Internal error, please contact administrator'}]\n response = JSONResponse(data, {}, response_mimetype(self.request))\n response['Content-Disposition'] = 'inline; filename=files.json'\n return response\n\n\nclass AppUploadKycFilesListView(SearchFormListView):\n template_name = 'carddirector/cd_app_upload/app_upload_kyc_files.html'\n context_object_name = 'object_list'\n paginate_by = 25\n form_class = AppUploadKycFilesSearchForm\n\n def get_queryset(self):\n app_file_id = self.kwargs['app_file_id']\n card_app_import_file = repos.find_card_app_import_file_by_id(app_file_id)\n import_kyc_files = repos.find_all_card_app_import_kyc_file_by_import_file(card_app_import_file)\n entries = services.generate_kyc_file_report_entry(card_app_import_file, import_kyc_files)\n return entries\n\n def get_context_data(self, **kwargs):\n context = super(AppUploadKycFilesListView, self).get_context_data(**kwargs)\n app_file_id = self.kwargs['app_file_id']\n card_app_import_file = repos.find_card_app_import_file_by_id(app_file_id)\n if card_app_import_file.import_type.name == db_constants.IMPORT_FILE_TYPE_SDD_FILE:\n raise Http404()\n\n context[\"app_file_id\"] = app_file_id\n context[\"kyc_file_summary\"] = services.get_kyc_file_summary(card_app_import_file)\n context[\"app_file_name\"] = card_app_import_file.original_filename\n\n return context\n\n def set_object_list(self, form=None):\n if form:\n if 'submit_search' in self.request.GET or 'submit_download' in self.request.GET:\n data = form.cleaned_data\n result_set = self.get_queryset()\n if data['uploaded']:\n result_set = services.filter_kyc_file_report_entries(result_set, data['uploaded'])\n self.object_list = result_set\n else:\n self.object_list = self.get_queryset()\n else:\n super(AppUploadKycFilesListView, self).set_object_list(form)\n\n def post(self, request, *args, **kwargs):\n form_class = self.get_form_class()\n form = self.get_form(form_class)\n\n app_file_id = self.kwargs['app_file_id']\n card_app_import_file = repos.find_card_app_import_file_by_id(app_file_id)\n\n try:\n services.validate_all_kyc_files_uploaded_by_import_file(card_app_import_file)\n filename = find_card_app_import_file_by_id(app_file_id)\n\n return HttpResponseRedirect(reverse('carddirector.cd_app_upload.views.kyc_batch_check_qgen', args=(self.kwargs['app_file_id'],)))\n except Exception as ex:\n logger.exception('%r' % ex)\n messages.add_message(self.request, messages.ERROR, str(ex))\n return HttpResponseRedirect(reverse('carddirector.cd_app_upload.views.kyc_files', args=(self.kwargs['app_file_id'],)))\n\nclass DeleteAppUploadKycFileView(DeleteView):\n template_name = 'carddirector/cd_app_upload/delete_kyc_file.html'\n slug_field = 'id'\n model = CardApplicationImportKycFile\n context_object_name = 'object'\n\n def get_object(self, queryset=None):\n kyc_file = super(DeleteAppUploadKycFileView, self).get_object(queryset=queryset)\n app_line = kyc_file.application\n app_line_for_result = CardAppImportLineForKycResult.objects.get(pk=app_line.id)\n if app_line_for_result.kyc_check_log:\n raise Http404\n return kyc_file\n\n def post(self, request, *args, **kwargs):\n app_upload_kyc_file_id = self.kwargs['slug']\n app_file_id = repos.get_card_app_import_file_id_by_kyc_file_id(app_upload_kyc_file_id)\n\n if 'confirm' in request.POST:\n app_upload_kyc_file = CardApplicationImportKycFile.objects.get(pk=app_upload_kyc_file_id)\n #file delete is handled by signal\n app_upload_kyc_file.delete()\n user_card_application_delete_kyc_file.send(\n sender=self.__class__, \n request=request, \n user=request.user, \n user_action_name=user_actions.CARD_APPLICATION__DELETE_KYC_FILE, \n details='Deleted KYC file \"{kyc_file.original_filename}\"[id={kyc_file.pk}]'\n .format(kyc_file=app_upload_kyc_file),\n )\n\n messages.add_message(self.request, messages.SUCCESS, \"File deleted successfully.\")\n return HttpResponseRedirect(reverse('carddirector.cd_app_upload.views.kyc_files', args=[app_file_id]))\n\n return HttpResponseRedirect(reverse('carddirector.cd_app_upload.views.kyc_files', args=[app_file_id]))\n\n\nclass AppUploadKycFileSuccessView(TemplateView):\n template_name = 'carddirector/cd_app_upload/kyc_file_success.html'\n\n def get_context_data(self, **kwargs):\n context = super(AppUploadKycFileSuccessView, self).get_context_data(**kwargs)\n context[\"app_file_id\"] = self.kwargs['app_file_id']\n return context\n\n\nclass AppUploadKycFileDownloadView(View):\n def get(self, request, *args, **kwargs):\n id = self.kwargs['id']\n kyc_file = CardApplicationImportKycFile.objects.get(pk=id)\n full_path = kyc_file.full_path\n bytes = os.path.getsize(full_path)\n ext = string_utils.get_file_ext(kyc_file.original_filename)\n mime_type = file_utils.get_mime_type(ext)\n\n wrapper = FileWrapper(file(full_path))\n response = HttpResponse(wrapper, mime_type)\n response['Content-Disposition'] = 'attachment;filename=%s' % kyc_file.original_filename\n response['Content-Length'] = bytes\n return response\n\n\nclass ApplicationLineListView(DownloadableSearchFormListView):\n template_name = 'carddirector/cd_app_upload/app_line_list.html'\n context_object_name = 'object_list'\n paginate_by = 25\n form_class = forms.ApplicationLineSearchForm\n csv_file_name = 'application_line_list.csv'\n \n def get_queryset(self):\n app_lines = CardAppImportLineForKycResult.objects.all()\n return app_lines\n\n def set_object_list(self, form=None):\n if form:\n filter_data = form.cleaned_data\n filter_status = filter_data['status']\n if not filter_status:\n filter_status = kyc_result_status_choices.LATEST\n\n filter_client_card_ref = filter_data['client_card_ref']\n filter_reseller = filter_data['reseller']\n filter_kyc_result = filter_data['kyc_result']\n filter_card_name = filter_data['card_name']\n filter_card_type = filter_data['card_type']\n filter_from_date = filter_data['from_date']\n filter_to_date = filter_data['to_date']\n filter_blackcard_paid_status = filter_data['blackcard_paid_status']\n filter_fis_submitted = filter_data['fis_submitted']\n # if no value then it selected the All option\n if filter_fis_submitted:\n filter_fis_submitted = True if filter_fis_submitted == 'YES' else False\n else:\n filter_fis_submitted = None\n \n\n self.object_list = services.filter_kyc_result(filter_status,\n client_card_ref=filter_client_card_ref,\n reseller=filter_reseller,\n kyc_result=filter_kyc_result,\n card_name=filter_card_name,\n card_type_code=filter_card_type,\n from_date=filter_from_date,\n to_date=filter_to_date,\n blackcard_paid_status=filter_blackcard_paid_status,\n is_fis_submitted=filter_fis_submitted\n ).order_by('-last_updated_date', 'reseller_client_code')\n \n else:\n super(ApplicationLineListView, self).set_object_list(form)\n\n\nclass ApplicationFileListView(DownloadableSearchFormListView):\n template_name = 'carddirector/cd_app_upload/app_file_list.html'\n paginate_by = 25\n form_class = forms.ApplicationFileListFilterForm\n csv_file_name = 'application_file_list.csv'\n\n def add_extra_properties(self, card_app_import_files):\n for import_file in card_app_import_files:\n import_file.kyc_file_summary = services.get_kyc_file_summary(import_file)\n import_file.kyc_result_summary = services.get_kyc_result_summary(import_file)\n import_file.fis_result_summary = services.get_fis_result_summary(import_file)\n\n def set_object_list(self, form=None):\n if form:\n filter_data = form.cleaned_data\n filter_client_card_ref = filter_data['client_card_ref']\n filter_filename = filter_data['filename']\n filter_filetype = filter_data['filetype']\n\n qs = services.filter_app_files(filter_filename, filter_filetype, filter_client_card_ref)\n self.add_extra_properties(qs)\n self.object_list = qs\n else:\n super(ApplicationFileListView, self).set_object_list(form)\n\nclass KycIIDBatchRequestView(TemplateView):\n template_name = 'carddirector/cd_app_upload/kyc_batch_check_iid.html'\n\n def _get_no_of_required_submission(self, card_applications):\n count = 0\n for card_application in card_applications:\n if not services.is_card_application_kyc_completed(card_application):\n count += 1\n return count\n\n def get(self, request, *args, **kwargs):\n context = self.get_context_data(**kwargs)\n app_file_id = self.kwargs['app_file_id']\n import_file = repos.find_card_app_import_file_by_id(app_file_id)\n card_applications = repos.find_all_card_app_import_line_by_import_file(import_file)\n no_of_applications = len(card_applications)\n\n context['card_app_import_file'] = import_file\n context['file_name'] = import_file.original_filename\n context['no_of_applications'] = \"(%s/%s)\" % (self._get_no_of_required_submission(card_applications), no_of_applications)\n\n kyc_result_summary = services.get_kyc_result_summary(import_file)\n if kyc_result_summary != 'Not Started':\n messages.add_message(self.request, messages.WARNING, 'This application has been already submitted to KYC.')\n\n return self.render_to_response(context)\n\n def post(self, request, *args, **kwargs):\n if 'cancel' in request.POST:\n return HttpResponseRedirect(reverse('carddirector.cd_app_upload.views.app_file_list'))\n\n try:\n context = self.get_context_data(**kwargs)\n app_file_id = self.kwargs['app_file_id']\n import_file = repos.find_card_app_import_file_by_id(app_file_id)\n\n services.validate_all_kyc_files_uploaded_by_import_file(import_file)\n\n card_applications = repos.find_all_card_app_import_line_by_import_file(import_file)\n error_ccrs = []\n apps_sent = 0\n for card_application in card_applications:\n if not services.is_card_application_kyc_completed(card_application):\n \n try:\n kyc_check = submit_kyc_checks(card_application)\n user_card_application_submit_kyc_check.send(\n sender=self.__class__, \n request=request, \n user=request.user, \n user_action_name=user_actions.CARD_APPLICATION__SUBMIT_KYC_CHECK, \n details='Submit {kyc_check.kyc_type.name} KYC check \"{kyc_check.uid}\"'.format(kyc_check=kyc_check),\n )\n apps_sent += 1\n except UnicodeDecodeError as e:\n error_ccrs.append(card_application.client_card_ref)\n \n messages.add_message(self.request, messages.SUCCESS, \"%s application(s) have been submitted to KYC.\" % str(apps_sent))\n if len(error_ccrs) > 0:\n messages.add_message(self.request, messages.ERROR, \"%s application(s) couldn't be submitted because they contain illegal characters. Please inspect the application(s) with the following CRR: %s.\" % (len(error_ccrs), \",\".join(error_ccrs)))\n \n return HttpResponseRedirect(reverse('carddirector.cd_app_upload.views.app_file_list'))\n except KycFileNotFoundError as ex:\n messages.add_message(self.request, messages.ERROR, str(ex))\n logger.exception(ex)\n return HttpResponseRedirect(reverse('carddirector.cd_app_upload.views.app_file_list'))\n except app_upload_exceptions.KycSubmitQgenCheckNotValidError as ex:\n messages.add_message(self.request, messages.ERROR, \"Fail to submit KYC checking. Please contact System Administrator.\")\n logger.exception(ex)\n return HttpResponseRedirect(reverse('carddirector.cd_app_upload.views.app_file_list'))\n except Exception as ex:\n messages.add_message(self.request, messages.ERROR, \"Fail to submit KYC checking. Please contact System Administrator.\")\n logger.exception(ex)\n return HttpResponseRedirect(reverse('carddirector.cd_app_upload.views.app_file_list'))\n\nclass KycIIDResultRequestView(TemplateView):\n template_name = 'carddirector/cd_app_upload/kyc_result_check_iid.html'\n\n def get(self, request, *args, **kwargs):\n context = self.get_context_data(**kwargs)\n app_line_id = self.kwargs['app_line_id']\n import_line = get_object_or_404(CardAppImportLine, pk=app_line_id)\n card_applications = import_line\n\n context['import_line'] = import_line\n return self.render_to_response(context)\n\n def post(self, request, *args, **kwargs):\n try:\n context = self.get_context_data(**kwargs)\n app_line_id = self.kwargs['app_line_id']\n import_line = get_object_or_404(CardAppImportLine, pk=app_line_id)\n\n services.validate_all_kyc_files_uploaded_by_import_line(import_line)\n\n if not services.is_card_application_kyc_completed(import_line):\n kyc_check = None\n try:\n kyc_check = submit_kyc_checks(import_line)\n \n user_card_application_submit_kyc_check.send(\n sender=self.__class__, \n request=request, \n user=request.user, \n user_action_name=user_actions.CARD_APPLICATION__SUBMIT_KYC_CHECK, \n details='Submit {kyc_check.kyc_type.name} KYC check \"{kyc_check.uid}\"'.format(kyc_check=kyc_check),\n )\n messages.add_message(self.request, messages.SUCCESS, \"Application with CCR '%s' submitted to KYC.\" % import_line.client_card_ref)\n except UnicodeEncodeError:\n messages.add_message(self.request, messages.ERROR, \"Application with CCR '%s' couldn't be submitted: illegal character found in it.\" % import_line.client_card_ref)\n \n return HttpResponseRedirect(reverse('carddirector.cd_app_upload.views.app_file_list'))\n except KycFileNotFoundError as ex:\n messages.add_message(self.request, messages.ERROR, str(ex))\n logger.exception(ex)\n return HttpResponseRedirect(reverse('carddirector.cd_app_upload.views.app_file_list'))\n except app_upload_exceptions.KycSubmitQgenCheckNotValidError as ex:\n messages.add_message(self.request, messages.ERROR, \"Fail to submit KYC checking. Please contact System Administrator.\")\n logger.exception(ex)\n return HttpResponseRedirect(reverse('carddirector.cd_app_upload.views.app_file_list'))\n except Exception as ex:\n messages.add_message(self.request, messages.ERROR, \"Fail to submit KYC checking. Please contact System Administrator.\")\n logger.exception(ex)\n return HttpResponseRedirect(reverse('carddirector.cd_app_upload.views.app_file_list'))\n\n\nclass KycResultList(DownloadableSearchFormListView):\n template_name = 'carddirector/cd_app_upload/app_line_kyc_result_list.html'\n context_object_name = \"object_list\"\n paginate_by = 25\n form_class = forms.FileResultListFilterForm\n csv_file_name = 'kyc_result_list.csv' \n\n def get_context_data(self, **kwargs):\n context = ListView.get_context_data(self, **kwargs)\n app_file_id = self.kwargs['app_file_id']\n card_app_import_file = repos.find_card_app_import_file_by_id(app_file_id)\n context[\"card_app_import_file\"] = card_app_import_file\n return context\n\n def set_object_list(self, form=None):\n if form:\n filter_data = form.cleaned_data\n filter_status = filter_data['status']\n if not filter_status:\n filter_status = kyc_result_status_choices.LATEST\n\n filter_client_card_ref = filter_data['client_card_ref']\n filter_reseller = filter_data['reseller']\n filter_kyc_result = filter_data['kyc_result']\n\n app_file_id = self.kwargs['app_file_id']\n card_app_import_file = repos.find_card_app_import_file_by_id(app_file_id)\n self.object_list = services.filter_kyc_result(filter_status, card_app_import_file, filter_client_card_ref, filter_reseller, filter_kyc_result)\n else:\n super(KycResultList, self).set_object_list(form)\n\n def post(self, request, *args, **kwargs):\n appline_ids = request.POST.getlist('appline_id')\n if len(appline_ids) == 0:\n messages.add_message(self.request, messages.ERROR, 'Please select at least one application line.')\n return self.get(request, *args, **kwargs)\n else:\n session_handler.set_import_line_ids(request, appline_ids)\n if 'mark_as_approved' in request.POST:\n return HttpResponseRedirect(reverse('carddirector.cd_app_upload.views.kyc_result_list_mark', kwargs={'mark_action': u'mark_as_approved'}))\n\n if 'unmark_approved' in request.POST:\n return HttpResponseRedirect(reverse('carddirector.cd_app_upload.views.kyc_result_list_mark', kwargs={'mark_action': u'unmark_approved'}))\n\n return self.get(request, *args, **kwargs)\n\n\nclass GlobalKycResultList(DownloadableSearchFormListView):\n template_name = 'carddirector/cd_app_upload/global_app_line_kyc_result_list.html'\n context_object_name = \"object_list\"\n paginate_by = 20\n form_class = forms.GlobalKycResultListFilterForm\n csv_file_name = 'global_kyc_result_list.csv' \n\n def set_object_list(self, form=None):\n if form:\n filter_data = form.cleaned_data\n filter_status = filter_data['status']\n if not filter_status:\n filter_status = kyc_result_status_choices.LATEST\n\n filter_client_card_ref = filter_data['client_card_ref']\n filter_reseller = filter_data['reseller']\n filter_kyc_result = filter_data['kyc_result']\n\n self.object_list = services.filter_global_kyc_result(\n filter_status,\n client_card_ref=filter_client_card_ref,\n reseller=filter_reseller,\n kyc_result=filter_kyc_result,\n is_fis_submitted=False\n )\n else:\n super(KycResultList, self).set_object_list(form)\n\n def post(self, request, *args, **kwargs):\n appline_ids = request.POST.getlist('appline_id')\n if len(appline_ids) == 0:\n messages.add_message(self.request, messages.ERROR, 'Please select at least one application line.')\n return self.get(request, *args, **kwargs)\n else:\n session_handler.set_import_line_ids(request, appline_ids)\n if 'mark_as_approved' in request.POST:\n return HttpResponseRedirect(reverse('carddirector.cd_app_upload.views.kyc_result_list_mark', kwargs={'mark_action': u'mark_as_approved'}) + '?next=' + reverse('carddirector.cd_app_upload.views.global_kyc_result_list'))\n\n if 'unmark_approved' in request.POST:\n return HttpResponseRedirect(reverse('carddirector.cd_app_upload.views.kyc_result_list_mark', kwargs={'mark_action': u'unmark_approved'}) + '?next=' + reverse('carddirector.cd_app_upload.views.global_kyc_result_list'))\n\n return self.get(request, *args, **kwargs)\n\n\nclass FailedKycResultList(DownloadableSearchFormListView):\n template_name = 'carddirector/cd_app_upload/app_line_failed_kyc_result_list.html'\n paginate_by = 25\n form_class = forms.FailedKycResultListFilterForm\n csv_file_name = 'failed_kyc_result_report.csv'\n\n def set_object_list(self, form=None):\n if form:\n filter_data = form.cleaned_data\n filter_logstatus = filter_data['log_status']\n filter_import_type = filter_data['import_type']\n filter_filename = filter_data['filename']\n filter_client_card_ref = filter_data['client_card_ref']\n\n self.object_list = services.filter_failed_kyc_result(filter_logstatus, filter_import_type, filter_filename, filter_client_card_ref)\n\n else:\n super(FailedKycResultList, self).set_object_list(form)\n\n\nclass KycCheckLogHistoryList(ListView):\n model = CardApplicationKycCheckLog\n template_name = 'carddirector/cd_app_upload/kyc_check_log_history_list.html'\n context_object_name = \"object_list\"\n paginate_by = 25\n \n def get_queryset(self):\n card_app_import_file = self.kwargs['id']\n return CardApplicationKycCheckLog.objects.filter(kyc_check__application__id=card_app_import_file).order_by(\"-pk\")\n\n\nclass RawRequestDetailView(DetailView):\n template_name = 'carddirector/cd_app_upload/raw_request.html'\n slug_field = 'id'\n context_object_name = 'check_log'\n\n def get_object(self):\n return CardApplicationKycCheckLog.objects.get(id__exact=self.kwargs['slug'])\n\n def get_context_data(self, **kwargs):\n context = super(RawRequestDetailView, self).get_context_data(**kwargs)\n check_log = self.get_object()\n\n if check_log.raw_request:\n context['raw_xml'] = string_utils.to_pretty_format(check_log.raw_request)\n else:\n context['raw_xml'] = ''\n\n return context\n\n\nclass RawResponseDetailView(DetailView):\n template_name = 'carddirector/cd_app_upload/raw_response.html'\n slug_field = 'id'\n context_object_name = 'check_log'\n\n def get_object(self):\n return CardApplicationKycCheckLog.objects.get(id__exact=self.kwargs['slug'])\n\n def get_context_data(self, **kwargs):\n context = super(RawResponseDetailView, self).get_context_data(**kwargs)\n check_log = self.get_object()\n\n if check_log.raw_response:\n context['raw_xml'] = string_utils.to_pretty_format(check_log.raw_response)\n else:\n context['raw_xml'] = ''\n\n return context\n\nclass KycCheckEditView(UpdateView):\n slug_field = 'id'\n \n def get_success_url(self):\n next = self.request.GET.get('next')\n if next:\n return next\n importline = self.get_object()\n file_id = importline.file.id\n return reverse('carddirector.cd_app_upload.views.kyc_result_list', kwargs={'app_file_id': file_id})\n\n def get_object(self):\n importline = get_object_or_404(CardAppImportLine, id=self.kwargs['slug'])\n importline = self._get_real_object(importline)\n return importline\n\n def get_form_class(self):\n importline = self.get_object()\n importline_type = importline.__class__.__name__\n form_name = importline_type + 'Form'\n fclass = getattr(forms, form_name)\n return fclass\n\n def get_template_names(self):\n importline = self.get_object()\n importline_type = importline.__class__.__name__\n template_name = 'carddirector/cd_app_upload/%s/kyc_check_edit.html' % importline_type\n return template_name\n\n def get_context_data(self, **kwargs):\n context = super(KycCheckEditView, self).get_context_data(**kwargs)\n context[\"file_ext\"] = utils.get_allowed_upload_file_extensions_array()\n context[\"file_ext_mime_types\"] = \",\".join( utils.get_allowed_upload_file_mime_types() )\n context['cancel_url'] = self.get_success_url()\n context['line_id'] = self.kwargs['slug']\n context['update_reason_form'] = generic_forms.UpdateNoteContentForm()\n if self.request.method == 'POST':\n context['update_reason_form'] = generic_forms.UpdateNoteContentForm(self.request.POST)\n return context\n\n\n def post(self, request, *args, **kwargs):\n self.object = self.get_object()\n form_class = self.get_form_class()\n form = self.get_form(form_class)\n \n update_reason_form = generic_forms.UpdateNoteContentForm(request.POST, target=self.object) \n try:\n if form.is_valid() and update_reason_form.is_valid():\n with transaction.commit_on_success():\n self.object = form.save(commit=False)\n new_revision = services.revise_card_application(self.object, request.user)\n messages.add_message(self.request, messages.SUCCESS, u\"Application '%s' updated.\" % (self.object.client_card_ref))\n \n # save kyc_docs\n self.__add_kyc_files(new_revision, request.FILES.getlist('file'))\n # delete kyc_docs\n self.__update_kyc_docs(new_revision, form.cleaned_data['kyc_ids_to_delete'])\n\n # also save generic update reason\n update_reason_form.save()\n \n user_card_application_modify.send(\n sender=self.__class__, \n request=request, \n user=request.user, \n user_action_name=user_actions.CARD_APPLICATION__MODIFY, \n details='Card Application [id={app.pk}] modified'.format(app=self.object),\n )\n\n return HttpResponseRedirect(self.get_success_url())\n else:\n for field in form:\n for error in field.errors:\n form.add_form_error(\"Field '%s': %s\" % (field.label, error))\n except Exception as ex:\n error_message = \"Fail to revise the application details as new version, %s\" % str(ex)\n logger.exception(error_message)\n form.add_form_error(error_message)\n\n return self.render_to_response(self.get_context_data(form=form))\n\n def _get_real_object(self, importline):\n obj = None\n importline_types = ['webblack_importline', 'sdd_importline', 'clientfile_importline']\n for importline_type in importline_types:\n try:\n obj = getattr(importline, importline_type)\n except ObjectDoesNotExist:\n continue\n else:\n break\n return obj\n \n def __update_kyc_docs(self, app_line, kyc_ids_to_delete):\n if kyc_ids_to_delete:\n original_filenames = CardApplicationImportKycFile.objects.filter(id__in=kyc_ids_to_delete).values_list('original_filename', flat=True)\n kyc_files = CardApplicationImportKycFile.objects.filter(original_filename__in=original_filenames).filter(application__id=app_line.id)\n kyc_files.delete()\n \n def __add_kyc_files (self, app_line, kyc_files_list):\n logger.debug('Uploaded files: %s', kyc_files_list)\n uploaded_filenames = set()\n for kyc_file in kyc_files_list:\n kyc_file_name = kyc_file.name\n if kyc_file_name in uploaded_filenames:\n logger.warn('Skipping duplicate file with name:%s', kyc_file_name)\n continue\n else:\n uploaded_filenames.add(kyc_file_name)\n repos.create_card_app_import_kyc_file(app_line, kyc_file.name, kyc_file)\n \n\nclass ImportLineCancelView(UpdateView):\n slug_field = 'id'\n template_name = 'carddirector/cd_app_upload/importline_cancel.html'\n model = CardAppImportLine\n\n def get_success_url(self):\n next = self.request.GET.get('next')\n if next:\n return next\n importline = self.get_object()\n file_id = importline.file.id\n return reverse('carddirector.cd_app_upload.views.kyc_result_list', kwargs={'app_file_id': file_id})\n\n def get_context_data(self, **kwargs):\n context = super(ImportLineCancelView, self).get_context_data(**kwargs)\n context['cancel_url'] = self.get_success_url()\n if self.request.method == 'GET':\n context['note_form'] = generic_forms.DeleteNoteContentForm()\n return context\n\n def post(self, request, *args, **kwargs):\n self.object = self.get_object()\n\n note_form = generic_forms.DeleteNoteContentForm(request.POST, target=self.object)\n if note_form.is_valid():\n note_form.save()\n\n if not self.object.is_cancelled:\n user_card_application_modify.send(\n sender=self.__class__, \n request=request, \n user=request.user, \n user_action_name=user_actions.CARD_APPLICATION__MODIFY, \n details='Card application [id={app.pk}] cancelled'.format(app=self.object)\n )\n self.object.is_cancelled = True\n self.object.save()\n messages.add_message(self.request, messages.SUCCESS, 'Application \\'%s\\' cancelled.' % self.object.client_card_ref)\n else:\n messages.add_message(self.request, messages.WARNING, 'Application \\'%s\\' has been cancelled previously.' % self.object.client_card_ref)\n\n else:\n messages.add_message(self.request, messages.ERROR, 'Delete Note is required.')\n return self.render_to_response(self.get_context_data(note_form=note_form))\n \n return HttpResponseRedirect(self.get_success_url())\n\n\nclass ImportLineDetailView(DetailView):\n slug_field = 'id'\n template_name = 'carddirector/cd_app_upload/importline_detail.html'\n\n def _get_real_object(self, importline):\n obj = None\n importline_types = ['webblack_importline', 'sdd_importline', 'clientfile_importline']\n for importline_type in importline_types:\n try:\n obj = getattr(importline, importline_type)\n except ObjectDoesNotExist:\n continue\n else:\n break\n return obj\n\n def get_object(self):\n importline = get_object_or_404(CardAppImportLine, id=self.kwargs['slug'])\n importline = self._get_real_object(importline)\n return importline\n \n def get_template_names(self):\n importline = self.get_object()\n importline_type = importline.__class__.__name__\n template_name = 'carddirector/cd_app_upload/%s/importline_detail.html' % importline_type\n return template_name\n\n def get_success_url(self):\n next = self.request.GET.get('next')\n if next:\n return next\n\n importline = self.get_object()\n file_id = importline.file.id\n \n return reverse('carddirector.cd_app_upload.views.kyc_result_list', kwargs={'app_file_id': file_id})\n\n def get_context_data(self, **kwargs):\n context = super(ImportLineDetailView, self).get_context_data(**kwargs)\n context['cancel_url'] = self.get_success_url()\n return context\n\n\nclass ImportLineKycFilesListView(ListView):\n template_name = 'carddirector/cd_app_upload/import_line_kyc_files.html'\n context_object_name = 'object_list'\n paginate_by = 25\n \n def get_success_url(self):\n if 'next' in self.request.GET:\n return self.request.GET['next']\n app_line_id = self.kwargs['app_line_id']\n import_line = CardAppImportLine.objects.get(pk=app_line_id)\n return reverse('carddirector.cd_app_upload.views.kyc_result_list', kwargs={'app_file_id': import_line.file.id}) \n\n def get_queryset(self):\n app_line_id = self.kwargs['app_line_id']\n import_line = CardAppImportLine.objects.get(pk=app_line_id)\n import_kyc_files = repos.find_all_card_app_import_kyc_file_by_import_line(import_line)\n return import_kyc_files\n\n def get_context_data(self, **kwargs):\n context = super(ImportLineKycFilesListView, self).get_context_data(**kwargs)\n app_line_id = self.kwargs['app_line_id']\n import_line = CardAppImportLine.objects.get(pk=app_line_id)\n\n if import_line.file.import_type.name == db_constants.IMPORT_FILE_TYPE_SDD_FILE:\n raise Http404()\n\n context[\"app_line_id\"] = app_line_id\n context[\"import_line\"] = import_line\n \n context['success_url'] = self.get_success_url()\n \n return context\n\n\nclass QGenSubmittedKycCheckListView(ListView):\n template_name = 'carddirector/cd_app_upload/qgen_kyc_list.html'\n queryset = CardApplicationKycCheck.objects.filter(kyc_type__name=db_constants.KYC_TYPE_FDD).exclude(status__name__in=(\n kyc_check_status_constants.KYC_CHECK_STATUS_APPROVED,\n kyc_check_status_constants.KYC_CHECK_STATUS_DECLINED_OR_FRAUD,\n kyc_check_status_constants.KYC_CHECK_STATUS_EXPIRED,\n kyc_check_status_constants.KYC_CHECK_STATUS_NO_RESULT_YET,\n )).order_by('-last_updated_date')\n\n\nclass SubmitQGenCallbackView(UpdateView):\n model = CardAppImportLine\n form_class = SubmitQGenKYCCallbackForm\n template_name = 'carddirector/cd_app_upload/submit_qgen_kyc_callback.html'\n\n def get_object(self, queryset=None):\n return get_card_application_import_line_by_kyc_check_id(kyc_check_id=self.get_kyc_check().pk)\n\n def get_kyc_check(self):\n return CardApplicationKycCheck.objects.get(pk=self.kwargs['kyc_check_id'])\n\n def form_valid(self, form):\n '''\n Do not save the form (which is done by super.form_valid()), \n but generate the XML for KYC callback instead. \n '''\n if 'generate_response' in self.request.POST:\n xml_response = self.generate_app_response_xml(form)\n form.cleaned_data['callback_xml'] = xml_response\n cleaned_form = self.form_class(form.cleaned_data)\n return self.render_to_response(self.get_context_data(form=cleaned_form))\n elif 'generate_docreturn' in self.request.POST:\n xml_response = self.generate_doc_return_xml(self.request.FILES)\n form.cleaned_data['callback_xml'] = xml_response\n cleaned_form = self.form_class(form.cleaned_data)\n return self.render_to_response(self.get_context_data(form=cleaned_form))\n else:\n return self.render_to_response(self.get_context_data(form=form))\n\n def generate_app_response_xml(self, form):\n applicant_info = self.generate_applicant_info_from_form(form.cleaned_data)\n xml_response = create_mock_qgen_response(\n self.get_kyc_check(),\n applicant_info,\n verification_type=form.cleaned_data['verification_type'],\n status=form.cleaned_data['status'],\n mrz_checked=form.cleaned_data['mrz_checked'],\n decision=form.cleaned_data['decision'],\n contactable=form.cleaned_data['contactable'],\n comment=form.cleaned_data['kyc_comment'],\n )\n return xml_response\n \n def generate_applicant_info_from_form(self, form):\n address_model_obj_mock = Namespace()\n address_model_obj_mock.address2 = form['address2']\n address_model_obj_mock.address3 = form['address3']\n applicant_address = ApplicantAddress()\n applicant_address.address_lines.append(form['address1'])\n applicant_address.address_lines.append(generate_address_line2_for_qgen_xml(address_model_obj_mock))\n applicant_address.city_town = form['city']\n applicant_address.country = form['country']\n applicant_address.post_code = form['post_code']\n applicant_address.type = entities.ADDRESS_TYPE_CURRENT\n \n applicant_info = ApplicantKYCInfo()\n applicant_info.last_name = form['family_name']\n applicant_info.first_name = form['given_name']\n applicant_info.date_of_birth = form['birth_date']\n applicant_info.gender = form['gender']\n applicant_info.post_code = form['post_code']\n applicant_info.title = form['title']\n applicant_info.emails = [form['email']]\n applicant_info.mobile_numbers = [form['mobile_phone']]\n applicant_info.phone_numbers = [form['home_phone']]\n applicant_info.addresses.append(applicant_address)\n return applicant_info\n \n\n def generate_doc_return_xml(self, form_data):\n input_file = form_data['kyc_file']\n\n xml_document = generate_doc_return_dom(self.get_kyc_check().uid, input_file,input_file.name)\n return xml_document.toxml('utf-8')\n \nclass FisIndividualSubmitView(ListView):\n template_name = 'carddirector/cd_app_upload/fis_individual_submit.html'\n context_object_name = 'object_list'\n paginate_by = 25\n\n def get_success_url(self):\n next = self.request.GET.get('next')\n if next:\n return next\n importline = self.get_queryset()[0]\n file_id = importline.file.id\n return reverse('carddirector.cd_app_upload.views.kyc_result_list', kwargs={'app_file_id': file_id}) \n\n def get_context_data(self, **kwargs):\n context = super(FisIndividualSubmitView, self).get_context_data(**kwargs)\n app_line_id = self.kwargs['slug']\n import_line = repos.get_card_app_import_line_by_id(app_line_id)\n\n if not services.is_application_ready_for_fis_submission(import_line):\n raise Http404\n\n card_submission_mode = services.get_fis_card_submission_mode(import_line)\n context['mode'] = card_submission_mode\n suffix = 'single request'\n if card_submission_mode == card_submission_modes.BATCH:\n suffix = 'Append in batch queue'\n context['title'] = 'Send to FIS (%s)' % suffix\n context['app_file_id'] = import_line.file.id\n return context\n\n def get_queryset(self):\n app_line_id = self.kwargs['slug']\n import_line = repos.get_card_app_import_line_by_id(app_line_id)\n import_lines = []\n import_lines.append(import_line)\n return import_lines\n\n def send_to_fis(self,import_line, request, *args, **kwargs):\n try:\n response = send_card_application_submission_non_txn_to_tps(card_submission_modes.SINGLE, [long(import_line.id)])\n\n logger.info(\"response: %s \" % response)\n if response and response.success == True:\n messages.add_message(self.request, messages.SUCCESS, 'Application \\'%s\\' has been submitted to FIS successfully.' % import_line.client_card_ref)\n return HttpResponseRedirect(self.get_success_url())\n else:\n if is_mq_timeout_tps_response(response):\n messages.add_message(self.request, messages.ERROR, 'Server is busy, your request is being processed.')\n messages.add_message(self.request, messages.ERROR, 'Please wait a while and check the account balance or transaction history.')\n else:\n messages.add_message(self.request, messages.ERROR, 'Fail to process transaction.')\n for response_entry in response.responseEntries:\n resp_msg = response_entry.responseMessage\n if response_entry.responseCode == 'INFO_FIS_ACTION_CODE':\n resp_msg = fis_utils.translate_action_code_to_full_desc(resp_msg)\n\n messages.add_message(self.request, messages.ERROR, ('%s - %s' % (response_entry.responseCode, resp_msg)))\n\n return self.get(request, *args, **kwargs)\n\n except Exception as ex:\n logger.exception('%r' % ex)\n messages.add_message(self.request, messages.ERROR, 'Fail to process transaction.')\n messages.add_message(self.request, messages.ERROR, 'Network error, CardDirector cannot connect to TPS. Please contact system administrator.')\n messages.add_message(self.request, messages.ERROR, '%r' % ex)\n return self.get(request, *args, **kwargs)\n\n def append_to_queue(self,import_line, request, *args, **kwargs):\n try:\n services.append_to_fis_batch_queue(import_line)\n messages.add_message(self.request, messages.SUCCESS, 'Application \\'%s\\' has been added into FIS Batch Queue.' % import_line.client_card_ref)\n return HttpResponseRedirect(self.get_success_url())\n except Exception as ex:\n logger.exception('%r' % ex)\n messages.add_message(self.request, messages.ERROR, 'Fail to process transaction.')\n messages.add_message(self.request, messages.ERROR, 'Network error, CardDirector cannot connect to TPS. Please contact system administrator.')\n messages.add_message(self.request, messages.ERROR, '%r' % ex)\n return self.get(request, *args, **kwargs)\n\n def post(self, request, *args, **kwargs):\n app_line_id = self.kwargs['slug']\n import_line = repos.get_card_app_import_line_by_id(app_line_id)\n card_submission_mode = services.get_fis_card_submission_mode(import_line);\n\n user_card_application_issue.send(\n sender=self.__class__, \n request=request, \n user=request.user, \n user_action_name=user_actions.CARD_APPLICATION__ISSUE, \n details='Request card to be issued for application[id={app.pk}]'.format(app=import_line)\n )\n if card_submission_mode == card_submission_modes.SINGLE:\n return self.send_to_fis(import_line,request, *args, **kwargs)\n else:\n return self.append_to_queue(import_line, request, *args, **kwargs)\n\n\nclass FisBatchSubmitView(SearchFormListView):\n template_name = 'carddirector/cd_app_upload/fis_batch_submit.html'\n context_object_name = 'object_list'\n paginate_by = 25\n form_class = FisBatchQueueSearchForm\n slug_field = 'id'\n \n default_delivery_method_ordinal = 4\n \n def get(self, request, *args, **kwargs):\n if 'dlvmethod' in request.GET:\n self.dlvmethod_id = request.GET['dlvmethod']\n else:\n self.dlvmethod_id = repos.find_cd_delivery_method_by_ordinal( self.default_delivery_method_ordinal ).id\n req_params = request.GET.copy()\n req_params['dlvmethod'] = self.dlvmethod_id\n request.GET = req_params\n return super(FisBatchSubmitView, self).get(request, *args, **kwargs)\n \n def get_queryset(self): \n return repos.find_import_lines_in_fis_batch_queue( self.dlvmethod_id )\n\n def post(self, request, *args, **kwargs):\n dlvmethod = request.POST['dlvmethod']\n try:\n import_lines = repos.find_import_lines_in_fis_batch_queue( dlvmethod )\n if not import_lines or len(import_lines) == 0:\n messages.add_message(self.request, messages.ERROR, 'There are no applications for this delivery method in the queue. ')\n return self.get(request, *args, **kwargs)\n \n import_lines_ids = list ( import_lines.values_list('id', flat=True) )\n user_card_application_issue.send(\n sender=self.__class__, \n request=request, \n user=request.user, \n user_action_name=user_actions.CARD_APPLICATION__ISSUE, \n details='Request card to be issued for applications[ids={ids}]'.format(ids=import_lines_ids)\n )\n response = send_card_application_submission_non_txn_to_tps(card_submission_modes.BATCH, import_lines_ids)\n\n logger.info(\"response: %s \" % response)\n if response and response.success == True:\n messages.add_message(self.request, messages.SUCCESS, '%d application(s) have been batch submitted to FIS.' % (len(import_lines_ids)) )\n \n repos.set_sent_to_fis_in_batch_queue( dlvmethod )\n \n return HttpResponseRedirect(reverse('carddirector.cd_app_upload.views.app_file_list'))\n else:\n if is_mq_timeout_tps_response(response):\n messages.add_message(self.request, messages.ERROR, 'Server is busy, your request is being processed.')\n messages.add_message(self.request, messages.ERROR, 'Please wait a while and check the account balance or transaction history.')\n else:\n messages.add_message(self.request, messages.ERROR, 'Fail to process transaction.')\n for response_entry in response.responseEntries:\n resp_msg = response_entry.responseMessage\n if response_entry.responseCode == 'INFO_FIS_ACTION_CODE':\n resp_msg = fis_utils.translate_action_code_to_full_desc(resp_msg)\n messages.add_message(self.request, messages.ERROR, ('%s - %s' % (response_entry.responseCode, resp_msg)))\n\n return self.get(request, *args, **kwargs)\n\n except Exception as ex:\n logger.exception('%r' % ex)\n messages.add_message(self.request, messages.ERROR, 'Fail to process transaction.')\n messages.add_message(self.request, messages.ERROR, 'Network error, CardDirector cannot connect to TPS. Please contact system administrator.')\n return self.get(request, *args, **kwargs)\n\nclass KycResultListMarkView(ListView):\n template_name = 'carddirector/cd_app_upload/app_line_kyc_result_list_mark.html'\n paginate_by = 25\n\n def get_queryset(self):\n appline_ids = session_handler.get_session_for_import_lines(self.request)\n applines = CardAppImportLineForKycResult.objects.filter(pk__in=appline_ids)\n return applines\n\n def post(self, request, *args, **kwargs):\n\n if 'confirm' in request.POST:\n try:\n mark_action = kwargs.get('mark_action', None)\n\n object_list = self.get_queryset()\n app_file_id = object_list[0].file.id\n\n warning_msg = None\n if mark_action == 'mark_as_approved':\n object_list, warning_msg = self.validate_mark_as_aproved(object_list)\n\n success = batch_update_handler.batch_mark_flag(self.request, object_list, mark_action)\n \n if warning_msg: # do this ugly thing so the warning doesn't show above the success msg\n messages.add_message(self.request, messages.WARNING, warning_msg )\n \n if success and success==True:\n session_handler.clean_session_for_import_lines(request)\n return HttpResponseRedirect(reverse('carddirector.cd_app_upload.views.kyc_result_list', args=[app_file_id]))\n except Exception as ex:\n logger.exception('%r' % ex)\n messages.add_message(self.request, messages.ERROR, '%s' % str(ex))\n return self.get(request, *args, **kwargs)\n\n return super(KycResultListMarkView, self).get(request, *args, **kwargs)\n\n\n def get_context_data(self, **kwargs):\n context = super(KycResultListMarkView, self).get_context_data(**kwargs)\n mark_action = self.kwargs.get('mark_action', None)\n context['mark_action'] = mark_action\n\n appline_ids = session_handler.get_session_for_import_lines(self.request)\n if appline_ids is None or len(appline_ids)==0:\n raise Http404()\n\n import_line = CardAppImportLineForKycResult.objects.get(id=appline_ids[0])\n context['app_file_id'] = import_line.file.id\n\n mark_action_header_map = {\n 'mark_as_approved': 'Marking as Approve',\n 'unmark_approved': 'Unmarking Approve',\n }\n context['mark_action_header'] = mark_action_header_map[mark_action]\n return context\n \n def validate_mark_as_aproved(self, import_lines):\n kyc_complete_ids = []\n kyc_incomplete_ccr = []\n for import_line in import_lines:\n if services.is_card_application_kyc_completed(import_line):\n kyc_complete_ids.append(import_line.id)\n else:\n kyc_incomplete_ccr.append(import_line.client_card_ref)\n warning_message = None\n if len(kyc_incomplete_ccr) > 0:\n warning_message = '%s application(s) could not be approved: %s. Complete KYC first.' % (str(len(kyc_incomplete_ccr)), (\", \".join( kyc_incomplete_ccr )))\n return CardAppImportLineForKycResult.objects.filter(id__in = kyc_complete_ids), warning_message\n \n\n","sub_path":"apps/carddirector/cd_app_upload/views/views_orig.py","file_name":"views_orig.py","file_ext":"py","file_size_in_byte":59506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"6016312","text":"#\n# [227] Basic Calculator II\n#\n# https://leetcode.com/problems/basic-calculator-ii/description/\n#\n# algorithms\n# Medium (30.44%)\n# Total Accepted: 68.4K\n# Total Submissions: 224.6K\n# Testcase Example: '\"3+2*2\"'\n#\n# Implement a basic calculator to evaluate a simple expression string.\n#\n# The expression string contains only non-negative integers, +, -, *, /\n# operators and empty spaces . The integer division should truncate toward\n# zero.\n#\n# Example 1:\n#\n#\n# Input: \"3+2*2\"\n# Output: 7\n#\n#\n# Example 2:\n#\n#\n# Input: \" 3/2 \"\n# Output: 1\n#\n# Example 3:\n#\n#\n# Input: \" 3+5 / 2 \"\n# Output: 5\n#\n#\n# Note:\n#\n#\n# You may assume that the given expression is always valid.\n# Do not use the eval built-in library function.\n#\n\n\nclass Solution:\n def calculate(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n arr, i = [], 0\n while i < len(s):\n if s[i] == ' ':\n i += 1\n continue\n elif ord(s[i]) >= ord('0') and ord(s[i]) <= ord('9'):\n j = i+1\n while j < len(s) and ord(s[j]) >= ord('0') and ord(s[j]) <= ord('9'):\n j += 1\n arr.append(int(s[i:j]))\n i = j-1\n else:\n arr.append(s[i])\n i += 1\n # Calculate * and /\n arr2, i = [], 0\n while i < len(arr):\n if arr[i] == '*':\n a = arr2.pop()\n arr2.append(a*arr[i+1])\n i += 1\n elif arr[i] == '/':\n a = arr2.pop()\n arr2.append(a//arr[i+1])\n i += 1\n else:\n arr2.append(arr[i])\n i += 1\n # Calculate + and -\n i, res, add, sub = 0, 0, False, False\n while i < len(arr2):\n if arr2[i] == '+':\n add = True\n elif arr2[i] == '-':\n sub = True\n else:\n if add:\n res += arr2[i]\n add = False\n elif sub:\n res -= arr2[i]\n sub = False\n else:\n res = arr2[i]\n i += 1\n return res\n","sub_path":"227.basic-calculator-ii.python3.py","file_name":"227.basic-calculator-ii.python3.py","file_ext":"py","file_size_in_byte":2218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"311231292","text":"import webapp2\nimport urllib\nimport urllib2\nimport cgi\n\napi_url = \"https://keyscores.api-us1.com/admin/api.php\"\napi_key = \"1f92db2479bcbfed65615e4748bd24606c9fadceea77eeee994c625e38e25a1e686f9257\" \n\n# class AccountView(webapp2.RequestHandler):\n# def get(self):\n# self.response.headers['Content-Type'] = 'text/html'\n# query_args = { 'api_key':api_key, 'api_action':'account_view', 'api_output':'json' }\n# # This urlencodes your data (that's why we need to import urllib at the top)\n# data = urllib.urlencode(query_args)\n# request = urllib2.Request(api_url,data)\n# self.response.write(urllib2.urlopen(request).read())\n\nclass EmailAdd(webapp2.RequestHandler):\n def post(self):\n self.response.headers['Content-Type'] = 'application/json'\n query_args = { \n \t'api_key':api_key, \n \t'api_action':'contact_add', \n \t'email':self.request.get('email'),\n \t'api_output':'json' \n }\n\n # This urlencodes your data (that's why we need to import urllib at the top)\n data = urllib.urlencode(query_args)\n request = urllib2.Request(api_url,data)\n\n self.response.write(urllib2.urlopen(request).read()) \n\napplication = webapp2.WSGIApplication([\n # ('/api-email/account', AccountView),\n ('/api-email/add', EmailAdd)\n], debug=True)","sub_path":"api-email.py","file_name":"api-email.py","file_ext":"py","file_size_in_byte":1350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"459879261","text":"# coding: utf-8\n\nfrom __future__ import absolute_import\n\nfrom utils.consts import (\n SUBJECT_MATH,\n SUBJECT_PHYSICS,\n SUBJECT_CHEMISTRY,\n SUBJECT_BIOLOGY\n)\n\nsubject_name2id = {\n 'math': SUBJECT_MATH,\n 'physics': SUBJECT_PHYSICS,\n 'chemistry': SUBJECT_CHEMISTRY,\n 'biology': SUBJECT_BIOLOGY\n}\n\nSCIENCE_CONSTS = {\n # math model\n 'K_MATH_CHOICE': 2000,\n 'K_MATH_CHOICE_ANALYSIS': 2001,\n\n 'K_MATH_BLANK': 2002,\n 'K_MATH_BLANK_QUESTION': 2003,\n 'K_MATH_BLANK_ANALYSIS': 2004,\n\n 'K_MATH_RESPONSE': 2006,\n 'K_MATH_RESPONSE_QUESTION': 2007,\n 'K_MATH_RESPONSE_ANALYSIS': 2008,\n\n # biology model\n 'K_BIOLOGY_CHOICE': 7000,\n 'K_BIOLOGY_CHOICE_ANALYSIS': 7002,\n\n 'K_BIOLOGY_BLANK': 7010,\n 'K_BIOLOGY_BLANK_QUESTION': 7011,\n 'K_BIOLOGY_BLANK_ANALYSIS': 7013,\n\n 'K_BIOLOGY_RESPONSE': 7020,\n 'K_BIOLOGY_RESPONSE_QUESTION': 7021,\n 'K_BIOLOGY_RESPONSE_ANALYSIS': 7023,\n\n # chemistry model\n 'K_CHEMISTRY_CHOICE': 7100,\n 'K_CHEMISTRY_CHOICE_ANALYSIS': 7102,\n\n 'K_CHEMISTRY_BLANK': 7110,\n 'K_CHEMISTRY_BLANK_QUESTION': 7111,\n 'K_CHEMISTRY_BLANK_ANALYSIS': 7113,\n\n 'K_CHEMISTRY_RESPONSE': 7120,\n 'K_CHEMISTRY_RESPONSE_QUESTION': 7121,\n 'K_CHEMISTRY_RESPONSE_ANALYSIS': 7123,\n\n # physics model\n 'K_PHYSICS_CHOICE': 7200,\n 'K_PHYSICS_CHOICE_ANALYSIS': 7202,\n\n 'K_PHYSICS_BLANK': 7210,\n 'K_PHYSICS_BLANK_QUESTION': 7211,\n 'K_PHYSICS_BLANK_ANALYSIS': 7213,\n\n 'K_PHYSICS_RESPONSE': 7220,\n 'K_PHYSICS_RESPONSE_QUESTION': 7221,\n 'K_PHYSICS_RESPONSE_ANALYSIS': 7223\n}\n\n\nQUESTION_TYPE_PRACTICE = 1 # 练题\nQUESTION_TYPE_CHALLENGE = 2 # 挑战\nQUESTION_TYPE_REVIEW = 3 # 查看\n\n","sub_path":"science/consts.py","file_name":"consts.py","file_ext":"py","file_size_in_byte":1681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"611555662","text":"from rest_framework import mixins, viewsets\n\nfrom docs.models import Document\nfrom docs.serializers import DocumentSerializer\n\n\nclass DocumentViewset(mixins.ListModelMixin,\n mixins.UpdateModelMixin,\n mixins.DestroyModelMixin,\n mixins.CreateModelMixin,\n mixins.RetrieveModelMixin,\n viewsets.GenericViewSet):\n queryset = Document.objects.all()\n serializer_class = DocumentSerializer\n","sub_path":"docs/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"260947395","text":"import librosa\nimport numpy as np\n\nfrom vad.acoustics.transforms.transform import Transform\nfrom vad.data_models.audio_data import AudioData\n\n\nclass MelSpectrogramTransform(Transform):\n feature_size: int\n\n def __init__(self, n_fft: int, hop_ms: int, window_ms: int, n_mels: int):\n self.n_fft = n_fft\n self.hop_ms = hop_ms\n self.window_ms = window_ms\n self.n_mels = n_mels\n\n self.feature_size = n_mels\n\n def apply(self, audio_data: AudioData) -> np.array:\n hop_samples = int(self.hop_ms / 1000 * audio_data.sample_rate)\n window_samples = int(self.window_ms / 1000 * audio_data.sample_rate)\n\n feature = librosa.feature.melspectrogram(\n y=audio_data.audio,\n sr=audio_data.sample_rate,\n n_mels=self.n_mels,\n n_fft=self.n_fft,\n hop_length=hop_samples,\n win_length=window_samples,\n )\n return feature\n","sub_path":"vad/acoustics/transforms/mel_spectrogram.py","file_name":"mel_spectrogram.py","file_ext":"py","file_size_in_byte":939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"598821807","text":"'''\nTrevor Urbshas\nKevin Reid\nICS 3U Flashtown Taxes\nNovember 1, 2013\nNovember 6, 2013\nThis program will ask input for the user's age and gross pay, and will output how much in taxes they owe.\n'''\n\n# Define Variables and tables\nageRanges = [18,26,36,56,65]\ntaxAmounts = [0,0.25,0.35,0.45,0.20,0]\n\n# Getting the user's age and gross pay\ndef ageAndPay() :\n\n # Getting the user's age\n while True :\n userAge = input('How old are you in years? ')\n try :\n float(userAge)\n except ValueError :\n print('Please enter a number greater than 0.')\n else :\n userAge = float(userAge)\n # Checking if the user inputted a valid age\n if userAge <= 0 :\n print('That is not a valid age. Please enter a number greater than 0.')\n else :\n break\n\n \n # Getting the user's gross pay\n while True :\n grossPay = input('What is your gross pay? ')\n try :\n float(grossPay)\n except ValueError :\n print('That is not a valid number. Please enter a number greater than or equal to 0.')\n else :\n grossPay = float(grossPay)\n # Check if the value of gross pay is valid\n if grossPay < 0 :\n print('You cannot have negative pay, try again.')\n else :\n break\n\n return userAge,grossPay\n\n# Determining tax range of user\ndef taxCalc() :\n taxRange = 0\n \n userAge, grossPay = ageAndPay()\n \n # Determining the age range of the user, then returning their tax range\n for indexValue in range(len(ageRanges)) :\n if userAge >= ageRanges[indexValue] : \n taxRange = taxRange + 1\n\n # Calculate tax owed\n taxOwed = grossPay * taxAmounts[taxRange]\n\n # Output how much the user owes\n print('You owe $',taxOwed,'of your gross pay in taxes.')\n \ntaxCalc()\n","sub_path":"ICS 3U-Trevor/Unit 3/U3A4(Flashtown Taxes).py","file_name":"U3A4(Flashtown Taxes).py","file_ext":"py","file_size_in_byte":1911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"100384816","text":"#/usr/bin/env python\n#coding: utf-8\n\n\n\n#ブレインダーライブラリ(コメント以外で日本語を使うな)\nimport bpy\nimport math\n\n\nAngle2 = 10 # 何度ごとに回転するか(0を指定するな)\nPath = \"../img/img\" # 画像を保存するパス(最後に\"/\"を入れるな)\nExt = \"jpeg\" # 最終的に出力される画像の拡張子\nName = \"\" # 最終的に出力される画像名\nNumber = 1 # 開始のレンダリングナンバー\n\n\ndef rotate(num, axis):\n \n global Angle2\n \n Angle = 0\n \n # \"axis\"を中心にオブジェクトを回転\n for i in range( num ):\n bpy.ops.transform.rotate( value = math.radians(Angle), orient_axis = axis)\n Angle = Angle + Angle2\n rendering()\n\n\ndef rendering():\n global Path\n global Name\n global Ext\n global Number\n\n Name = Path + \"/\" + str(Number) + \".\" + Ext\n\n # レンダリングしてイメージを保存\n bpy.ops.render.render()\n bpy.data.images[\"Render Result\"].save_render( filepath = Name )\n\n Number = Number + 1\n\n\ndef main():\n \n global flag_camera\n flag_camera = 0\n \n\n # レンダリング画像の背景を白にするため大きな床を作る\n bpy.ops.mesh.primitive_plane_add(location = (0, 0, -20))\n bpy.ops.rigidbody.object_add(type = \"PASSIVE\")\n bpy.data.objects[\"Plane\"].scale = (500, 500, 1)\n\n # 床に色をつける\n activeobject = bpy.context.active_object\n mat = bpy.data.materials.new(name = \"myMaterial\")\n activeobject.data.materials.append(mat)\n bpy.context.object.active_material.diffuse_color=(255, 255, 255, 0)\n \n # 床の情報を取得\n obj_plane = bpy.context.object\n \n # コレクション内の全てのオブジェクトを走査\n for col in bpy.data.collections:\n \n for ob in col.objects:\n # カメラがあった場合はフラグをセット\n if ob.type == \"CAMERA\":\n flag_camera = 1\n\n # カメラを作成,アクティブカメラに設定\n if flag_camera == 0:\n bpy.ops.object.camera_add(location = (0, -5, 5 ), rotation=( 0.8, 0, 0 ))\n bpy.context.scene.camera = bpy.data.objects[\"Camera\"]\n obj_camera = bpy.data.objects[\"Camera\"]\n obj_camera.select_set(False)\n\n\n # コレクション内の全てのオブジェクトを走査\n for col in bpy.data.collections:\n \n for ob in col.objects:\n \n # メッシュタイプの全てを選択\n if ob.type == 'MESH' and ob.parent == None :\n ob.select_set(True)\n bpy.context.view_layer.objects.active = ob\n else:\n # メッシュでなければ選択状態にしない\n ob.select_set(False)\n \n \n\n\n\n # 床が選択されるためこのままだと床が回転するので床の選択を外す\n obj_plane.select_set(False)\n\n\n\n # 何回for文を回すかを計算\n num = int( 360 / Angle2 )\n\n rotate( num, \"X\" )\n rotate( num, \"Y\" )\n rotate( num, \"Z\" )\n\n\n\n \n\n\n\n\n\n\n\nif __name__ == \"__main__\":\n main()\n\n\n","sub_path":"script_01/script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":3176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"361052834","text":"# coding: utf-8\n__author__ = 'leggnom'\n\nimport sys\nimport logging\n\n\nfrom proxy import Proxy\nfrom freelance import Freelance\n\n\nlogging.basicConfig(filename='app.log', level=logging.WARNING)\n\n\ninstance = {\n 'proxy': Proxy,\n 'freelance': Freelance\n}\n\n\nif len(sys.argv) > 1:\n driver = sys.argv[1]\n if driver in instance:\n instance[driver]().run()\n","sub_path":"init.py","file_name":"init.py","file_ext":"py","file_size_in_byte":362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"189822378","text":"start_speed = 60\nend_speed = 131\nincrement = 10\nconversion_factor = 0.6214\n\nprint ('KPH\\tMPH')\nprint('--------------')\n\nfor kph in range(start_speed, end_speed, increment):\n mph = kph * conversion_factor\n print(kph, '\\t', format(mph, '.1f'))\n\n","sub_path":"Program_4-9.py","file_name":"Program_4-9.py","file_ext":"py","file_size_in_byte":249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"603155859","text":"class Node:\n def __init__(self, data):\n self.left = None\n self.right = None\n self.data = data\n\ndef insert(root, key):\n if root is None:\n root = Node(key)\n if root:\n if keyroot.data:\n root.right = delete(root.right, key)\n elif root.data==key and root.left == None and root.right == None:\n return None\n else:\n if root.left is None:\n temp = root.right\n root = None\n print('single child node is deleted')\n return temp\n elif root.right is None:\n temp = root.left\n root = None\n print('single child node is deleted')\n return temp\n\n temp = minValue(root.right)\n root.data = temp.data\n root.right = delete(root.right, temp.data)\n print('two child node is deleted')\n\n return root\n \n\ndef inorder_print(root):\n if root:\n inorder_print(root.left)\n print(root.data)\n inorder_print(root.right)\n\nroot=Node(50)\ninsert(root, 30)\ninsert(root, 20)\n#insert(root, 40)\ninsert(root, 60)\nprint('before deletion')\ninorder_print(root)\ndelete(root, 50)\nprint('after deletion')\ninorder_print(root)","sub_path":"tree/BST_delete.py","file_name":"BST_delete.py","file_ext":"py","file_size_in_byte":1872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"153059594","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Feb 26 14:10:25 2015\n\n@author: Willem\n\"\"\"\nfrom __future__ import division\nimport numpy as np\nimport numpy.ma as ma\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nimport functions\nimport md_animation\n\nplt.close('all')\n\ndens = 0.001\nT = 100\nn_t = 1000; \ndt = 0.004\nn = 5\nN = 4*n**3 #number of particles\n\nbox_len = (N/dens)**(1.0/3) #bigger than 1 otherwise fcc lattice will bug out\n\npos = functions.init_fcc(n,box_len)\nmom = functions.init_mom(N,T)\n\nn_samples = 20\n\nE_avg = np.zeros(n_samples)\nE_std = np.zeros(n_samples)\nP_avg = np.zeros(n_samples)\nP_std = np.zeros(n_samples)\nD_avg = np.zeros(n_samples)\nD_std = np.zeros(n_samples)\n\n\ni = 0\n\"\"\"\nfor i in range(0,n_samples): \n dens = 0.001 + i*(3/n_samples)\n print i\n E_avg[i],E_std[i],P_avg[i],P_std[i],D_avg[i],D_std[i],g_avg,g_std,g_xaxis = functions.calcloop(dens,T,n,200,10,200)\n\nx = np.arange(0.001,3.001,(3/n_samples))\nfig1 = plt.figure()\nax1 = fig1.add_subplot(111)\n\nax1.plot(x,E_std/E_avg,'k--')\nax1.set_title('Measure of fluctuations in energy')\nax1.set_xlabel('Density')\nax1.set_ylabel('Relative size of the fluctuations')\n\nfig2 = plt.figure()\nax3 = fig2.add_subplot(111)\nax3.plot(x,P_avg,'k')\nax3.plot(x,P_std,'k--')\nax3.set_title('Deviation from ideal gas presure as a function of density')\nax3.set_xlabel('Density')\nax3.set_ylabel('Pressure')\n\n\nfig3 = plt.figure()\nax5 = fig3.add_subplot(111)\n\nax5.plot(x,D_avg,'k')\nax5.plot(x,D_std,'k--')\nax5.set_title('Diffusion constant as a function of density')\nax5.set_xlabel('Density')\nax5.set_ylabel('Diffusion constant')\n\n\"\"\"\ng_avg,g_std,g_xaxis = functions.calcloop(dens,T,n,100,40,200)\n\nfig = plt.figure()\nax = fig.add_subplot(111)\nax.plot(g_xaxis, g_avg,'k')\nax.set_title('Pair Correlation Function, Density = 0.001')\nax.plot(g_xaxis, g_std,'0.5')\nax.set_xlabel('Distance')\nax.set_ylabel('Particle density')\n\n\n\n\nif __name__ == '__main__':\n anim = md_animation.AnimatedScatter(N, box_len, pos,\n mom, functions.verlet,\n dt)\n anim.show()\n","sub_path":"testrun.py","file_name":"testrun.py","file_ext":"py","file_size_in_byte":2096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"527120265","text":"\n\nfrom xai.brain.wordbase.verbs._toast import _TOAST\n\n#calss header\nclass _TOASTING(_TOAST, ):\n\tdef __init__(self,): \n\t\t_TOAST.__init__(self)\n\t\tself.name = \"TOASTING\"\n\t\tself.specie = 'verbs'\n\t\tself.basic = \"toast\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/verbs/_toasting.py","file_name":"_toasting.py","file_ext":"py","file_size_in_byte":235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"471139461","text":"import os\nfrom torch.autograd import Variable\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nConvMethod = \"in_channel_is_embedding_dim\"\n\nclass CNN_GRU(nn.Module):\n\tdef __init__(self, **kwargs):\n\t\tsuper(CNN_GRU, self).__init__()\n\t\t\n\t\tself.MODEL = kwargs[\"MODEL\"]\n\t\tself.BATCH_SIZE = kwargs[\"BATCH_SIZE\"]\n\t\tself.MAX_SENT_LEN = kwargs[\"MAX_SENT_LEN\"]\n\t\tself.WORD_DIM = kwargs[\"WORD_DIM\"]\n\t\tself.VOCAB_SIZE = kwargs[\"VOCAB_SIZE\"]\n\t\tself.CLASS_SIZE = kwargs[\"CLASS_SIZE\"]\n\t\tself.FILTERS = kwargs[\"FILTERS\"]\n\t\tself.FILTER_NUM = kwargs[\"FILTER_NUM\"]\n\t\tself.DROPOUT_PROB = kwargs[\"DROPOUT_PROB\"]\n\t\tself.IN_CHANNEL = 1\n\t\tself.USE_CUDA = True\n\n\t\tself.HIDDEN_DIM = kwargs[\"HIDDEN_DIM\"]\n\t\tself.NUM_LAYERS = kwargs[\"NUM_LAYERS\"]\n\t\tself.bidirectional = kwargs[\"BIDIRECTIONAL\"]\n\n\t\tself.embedding = nn.Embedding(self.VOCAB_SIZE + 2, self.WORD_DIM, padding_idx=self.VOCAB_SIZE + 1)\n\t\tif self.MODEL == \"static\" or self.MODEL == \"non-static\" or self.MODEL == \"multichannel\":\n\t\t\tself.WV_MATRIX = kwargs[\"WV_MATRIX\"]\n\t\t\tself.embedding.weight.data.copy_(torch.from_numpy(self.WV_MATRIX))\n\t\tif self.MODEL == \"static\":\n\t\t\tself.embedding.weight.requires_grad = False\n\t\telif self.MODEL == \"multichannel\":\n\t\t\tself.embedding2 == nn.Embedding(self.VOCAB_SIZE + 2, self_WORD_DIM, padding_idx=self.VOCAB_SIZE + 1)\n\t\t\tself.embedding2.weight.data.copy_(torch.from_numpy(self.WV_MATRIX))\n\t\t\tself.embedding2.weight.requires_grad = False\n\t\t\tself.IN_CHANNEL = 2\n\n\t\tconv_blocks = []\n\t\tfor filter_size in self.FILTERS:\n\t\t\tmaxpool_kernel_size = self.MAX_SENT_LEN - filter_size + 1\n\t\t\tif ConvMethod == \"in_channel_is_embedding_dim\":\n\t\t\t\tconv1d = nn.Conv1d(in_channels = self.WORD_DIM, out_channels = self.FILTER_NUM, kernel_size = filter_size, stride = 1)\n\t\t\t\tconv2 = nn.Conv1d(in_channels = self.FILTER_NUM , out_channels = self.FILTER_NUM, kernel_size = filter_size/2, stride = 1)\n\t\t\telse:\n\t\t\t\tconv1d = nn.Conv1d(in_channels = 1, out_channels = self.FILTER_NUM, kernel_size = filter_size * self.WORD_DIM, stride = self.WORD_DIM)\n\t\t\t\tconv2 = nn.Conv1d(in_channels = self.FILTER_NUM, out_channels = self.FILTER_NUM, kernel_size = filter_size * self.WORD_DIM, stride = self.WORD_DIM)\n\n\t\t\tcomponent = nn.Sequential(\n\t\t\t\tconv1d,\n\t\t\t\tnn.ReLU(),\n\t\t\t\tnn.MaxPool1d(kernel_size = maxpool_kernel_size),\n\t\t\t)\n\t\t\tif self.USE_CUDA:\n\t\t\t\tcomponent = component.cuda()\n\t\t\t\t\t\n\t\t\tconv_blocks.append(component)\n\t\tself.conv_blocks = nn.ModuleList(conv_blocks)\n\t\tself.GRU = nn.GRU(self.FILTER_NUM * len(self.FILTERS), self.HIDDEN_DIM, dropout=self.DROPOUT_PROB, num_layers=self.NUM_LAYERS)\n\t\tself.hidden2label = nn.Linear(self.HIDDEN_DIM, self.CLASS_SIZE)\n\t\tself.hidden = self.init_hidden()\n\n\tdef init_hidden(self):\n\t\tif self.USE_CUDA == True:\n\t\t\treturn Variable(torch.zeros(1 * self.NUM_LAYERS, self.BATCH_SIZE, self.HIDDEN_DIM)).cuda()\n\t\telse:\n\t\t\treturn Variable(torch.zeros(1 * self.NUM_LAYERS, self.BATCH_SIZE, self.HIDDEN_DIM))\n\n\tdef forward(self, x):\n\t\tx = self.embedding(x)\n\t\tif ConvMethod == \"in_channel_is_embedding_dim\":\n\t\t\tx = x.transpose(1,2)\t # (batch, embed_dim, sent_len)\n\t\telse:\n\t\t\tx = x.view(x.size(0), 1, -1) # (batch, 1, sent_len*embed_dim)\n\t\tx_list = [conv_block(x) for conv_block in self.conv_blocks]\n\t\tout = torch.cat(x_list, 2)\n\t\tout = out.view(out.size(0), -1)\n\t\tout = out.unsqueeze(0)\n\t\tout, self.hidden = self.GRU(out, self.hidden)\n\t\tout = self.hidden2label(out[-1].squeeze(0))\n\t\treturn F.log_softmax(out)\n\t\t\n","sub_path":"models/models/CNN_GRU.py","file_name":"CNN_GRU.py","file_ext":"py","file_size_in_byte":3399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"23654554","text":"from django.shortcuts import render, get_object_or_404\nfrom .models import Page\nfrom django.utils import timezone\nfrom .forms import PageForm\nfrom django.shortcuts import redirect\nfrom django.core.paginator import Paginator\n\n\n# Create your views here.\n\n\ndef page_list(request):\n\tpages = Page.objects.filter(published_date__lte=timezone.now()).order_by('published_date')\n\n\tpaginator = Paginator(pages, 1)\n\n\tpage = request.GET.get('page')\n\tpages = paginator.get_page(page)\n\n\treturn render(request, 'comic/page_list.html', {'pages':pages})\n\n\n\ndef page_detail(request, pk): \n\tpage = get_object_or_404(Page, pk=pk)\n\treturn render(request, 'comic/page_detail.html', {'page': page})\n\n\n\ndef page_new(request):\n\tif request.method == \"POST\":\n\t\tform = PageForm(request.POST, request.FILES)\n\t\tif form.is_valid():\n\t\t\tpage = form.save(commit=False)\n\t\t\tpage.author = request.user\n\t\t\tpage.published_date = timezone.now()\n\t\t\tpage.save()\n\t\t\treturn redirect('page_detail', pk=page.pk)\n\telse:\n\t\tform = PageForm()\n\treturn render(request, 'comic/page_edit.html', {'form': form})\n\n\n\ndef page_edit(request, pk): \n\tpage = get_object_or_404(Page, pk=pk)\n\tif request.method == \"POST\":\n\t\tform = PageForm(request.POST, request.FILES, instance=page)\n\t\tif form.is_valid():\n\t\t\tpage = form.save(commit=False)\n\t\t\tpage.author = request.user\n\t\t\tpage.published_date = timezone.now()\n\t\t\tpage.save()\n\t\t\treturn redirect('page_detail', pk=page.pk)\n\telse:\n\t\tform = PageForm(instance=page)\n\treturn render(request, 'comic/page_edit.html', {'form':form})\n\n\ndef page_next(request,pk):\n\tpage = get_object_or_404(Page, pk=pk +1)\n\treturn redirect('page_detail', pk=page.pk +1)\n\n\n\n\ndef about(request):\n\treturn render(request, 'comic/about.html')\n\n\ndef updates(request):\n\treturn render(request, 'comic/updates.html')","sub_path":"comic/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"300255913","text":"n=input(\"Unesite broj elemenata:\")\n\ni=0\na=[]\nb=0\n\nwhile i 0:\n\t\t\tprint(x.CHROM, x.POS, x.num_called, x.call_rate, x.num_unknown, x.num_hom_ref, x.num_hom_alt, x.num_het, x.nucl_diversity)\n\t\telse:\n\t\t\tpass\n\nPour imprimer les genotypes de tout les echantillons pour tout les SNP, si le genotype n'est pas nul\n\tmyvcf=vcf.Reader(open(file,'r'))\n\tfor y in myvcf:\n\t\tfor sample in y.samples:\n\t\t\tif sample['GT'] <> None:\n\t\t\t\tpass\n\t\t\t\t#print(y.CHROM, y.POS, sample, sample['GT'])\n\t\t\telse:\n\t\t\t\tprint(y.CHROM, y.POS, sample, sample['GT'])\n\t\t\t\t#pass\n\n\n\n\trecord=myvcf.next()\n\tprint(record.POS)\n\tprint(record.num_called, record.call_rate, record.num_unknown)\n\tprint(record.num_hom_ref, record.num_het, record.num_hom_alt)\n\tprint(record.is_snp, record.is_indel, record.is_transition, record.is_deletion)\n\tprint(record.nucl_diversity, record.aaf, record.heterozygosity)\n\"\"\"\n\ndef readvcf(file):\n\t\"\"\"Pour obtenir les valeurs du champs FILTER dans le fichier vcf pour chaque variant\n\tImprime une liste des filtres: ['Q20', 'HapScore', 'badReads', 'QD']\"\"\"\n\tmyvcf=vcf.Reader(open(file,'r'))\n\tout=open(file+\"_table-2.txt\",\"w\")\n\tout.write(\"Contig\\tPosition\\tREF\\tALT\\tTC\\tTR\\tG-NR\\tG-NV\\tC-NR\\tC-NV\\tR-NR\\tR-NV\\n\")\n\tfor x in myvcf:\n\t\tliste=[]\n#\t\tprint(x.ALT[0])\n#\t\tliste.append(x.ALT[0])\n#\t\talt_al=str(x.ALT)\n\t\t\n\t\tprint(x.ALT, len(x.ALT))\n#\t\tprint(alt_al, alt_al.replace('[','').replace(']','')\n\t\tliste.append(x.CHROM),liste.append(str(x.POS)),liste.append(x.REF),liste.append(str(x.ALT)),liste.append(str(x.INFO['TC'])),liste.append(str(x.INFO['TR']))\n\t\tfor sample in x.samples:\n\t\t\tliste.append(str(sample['NR'])),liste.append(str(sample['NV']))\n\t\tout.write(\"%s\\n\"%('\\t'.join(liste)))\n#\tprint(liste)\n#\tfor x in liste:\n#\t\tprint(type(x))\n\tout.close()\n\n#,x.samples[0]\n\n#Pour obtenir les valeurs du champs INFO dans le fichier vcf pour chaque variant\n#Imprime une liste des filtres: ['Q20', 'HapScore', 'badReads', 'QD']\n#\tmyvcf=vcf.Reader(open(file,'r'))\n#\tfor x in myvcf:\n#\t\tprint(x.INFO['TC'])\n#x.INFO['FR']\n#x.INFO['TC']\n\n\ndef printfilter(file):\n\t\"\"\"Pour afficher les filtres qui ont ete actives lors du call des SNPs\n\tgv=good variant that passe filters; bv=bad variant that do not pass filters\"\"\"\n\tgv,bv=0,0\n\tmyvcf=vcf.Reader(open(file,'r'))\n\tfor x in myvcf:\n\t\tif len(x.FILTER) > 0:\n\t\t\tbv+=1\n\t\t\tprint(x.CHROM, x.POS)\n\t\t\tfor a in x.FILTER:\n\t\t\t\tif a in ['badReads','alleleBias','Q20','strandBias']:\n\t\t\t\t\tif a =='Q20':\n\t\t\t\t\t\tprint('\\t',a,x.QUAL)\n\t\t\t\t\telif a=='badReads':\n\t\t\t\t\t\tprint('\\t',a,x.INFO['MMLQ'])\n\t\t\t\t\telse:\n\t\t\t\t\t\tprint('\\t',a)\n\t\t\t\telse:\n\t\t\t\t\tprint('\\t',a, x.INFO[a])\n\t\telse:\n\t\t\tgv+=1\n\t\t\tpass\n\tprint(\"Good Variants: \", gv)\n\tprint(\"Bad Variants: \", bv)\n\tprint(\"Total number of variants: \",gv+bv)\n\ndef filter_quality(file):\n\t\"\"\"Section pour comprendre le calcul du QD Quality/Depth ratio\"\"\"\n\tmyvcf=vcf.Reader(open(file,'r'))\n\tfor x in myvcf:\n\t\tif len(x.FILTER) > 0:\n\t\t\tprint(x.CHROM, x.POS)\n\t\t\tprint('\\t','Qual/Depth: ',x.INFO['QD'],'QUALITY: ',x.QUAL)\n\t\t\tprint('\\t','Total number of reads containing this variant',x.INFO['TR'])\n\t\t\tprint('\\t','Total number of forward reads containing this variant',x.INFO['NF'])\n\t\t\tprint('\\t','Total forward strand coverage at this locus',x.INFO['TCF'])\n\t\t\tprint('\\t','Total number of reverse reads containing this variant',x.INFO['NR'])\n\t\t\tprint('\\t','Total coverage at this locus',x.INFO['TC'])\n\t\t\tfor a in x.FILTER:\n\t\t\t\tif a == 'Q20':\n\t\t\t\t\tprint('\\t',a,'QUALITY: ',x.QUAL)\n\t\t\t\telif a == 'QD':\n\t\t\t\t\tprint('\\t',a, x.INFO[a])\n\t\t\t\telse:\n\t\t\t\t\tpass\n\t\telse:\n\t\t\tpass\n\n\ndef scanfile(fg):\n\t\"\"\"\"\"\"\n\tout=open(\"Corresp_SNPs_vs_Genes.txt\",\"w\")\n\tout2=open(\"NO_Corresp_SNPs_vs_Genes.txt\",\"w\")\n#\tout.write(\"SNP-Affx\\tScaffold-SNP\\tSNP-Position\\tGENE\\tTRANSCRIPT\\tCHROM\\tSTART\\tSTOP\\tSTRAND\\tGeneName\\tInterpro\\tGO_Number\\tKO_Number\\tEC_Number Product\\n\")\n\tgene = open(fg,'r')\n\tline = gene.readline()\n\tline = gene.readline()\n\tchrom={}\n\twhile line:\n\t\tlist=line.split()\n\t\tstart=int(list[3])\n\t\tend=int(list[4])\n\t\t#On enregistre la position moyenne entre le debut et la\n\t\t#fin du gene\n\t\tmid=(end+start)/2\n\t\tchr=list[2].replace('-','_')\n\t\tgen=list[0]\n\t\tif chrom.has_key(chr)==False:\n\t\t\tchrom[chr]={}\n\t\t\tchrom[chr][mid]=[]\n\t\t\tchrom[chr][mid]=' '.join(list)\n\t\telse:\n\t\t\tchrom[chr][mid]=' '.join(list)\n\t\tline=gene.readline()\n\n\tsnp = open(fs,'r')\n\tline = snp.readline()\n\tline = snp.readline()\n\twhile line:\n\t\tsnplist=line.split()\n\t\tnomsnp=snplist[0]\n\t\tchr=snplist[1].replace('-','_')\n\t\tpossnp=int(snplist[2])\n\t\tif chrom.has_key(chr)==True:\n\t\t\trep=min(chrom[chr], key=lambda x:abs(x-possnp))\n\t\t\tout.write(\"%s %s %s %s\\n\"%(nomsnp,chr,str(possnp),chrom[chr][rep]))\n\t\telse:\n\t\t\tout2.write(\"%s %s %s %s\\n\"%(nomsnp,chr,str(possnp),\"No corespondance in genes file\"))\n\t\tline = snp.readline()\n\tsnp.close()\n\tout.close()\n\tout2.close()\n\ndef scangene2(fg,fs):\n\t\"\"\"\"\"\"\n\tout=open(\"SNPs_inside_Genes.txt\",\"w\")\n#\tout.write(\"SNP-Affx\\tScaffold-SNP\\tSNP-Position\\tGENE\\tTRANSCRIPT\\tCHROM\\tSTART\\tSTOP\\tSTRAND\\tGeneName\\tInterpro\\tGO_Number\\tKO_Number\\tEC_Number Product\\n\")\n\tgene = open(fg,'r')\n\tline = gene.readline()\n\tline = gene.readline()\n\tchrom={}\n\twhile line:\n\t\tlist=line.split()\n\t\tstart=int(list[3])\n\t\tend=int(list[4])\n\t\t#On enregistre la position moyenne entre le debut et la\n\t\t#fin du gene\n\t\tmid=(end+start)/2\n\t\tchr=list[2].replace('-','_')\n\t\tgen=list[0]\n\t\tif chrom.has_key(chr)==False:\n\t\t\tchrom[chr]={}\n\t\t\tchrom[chr][gen]=[]\n\t\t\tchrom[chr][gen].append(start)\n\t\t\tchrom[chr][gen].append(end)\n\t\telse:\n\t\t\tchrom[chr][gen]=[]\n\t\t\tchrom[chr][gen].append(start)\n\t\t\tchrom[chr][gen].append(end)\n\t\tline=gene.readline()\n\t#print(chrom)\n\n\tsnp = open(fs,'r')\n\tline = snp.readline()\n\tline = snp.readline()\n\twhile line:\n\t\tsnplist=line.split()\n\t\tnomsnp=snplist[0]\n\t\tchr=snplist[1].replace('-','_')\n\t\tpossnp=int(snplist[2])\n\t\tif chrom.has_key(chr)==True:\n\t\t\tfor x in chrom[chr]:\n\t\t\t\tif possnp > chrom[chr][x][0] and possnp < chrom[chr][x][1]:\n\t\t\t\t\tout.write(\"%s %s %s %s\\n\"%(nomsnp,possnp,chrom[chr][x],x))\n\t\t\t\telse:\n\t\t\t\t\tpass\n\t\t\t\n\t\t\t#rep=min(chrom[chr], key=lambda x:abs(x-possnp))\n\t\t\t#out.write(\"%s %s %s %s\\n\"%(nomsnp,chr,str(possnp),chrom[chr][rep]))\n\t\telse:\n\t\t\tpass\n\t\t\t#out.write(\"%s %s %s %s\\n\"%(nomsnp,chr,str(possnp),\"No corespondance in genes file\"))\n\t\tline = snp.readline()\n\tsnp.close()\n\tout.close()\n\ndef selectlines(fichier):\n\tvcf = open(fichier,'r')\n\tout = open(fichier+'_new','w')\n\tline = vcf.readline()\n\twhile line:\n\t\tliste=line.split()\n\t\tif '#' not in liste[0] and liste[0]=='10':\n\t\t\tout.write(line)\n\t\t\t\n\t\telse:\n\t\t\tpass\n\t\tline = vcf.readline()\n\tvcf.close()\n\tout.close()\n\t\n\ndef compare_vcf(file1,file2):\n\t\"\"\"Permet de trouver les SNPs en communs dans 2 fichiers vcf\"\"\"\n\t\n\tsnp1=[]\n\twith open(file1,'r') as f:\n\t\tfor line in f:\n\t\t\tif '#' not in line:\n\t\t\t\tsnp1.append(line.split()[0]+'_'+line.split()[1])\n\t\t\telse:\n\t\t\t\tpass\n\tsnp2=[]\n\twith open(file2,'r') as g:\n\t\tfor line in g:\n\t\t\tif '#' not in line:\n\t\t\t\tsnp2.append(line.split()[0]+'_'+line.split()[1])\n\t\t\telse:\n\t\t\t\tpass\n\t\n\tout=open('Intersection.txt','w')\n\tinter=set(snp1).intersection(snp2)\n\tfor i in inter:\n\t\tout.write(i+'\\n')\n\tout.close()\n\t\n\tprint(\"Il y a %s SNPs dans le fichier %s\"%(len(snp1),file1))\n\tprint(\"Il y a %s SNPs dans le fichier %s\"%(len(snp2),file2))\n\tprint(\"Il y a %s SNPs en commun entre les 2 fichiers\"%(len(inter)))\n\t\n\t\ndef compare_inter(file1,file2):\n\t\"\"\"Permet de trouver les SNPs en communs dans 2 fichiers intersection\"\"\"\n\t\n\tsnp1=[]\n\twith open(file1,'r') as f:\n\t\tfor line in f:\n\t\t\tif '#' not in line:\n\t\t\t\tsnp1.append(line.split()[0])\n\t\t\telse:\n\t\t\t\tpass\n\tsnp2=[]\n\twith open(file2,'r') as g:\n\t\tfor line in g:\n\t\t\tif '#' not in line:\n\t\t\t\tsnp2.append(line.split()[0])\n\t\t\telse:\n\t\t\t\tpass\n\t\n\tout=open('Intersection.txt','w')\n\tinter=set(snp1).intersection(snp2)\n\tfor i in inter:\n\t\tout.write(i+'\\n')\n\tout.close()\n\t\n\tprint(\"Il y a %s SNPs dans le fichier %s\"%(len(snp1),file1))\n\tprint(\"Il y a %s SNPs dans le fichier %s\"%(len(snp2),file2))\n\tprint(\"Il y a %s SNPs en commun entre les 2 fichiers\"%(len(inter)))\n\n\ndef addInfo2vcf(vcf,inter):\n\t\"\"\"Permet de pointer les SNPs communs dans le fichier vcf\"\"\"\n\tsnp=[]\n\twith open(inter,'r') as f:\n\t\tfor line in f:\n\t\t\tsnp.append(line.split()[0])\n\t\t\t\n\tout=open('new_vcf.txt','w')\n\twith open(vcf,'r') as g:\n\t\tfor line in g:\n\t\t\tif '#' not in line:\n\t\t\t\tsnp2=line.split()[0]+'-'+line.split()[1]\n\t\t\t\tif snp2 in snp:\n\t\t\t\t\tout.write('*'+line)\n\t\t\t\telse:\n\t\t\t\t\tout.write(line)\n\t\t\t\t\n\t\t\telse:\n\t\t\t\tout.write(line)\n\n\tout.close()\n\t\n\ndef selectSNP(vcf,inter):\n\t\"\"\"Permet de sortir les SNPs communs, dans le fichier inter, qui n'ont pas de voisins\n\ta moins de 50 nt\"\"\"\n\tlist_snp_select={}\n\tsnp_select={}\n\twith open(inter,'r') as f:\n\t\tfor line in f:\n\t\t\t\tsnp=line.split('_')[0]\n\t\t\t\tpos=int(line.split('_')[1])\n\t\t\t\tlist_snp_select[snp+'_'+str(pos)]=''\n\t\t\t\tif snp_select.has_key(snp)==False:\n\t\t\t\t\tsnp_select[snp]=[]\n\t\t\t\t\tsnp_select[snp].append(pos)\n\t\t\t\telse:\n\t\t\t\t\tsnp_select[snp].append(pos)\n\n#\tprint(list_snp_select)\n\tprint(len(list_snp_select))\n\tprint(len(snp_select))\n\n\tsnp_vcf={}\n\twith open(vcf,'r') as g:\n\t\tfor line in g:\n\t\t\tif '#' not in line:\n\t\t\t\tsnp=line.split()[0]\n\t\t\t\tpos=int(line.split()[1])\n\t\t\t\tclef=snp+'_'+str(pos)\n\t\t\t\tif snp_vcf.has_key(snp)==False:\n\t\t\t\t\tsnp_vcf[snp]=[]\n\t\t\t\t\tif clef not in list_snp_select:\n\t\t\t\t\t\tsnp_vcf[snp].append(pos)\n\t\t\t\t\telse:\n\t\t\t\t\t\tpass\n\t\t\t\telse:\n\t\t\t\t\tif clef not in list_snp_select:\n\t\t\t\t\t\tsnp_vcf[snp].append(pos)\n\t\t\t\t\telse:\n\t\t\t\t\t\tpass\t\t\t\t\n\t\t\telse:\n\t\t\t\tpass\n\t\t\n\tprint(len(snp_vcf))\n\n\tgood_snps=open('A5_good_snp_indels.txt','w')\n\tbad_snps=open('A5_bad_snp_indels.txt','w')\n\tfor x in snp_select:\n\t\tfor y in snp_select[x]:\n\t\t\ta=0\n\t\t\tfor z in snp_vcf[x]:\n\t\t\t\t#print(x,z,y)\n\t\t\t\tif z >= y-50 or z < y+51:\n\t\t\t\t\ta+=1\n\t\t\t\telse:\n\t\t\t\t\tpass\n\t\t\tif a > 0:\n\t\t\t\tbad_snps.write(x+'_'+str(y)+'\\n')\n\t\t\telse:\n\t\t\t\tgood_snps.write(x+'_'+str(y)+'\\n')\n\t\t\t\t\n\tgood_snps.close()\n\tbad_snps.close()\n\n\n\n\ndef filter_contigs_method1(file):\n\t\"\"\"Filtrer les contigs en fonction de leur couverture apres alignement avec bwa mem\n\t\n\tNecessite un fichier obtenu avec la commande: \n\tjava -jar /prg/picard-tools/1.119/BamIndexStats.jar INPUT=PoolR_S1_sort.bam > PoolR_S1_sort_BamIndexStats.txt\n\t\n\t\n\tcontig-5985000002 length= 239 Aligned= 58 Unaligned= 24\n\tcontig-4289000003 length= 290 Aligned= 52 Unaligned= 1\n\tcontig-21857000003 length= 149 Aligned= 47 Unaligned= 6\n\tcontig-15802000005 length= 173 Aligned= 23 Unaligned= 9\n\tcontig-29193000001 length= 127 Aligned= 34 Unaligned= 2\n\tcontig-18431000006 length= 163 Aligned= 55 Unaligned= 23\n\tcontig-29445000002 length= 126 Aligned= 47 Unaligned= 14\n\t\n\tNOTE: remplacer les espaces par des tab (\\t)\n\t\n\tchr1:0-100000\n\tchr2:1000-2000\n\tchrY:0-100\n\t\n\t\"\"\"\n\t\n\t\n\tout=open('regions_method1.txt','w')\n\ttotal_reads=0\n\tkeep_reads=0\n\twith open(file,'r') as f:\n\t\tfor line in f:\n\t\t\tif 'NoCoordinateCount' not in line:\n\t\t\t\tlys=line.replace(' ','\\t')\n\t\t\t\tcontig=lys.split('\\t')[0]\n\t\t\t\tlength=int(lys.split('\\t')[2])\n\t\t\t\taligned=int(lys.split('\\t')[4])\n\t\t\t\ttotal_reads+=aligned\n\t\t\t\tif aligned > 25 and aligned < 500:\n\t\t\t\t\tratio=float(length/aligned)\n\t\t\t\t\tif ratio > 2:\n\t\t\t\t\t\tkeep_reads+=aligned\n\t\t\t\t\t\tend=str(length-25)\n\t\t\t\t\t\tout.write(\"%s:1-%s\\n\"%(contig,length))\n\t\t\t\t\telse:\n\t\t\t\t\t\tpass\n\t\t\t\telse:\n\t\t\t\t\tpass\n\t\t\telse:\n\t\t\t\tpass\n\n\tout.close()\n\tprint(\"Nombre total de reads alignes: %s\"%(total_reads))\n\tprint(\"Nombre total de reads alignes conserves: %s\"%(keep_reads))\n\ndef selectSNPFromVCF(vcf):\n\t\"\"\"Permet de sortir les SNPs qui n'ont pas de voisins\n\ta moins de 50 nt\"\"\"\n\tlist_snp_select={}\n\tsnp_select={}\n\twith open(vcf,'r') as f:\n\t\tfor line in f:\n\t\t\tif '#' not in line:\n\t\t\t\tsnp=line.split()[0]\n\t\t\t\tpos=int(line.split()[1])\n\t\t\t\tlist_snp_select[snp+'_'+str(pos)]=''\n\t\t\t\tif snp_select.has_key(snp)==False:\n\t\t\t\t\tsnp_select[snp]=[]\n\t\t\t\t\tsnp_select[snp].append(pos)\n\t\t\t\telse:\n\t\t\t\t\tsnp_select[snp].append(pos)\n\t\t\telse:\n\t\t\t\tpass\n\n#\tprint(list_snp_select)\n#\tprint(len(list_snp_select))\n\t\"\"\"list_snp_select est un dictionnaire qui contient seulement les contigs:\n\t{'contig-26465000006_73': '', 'contig-8909000002_215': '', 'contig-2139000000_284': ''}\"\"\"\n\n#\tprint(snp_select)\n#\tprint(len(snp_select))\n\t\"\"\"'snp_select est un dictionnaire qui contient les positions des SNPs pour chaque contigs\n\tsnp_select={contig-653000001': [383], 'contig-21932000002': [95, 167, 211, 347, 380]}\"\"\"\n\n\n\tsnp_vcf={}\n\twith open(vcf,'r') as g:\n\t\tfor line in g:\n\t\t\tif '#' not in line:\n\t\t\t\tsnp=line.split()[0]\n\t\t\t\tpos=int(line.split()[1])\n\t\t\t\tclef=snp+'_'+str(pos)\n\t\t\t\tprint(snp,pos,clef)\n\t\t\t\tif snp_vcf.has_key(snp)==False:\n\t\t\t\t\tsnp_vcf[snp]=[]\n\t\t\t\t\tif clef not in list_snp_select:\n\t\t\t\t\t\tsnp_vcf[snp].append(pos)\n\t\t\t\t\telse:\n\t\t\t\t\t\tpass\n\t\t\t\telse:\n\t\t\t\t\tif clef not in list_snp_select:\n\t\t\t\t\t\tsnp_vcf[snp].append(pos)\n\t\t\t\t\telse:\n\t\t\t\t\t\tpass\t\t\t\t\n\t\t\telse:\n\t\t\t\tpass\n#\tprint(snp_vcf)\n#\tprint(len(snp_vcf))\n\n\n\tgood_snps=open('A5_good_snp_indels2.txt','w')\n\tbad_snps=open('A5_bad_snp_indels2.txt','w')\n\tfor x in snp_select:\n\t\tfor y in snp_select[x]:\n\t\t\ta=0\n\t\t\tfor z in snp_vcf[x]:\n\t\t\t\t#print(x,z,y)\n\t\t\t\tif z >= y-50 or z < y+51:\n\t\t\t\t\ta+=1\n\t\t\t\telse:\n\t\t\t\t\tpass\n\t\t\tif a > 0:\n\t\t\t\tbad_snps.write(x+'_'+str(y)+'\\n')\n\t\t\telse:\n\t\t\t\tgood_snps.write(x+'_'+str(y)+'\\n')\n\t\t\t\t\n\tgood_snps.close()\n\tbad_snps.close()\n\n\ndef makeVCFfromgoodSNP(vcf,goodsnp):\n\t\"\"\"Permet d'aller rechercher la ligne du fichier vcf\n\tpour les SNPs selectionnes.\n\tProduit un fichier au format vcf lisible par la fonction readvcf_plus\"\"\"\n\tsnp_good={}\n\twith open(goodsnp,'r') as f:\n\t\tfor line in f:\n\t\t\t\tsnp=line.split('_')[0]\n\t\t\t\tpos=int(line.split('_')[1])\n\t\t\t\tsnp_good[snp+'_'+str(pos)]=''\n\n\tout=open('VCF_goodSNP_noIndels.vcf','w')\n\twith open(vcf,'r') as g:\n\t\tfor line in g:\n\t\t\tif '#' not in line:\n\t\t\t\tsnp=line.split()[0]\n\t\t\t\tpos=int(line.split()[1])\n\t\t\t\tclef=snp+'_'+str(pos)\n\t\t\t\tif clef in snp_good:\n\t\t\t\t\tout.write(line)\n\t\t\t\telse:\n\t\t\t\t\tpass\n\t\t\telse:\n\t\t\t\tout.write(line)\n\tout.close()\n\t\n\t\ndef readvcf_plus(file):\n\t\"\"\"Pour filtrer les entrees lorsqu'il y a plusieurs alleles alternatifs\"\"\"\n\tmyvcf=vcf.Reader(open(file,'r'))\n\tout=open(file+\"_alt_al_single.txt\",\"w\")\n\tout2=open(file+\"_alt_al_multiple.txt\",\"w\")\n\tout.write(\"Contig\\tPosition\\tREF\\tALT\\tTC\\tTR\\tG-NR\\tG-NV\\tC-NR\\tC-NV\\tR-NR\\tR-NV\\n\")\n\tout2.write(\"Contig\\tPosition\\tREF\\tALT\\tTC\\tTR\\tG-NR\\tG-NV\\tC-NR\\tC-NV\\tR-NR\\tR-NV\\n\")\n\tfor x in myvcf:\n\t\tliste1=[]\n\t\tliste2=[]\n\n\t\t#On ne conserve que les alleles alternatifs uniques\n\t\tif len(x.ALT)==1 and len(x.REF)==1 and len(x.ALT[0])==1:\n\t\t\tALT=str(x.ALT).replace('[','').replace(']','')\n\t\t\tTR=str(x.INFO['TR']).replace('[','').replace(']','')\n\t\t#\tif int(TR) > 0 and int(str(x.INFO['TC'])) > 24:\n\t\t\tliste1.append(x.CHROM),liste1.append(str(x.POS)),liste1.append(x.REF),liste1.append(ALT),liste1.append(str(x.INFO['TC'])),liste1.append(TR)\n\t\t\tfor sample in x.samples:\n\t\t\t\tliste1.append(str(sample['NR'])),liste1.append(str(sample['NV']))\n\t\t\tout.write(\"%s\\n\"%('\\t'.join(liste1)))\n\t\t#\telse:\n\t\t#\t\tpass\n\t\telse:\n\t\t\t#print(x.ALT, x.ALT[0],x.ALT[1])\n\t\t\tALT=str(x.ALT).replace('[','').replace(']','')\n\t\t\tTR=str(x.INFO['TR']).replace('[','').replace(']','')\n\t\t\tliste2.append(x.CHROM),liste2.append(str(x.POS)),liste2.append(x.REF),liste2.append(ALT),liste2.append(str(x.INFO['TC'])),liste2.append(TR)\n\t\t\tfor sample in x.samples:\n\t\t\t\tliste2.append(str(sample['NR'])),liste2.append(str(sample['NV']))\n\t\t\tout2.write(\"%s\\n\"%('\\t'.join(liste2)))\n\t\t\t\n\tout.close()\n\tout2.close()\n\t\n\t\ndef selectSNP(tabSNPs):\n\tnom=os.path.splitext(os.path.basename(tabSNPs))\n\tname=nom[0]\n\text=nom[1]\n\tout=open(name+'_bestSNP.txt','w')\n\tout2=open(name+'_discardedVariants.txt','w')\n\twith open(tabSNPs,'r') as f:\n\t\theader=next(f)\n\t\tout.write(header)\n\t\tout2.write(header)\n\t\tfor line in f:\n\t\t\tif line.split()[3]=='SNP':\n\t\t\t\tout.write(line)\n\t\t\telse:\n\t\t\t\tout2.write(line)\n\t\t\t\t\n\tout.close()\n\tout2.close()\n\n##########################################\n\ndef filter_contigs_method2(file):\n\t\"\"\"Ce programme produit un fichier 'regions.txt' pour platypus.\n\tCe fichier indique à platypus quels contigs et quelles regions utiliser.\n\t\t\n\tPour sélectionner les contigs, le programme applique un filtre basé sur le ratio\n\t'(nb de reads * 300)/ longueur du contig'\n\t\n\tOn filtre les contigs en fonction de leur couverture apres alignement avec bwa mem\n\t\n\tLe fichier lu par ce programme est obtenu avec la commande suivante sur un fichier bam: \n\tjava -jar /prg/picard-tools/1.119/BamIndexStats.jar INPUT=PoolR_S1_sort.bam > PoolR_S1_sort_BamIndexStats.txt\n\t\n\tFormat du fichier BamIndexStats:\n\tcontig-5985000002 length= 239 Aligned= 58 Unaligned= 24\n\tcontig-4289000003 length= 290 Aligned= 52 Unaligned= 1\n\tcontig-21857000003 length= 149 Aligned= 47 Unaligned= 6\n\tcontig-15802000005 length= 173 Aligned= 23 Unaligned= 9\n\tcontig-29193000001 length= 127 Aligned= 34 Unaligned= 2\n\tcontig-18431000006 length= 163 Aligned= 55 Unaligned= 23\n\tcontig-29445000002 length= 126 Aligned= 47 Unaligned= 14\n\t\n\tNOTE: il faut remplacer les espaces par des tab (\\t)\n\t\n\t\n\tExemple du fichier regions.txt:\n\tchr1:0-100000\n\tchr2:1000-2000\n\tchrY:0-100\n\t\"\"\"\n\t\n\tout=open('regions_method2.txt','w')\n\ttotal_reads=0\n\tkeep_reads=0\n\twith open(file,'r') as f:\n\t\tfor line in f:\n\t\t\tif 'NoCoordinateCount' not in line:\n\t\t\t\tlys=line.replace(' ','\\t')\n\t\t\t\tcontig=lys.split('\\t')[0]\n\t\t\t\tlength=int(lys.split('\\t')[2])\n\t\t\t\taligned=int(lys.split('\\t')[4])\n\t\t\t\tratio=float((aligned*300)/length)\n\t\t\t\ttotal_reads+=aligned\n\t\t\t\tif 25 < ratio < 800:\n\t\t\t\t\tkeep_reads+=aligned\n\t\t\t\t\tend=str(length-25)\n\t\t\t\t\tout.write(\"%s:1-%s\\n\"%(contig,length))\n\t\t\t\telse:\n\t\t\t\t\tpass\n\t\t\telse:\n\t\t\t\tpass\n\tout.close()\n\tprint(\"Nombre total de reads alignes: %s\"%(total_reads))\n\tprint(\"Nombre total de reads alignes conserves: %s\"%(keep_reads))\n\n\ndef convert_vcf(results):\n\t\"\"\"Permet de convertir le fichier vcf en tableau texte.\n\tN'applique aucun filtre sur les entrees (eg, il y a plusieurs alleles alternatifs).\n\tSi c'est necessaire, utiliser la fonction readvcf_plus.\n\t\"\"\"\n\tmyvcf=vcf.Reader(open(results,'r'))\n\tnom=os.path.splitext(os.path.basename(results))\n\tname=nom[0]\n\text=nom[1]\n\tout=open(name+'_table.txt','w')\n\tout.write(\"Contig\\tPosition\\tREF\\tALT\\tQUAL\\tFILTER\\tTC\\tTR\\tG-NR\\tG-NV\\tC-NR\\tC-NV\\tR-NR\\tR-NV\\tSC\\n\")\n\tfor x in myvcf:\n\t\tliste1=[]\n#\t\tprint(x.ALT,x.ALT[0]\n#\t\tALT=str(x.ALT).replace('[','').replace(']','')\n\t\tALT=str(x.ALT[0])\n\t\tif isinstance(x.INFO['TR'],int):\n\t\t\tTR=str(x.INFO['TR'])\t\n\t\telse:\n\t\t\tTR=str(x.INFO['TR'][0])\n#\t\tTR=str(x.INFO['TR']).replace('[','').replace(']','')\n\t\tif len(x.FILTER)==0:\n\t\t\tfiltre='PASS'\n\t\telse:\n\t\t\tfiltre=','.join(x.FILTER)\n\t\tliste1.append(x.CHROM),liste1.append(str(x.POS)),liste1.append(x.REF),liste1.append(ALT),liste1.append(str(x.QUAL)),liste1.append(filtre),liste1.append(str(x.INFO['TC'])),liste1.append(TR)\n\t\tfor sample in x.samples:\n\t\t\tif isinstance(sample['NV'],int):\n\t\t\t\techNV=str(sample['NV'])\n\t\t\t\techNR=str(sample['NR'])\n\t\t\telse:\n\t\t\t\techNV=str(sample['NV'][0])\n\t\t\t\techNR=str(sample['NR'][0])\n\t\t\tliste1.append(echNR),liste1.append(echNV)\n\t\tliste1.append(x.INFO['SC'])\n\t\tout.write(\"%s\\n\"%('\\t'.join(liste1)))\n\t\t\t\n\tout.close()\n\n\ndef neighbor(tabSNPs):\n\t\"\"\"Ajoute le champs 'Neighbor' au fichier de variants avec l'information\n\t'*' au variant si le variant possède un voisin a moins de 100 nt en amont ou en aval\n\t\t\n\tContig Position REF ALT TC TR G-NR G-NV C-NR C-NV R-NR R-NV\n\tcontig_10 643 C G 771 48 53 0 366 3 352 45\n\tcontig_10 816 A C 811 254 59 18 392 129 360 107\n\tcontig_10 844 A G 805 264 63 18 382 131 360 115\n\tcontig_10 1113 C G 556 237 50 13 246 112 260 112\n\tcontig_10 1140 C T 562 279 49 19 257 130 256 130\n\tcontig_10 1255 G C 622 267 39 16 296 125 287 126\n\tcontig_10 1573 T G 365 140 34 15 174 60 157 65\n\tcontig_10 1698 G C 291 49 23 2 134 20 134 27\n\tcontig_10 2142 T C 225 85 18 0 106 49 101 36\n\tcontig_10 2613 T C 257 151 9 1 115 81 133 69\n\t\"\"\"\n\t\n\tnom=os.path.splitext(os.path.basename(tabSNPs))\n\tname=nom[0]\n\text=nom[1]\n\tout=open(name+'_neighbor.txt','w')\n\n\tSNP={}\n\tVCF={}\n\twith open(tabSNPs,'r') as f:\n\t\theader=next(f)\n\t\tlys=header.split()\n\t\tout.write('\\t'.join(lys[0:2])+'\\t'+'Neighbor\\t'+'\\t'.join(lys[2:])+'\\n')\n\t\tfor line in f:\n\t\t\tcontig=line.split()[0]\n\t\t\tpos=int(line.split()[1])\n\t\t\tsnp=contig+'-'+str(pos)\n\t\t\tVCF[snp]=line.split()[2:]\n\t\t\tif SNP.has_key(contig)==False:\n\t\t\t\tSNP[contig]=[]\n\t\t\t\tSNP[contig].append(pos)\n\t\t\telse:\n\t\t\t\tSNP[contig].append(pos)\n\n\tINFO={}\n\tfor x in SNP:\n\t\tSNP[x].sort()\n\t\tfor y in SNP[x]:\n\t\t\tif INFO.has_key(x+'-'+str(y))==False:\n\t\t\t\tINFO[x+'-'+str(y)]=''\n\t\t\telse:\n\t\t\t\tpass\n\t\t\tidx=SNP[x].index(y)+1\n\t\t\twhile idx < len(SNP[x]):\n\t\t\t\tif y-100 <= SNP[x][idx] < y+101:\n\t\t\t\t\tINFO[x+'-'+str(y)]='*'\n\t\t\t\t\tINFO[x+'-'+str(SNP[x][idx])]='*'\n\t\t\t\telse:\n\t\t\t\t\tpass\n\t\t\t\tidx+=1\n\t\t\t\n#\tprint(INFO\n\tlistkeys=INFO.keys()\n\tlistkeys.sort()\n\tfor a in listkeys:\n\t\tout.write(\"%s\\t%s\\t%s\\t%s\\n\"%(a.split('-')[0],a.split('-')[1],INFO[a],'\\t'.join(VCF[a])))\n\tout.close\n\n\ndef variantType(tabSNPs):\n\t\"\"\"Ajoute le champs 'type' au fichier de variants avec l'information\n\tSNP (Single Nucleotide Polymorphism) ou MNP (Multi Nucleotide Polymorphism)\n\tpour chaque variant\n\t\"\"\"\n\n\tnom=os.path.splitext(os.path.basename(tabSNPs))\n\tname=nom[0]\n\text=nom[1]\n\tout=open(name+'_type.txt','w')\n\twith open(tabSNPs,'r') as f:\n\t\theader=next(f)\n\t\tlys=header.split()\n\t\tout.write('\\t'.join(lys[0:3])+'\\t'+'Type\\t'+'\\t'.join(lys[3:])+'\\n')\n\t\tfor line in f:\n#\t\t\tprint(line.split(),len(line.split())\n\t\t\tif len(line.split())==15:\n\t\t\t\tnewlist=line.split()[0:2]\n\t\t\t\tnewlist.append('-')\n\t\t\t\tnewlist+=line.split()[2:]\n\t\t\telse:\n\t\t\t\tnewlist=line.split()\n\t\t\tref=newlist[3]\n\t\t\talt=newlist[4]\n#\t\t\tprint(newlist,len(newlist)\n\t\t\tif len(newlist)>16 or len(ref)>1 or len(alt)>1:\n\t\t\t\ttype='MNP'\n\t\t\telse:\n\t\t\t\ttype='SNP'\n\t\t\tinfo=newlist[0:3]\n\t\t\tinfo.append(type)\n\t\t\tinfo+=newlist[3:]\n\t\t\tout.write(\"%s\\n\"%('\\t'.join(info)))\n\t\t\ndef extract_seq_from_contigs(tabSNPs,fichierseq):\n\t\"\"\"Pour extraire les sequences entourant les SNPs avec seqret\n\tet indiquer les SNPs dégénérés\n\t\n\tCete fonction prend beacoup de temps, plusieurs heures pour traiter un fichier vcf de 140K variants\n\t\n\t\"\"\"\n\tnom=os.path.splitext(os.path.basename(tabSNPs))\n\tname=nom[0]\n\text=nom[1]\n\t\n\tprint(\"Etape 1: Construction du dictionnaire\")\n\t\n\tdict={}\n\t\"\"\"Dans cette premiere etape, on entre les clefs primaire, contig+'-'+str(pos),\n\tet leur valeur, un dictionnaire. Ces clefs primaires, ce sont tous les variants\n\tcontenus dans le fichier tabSNPs. Les valeurs de ces clefs seront les variants voisins\n\tde ces variants principaux à moins de 101 nt de distance: \n\t\n\tdict={'contig_10-4494': {}, 'contig_10-8293': {}, 'contig_10000-103': {}, \n\t'contig_10-3200': {}, 'contig_10-675': {}, 'contig_10000-802': {},\n\t'contig_10004-831': {}, 'contig_10-3726': {}, 'contig_1000-1622': {},\n\t 'contig_10000-362': {}, 'contig_10-816': {}}\n\t\"\"\"\n\twith open(tabSNPs,'r') as f:\n\t\theader=next(f)\n\t\tfor line in f:\n\t\t\tcontig=line.split()[0]\n\t\t\tpos=int(line.split()[1])\n\t\t\tneiggbor=line.split()[2]\n\t\t\ttype=line.split()[3]\n\t\t\tref=line.split()[4]\n\t\t\talt=line.split()[5]\n\t\t\t#if len(ref)==1:\n\t\t\tdict[contig+'-'+str(pos)]={}\n\tf.close()\n\t\n\tprint(\"\\tIl y a %s valeurs dans le dictionnaire\"%(len(dict)))\n\t\n\t\"\"\"Dans cette deuxieme etape, on remplit le dictionnaire dict avec les valeurs des voisins:\t\n\t\n\tdict={'contig_10-4494': {\n\t 'contig_10-4494': [4494, '[ATT/GTC]', 0],\n\t 'contig_10-4510': [4510, '[G/A]', 16],\n\t 'contig_10-4453': [4453, '[A/C]', -41],\n\t 'contig_10-4579': [4579, '[G/A]', 85]\n\t },\n\t \n\t 'contig_10-8293': {'contig_10-8293': [8293, '[T/A]', 0]},\n\t 'contig_10000-103': {'contig_10000-103': [103, '[A/C]', 0]},\n\t 'contig_10-3200': {'contig_10-3200': [3200, '[T/C]', 0], 'contig_10-3213': [3213, '[A/T]', 13],\n\t 'contig_10-3230': [3230, '[CTTGTTTGCT/TTTGTTTGCC]', 30], 'contig_10-3179': [3179, '[T/C]', -21]},\n\t 'contig_10-675': {'contig_10-643': [643, '[C/G]', -32], 'contig_10-675': [675, '[CTGG/C]', 0]},\n\t 'contig_10000-802': {'contig_10000-802': [802, '[A/G]', 0]}}\n\t\n\tDescription DoncDans chacun des dictionnaires, on retrouve:\n\tPremière sous-valeur: \n\t\n\t\n\tIUPAC codes\n\tG/A\tR\n\tT/C\tY\n\tG/T\tK\n\tA/C\tM\n\tG/C\tS\n\tA/T\tW\n\t\n\t\"\"\"\n\tprint(\"Etape 2: Ajout des valeurs des voisins dans le dictionnaire\")\n\n\tiupac={'G/A':'R','A/G':'R','T/C':'Y','C/T':'Y','G/T':'K','T/G':'K','A/C':'M','C/A':'M','G/C':'S','C/G':'S','A/T':'W','T/A':'W'}\n\n\n\twith open(tabSNPs,'r') as f:\n\t\theader=next(f)\n\t\tfor line in f:\n\t\t\tcontig=line.split()[0]\n\t\t\tpos=int(line.split()[1])\n\t\t\tneiggbor=line.split()[2]\n\t\t\ttype=line.split()[3]\n\t\t\tref=line.split()[4]\n\t\t\talt=line.split()[5]\n\t\t\tfor i in dict:\n\t\t\t\tif contig==i.split('-')[0] and abs(pos-int(i.split('-')[1]))<=100:\n\t\t\t\t\tif len(alt)>1 or len(ref)>1:\n\t\t\t\t\t\tif pos == int(i.split('-')[1]):\n\t\t\t\t\t\t\tdict[i][contig+'-'+str(pos)]=[]\n\t\t\t\t\t\t\tdict[i][contig+'-'+str(pos)].append(pos)\n\t\t\t\t\t\t\tdict[i][contig+'-'+str(pos)].append(\"[MNPcentral]\")\n\t\t\t\t\t\t\tdict[i][contig+'-'+str(pos)].append(pos-int(i.split('-')[1]))\n\t\t\t\t\t\telif pos != int(i.split('-')[1]):\n\t\t\t\t\t\t\tdict[i][contig+'-'+str(pos)]=[]\n\t\t\t\t\t\t\tdict[i][contig+'-'+str(pos)].append(pos)\n\t\t\t\t\t\t\tdict[i][contig+'-'+str(pos)].append(\"[MNP]\")\n\t\t\t\t\t\t\tdict[i][contig+'-'+str(pos)].append(pos-int(i.split('-')[1]))\n\t\t\t\t\t\t\n\t\t\t\t\telse:\n\t\t\t\t\t\tif pos == int(i.split('-')[1]):\n\t\t\t\t\t\t\tdict[i][contig+'-'+str(pos)]=[]\n\t\t\t\t\t\t\tdict[i][contig+'-'+str(pos)].append(pos)\n\t\t\t\t\t\t\tdict[i][contig+'-'+str(pos)].append(\"[%s/%s]\"%(ref,alt))\n\t\t\t\t\t\t\tdict[i][contig+'-'+str(pos)].append(pos-int(i.split('-')[1]))\n\t\t\t\t\t\telif pos != int(i.split('-')[1]):\n\t\t\t\t\t\t\tdict[i][contig+'-'+str(pos)]=[]\n\t\t\t\t\t\t\tdict[i][contig+'-'+str(pos)].append(pos)\n\t\t\t\t\t\t\tdict[i][contig+'-'+str(pos)].append(iupac[\"%s/%s\"%(ref,alt)])\n\t\t\t\t\t\t\tdict[i][contig+'-'+str(pos)].append(pos-int(i.split('-')[1]))\n\t\t\t\telse:\n\t\t\t\t\tpass\n\n\tout=open(\"Liste_SNPs_neighbor_IUPAC.txt\",\"w\")\n\trecords=SeqIO.to_dict(SeqIO.parse(fichierseq,\"fasta\"))\n\t\n\t#out.write(str(dict)+'\\n')\n\t\n\tprint(\"Etape 3: Traitement des valeurs\")\n\n\tfor x in dict:\n\t\tnom=x.split('-')[0]\n\t\tsnp=int(dict[x][x][0])\n\t\tstart=snp-101\n\t\tend=snp+100\n\t\tallseq=records[nom].seq\n\n\t\t#out.write(\"\\n%s\\t%s\\t%s\\t%s\\t%s\\n\"%(nom,start,snp,end,len(allseq)))\n\n\t\tif 0 > start:\n\t\t\tstart=0\n\t\t\t#out.write(\"start negatif\")\n\t\t\t#out.write(\"%s\\t%s\\t%s\\t%s\\t%s\\n\"%(nom,start,snp,end,len(allseq)))\n\t\t\n\t\tif end > len(allseq):\n\t\t\tend=len(allseq)\n\t\t\t#out.write(\"end plus grand que la sequence\")\n\t\t\t#out.write(\"%s\\t%s\\t%s\\t%s\\t%s\\n\"%(nom,start,snp,end,len(allseq)))\n\n\t\t#La sequence est produite sous forme de liste\n\t\tseq1=list(records[nom].seq[start:end])\n\t\t#print(seq1,str(len(seq1)))\n\t\t#out.write(''.join(seq1)+'\\n')\n\n#\t\tout.write(str(len(seq1))+'\\n')\n#\t\tout.write(\"%s\\t%s\\t%s\\n\"%(seq1[99],seq1[100],seq1[101]))\n\n\t\tdic={}\n\t\tfor y in dict[x]:\n\t\t\t#out.write(\"%s\\t%s\\t%s\\n\"%(dict[x][y][0],dict[x][y][2],dict[x][y][1]))\n\t\t\tif start==0:\n\t\t\t\tdic[dict[x][y][0]-1]=dict[x][y][1]\n\t\t\telse:\n\t\t\t\tdic[dict[x][y][2]+100]=dict[x][y][1]\n\t\t\n\t\t#out.write(str(dic)+'\\n')\n\t\tdic_clef=list(dic.keys())\n\t\tdic_clef.sort(reverse=True)\n#\t\tprint(dic_clef)\n\t\t\n#\t\tprint(\"Etape 1: Modification de la sequence\")\n\t\tfor i in dic_clef:\n\t\t\t#print(dic_clef)\n\t\t\t#print(x)\n\t\t\t#print(i)\n\t\t\tseq1[i]=dic[i]\n\n\t\tout.write(x+'\\t'+''.join(seq1)+'\\n')\t\n\t\t\t\n\tout.close()\n\ndef mix_files(filevcf,table_clusters_contigs,fileseq):\n\t\"\"\"Permet de produire un fichier final en fusionnant l'information des frequences de reads,\n\tdes sequences et des noms des clusters GCAT\n\t\"\"\"\n\n\tcontigs={}\n\twith open(table_clusters_contigs,'r') as o:\n\t\tfor line in o:\n\t\t\tlis = line.split()\n\t\t\tlist_contigs=lis[1:]\n\t\t\tcluster=lis[0]\n\t\t\tfor x in list_contigs:\n\t\t\t\tcontigs[x]=cluster\n\tsequences={}\n\twith open(fileseq,'r') as s:\n\t\tfor line in s:\n\t\t\tsequences[line.split()[0]]=line.split()[1]\n\n\tout = open('Liste_variants_A5_platypus-IUPAC.txt','w')\n\n\twith open(filevcf,'r') as f:\n\t\theader=next(f)\n\t\tout.write('GCAT_cluster\\t'+header.replace('\\n','')+'\\t'+'Sequence\\n')\n\t\tfor line in f:\n\t\t\tcontig=line.split()[0]\n\t\t\tclef=line.split()[0]+'-'+str(line.split()[1])\n\t\t\tout.write(\"%s\\t%s\\t%s\\n\"%(contigs[contig],line.replace('\\n',''),sequences[clef]))\n\tout.close()\n\n\n\n\nif __name__ == '__main__':\n\t#en sys.argv[1] le nom du fichier des positions de genes\n\t#en sys.argv[2] le nom du fichier des SNPs\n#\tcompare_vcf(sys.argv[1],sys.argv[2])\n#\tcompare_inter(sys.argv[1],sys.argv[2])\n#\taddInfo2vcf(sys.argv[1],sys.argv[2])\n#\tselectSNP(sys.argv[1],sys.argv[2])\n#\tprintfilter(sys.argv[1])\n#\tselectlines(sys.argv[1])\n#\tscangene(sys.argv[1],sys.argv[2])\n#\tselectSNPFromVCF(sys.argv[1])\n#\tmakeVCFfromgoodSNP(sys.argv[1],sys.argv[2])\n#\treadvcf_plus(sys.argv[1])\n#\tselectSNP(sys.argv[1])\n\n#\tNEW_extract_seq_from_contigs('short_table.txt','SelectedContigsA503.fasta')\n#\tNEW_extract_seq_from_contigs('A5_mem_k33_regions_method2_qd10_def-ab_platypus_table_neighbor_type.txt','SelectedContigsA503.fasta')\n#\tNEW_extract_seq_from_contigs('Partiel_table_neighbor_type.txt','SelectedContigsA503.fasta')\n\n\n#\tfilter_contigs_method2(sys.argv[1])\n#\tconvert_vcf(sys.argv[1])\n#\tneighbor(sys.argv[1])\n#\tvariantType(sys.argv[1])\n#\textract_seq_from_contigs('short_table.txt','SelectedContigsA503.fasta')\n\tmix_files(sys.argv[1],sys.argv[2],sys.argv[3])","sub_path":"scan_vcf.py","file_name":"scan_vcf.py","file_ext":"py","file_size_in_byte":30673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"95451063","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Dec 10 09:35:35 2018\r\n\r\n@authors: MrWormsy (AKA Antonin ROSA-MARTIN), Loick Combrie, Lucile Delage and David Petit\r\n\"\"\"\r\n\r\n#demande de sauvegarde de partie \r\n#fen recalcule le fen \r\n\r\nimport chess\r\nfrom MinMax import MinMax\r\nimport chess.svg\r\n\r\nimport Evaluation_FEN\r\nfrom savgame import SaveGame\r\n\r\nfrom IPython.display import SVG, display\r\n\r\nclass ModeJoueurContreOrdinateur:\r\n \r\n def __init__(self):\r\n self.player = input(\"Nom du joueur : \")\r\n self.nameAI = \"AI\"\r\n self.turnId = 0\r\n \r\n self.board = chess.Board()\r\n \r\n self.gam = SaveGame(self.board)\r\n self.gam.headers([\"test\",None,None,None,None,None,None])\r\n print(\"Affichage PGN :\")\r\n self.listCoups = [] \r\n \r\n def commencerPartie(self):\r\n \r\n lastMove = None\r\n \r\n while(self.partieEstFinie()):\r\n \r\n self.notificationTourJoueur()\r\n \r\n #Si l'action est possible alors on la réalise\r\n move = self.getAction()\r\n self.board.push(move)\r\n \r\n #On print le plateau et c'est au joueur suivant de jouer si il n'est pas en echec et mat\r\n if(lastMove == None):\r\n display(SVG(chess.svg.board(board=self.board, lastmove = move)))\r\n else:\r\n display(SVG(chess.svg.board(board=self.board, lastmove = lastMove)))\r\n \r\n #On incremente l'id\r\n self.turnId += 1\r\n \r\n self.listCoups.append(move)\r\n \r\n lastMove = move\r\n \r\n self.finDePartie()\r\n \r\n def notificationTourJoueur(self):\r\n #Un joueur choisi une action (on annonce le tour du joueur, si id%2 == 0 alors blanc donc joueur sinon noir)\r\n if(self.turnId%2 == 0):\r\n print(\"C'est au tour de\", self.player)\r\n else:\r\n print(\"C'est au tour de\", self.nameAI)\r\n \r\n print(Evaluation_FEN.evaluation(self.board.fen()))\r\n \r\n def getAction(self):\r\n bestMove = \"\"\r\n with chess.polyglot.open_reader(\"bookfish.bin\") as reader:\r\n for entry in reader.find_all(self.board):\r\n bestMove = entry.move().__str__()\r\n break\r\n \r\n #If the try succeed we can use bookfish, else we use min max with aplha beta\r\n try:\r\n move = chess.Move.from_uci(bestMove)\r\n method = \"(Move by Bookfish)\"\r\n \r\n except: \r\n move = MinMax.minimaxRoot(3,self.board,True)\r\n method = \"(Move by Min Max and Alpha Beta pruning\"\r\n \r\n #Player\r\n if(self.turnId%2 == 0):\r\n action = input(\"Donner une action à réaliser (ex:\" + str(move) + \") : \")\r\n while(self.moveEstLegal(action) == False):\r\n print(\"L'action n'est pas autorisée, veuillez recommencer\")\r\n action = input(\"Donner une action à réaliser (ex:\" + str(move) + \") : \")\r\n return chess.Move.from_uci(action)\r\n else: \r\n print(self.nameAI + \" a joue \" + str(move), method)\r\n return move\r\n \r\n def moveEstLegal(self, action):\r\n try:\r\n tempMove = chess.Move.from_uci(action)\r\n except:\r\n return False\r\n \r\n if (tempMove in self.board.legal_moves):\r\n return True\r\n else: return False\r\n \r\n \r\n def partieEstFinie(self):\r\n return not self.board.is_game_over()\r\n \r\n def finDePartie(self):\r\n self.gam.save_game(self.listCoups)\r\n \r\n if (self.turnId%2 == 0):\r\n print(self.player, \" a gagné\")\r\n else:\r\n print(self.nameAI, \" a gagné\")","sub_path":"ModeJoueurContreOrdinateur.py","file_name":"ModeJoueurContreOrdinateur.py","file_ext":"py","file_size_in_byte":3800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"571547524","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport pyodbc as db\nimport xlrd\nfrom PIL import Image\nfrom matplotlib.patches import Patch\nimport datetime as dd\n\nfrom datetime import datetime\nimport os\n\nimport pyodbc as db\n\n\nconnection = db.connect('DRIVER={SQL Server};'\n 'SERVER=;' # Provide server\n 'DATABASE=;' # provide database \n 'UID=;PWD=') # provide username and password\ncursor = connection.cursor()\ndirpath = os.path.dirname(os.path.realpath(__file__))\n\nsupport_df = pd.read_sql_query(\"\"\"Select sum(CAST((DATEDIFF(minute, start_time, end_time)) as decimal(5, 2))/60) as 'Support Working Hour'\n from tasks\nwhere YEAR(task_date) =YEAR(CONVERT(varchar(10), getdate()-1,126))\nand taskcategory_name='Support & Maintenance'\"\"\", connection)\n\ndevelopment_df = pd.read_sql_query(\"\"\"Select sum(CAST((DATEDIFF(minute, start_time, end_time)) as decimal(5, 2))/60) as 'Development Working Hour'\n from tasks\nwhere YEAR(task_date) =YEAR(CONVERT(varchar(10), getdate()-1,126))\nand taskcategory_name='Research & Development'\"\"\", connection)\n\n\n\n# Pie chart, where the slices will be ordered and plotted counter-clockwise:\nsupport = int(support_df['Support Working Hour'])\ndevelopment = int(development_df['Development Working Hour'])\n\ndata = [support, development]\n#print(data)\nlegend_element = [Patch(facecolor='#EC6B56', label='Support & \\nMaintenance'),\n Patch(facecolor='#FFC154', label='Research & \\nDevelopment')]\n\n\ncolors = ['#EC6B56', '#FFC154']\n\n\nDataLabel=['Support \\n & \\n Maintenance','Research \\n & \\n Development']\nexplode=(0.05,0)\n\nfig, ax = plt.subplots()\nwedges, labels, autopct = ax.pie(data, explode=explode, colors=colors, autopct='%.1f%%', startangle=90, pctdistance=.5)\nplt.setp(autopct, fontsize=12, color='black', fontweight='bold')\n\n\nplt.text(0, 1.28, '7. YTD Working Area Wise Percentage', ha='center',color='#3238a8', fontsize=14, fontweight='bold')\nax.axis('equal')\nplt.legend(handles=legend_element, loc='upper right', fontsize=9)\n\nplt.tight_layout()\nplt.savefig('YTD_SupportvsDevelopment.png')\n#plt.show()\nplt.close()\nprint('7. YTD Working Area Wise Percentage generated')","sub_path":"YTD_support_and_development.py","file_name":"YTD_support_and_development.py","file_ext":"py","file_size_in_byte":2262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"439914481","text":"\"\"\"\r\nCode by Amy Worth\r\nA-level midterm project library\r\n\"\"\"\r\nimport re\r\n\r\nbooleanOperators = ['==','!=', '<=', '>=', '<', '>']\r\ndataTypes = ['int', 'boolean', 'String', 'Scanner', 'Person', 'void']\r\noperators = ['+', '-', '*']\r\nbooleans = ['true', 'false']\r\nprotections = ['public', 'private', 'protected']\r\n\r\n#------------------------------------------------------------------------------\r\n\r\ndef Clean(data):\r\n '''returns clean data string without newlines, tabs, comments'''\r\n newData = []\r\n for line in data:\r\n newLine = re.sub(r'^\\s*', '', line)\r\n newLine = re.sub(r'\\n', 'new_line', newLine)\r\n comment = re.search(r'^\\/\\/', newLine)\r\n if not comment:\r\n newData.append(newLine)\r\n newData = RemoveBlockComments(''.join(newData))\r\n return newData\r\n\r\ndef RemoveBlockComments(data):\r\n '''used by clean() to remove block comments'''\r\n data = re.sub(r'\\/\\*.*?\\*\\/new_line', '', data)\r\n return data\r\n\r\n#------------------------------------------------------------------------------\r\n\r\ndef CheckSemicolons(data):\r\n '''checks for duplicate semi-colons'''\r\n if re.match(r'.*;;.*', data):\r\n raise Exception('There are duplicate semicolons in your code.')\r\n return data\r\n\r\ndef CheckOpenBraces(data):\r\n '''checks for duplicate open braces'''\r\n if re.match(r'.*\\{\\{.*', data):\r\n raise Exception('There are duplicate opening braces in your code.')\r\n\r\ndef CheckBracesCount(data):\r\n '''checks for missing braces'''\r\n openBraces = re.findall(r'\\{', data)\r\n closeBraces = re.findall(r'\\}', data)\r\n if len(openBraces) != len(closeBraces):\r\n raise Exception('You are missing a brace in your code.')\r\n \r\ndef CheckParenthesesCount(data):\r\n '''checks for missing parentheses'''\r\n openParentheses = re.findall(r'\\(', data)\r\n closeParentheses = re.findall(r'\\)', data)\r\n if len(openParentheses) != len(closeParentheses):\r\n raise Exception('You are missing a parenthesis in your code.')\r\n \r\ndef CheckBracketsCount(data):\r\n '''checks for missing brackets'''\r\n openBrackets = re.findall(r'\\[', data)\r\n closeBrackets = re.findall(r'\\]', data)\r\n if len(openBrackets) != len(closeBrackets):\r\n raise Exception('You are missing a bracket in your code.')\r\n\r\n#------------------------------------------------------------------------------\r\n \r\ndef RemoveImports(data):\r\n '''removes properly formatted imports'''\r\n data = re.sub(r'(?<=new_line)import\\s+\\S+\\s*?;new_line|^import\\s+\\S+\\s*?;new_line', '', data)\r\n return data\r\n\r\ndef RemoveDeclarations(data):\r\n '''removes properly formatted declarations (e.g. int age;)'''\r\n declarations = re.findall(r'(?<=new_line)\\w+\\s\\w+;new_line', data)\r\n for line in declarations:\r\n words = line.split()\r\n if words[0] not in dataTypes:\r\n raise Exception('Datatype doesn''t exist: '+ line)\r\n if not words[1][0].isalpha():\r\n raise Exception('Incorrect variable name: '+ line)\r\n data = re.sub(r'(?<=new_line)\\w+\\s+\\w+\\s*;new_line','' , data)\r\n return data\r\n\r\ndef RemovePrintStatements(data):\r\n '''removes properly formatted print statements (e.g. int age;)'''\r\n prints = re.findall(r'(?<=new_line)System.out.println\\s*\\(.*?\\);new_line', data)\r\n for line in prints:\r\n formatQuotes = re.sub(r'\\\"(.*?)\\\"','\"' ,line)\r\n formatVariables = re.sub(r'[a-zA-Z]\\w*', 'k', formatQuotes)\r\n removeWhite = re.sub(r'\\s', '', formatVariables)\r\n inside = re.findall(r'(?<=\\()(.*)(?=\\))', removeWhite)\r\n splitInside = re.split(r'\\+', inside[0])\r\n for value in splitInside:\r\n if len(value) != 1:\r\n raise Exception('Print statement incorrect: '+ line)\r\n data = re.sub(r'(?<=new_line)System.out.println\\s*\\(.*?\\)\\s*;new_line','' , data)\r\n return data\r\n\r\ndef RemoveAssignmentStatements(data):\r\n '''removes properly formatted assignment statements (checks all types)'''\r\n statements = re.findall(r'(?<=new_line)\\w+\\s=.*?;new_line|(?<=new_line)\\w+\\s\\w+\\s=.*?;new_line', data)\r\n for line in statements:\r\n dataType = CheckLeftHandSide(re.findall(r'.*(?==)', line))\r\n CheckRightHandSide(re.findall(r'(?<== ).*', line), dataType)\r\n data = re.sub(r'(?<=new_line)\\w+\\s+=.*?;new_line|(?<=new_line)\\w+\\s+\\w+\\s+=.*?;new_line','' , data)\r\n return data\r\n\r\ndef CheckLeftHandSide(data):\r\n '''checks for properly formatted lhs then passes dataType back'''\r\n words = re.split(r'\\s', data[0])\r\n words = FixSpacing(words)\r\n if len(words) == 2:\r\n if words[0] not in dataTypes:\r\n cleanWords = re.sub(r'new_line', '', words[0])\r\n raise Exception('Not a recognized dataType: '+ cleanWords)\r\n if not words[1][0].isalpha():\r\n raise Exception('Incorrect variable name: '+ words[1])\r\n return words[0]\r\n elif len(words) == 1:\r\n if not words[0][0].isalpha():\r\n raise Exception('Incorrect variable name: '+ words[0])\r\n return 'none'\r\n else:\r\n raise Exception('Incorrect statement on the left of an equals sign: '+ data[0])\r\n\r\ndef CheckRightHandSide(data, dataType):\r\n '''checks for properly formatted rhs'''\r\n if dataType == 'Person':\r\n if not re.match(r'new Person\\(\\w*\\,\\s\\w*\\);new_line', data[0]):\r\n raise Exception('Incorrect Person object declaration.')\r\n \r\n elif dataType == 'Scanner':\r\n if data[0] != 'new Scanner(System.in);new_line':\r\n raise Exception('Incorrect Scanner declaration.')\r\n \r\n elif dataType == 'String' and re.match(r'.*\".*', data[0]):\r\n cutData = re.sub(r';new_line', '', data[0])\r\n formatQuotes = re.sub(r'\\\"(.*?)\\\"','\"' ,cutData)\r\n formatVariables = re.sub(r'[a-zA-Z]\\w*', 'k', formatQuotes)\r\n removeWhite = re.sub(r'\\s', '', formatVariables) \r\n splitInside = re.split(r'\\+', removeWhite)\r\n for value in splitInside:\r\n if len(value) != 1:\r\n raise Exception('String statement incorrect: '+ data[0]) \r\n else:\r\n cutData = re.sub(r';new_line', '', data[0])\r\n splitData = re.split(r'\\s', cutData) \r\n if len(splitData) == 1:\r\n if not splitData[0][0].isalpha() and re.match(r'[a-zA-Z]', splitData[0]):\r\n raise Exception('Incorrect variable name: '+ splitData[0])\r\n elif len(splitData) == 3:\r\n if not splitData[0][0].isalpha() and re.match(r'[a-zA-Z]', splitData[0]): \r\n raise Exception('Incorrect variable name: '+ splitData[0]) \r\n if not splitData[2][0].isalpha() and re.match(r'[a-zA-Z]', splitData[2]): \r\n raise Exception('Incorrect variable name: '+ splitData[2]) \r\n if splitData[1] not in operators:\r\n raise Exception('Not a recognized operator: '+ splitData[1])\r\n \r\n else:\r\n raise Exception('Incorrect statement on the right of an equals sign: '+ cutData)\r\n\r\ndef RemoveIfElse(data):\r\n '''removes properly formatted if and else statements (not including else's that don't follow an if)'''\r\n ifelses = re.findall(r'(if\\s*\\(.*?\\)\\s*{.*?}new_line)(else\\s*{.*?}){0,1}', data)\r\n flatten = []\r\n \r\n for sublist in ifelses:\r\n for item in sublist:\r\n flatten.append(item)\r\n \r\n for each in flatten:\r\n cleanLine = re.sub(r'new_line', '', each)\r\n if not re.match(r'.*{\\s*}.*', cleanLine): \r\n raise Exception('Error in the if / else: '+ cleanLine)\r\n if re.match(r'(?<=\\().*(?=\\))', cleanLine):\r\n inside = re.findall(r'(?<=\\().*(?=\\))', cleanLine)\r\n CheckBoolean(inside[0])\r\n \r\n data = re.sub(r'(if\\s*\\(.*?\\)\\s*{.*?}new_line)(else\\s*{.*?}new_line){0,1}', '', data)\r\n return data\r\n\r\ndef CheckBoolean(data):\r\n '''checks for correct form of possible boolean statements'''\r\n splitData = re.split(r'\\s', data)\r\n splitData = FixSpacing(splitData)\r\n \r\n if len(splitData) == 1:\r\n if not splitData[0][0].isalpha() and re.match(r'[a-zA-Z]', splitData[0]):\r\n raise Exception('Incorrect variable name in boolean ( '+ data)\r\n elif len(splitData) == 3:\r\n if not splitData[0][0].isalpha() and re.match(r'[a-zA-Z]', splitData[0]): \r\n raise Exception('Incorrect variable name in boolean ( '+ data) \r\n if not splitData[2][0].isalpha() and re.match(r'[a-zA-Z]', splitData[2]): \r\n raise Exception('Incorrect variable name in boolean ( '+ data) \r\n if splitData[1] not in booleanOperators:\r\n raise Exception('Not a recognized boolean operator: '+ data)\r\n else:\r\n raise Exception('Incorrect statement in boolean ( '+ data)\r\n\r\ndef RemoveWhile(data):\r\n '''removes properly formatted while loops'''\r\n whiles = re.findall(r'while\\s*\\(.*?\\)\\s*{.*?}', data)\r\n \r\n for element in whiles:\r\n cleanwhile = re.sub(r'new_line', '', element)\r\n if not re.match(r'.*{\\s*}.*', cleanwhile):\r\n raise Exception('Error within the while statement braces: '+ cleanwhile)\r\n inside = re.findall(r'(?<=\\().*(?=\\))', cleanwhile)\r\n CheckBoolean(inside[0])\r\n \r\n data = re.sub(r'while\\s*\\(.*?\\)\\s*{.*?}', '', data)\r\n return data\r\n\r\ndef RemoveConstructor(data):\r\n '''removes properly formated constructors'''\r\n constructors = re.findall(r'(?<=new_line)\\w+\\s+\\w+\\(.*?\\)\\s*{.*?}', data)\r\n \r\n for element in constructors:\r\n cleanconstructor = re.sub(r'new_line', '', element)\r\n \r\n outside = re.findall(r'.*(?=\\()', cleanconstructor)\r\n outside = outside[0]\r\n split = re.split(r'\\s+', outside)\r\n split = FixSpacing(split)\r\n if len(split) != 2:\r\n raise Exception('Incorrect constructor format '+ outside)\r\n if split[0] not in protections:\r\n raise Exception('Incorrect protection for constructor '+ outside)\r\n if not split[1][0].isalpha(): \r\n raise Exception('Incorrect class name for constructor '+ outside) \r\n \r\n if not re.match(r'.*{\\s*}.*', cleanconstructor):\r\n raise Exception('Error in the constructor: '+ cleanconstructor)\r\n \r\n inside = re.findall(r'(?<=\\().*(?=\\))', cleanconstructor)\r\n inside = re.split(r',', inside[0])\r\n if len(inside) > 1:\r\n for each in inside:\r\n split = re.split(r'\\s+', each)\r\n split = FixSpacing(split)\r\n if len(split) != 2:\r\n raise Exception('Incorrect constructor format '+ inside)\r\n if split[0] not in dataTypes:\r\n raise Exception('Incorrect datatype in constructor '+ inside)\r\n if not split[1][0].isalpha(): \r\n raise Exception('Incorrect variable name in constructor '+ inside) \r\n \r\n data = re.sub(r'(?<=new_line)\\w+\\s+\\w+\\s*\\(.*?\\)\\s*{.*?}', '', data)\r\n return data\r\n\r\ndef FixSpacing(listdata):\r\n newlist = []\r\n for element in listdata:\r\n if element != '':\r\n newlist.append(element)\r\n return newlist\r\n\r\ndef RemoveMethod(data):\r\n '''removes properly formatted methods'''\r\n methods = re.findall(r'(?<=new_line)\\w+\\s+\\w+\\s+\\w+\\s*\\(.*?\\)\\s*{.*?}', data)\r\n \r\n for method in methods:\r\n cleanMethod = re.sub(r'new_line', '', method)\r\n \r\n outside = re.findall(r'.*(?=\\()', cleanMethod)\r\n outside = outside[0]\r\n split = re.split(r'\\s+', outside)\r\n split = FixSpacing(split)\r\n if len(split) != 3:\r\n raise Exception('Incorrect method format '+ outside)\r\n if split[0] not in protections:\r\n raise Exception('Incorrect protection for method '+ outside)\r\n if split[1] not in dataTypes:\r\n raise Exception('Incorrect datatype for method '+ outside)\r\n if not split[2][0].isalpha(): \r\n raise Exception('Incorrect name for method '+ outside) \r\n \r\n if not re.match(r'.*{\\s*}.*', cleanMethod):\r\n raise Exception('Error in the method: '+ cleanMethod)\r\n \r\n inside = re.findall(r'(?<=\\().*(?=\\))', cleanMethod)\r\n if len(inside) > 1:\r\n inside = re.split(r',', inside[0])\r\n for each in inside:\r\n split = re.split(r'\\s+', each)\r\n split = FixSpacing(split)\r\n if len(split) != 2:\r\n raise Exception('Incorrect method format '+ each)\r\n if split[0] not in dataTypes:\r\n raise Exception('Incorrect datatype in method '+ each)\r\n if not split[1][0].isalpha(): \r\n raise Exception('Incorrect variable name in method '+ each)\r\n \r\n data = re.sub(r'(?<=new_line)\\w+\\s+\\w+\\s+\\w+\\s*\\(.*?\\)\\s*{.*?}', '', data)\r\n return data\r\n\r\ndef RemoveMethodCall(data):\r\n '''removes properly formatted method calls'''\r\n calls = re.findall(r'(?<=new_line)\\s*[a-zA-Z]+\\w*\\.[a-zA-Z]+\\w*\\s*\\(.*?\\)\\s*;', data)\r\n \r\n for call in calls:\r\n cleanCall = re.sub(r'new_line', '', call)\r\n inside = re.findall(r'(?<=\\().*(?=\\))', cleanCall)\r\n if len(inside) > 1:\r\n inside = re.split(r',', inside[0])\r\n for each in inside:\r\n split = re.split(r'\\s+', each)\r\n split = FixSpacing(split)\r\n if len(split) != 1:\r\n raise Exception('Incorrect method call '+ cleanCall)\r\n if not split[0][0].isalpha(): \r\n raise Exception('Incorrect variable name in method call '+ cleanCall)\r\n \r\n data = re.sub(r'(?<=new_line)\\s*[a-zA-Z]+\\w*\\.[a-zA-Z]+\\w*\\s*\\(.*?\\)\\s*;', '', data)\r\n return data\r\n \r\ndef RemoveMain(data):\r\n '''removes properly formatted main method'''\r\n main = re.findall('public\\s+static\\s+void\\s+main\\s*\\(\\s*String\\s+\\[\\s*\\]\\s+args\\s*\\){.*?}', data)\r\n if main:\r\n cleanMain = re.sub(r'new_line', '', main[0])\r\n if not re.match(r'.*{\\s*}.*', cleanMain):\r\n raise Exception('Error within main: '+ cleanMain)\r\n \r\n data = re.sub(r'public\\s+static\\s+void\\s+main\\s*\\(\\s*String\\s+\\[\\s*\\]\\s+args\\s*\\)\\s*{.*?}', '', data)\r\n return data\r\n \r\ndef RemoveClass(data):\r\n '''removes properly formatted classes'''\r\n classes = re.findall(r'class\\s+\\w+{.*?}', data)\r\n \r\n for element in classes:\r\n cleanElement = re.sub(r'new_line', '', element)\r\n if not re.match(r'.*{\\s*}.*', cleanElement):\r\n raise Exception('Error in class line(s): '+ cleanElement)\r\n \r\n outside = re.findall(r'.*(?={)', element)\r\n split = re.split(r'\\s+', outside[0])\r\n split = FixSpacing(split)\r\n if len(split) != 2:\r\n raise Exception('Incorrect class format: '+ outside[0])\r\n if not split[1][0].isalpha(): \r\n raise Exception('Incorrect class name: '+ outside[0])\r\n \r\n data = re.sub(r'class\\s+\\w+\\s*{.*?}', '', data)\r\n return data\r\n \r\n\r\n\r\n","sub_path":"midterm_lib.py","file_name":"midterm_lib.py","file_ext":"py","file_size_in_byte":15036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"425471883","text":"'''\nGRADING 2.0\n-------------------\nCopy your Grading 1.0 program and modify it to also print out the letter grade depending on the numerical grade.\nIf they fail, tell them to \"Transfer to Johnston!\"\n'''\n\nsem= int(input(\"Please enter your semester grade: \"))\nfinal= int(input(\"Please enter your final exam grade: \"))\nworth= int(input(\"Please enter your exam worth: \"))\noverall= (sem*((100-worth)/100))+(final*(worth/100))\nif overall > 92:\n letter = \"A\"\nelif overall > 87:\n letter = \"A-\"\nelif overall > 85:\n letter = \"B+\"\nelif overall > 82:\n letter = \"B\"\nelif overall > 77:\n letter = \"B-\"\nelif overall > 75:\n letter = \"C+\"\nelif overall > 72:\n letter = \"C\"\nelif overall > 67:\n letter = \"C-\"\nelif overall > 65:\n letter = \"D+\"\nelif overall > 62:\n letter = \"D\"\nelif overall > 50:\n letter = \"D-\"\nelse:\n letter = \"F\"\n overall = \"Transfer to Johnston!\"\nprint(\"This is your overall final grade:\",letter, \"\" ,overall,)","sub_path":"4.2_Grading_2.0.py","file_name":"4.2_Grading_2.0.py","file_ext":"py","file_size_in_byte":947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"509886072","text":"import os\n\n#Statement for enabling the development environment\nDEBUG = True\n\n#Define the application directory\nBASE_DIR = os.path.abspath(os.path.dirname(__file__))\n\n#Define the database\nSQLALCHEMY_DATABASE_URI = 'postgresql://postgres:demons@localhost/mydatabase'\n\nDATABASE_CONNECT_OPTIONS = {}\n\nUPLOADS_FOLDER = os.path.realpath('.')+'/uploads/'\n\nALLOWED_EXTENSIONS = 'StormReplay'\n\n#Application threads\nTHREADS_PER_PAGE = 2\n\n#Enable Cross-site Request Forgery protection\nCSRF_ENABLED = True\n\n#Secret key for CSRF\nCSRF_SESSION_KEY = \"secret\"\n\n#secret key for signing cookies\nSECRET_KEY = \"secret\"\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"536358726","text":"__author__ = 'web'\n\n# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\n\nclass Solution:\n # @param head, a ListNode\n # @return a list node\n def detectCycle(self, head):\n m = set()\n cur = head\n while cur is not None:\n if cur in m:\n return cur\n m.add(cur)\n cur = cur.next","sub_path":"web/python/solution/Linked List Cycle II.py","file_name":"Linked List Cycle II.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"409423255","text":"import os\nimport re\n\nfrom distutils.core import setup\n\n\ndef get_version(package):\n \"\"\"\n Return package version as listed in `__version__` in `init.py`.\n \"\"\"\n init_py = open(os.path.join(package, '__init__.py')).read()\n return re.search(\"__version__ = ['\\\"]([^'\\\"]+)['\\\"]\", init_py).group(1)\n\n\nversion = get_version('django_om')\n\nsetup(\n name='django-om',\n packages=['django_om'],\n version=version,\n description='Om.next query parser for Django',\n author='Chargeads',\n author_email='devs@chargeads.com',\n url='https://github.com/chargeads/django-om',\n download_url='https://github.com/chargeads/django-om/tarball/0.1',\n keywords=['django', 'om', 'next', 'query', 'parser'],\n classifiers=[\n 'Environment :: Web Environment',\n 'Framework :: Django',\n 'Framework :: Django :: 1.7',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 2',\n 'Programming Language :: Python :: 2.7',\n 'Topic :: Internet :: WWW/HTTP',\n 'Topic :: Internet :: WWW/HTTP :: Dynamic Content',\n ],\n)\n","sub_path":"pypi_install_script/django-om-0.1.0-alpha21.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"593504525","text":"# インポートするライブラリ\r\nfrom flask import Flask, request, abort\r\n\r\nfrom linebot import (\r\n LineBotApi, WebhookHandler\r\n)\r\nfrom linebot.exceptions import (\r\n InvalidSignatureError\r\n)\r\nfrom linebot.models import (\r\n FollowEvent, MessageEvent, TextMessage, TextSendMessage, ImageMessage, ImageSendMessage, TemplateSendMessage, ButtonsTemplate, PostbackTemplateAction, MessageTemplateAction, URITemplateAction\r\n)\r\nimport os\r\n\r\n# 軽量なウェブアプリケーションフレームワーク:Flask\r\napp = Flask(__name__)\r\n\r\n# 環境変数からLINE Access Tokenを設定\r\n# LINE_CHANNEL_ACCESS_TOKEN = os.environ[\"LINE_CHANNEL_ACCESS_TOKEN\"]\r\n# 環境変数からLINE Channel Secretを設定\r\n# LINE_CHANNEL_SECRET = os.environ[\"LINE_CHANNEL_SECRET\"]\r\n\r\nYOUR_CHANNEL_ACCESS_TOKEN = os.environ[\"YOUR_CHANNEL_ACCESS_TOKEN\"]\r\nYOUR_CHANNEL_SECRET = os.environ[\"YOUR_CHANNEL_SECRET\"]\r\n\r\nline_bot_api = LineBotApi(YOUR_CHANNEL_ACCESS_TOKEN)\r\nhandler = WebhookHandler(YOUR_CHANNEL_SECRET)\r\n\r\n#Webhookからのリクエストをチェック\r\n@app.route(\"/callback\", methods=['POST'])\r\ndef callback():\r\n # リクエストヘッダーから署名検証のための値を取得\r\n # get X-Line-Signature header value\r\n signature = request.headers['X-Line-Signature']\r\n # リクエストボディを取得\r\n # get request body as text\r\n body = request.get_data(as_text=True)\r\n app.logger.info(\"Request body: \" + body)\r\n # 署名を検証し、問題なければhandleに定義されている関数を呼び出す\r\n # handle webhook body\r\n try:\r\n handler.handle(body, signature)\r\n # 署名検証で失敗した場合、例外を出す\r\n except InvalidSignatureError:\r\n abort(400)\r\n # handleの処理を終えればOK\r\n return 'OK'\r\n\r\n#LINEのメッセージの取得と返信内容の設定(オウム返し)\r\n#LINEでMessageEvent(普通のメッセージを送信された場合)が起こった場合に、\r\n#def以下の関数を実行\r\n#reply_messageの第一引数のevent.reply_tokenは、イベントの応答に用いるトークン \r\n#第二引数には、linebot.modelsに定義されている返信用のTextSendMessageオブジェクトを渡す\r\n# MessageEvent\r\n@handler.add(MessageEvent, message=TextMessage)\r\ndef handle_message(event):\r\n\tline_bot_api.reply_message(\r\n event.reply_token,\r\n TextSendMessage(text=event.message.text)#ここでオウム返しのメッセージを返す\r\n )\r\n\r\n# ポート番号の設定\r\nif __name__ == \"__main__\":\r\n port = int(os.getenv(\"PORT\", 5000))\r\n app.run(host=\"0.0.0.0\", port=port)","sub_path":"lineBot/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"647819828","text":"import os\nimport torch.backends.cudnn as cudnn\nimport torch.utils.data\nfrom torch.autograd import Variable\nfrom torchvision import transforms\nfrom dataset.data_loader import GetLoader, get_dataset, dataset_list\nfrom torchvision import datasets\n\ncache = {}\n\n\ndef get_dataloader(dataset_name, image_size, limit, batch_size, tune_stats=False):\n dataloader = cache.get(dataset_name, None)\n if tune_stats:\n mode = \"test_tuned\"\n else:\n mode = \"test\"\n if dataloader is None:\n dataloader = torch.utils.data.DataLoader(\n dataset=get_dataset(dataset_name, image_size, mode=mode, limit=limit),\n batch_size=batch_size,\n shuffle=False,\n num_workers=4,\n pin_memory=True\n )\n cache[dataset_name] = dataloader\n return dataloader\n\n\ndef test(dataset_name, epoch, model, image_size, batch_size=1024, limit=None, tune_stats=False):\n assert dataset_name in dataset_list\n model.eval()\n cuda = True\n cudnn.benchmark = True\n lambda_val = 0\n\n n_total = 0.0\n n_correct = 0.0\n\n model.train(False)\n dataloader = get_dataloader(dataset_name, image_size, limit, batch_size, tune_stats=tune_stats)\n for i, (t_img, t_label) in enumerate(dataloader):\n batch_size = len(t_label)\n if cuda:\n t_img = t_img.cuda()\n t_label = t_label.cuda()\n\n class_output, _ = model(input_data=Variable(t_img, volatile=True), lambda_val=lambda_val)\n pred = class_output.data.max(1, keepdim=True)[1]\n n_correct += pred.eq(t_label.view_as(pred)).cpu().sum()\n n_total += batch_size\n\n accu = n_correct / n_total\n\n print('epoch: %d, accuracy of the %s dataset (%d batches): %f' % (epoch, dataset_name, len(dataloader), accu))\n return accu\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"265103517","text":"#!/usr/bin/env python\n\n\"\"\" This is a test of base workchain submission for CRYSTAL properties calculation\n\"\"\"\n\nfrom aiida.plugins import DataFactory, Code, load_node\nfrom aiida.engine import submit\nfrom aiida_crystal_dft.workflows.base import BasePropertiesWorkChain\n\n\ninputs = BasePropertiesWorkChain.get_builder()\ninputs.code = Code.get_from_string('properties@torquessh')\ninputs.parameters = DataFactory('parameter')(dict={\n \"band\": {\n \"shrink\": 12,\n \"k_points\": 30,\n \"first\": 7,\n \"last\": 14,\n \"bands\": [[\"G\", \"W\"]]\n }\n})\n\nwf = load_node(13)\nassert isinstance(wf, DataFactory('singlefile'))\ninputs.wavefunction = wf\ninputs.options = DataFactory('parameter')(dict={\n 'resources': {\n 'num_machines': 1,\n 'num_mpiprocs_per_machine': 1\n }\n})\n\ncalc = submit(BasePropertiesWorkChain, **inputs)\nprint(\"submitted WorkChain; calc=WorkCalculation(PK={})\".format(\n calc.dbnode.pk))\n","sub_path":"examples/test_MgO_props_WC.py","file_name":"test_MgO_props_WC.py","file_ext":"py","file_size_in_byte":938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"487178340","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.optimize import root\n\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\nfrom matplotlib.ticker import LinearLocator, FormatStrFormatter\nimport numpy as np\n\npaths = np.loadtxt(\"path.txt\", dtype='string')\n\nloadPath = paths[0]\nsavePath = paths[1]\n\nname = \"grandCanonicalSumsH0.txt\"\n\nFrrdata = np.loadtxt(loadPath + name, delimiter=\",\")\n\nnumStates = Frrdata[0][0]\ndosF = Frrdata[0][1]\nVuc = Frrdata[1][0]\ndim = Frrdata[2][0]\nTc = Frrdata[3][0]\n\nkb = 8.67e-5\ngamma = 2.0/3.0*np.pi*np.pi*dosF*kb*kb\n\ntData = Frrdata[0][2:]/Tc\n# betaData = np.array([1/T for T in tData])\ndNum= 4\ngData = np.sort(Frrdata.transpose()[1][1::dNum])\n\n\ngtDataBlockUnsorted = np.array([Frrdata[1:][dN::dNum] for dN in range(dNum)])\ngtDataBlock = np.array([gtDataBlockUnsorted[dN][gtDataBlockUnsorted[dN][:,1].argsort()] for dN in range(dNum)])\n\nFreshData = gtDataBlock.transpose()[2:].transpose()\n# cfData = np.array([[FreshData[0][G][T]-FreshData[4][G][T]*tData[T] - dim/Vuc*FreshData[5][G][T]*FreshData[2][G][T] for T in range(len(tData))] for G in range(len(gData))])\n\nfigTitle = [ \"Entropy\", \"HeatCapacity\", \"EnergyAverage\", \"Grand Potential\" ]\n\nplotData = np.array([FreshData[3]/(gamma*Tc),FreshData[1]/(gamma*Tc),FreshData[0]/(gamma*Tc*Tc),FreshData[2]/(gamma*Tc*Tc)])\nplotLabel = [\"$S/V(\\gamma T_C)$\",\"$C/V(\\gamma T_C)$\", r\"$\\langle E\\rangle/V(\\gamma T_C^2)$ \", \"$\\Omega/V(\\gamma T_C^2)$\"]\n\n\n\nThermoFig = plt.figure(\"Thermo Sums\", figsize=plt.figaspect(2.0/3.0))\nplt.subplots_adjust(hspace = 0.3)\n\nfor gIndex in range(10):\n rows =2\n cols =2\n for r in range(rows):\n for c in range(cols):\n plotIndex = r*(rows)+c\n fig = ThermoFig.add_subplot(rows,cols,plotIndex+1)\n plt.plot(tData,plotData[plotIndex][gIndex],label=gData[gIndex])\n fig.set_title(plotLabel[plotIndex])\n # fig.set_ylabel(plotLabel[plotIndex])\n fig.set_xlabel(\"$T/T_C$\")\nplt.tight_layout()\n#################################################################################################################################################################################################\n#Saving\nplotName = \"2DThermoPlots\"\nextensionTypes = [\".png\" ,\".pdf\"]\nfor ext in extensionTypes : plt.savefig(savePath+plotName+ext)\n#################################################################################################################################################################################################\n\n\nplt.show()\n","sub_path":"thermoSum/odSuper/Plot/EnergyDensity.py","file_name":"EnergyDensity.py","file_ext":"py","file_size_in_byte":2591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"272631219","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n'''\n\n.. _module_mc_env:\n\nmc_env / env registry\n============================================\n\nIf you alter this module and want to test it, do not forget\nto deploy it on minion using::\n\n salt '*' saltutil.sync_modules\n\nDocumentation of this module is available with::\n\n salt '*' sys.doc mc_env\n\n'''\n# Import python libs\nimport logging\nimport os\nimport mc_states.api\nfrom mc_states.modules.mc_pillar import PILLAR_TTL\n\n__name = 'env'\n\nlog = logging.getLogger(__name__)\nRVM_URL = (\n 'https://raw.github.com/wayneeseguin/env/master/binscripts/env-installer')\n\n\ndef is_reverse_proxied():\n return __salt__['mc_cloud.is_vm']()\n\n\ndef settings():\n '''\n env registry\n\n default_env\n Environment defaults (one of: dev/prod/preprod)\n '''\n @mc_states.api.lazy_subregistry_get(__salt__, __name)\n def _settings():\n _s = __salt__\n default_env = _s['mc_utils.get']('default_env', None)\n # ATTENTION: DO NOT USE 'env' to detect when we configure\n # over when we inherit between salt modes\n local_conf = __salt__['mc_macros.get_local_registry'](\n 'default_env', registry_format='pack')\n # in makina-states, only salt mode,\n if default_env is None:\n default_env = local_conf.get('default_env', None)\n mid = __opts__['id']\n if default_env is None:\n for pattern in ['prod', 'staging', 'dev']:\n if pattern in mid:\n default_env = pattern\n if default_env is None:\n default_env = 'dev'\n # rely mainly on pillar:\n # - makina-states.localsettings.env.env\n # but retro compat and shortcut on pillar\n # - default_env\n data = _s['mc_utils.defaults'](\n 'makina-states.localsettings.env', {\n 'env': None})\n save = False\n # detect when we configure over default value\n if data['env'] is None:\n data['env'] = default_env\n else:\n save = True\n # retro compat\n data['default_env'] = data['env']\n if save:\n local_conf['default_env'] = data['env']\n __salt__['mc_macros.update_registry_params'](\n 'default_env', local_conf, registry_format='pack')\n return data\n return _settings()\n\n\ndef env():\n return settings()['env']\n\n\ndef ext_pillar(id_, ttl=PILLAR_TTL, *args, **kw):\n def _do(id_, args, kw):\n rdata = {}\n conf = __salt__['mc_pillar.get_configuration'](id_)\n rdata['default_env'] = rdata['env'] = conf['default_env']\n return rdata\n cache_key = '{0}.{1}.{2}'.format(__name, 'ext_pillar', id_)\n return __salt__['mc_utils.memoize_cache'](\n _do, [id_, args, kw], {}, cache_key, ttl)\n# vim:set et sts=4 ts=4 tw=80:\n","sub_path":"doc/sphinx/mc_states/modules/mc_env.py","file_name":"mc_env.py","file_ext":"py","file_size_in_byte":2825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"190003384","text":"# File: buttonController\r\n# By: Camiel Verschoor, Sander Nugteren & Erik van Egmond\r\n\r\nfrom naoqi import ALProxy\r\nimport time\r\n\r\nclass buttonController():\r\n # VARIABLES\r\n chestButtonPressed = False\r\n manual = True\r\n teamColor = 0\r\n penalty = 0\r\n kickOff = 0\r\n\r\n # CONSTRUCTOR\r\n def __init__(self, ttsProxy, memProxy, interval=0.5):\r\n self.interval = interval\r\n #self.chestButtonPressed = False\r\n self.manual = True\r\n self.memProxy = memProxy\r\n self.ttsProxy = ttsProxy\r\n\r\n # FUNCTIONS\r\n def chestButton(self):\r\n return not(self.memProxy.getData(\"ChestButtonPressed\", 0) == 0.0)\r\n \r\n def bumperButton(self):\r\n return not((self.memProxy.getData(\"LeftBumperPressed\", 0) == 0.0) or (self.memProxy.getData(\"RightBumperPressed\", 0) == 0.0))\r\n \r\n # THE FUNCTIONS TO SETUP THE NAO\r\n def getSetup(self):\r\n if self.manual:\r\n self.ttsProxy.say(\"This is the manual setup. Choose my team\")\r\n if (self.teamColor == 0):\r\n self.ttsProxy.say(\"My current team color is, blue\")\r\n else:\r\n self.ttsProxy.say(\"My current team color is, red\")\r\n self.teamColor = self.chooseTeam()\r\n time.sleep(1)\r\n \r\n self.ttsProxy.say(\"Choose mode\")\r\n if (self.penalty == 0):\r\n self.ttsProxy.say(\"Current mode, Match mode\")\r\n else:\r\n self.ttsProxy.say(\"Current mode, Penalty mode\")\r\n self.penalty = self.chooseMode()\r\n time.sleep(1)\r\n \r\n self.ttsProxy.say(\"Choose kick off\")\r\n if (self.kickOff == 0):\r\n self.ttsProxy.say(\"I have kick off\")\r\n else:\r\n self.ttsProxy.say(\"I do not have kick off\")\r\n self.kickOff = self.chooseKickOff()\r\n time.sleep(1)\r\n \r\n self.manual = False\r\n return (self.teamColor, self.penalty, self.kickOff)\r\n\r\n def chooseTeam(self):\r\n startTime = time.time()\r\n while (time.time() - startTime < 4):\r\n if (self.bumperButton()):\r\n if(self.teamColor == 0):\r\n self.teamColor = 1\r\n self.ttsProxy.say(\"My team color is, red\")\r\n else:\r\n self.teamColor = 0\r\n self.ttsProxy.say(\"My team color is, blue\")\r\n time.sleep(0.5)\r\n return self.teamColor\r\n\r\n def chooseMode(self):\r\n startTime = time.time()\r\n while (time.time() - startTime < 4):\r\n if (self.bumperButton()):\r\n if(self.penalty == 0):\r\n self.penalty = 1\r\n self.ttsProxy.say(\"Penalty mode\")\r\n else:\r\n self.penalty = 0\r\n self.ttsProxy.say(\"Match mode\")\r\n time.sleep(0.5)\r\n return self.penalty\r\n\r\n def chooseKickOff(self):\r\n startTime = time.time()\r\n while (time.time() - startTime < 4):\r\n if (self.bumperButton()):\r\n if(self.kickOff == 0):\r\n self.kickOff = 1\r\n self.ttsProxy.say(\"Kick off\")\r\n else:\r\n self.kickOff = 0\r\n self.ttsProxy.say(\"No kick off\")\r\n time.sleep(0.5)\r\n return self.kickOff\r\n\r\n # GET FUNCTIONS\r\n def getChestButton(self):\r\n button = self.chestButton()\r\n if button:\r\n while self.chestButton():\r\n pass\r\n return button","sub_path":"naoqi/lib/buttonController.py","file_name":"buttonController.py","file_ext":"py","file_size_in_byte":3590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"359386443","text":"# Requires Python 3.X\n# Author: greg zakharov\n# PE data reader.\nfrom os import name\nif name != 'nt':\n raise OSError('Windows is required.')\n\nfrom ctypes import (\n POINTER, Structure, byref, cast, create_string_buffer, c_byte, c_ulong,\n c_ulonglong, c_ushort, c_void_p, c_wchar_p, memmove, windll\n)\nfrom enum import Enum\n\nclass IMAGE_FILE_MACHINE(Enum):\n Unknown = 0\n I386 = 0x014C #Intel 386\n R3000 = 0x0162 #MIPS little-endian, 0x160 big-endian\n R4000 = 0x0166 #MIPS little-endian\n R10000 = 0x0168 #MIPS little-endian\n WCEMIPSV2 = 0x0169 #MIPS little-endian WCE v2\n ALPHA = 0x0184 #Alpha_APX\n SH3 = 0x01A2 #SH3 little-endian\n SH3DSP = 0x01A3\n SH3E = 0x01A4 #SH3 little-endian\n SH4 = 0x01A6 #SH4 little-endian\n SH5 = 0x01A8 #SH5\n ARM = 0x01C0 #ARM little-endian\n THUMB = 0x01C2\n AM33 = 0x01D3\n POWERPC = 0x01F0 #IBM PowerPC little-endian\n POWERPCFP = 0x01F1\n IA64 = 0x0200\n MIPS16 = 0x0266 #MIPS\n ALPHA64 = 0x0284 #ALPHA64\n MIPSFPU = 0x0366 #MIPS\n MIPSFPU16 = 0x0466 #MIPS\n AXP64 = ALPHA64\n TRICORE = 0x0520 #Infineon\n CEF = 0x0CEF\n EBC = 0x0EBC #EFI byte code\n AMD64 = 0x8664 #AMD64 (K8)\n M32R = 0x9041 #M32R little-endian\n CEE = 0xC0EE\n\nIMAGE_FILE_CHARACTERISTICS = dict(\n RelocsStripped = 0x0001,\n Executable = 0x0002,\n LineNumsStripped = 0x0004,\n LocalSymsStripped = 0x0008,\n AggressiveWsTrim = 0x0010,\n LargeAddressAware = 0x0020,\n BytesReservedLo = 0x0080,\n Machine32Bit = 0x0100,\n DebugStripped = 0x0200,\n RemovableFromSwap = 0x0400,\n NetRunFromSwap = 0x0800,\n System = 0x1000,\n Dll = 0x2000,\n UpSystemOnly = 0x4000,\n BytesReservedHi = 0x8000\n)\n\nclass IMAGE_SUBSYSTEM(Enum):\n Unknown = 0\n Native = 1\n WindowsGUI = 2\n WindowsCUI = 3\n WindowsCE = 4\n OS2CUI = 5\n POSIXCUI = 7\n NativeWindows = 8\n WindowsCEGUI = 9\n EFIApplication = 10\n EFIBootServiceDriver = 11\n EFIRuntimeDriver = 12\n EFIRom = 13\n XBox = 14\n WindowsBootApplication = 16\n\nIMAGE_DLLCHARACTERISTICS = dict(\n ProcessInit = 0x0001,\n ProcessTerm = 0x0002,\n ThreadInit = 0x0004,\n ThreadTerm = 0x0008,\n DynamicBase = 0x0040,\n ForceIntegrity = 0x0080,\n NXCompatibale = 0x0100,\n NoIsolation = 0x0200,\n NoSEH = 0x0400,\n NoBind = 0x0800,\n Reserved1 = 0x1000,\n WDMDriver = 0x2000,\n Reserved2 = 0x4000,\n TerminalSrvAware = 0x8000\n)\n\nclass IMAGE_FILE_HEADER(Structure):\n _fields_ = [\n ('Machine', c_ushort),\n ('NumberOfSections', c_ushort),\n ('TimeDateStamp', c_ulong),\n ('PointerToSymbolTable', c_ulong),\n ('NumberOfSymbols', c_ulong),\n ('SizeOfOptionalHeader', c_ushort),\n ('Characteristics', c_ushort),\n ]\n\nclass IMAGE_OPTIONAL_HEADER32(Structure):\n _fields_ = [\n ('Magic', c_ushort),\n ('MajorLinkerVersion', c_byte),\n ('MinorLinkerVersion', c_byte),\n ('SizeOfCode', c_ulong),\n ('SizeOfInitializedData', c_ulong),\n ('SizeOfUninitializedData', c_ulong),\n ('AddressOfEntryPoint', c_ulong),\n ('BaseOfCode', c_ulong),\n ('BaseOfData', c_ulong),\n ('ImageBase', c_ulong),\n ('SectionAlignment', c_ulong),\n ('FileAlignment', c_ulong),\n ('MajorOperatingSystemVersion', c_ushort),\n ('MinorOperatingSystemVersion', c_ushort),\n ('MajorImageVersion', c_ushort),\n ('MinorImageVersion', c_ushort),\n ('MajorSubsystemVersion', c_ushort),\n ('MinorSubsystemVersion', c_ushort),\n ('Win32VersionValue', c_ulong),\n ('SizeOfImage', c_ulong),\n ('SizeOfHeaders', c_ulong),\n ('CheckSum', c_ulong),\n ('Subsystem', c_ushort),\n ('DllCharacteristics', c_ushort),\n ('SizeOfSteckReserve', c_ulong),\n ('SizeOfStackCommit', c_ulong),\n ('SizeOfHeapReserve', c_ulong),\n ('SizeOfHeapCommit', c_ulong),\n ('LoaderFlags', c_ulong),\n ('NumberOfRvaAndSizes', c_ulong),\n ]\n\nclass IMAGE_OPTIONAL_HEADER64(Structure):\n _fields_ = [\n ('Magic', c_ushort),\n ('MajorLinkerVersion', c_byte),\n ('MinorLinkerVersion', c_byte),\n ('SizeOfCode', c_ulong),\n ('SizeOfInitializedData', c_ulong),\n ('SizeOfUninitializedData', c_ulong),\n ('AddressOfEntryPoint', c_ulong),\n ('BaseOfCode', c_ulong),\n ('ImageBase', c_ulonglong),\n ('SectionAlignment', c_ulong),\n ('FileAlignment', c_ulong),\n ('MajorOperatingSystemVersion', c_ushort),\n ('MinorOperatingSystemVersion', c_ushort),\n ('MajorImageVersion', c_ushort),\n ('MinorImageVersion', c_ushort),\n ('MajorSubsystemVersion', c_ushort),\n ('MinorSubsystemVersion', c_ushort),\n ('Win32VersionValue', c_ulong),\n ('SizeOfImage', c_ulong),\n ('SizeOfHeaders', c_ulong),\n ('CheckSum', c_ulong),\n ('Subsystem', c_ushort),\n ('DllCharacteristics', c_ushort),\n ('SizeOfStackReserve', c_ulonglong),\n ('SizeOfStackCommit', c_ulonglong),\n ('SizeOfHeapReserve', c_ulonglong),\n ('SizeOfHeapCommit', c_ulonglong),\n ('LoaderFlags', c_ulong),\n ('NumberOfRvaAndSizes', c_ulong),\n ]\n\nclass IMAGE_NT_HEADERS32(Structure):\n _fields_ = [\n ('Signature', c_ulong),\n ('FileHeader', IMAGE_FILE_HEADER),\n ('OptionalHeader', IMAGE_OPTIONAL_HEADER32),\n ]\n\nclass IMAGE_NT_HEADERS64(Structure):\n _fields_ = [\n ('Signature', c_ulong),\n ('FileHeader', IMAGE_FILE_HEADER),\n ('OptionalHeader', IMAGE_OPTIONAL_HEADER32),\n ]\n\nclass VS_FIXEDFILEINFO(Structure):\n _fields_ = [\n ('dwSignature', c_ulong),\n ('dwStrucVersion', c_ulong),\n ('dwFileVersionMS', c_ulong),\n ('dwFileVersionLS', c_ulong),\n ('dwProductVersionMS', c_ulong),\n ('dwProductVersionLS', c_ulong),\n ('dwFileFlagMask', c_ulong),\n ('dwFileFlags', c_ulong),\n ('dwFileOS', c_ulong),\n ('dwFileType', c_ulong),\n ('dwFileSubtype', c_ulong),\n ('dwFileDateMS', c_ulong),\n ('dwFileDateLS', c_ulong),\n ]\n\nFORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100\nFORMAT_MESSAGE_FROM_SYSTEM = 0x00001000\nLANG_NEUTRAL = 0x00000000\nSUBLANG_DEFAULT = 0x00000001\nGENERIC_READ = 0x80000000\nFILE_SHARE_READ = 0x00000001\nOPEN_EXISTING = 0x00000003\nINVALID_HANDLE_VALUE = -1\nPAGE_READONLY = 0x00000002\nFILE_MAP_READ = 0x00000004\nLOAD_LIBRARY_AS_DATAFILE = 0x00000002\n\nCloseHandle = windll.kernel32.CloseHandle\nCreateFile = windll.kernel32.CreateFileW\nCreateFileMapping = windll.kernel32.CreateFileMappingW\nFindResource = windll.kernel32.FindResourceW\nFormatMessage = windll.kernel32.FormatMessageW\nFreeLibrary = windll.kernel32.FreeLibrary\nGetFileVersionInfoSize = windll.version.GetFileVersionInfoSizeW\nGetFileVersionInfo = windll.version.GetFileVersionInfoW\nGetLastError = windll.kernel32.GetLastError\nImageNtHeader = windll.dbghelp.ImageNtHeader\nLoadLibraryEx = windll.kernel32.LoadLibraryExW\nLoadResource = windll.kernel32.LoadResource\nLocalFree = windll.kernel32.LocalFree\nLockResource = windll.kernel32.LockResource\nMapViewOfFile = windll.kernel32.MapViewOfFile\nSizeofResource = windll.kernel32.SizeofResource\nUnmapViewOfFile = windll.kernel32.UnmapViewOfFile\nVerQueryValue = windll.version.VerQueryValueW\n\ndef printwin32error():\n def MAKELANGID(p, s):\n return c_ulong((s << 10) | p)\n msg = c_void_p()\n FormatMessage(\n FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,\n None,\n GetLastError(),\n MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),\n byref(msg),\n 0,\n None\n )\n m = c_wchar_p(msg.value).value\n print(m.strip() if m else 'Unknown exception has been occured.')\n LocalFree(msg)\n\n\"\"\"Gets PE brief \"\"\"\ndef getpebrief(pe):\n #return PE characteristics\n def convert2str(d, e):\n des = ''\n for i in d.keys():\n if e & d[i]:\n des += i + '; '\n return des.strip() if des else des\n \n try:\n itm_ptr = CreateFile(pe, GENERIC_READ, FILE_SHARE_READ, None, OPEN_EXISTING, 0, None)\n if itm_ptr == INVALID_HANDLE_VALUE:\n printwin32error()\n return\n \n img_ptr = CreateFileMapping(itm_ptr, None, PAGE_READONLY, 0, 0, None)\n img_map = MapViewOfFile(img_ptr, FILE_MAP_READ, 0, 0, None)\n hdr_ptr = ImageNtHeader(img_map)\n \n img_nt_hdr = cast(hdr_ptr, POINTER(IMAGE_NT_HEADERS32)).contents\n if img_nt_hdr.OptionalHeader.Magic == 0x20B:\n img_nt_hdr = cast(hdr_ptr, POINTER(IMAGE_NT_HEADERS64)).contents\n \n from datetime import datetime as dt\n for f, ctype in img_nt_hdr.FileHeader._fields_:\n res = getattr(img_nt_hdr.FileHeader, f)\n if f == 'Machine':\n res = IMAGE_FILE_MACHINE(res).name\n elif f == 'TimeDateStamp':\n res = dt.fromtimestamp(res)\n elif f == 'Characteristics':\n res = convert2str(IMAGE_FILE_CHARACTERISTICS, res)\n else:\n res = None\n \n print('%-21s: %s' % (f, res)) if res else 0\n \n def getfield(f, s): #s indicates returned type\n res = getattr(img_nt_hdr.OptionalHeader, f)\n return str(res) if s else res\n \n print('%-21s: %s' % ('Magic', 'PE32' if getfield('Magic', 0) == 0x10B else 'PE32+'))\n print('%-21s: %s' % ('LinkerVersion', getfield('MajorLinkerVersion', 1) + '.' + getfield('MinorLinkerVersion', 1)))\n print('%-21s: %s' % ('EntryPoint', hex(getfield('AddressOfEntryPoint', 0))))\n print('%-21s: %s' % ('SizeOfImage', hex(getfield('SizeOfImage', 0))))\n print('%-21s: %s' % ('CheckSum', hex(getfield('CheckSum', 0))))\n print('%-21s: %s' % ('Subsystem', IMAGE_SUBSYSTEM(getfield('Subsystem', 0)).name))\n print('%-21s: %s' % ('DllCharacteristics', convert2str(IMAGE_DLLCHARACTERISTICS, getfield('DllCharacteristics', 0))))\n except Exception as e:\n print(e)\n finally:\n UnmapViewOfFile(img_map) #unmap image\n CloseHandle(img_ptr) #close file mapping\n CloseHandle(itm_ptr) #close file handle\n\n\"\"\" Gets PE manifest \"\"\"\ndef getpemanifest(pe):\n module = c_void_p() #PE\n res_info = c_void_p() #resource pointer\n res_load = c_void_p() #handle of the loaded resource\n res_lock = c_void_p() #locked resource data\n res_info = c_ulong() #size of resource\n \n module = LoadLibraryEx(pe, None, LOAD_LIBRARY_AS_DATAFILE)\n if module == 0:\n printwin32error()\n return\n \n res_info = FindResource(module, '#1', '#24')\n if res_info == 0:\n printwin32error()\n else:\n res_size = SizeofResource(module, res_info)\n if res_size == 0:\n printwin32error()\n else:\n res_load = LoadResource(module, res_info)\n res_lock = LockResource(res_load)\n buf = create_string_buffer(res_size)\n memmove(buf, res_lock, res_size)\n \n FreeLibrary(module)\n try:\n print(str(buf.raw, 'utf8'))\n except UnicodeEncodeError as e:\n print(e.reason)\n\n\"\"\" Gets PE version \"\"\"\ndef getpeversion(pe):\n sz_data = GetFileVersionInfoSize(pe, 0)\n if sz_data == 0:\n printwin32error()\n return\n \n buf = create_string_buffer(sz_data)\n if not GetFileVersionInfo(pe, 0, sz_data, byref(buf)):\n printwin32error()\n return\n \n lp_buf = c_void_p()\n pu_len = c_ulong()\n if not VerQueryValue(buf, \"\\\\\", byref(lp_buf), byref(pu_len)):\n printwin32error()\n return\n \n vffi = cast(lp_buf, POINTER(VS_FIXEDFILEINFO)).contents\n print('%u.%u' % ((vffi.dwFileVersionMS & 0xffff0000) >> 16, vffi.dwFileVersionMS & 0x0000ffff))\n\n\"\"\" Prints usage info \"\"\"\ndef usage():\n print('%s v1.0 - PE data reader\\nCopyright (C) 2014 greg zakharov\\n' % argv[0])\n print('Usage: %s [-b][-m][-v]' % argv[0])\n print(' -b Show basic PE headers data')\n print(' -m Dump PE manifest')\n print(' -v Get PE version only')\n exit(1)\n\n\nif __name__ == '__main__':\n from sys import argv, exit\n if len(argv) != 3: usage() #two arguments are required\n if len(argv[1]) != 2 or not (argv[1][0] == '-' or argv[1][0] == '/'): usage()\n \n if argv[1][1] == 'b':\n getpebrief(argv[2])\n elif argv[1][1] == 'm':\n getpemanifest(argv[2])\n elif argv[1][1] == 'v':\n getpeversion(argv[2])\n else:\n usage()\n","sub_path":"pe_read.py","file_name":"pe_read.py","file_ext":"py","file_size_in_byte":13473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"104507223","text":"from django.utils import timezone\nfrom django.contrib.auth.models import User\nfrom django.db import models\n\nclass TeamWorkWrite(models.Model):\n \"\"\"工作概况\"\"\"\n title = models.CharField(max_length=300)\n # 一个用户对应多篇文章\n author = models.ForeignKey(User, related_name=\"work_posts\", on_delete=models.CASCADE) # ForeignKey 一对多的关系\n body = models.TextField()\n publish = models.DateTimeField(default=timezone.now) #带时区的\n total_views = models.PositiveIntegerField(default=0)#总浏览次数\n\n def instance_recently(self):\n \"\"\"优化时间显示\"\"\"\n diff = timezone.now()- self.publish #发布文字的时间差值\n seconds = diff.seconds\n minutes,seconds = divmod(seconds,60)\n hours, minutes = divmod(minutes, 60)\n days, hours = divmod(hours, 24)\n months, days = divmod(days, 30)\n years, months = divmod(months, 12)\n print(\"时间差:\",diff)\n\n if years!=0:\n time = str(years) + '年前'\n return time\n elif months!=0:\n time = str(months) + '个月前'\n return time\n elif days!=0:\n time = str(days) + '天前'\n return time\n elif hours!=0:\n time = str(hours) + '小时前'\n return time\n elif minutes!=0:\n time = str(minutes) + '分钟前'\n return time\n elif seconds!=0:\n time = str(seconds) + '秒前'\n return time\n else:\n time = '刚刚'\n return time\n\n\n\n # 按照指定的字段进行数据库的排序 用于给 model 定义元数据\n class Meta:\n \"\"\"元类,可选类,写了可以让我们更好理解\"\"\"\n db_table = 'teamwork_teamworkwrite' #数据库表名\n verbose_name = '工作概况' #后台管理系统的名称\n verbose_name_plural = verbose_name\n ordering = (\"-publish\",) # 倒序显示\n\n # 定义了需要表示数据时应该显示的名称,体现在后台管理系统中。\n def __str__(self):\n return self.title\n","sub_path":"teamwork/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"219694940","text":"import matplotlib.pyplot as plt\nimport matplotlib.patches as patches\n\n\n\n\n\npatterns = ['-', '+', 'x', 'o', 'O', '.', '*'] # more patterns\nfig4 = plt.figure()\nax4 = fig4.add_subplot(111, aspect='equal')\nfor p in [\n patches.Rectangle(\n (0.05 + (i * 0.13), 0.1),\n 0.1,\n 0.6,\n hatch=patterns[i],\n fill=False\n ) for i in range(len(patterns))\n]:\n ax4.add_patch(p)\n\nplt.show()","sub_path":"plot_interval.py","file_name":"plot_interval.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"85552246","text":"# -*- coding: UTF-8 -*-\nfrom decimal import Decimal\nfrom lxml import etree\n__author__ = 'ffernandez@apsl.net'\n\n\n\ndef compararStrings(cadena1, cadena2, print_cadenas=False):\n ''' Compara si dos cadenas son iguales.\n '''\n if print_cadenas:\n print(cadena1+\" len: \"+str(len(cadena1)))\n print(\"-----------\")\n print(cadena2+\" len: \"+str(len(cadena2)))\n if len(cadena1) > len(cadena2):\n while len(cadena1) != len(cadena2):\n cadena2 += \"-\"\n if len(cadena1) < len(cadena2):\n while len(cadena1) != len(cadena2):\n cadena1 += \"-\"\n i = 0\n while cadena1[i] == cadena2[i] and i <= len(cadena1)-2:\n\n i += 1\n if cadena1[i] != cadena2[i]:\n cont = 0\n while cont <= i:\n print(cadena1[cont]) #, end=\"\") # python 3.4\n cont += 1\n return (\"\\nDiferencia en la posicion: \"+str(i+1))\n\n return (\"Cadenas iguales.\")\n\n\ndef remove_blank_text_xml(cadena):\n parser = etree.XMLParser(remove_blank_text=True)\n root = etree.XML(cadena, parser)\n return etree.tounicode(root)\n\n\n\n\n","sub_path":"facturae/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"60502089","text":"import matplotlib.pyplot as plot\n\ndef f(x):\n if x % 2 == 0:\n return -1\n else:\n return 1\n\nxVal = range(-5,6)\nyVal = []\nfor x in xVal:\n yVal.append(f(x))\nplot.bar(xVal,yVal)\nplot.show()\n","sub_path":"oddeven.py","file_name":"oddeven.py","file_ext":"py","file_size_in_byte":207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"366576005","text":"#!/usr/bin/python\nimport sys, re, codecs\nfrom optparse import OptionParser\n\n# coarse hack for coercing input to utf-8\n#reload(sys)\n\ndef strip_chars(f): \n _illegal_unichrs = [(0x00, 0x08), (0x0B, 0x0C), (0x0E, 0x1F), \n (0x7F, 0x84), (0x86, 0x9F), \n (0xFDD0, 0xFDDF), (0xFFFE, 0xFFFF)] \n if sys.maxunicode >= 0x10000: # not narrow build \n _illegal_unichrs.extend([(0x1FFFE, 0x1FFFF), (0x2FFFE, 0x2FFFF), \n (0x3FFFE, 0x3FFFF), (0x4FFFE, 0x4FFFF), \n (0x5FFFE, 0x5FFFF), (0x6FFFE, 0x6FFFF), \n (0x7FFFE, 0x7FFFF), (0x8FFFE, 0x8FFFF), \n (0x9FFFE, 0x9FFFF), (0xAFFFE, 0xAFFFF), \n (0xBFFFE, 0xBFFFF), (0xCFFFE, 0xCFFFF), \n (0xDFFFE, 0xDFFFF), (0xEFFFE, 0xEFFFF), \n (0xFFFFE, 0xFFFFF), (0x10FFFE, 0x10FFFF)]) \n\n _illegal_ranges = [\"%s-%s\" % (chr(low), chr(high)) \n for (low, high) in _illegal_unichrs] \n remove_re = re.compile(u'[%s]' % u''.join(_illegal_ranges)) \n\n i = 1\n stripped = 0\n for line in f:\n new_line, count = remove_re.subn('', line) \n if count > 0:\n plur = ((count > 1) and u's') or u''\n sys.stderr.write('Line %d, removed %s character%s.\\n'\n % (i, count, plur))\n sys.stdout.write(new_line)\n stripped = stripped + count\n i = i + 1\n sys.stderr.write('Stripped %d characters from %d lines.\\n'\n % (stripped, i))\n\ndef main():\n p = OptionParser(\"usage: strip_xml_entities.py file/to/parse.xml\")\n (options, args) = p.parse_args()\n\n\n # if positional arg, use that file, otherwise stdin\n fin = (len(args) and open(args[0], 'r')) or sys.stdin\n strip_chars(fin)\n fin.close()\n\nif __name__ == '__main__':\n sys.exit(main())","sub_path":"f0001/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"55194847","text":"import os\n\nfrom django.shortcuts import get_object_or_404\nfrom django.conf import settings\nfrom django.http import HttpResponse\n\nfrom rest_framework.response import Response\nfrom rest_framework.parsers import FileUploadParser\nfrom rest_framework.views import APIView\nfrom rest_framework import status\n\nfrom rest_framework.decorators import api_view\n\nfrom agents.models import Agent\n\nfrom .models import Script\n\nfrom .serializers import ScriptSerializer\n\n\nclass UploadScript(APIView):\n parser_class = (FileUploadParser,)\n\n def put(self, request, format=None):\n if \"script\" not in request.data:\n raise ParseError(\"Empty content\")\n\n f = request.data[\"script\"]\n filename = str(f)\n\n name = request.data[\"name\"]\n desc = request.data[\"desc\"]\n shell = request.data[\"shell\"]\n\n if not Script.validate_filename(filename):\n return Response(\n \"Please upload a file with correct extension (.bat, .py, .ps1)\",\n status=status.HTTP_400_BAD_REQUEST,\n )\n\n script_path = os.path.join(\"/srv/salt/scripts/userdefined\", filename)\n\n if os.path.exists(script_path):\n return Response(\n f\"Filename {filename} already exists. Delete or edit the existing script first\",\n status=status.HTTP_400_BAD_REQUEST,\n )\n\n with open(script_path, \"wb+\") as j:\n for chunk in f.chunks():\n j.write(chunk)\n\n Script(name=name, description=desc, filename=filename, shell=shell).save()\n\n return Response(f\"asd\", status=status.HTTP_201_CREATED)\n\n\n@api_view()\ndef view_script_code(request, pk):\n script = get_object_or_404(Script, pk=pk)\n\n with open(script.file, \"r\") as f:\n text = f.read()\n\n return Response({\"name\": script.filename, \"text\": text})\n\n\n@api_view([\"DELETE\"])\ndef delete_script(request):\n script = get_object_or_404(Script, pk=request.data[\"pk\"])\n filename = script.filename\n\n try:\n os.remove(script.file)\n except OSError:\n pass\n\n script.delete()\n\n return Response(filename)\n\n\n@api_view()\ndef get_script(request, pk):\n script = get_object_or_404(Script, pk=pk)\n return Response(ScriptSerializer(script).data)\n\n\n@api_view()\ndef download_script(request, pk):\n script = get_object_or_404(Script, pk=pk)\n\n if settings.DEBUG:\n with open(script.file, \"rb\") as f:\n response = HttpResponse(f.read(), content_type=\"text/plain\")\n response[\"Content-Disposition\"] = f\"attachment; filename={script.filename}\"\n return response\n else:\n response = HttpResponse()\n response[\"Content-Disposition\"] = f\"attachment; filename={script.filename}\"\n response[\"X-Accel-Redirect\"] = f\"/protectedscripts/{script.filename}\"\n return response\n\n\nclass EditScript(APIView):\n parser_class = (FileUploadParser,)\n\n def put(self, request, format=None):\n\n script = get_object_or_404(Script, pk=request.data[\"pk\"])\n name = request.data[\"name\"]\n desc = request.data[\"desc\"]\n shell = request.data[\"shell\"]\n\n script.name = name\n script.description = desc\n script.shell = shell\n\n if \"script\" in request.data:\n # if uploading a new version of the script\n f = request.data[\"script\"]\n filename = str(f)\n if not script.validate_filename(filename):\n return Response(\n \"Please upload a file with correct extension (.bat, .py, .ps1)\",\n status=status.HTTP_400_BAD_REQUEST,\n )\n\n # delete the old file\n try:\n os.remove(script.file)\n except OSError:\n pass\n\n updated_path = os.path.join(\"/srv/salt/scripts/userdefined/\", filename)\n with open(updated_path, \"wb+\") as j:\n for chunk in f.chunks():\n j.write(chunk)\n\n script.filename = filename\n script.save(update_fields=[\"name\", \"description\", \"shell\", \"filename\"])\n else:\n script.save(update_fields=[\"name\", \"description\", \"shell\"])\n\n return Response(f\"asd\", status=status.HTTP_201_CREATED)\n","sub_path":"api/tacticalrmm/checks/scriptviews.py","file_name":"scriptviews.py","file_ext":"py","file_size_in_byte":4250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"489541039","text":"import datetime\n\ninfo_list = []\n\nuser_input = input(\"What is your Name and Age: \").split()\n\nfor x in user_input:\n info_list.append(x)\n\nnow = datetime.datetime.now()\n\nold = (now.year - (int(info_list[-1]) + 1)) + 100\n\nif int(info_list[-1]) >= 100:\n print(\"Wow! You are over 100!\")\n statement_return = (f\"You turned 100 in {old}!!!!\")\n unless = (\n f\"....unless your birthday was before today this year, then you turned 100 in {old + 1}!\")\n print(statement_return)\n print(unless)\nelse:\n statement_return = (f\"{info_list[0]}, you will be 100 in the year {old}!\")\n unless = (\n f\"Unless your birthday is before today, then you will turn 100 in {old + 1}\")\n print(statement_return)\n print(unless)\n\nnumber = int(input(\"Pick a number! \"))\ni = 0\n\nwhile number > 0:\n i += 1\n print(statement_return)\n if i == number:\n break\n","sub_path":"ageCalculator.py","file_name":"ageCalculator.py","file_ext":"py","file_size_in_byte":872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"452511173","text":"from . import api\nfrom flask import request, current_app, jsonify\nfrom itsdangerous import TimedJSONWebSignatureSerializer as Serializer\nfrom ..tools import db_tool\n \n@api.route('/tokens', methods = ['POST'])\ndef get_token():\n data = request.get_json()\n email = data.get('email')\n pwd = data.get('pwd')\n with db_tool.get_cursor() as cursor:\n sql = \"SELECT id, nm FROM user_info WHERE email = %s AND pwd = %s\"\n if cursor.execute(sql, (email, pwd)) == 0:\n return {'message': 'email or pwd is wrong'}\n result = cursor.fetchone()\n s = Serializer(current_app.config['SECRET_KEY'], expires_in = 36000)\n token = s.dumps({'user_id': result['id']}).decode('utf-8')\n return jsonify({\n 'id' : result['id'],\n 'nm' : result['nm'],\n 'token' : token\n })\n\n\n\n\n ","sub_path":"flaskr/api/token.py","file_name":"token.py","file_ext":"py","file_size_in_byte":828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"321156368","text":"import torch\nimport torch.nn as nn\nimport torchvision.datasets as dset\nimport torchvision.transforms as transforms\nfrom torch.utils.tensorboard import SummaryWriter\nfrom tqdm import tqdm\nimport pdb\n\n\nsaver_path = \".\"\n\nepoch = 15\nbatch_size = 100\nlearning_rate = 0.001\n\n# Download Data\n\nfmnist_train = dset.FashionMNIST(\n \"./\",\n train=True,\n transform=transforms.ToTensor(),\n target_transform=None,\n download=True,\n)\nfmnist_test = dset.FashionMNIST(\n \"./\",\n train=False,\n transform=transforms.ToTensor(),\n target_transform=None,\n download=True,\n)\n\n# Set Data Loader(input pipeline)\n\ntrain_loader = torch.utils.data.DataLoader(\n dataset=fmnist_train, batch_size=batch_size, shuffle=True\n)\ntest_loader = torch.utils.data.DataLoader(\n dataset=fmnist_test, batch_size=batch_size, shuffle=True\n)\n\n\n# SET DEVICE (GPU)\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n\nclass Model(nn.Module):\n def __init__(self):\n super(Model, self).__init__()\n self.layer1 = nn.Sequential(\n nn.Conv2d(1, 32, 3, padding=1),\n nn.ReLU(),\n nn.Conv2d(32, 32, 3, padding=1),\n nn.ReLU(),\n nn.Conv2d(32, 32, 3, padding=1),\n nn.ReLU(), # Activation function was missing (the bug)\n )\n\n self.layer2 = nn.Sequential(\n torch.nn.Linear(32 * 28 * 28, 256, bias=True),\n nn.ReLU(),\n torch.nn.Linear(256, 10, bias=True),\n )\n\n def forward(self, x):\n\n out = self.layer1(x)\n out = out.view(-1, 32 * 28 * 28) # Flatten\n out = self.layer2(out)\n\n return out\n\n # def __init__(self):\n # \tsuper(Model, self).__init__()\n # \tself.layer1 = nn.Sequential(\n # \t\tnn.Conv2d(1, 32, 3, padding=1),\n # \t\tnn.BatchNorm2d(32),\n # \t\tnn.ReLU(),\n\n # \t\tnn.Conv2d(32, 64, 3, padding=1),\n # \t\tnn.ReLU(),\n\n # \t\tnn.Conv2d(64, 64, 3, padding=1),\n # \t\tnn.BatchNorm2d(64),\n # \t\tnn.ReLU(),\n # \t\tnn.MaxPool2d(2),\n # \t)\n\n # \tself.layer2 = nn.Sequential(\n # \t\ttorch.nn.Linear(64*14*14, 256, bias=True),\n # \t\tnn.ReLU(),\n # \t\ttorch.nn.Linear(256, 10, bias=True),\n # \t)\n\n # def forward(self, x):\n\n # \tout = self.layer1(x)\n # \tout = out.view(-1,64*14*14) # Flatten\n # \tout = self.layer2(out)\n\n # \treturn out\n\n\nmodel = Model().to(device=device)\n\n\nparameters = list(model.parameters())\nloss_func = nn.CrossEntropyLoss()\n\n# TODO : Fill in your favourite optimizer\noptimizer = torch.optim.Adam(parameters, lr=learning_rate, weight_decay=1e-4)\n\n\ndef accuracy_measure(logits, labels):\n \"\"\"Accuracy\n\t\tArgs:\n\t\t\tlogits : logits of shape [B, 10]\n\t\t\tlabels : labels of shape [B, ]\n\t\tReturns:\n\t\t Tensor: accuracy (scalar)\n\t\t\"\"\"\n # TODO: fill the accuracy implementation\n predicted = torch.argmax(logits, axis=1)\n return (predicted == labels).sum()\n\n\nfor i in range(epoch):\n\n loss_total = 0.0\n loss_test_total = 0.0\n\n accuracy_train = 0.0\n accuracy_test = 0.0\n\n ## TRAIN\n for idx, dp in enumerate(tqdm(train_loader)):\n # THIS MEANS ALL THE PARAMETERS ARE IN TRAIN MODE\n model.train()\n\n # NOTE there is one bug in this train loop\n # TODO\n optimizer.zero_grad() # This was missing (the bug)\n\n image, label = dp\n\n input_matrix = image.to(device) # Another bug(.to(device))\n\n label_network_prediction = model(input_matrix)\n label_ground_truth = label.to(device) # (.to(device))\n\n loss = loss_func(label_network_prediction, label_ground_truth.long())\n\n # accuracy\n accuracy = accuracy_measure(label_network_prediction, label_ground_truth)\n\n accuracy_train += accuracy\n\n loss.backward()\n optimizer.step()\n\n # writer.add_scalar('training loss',\n # \t\t\t\t loss.item(),\n # \t\t\t\t i * len(train_loader) + idx)\n # writer.add_scalar('training accuracy',\n # \t\t\t\t accuracy.item(),\n # \t\t\t\t i * len(train_loader) + idx)\n\n loss_total += loss\n\n ## TEST\n\n for idx_test, dp_test in enumerate(tqdm(test_loader)):\n # THIS MEANS ALL THE PARAMETERS ARE IN EVAL MODE\n\n optimizer.zero_grad()\n\n with torch.no_grad():\n\n image_test, label_test = dp_test\n\n input_matrix_test = image_test.to(device)\n\n label_network_prediction_test = model(input_matrix_test)\n label_ground_truth_test = label_test.to(device)\n\n loss_test = loss_func(\n label_network_prediction_test, label_ground_truth_test.long()\n )\n accuracy_t = accuracy_measure(\n label_network_prediction_test, label_ground_truth_test\n )\n\n accuracy_test += accuracy_t\n\n # writer.add_scalar('validation loss',\n # \t\t\t\t loss_test.item(),\n # \t\t\t\t i * len(test_loader) + idx_test)\n # writer.add_scalar('validation accuracy',\n # \t\t\t\t accuracy_t.item(),\n # \t\t\t\t i * len(test_loader) + idx_test)\n\n loss_test_total += loss_test\n\n print(\"epoch done: \", i)\n # torch.save([model], saver_path + 'model_1_a.pth')\n # print('Train Loss :',loss_total.item()/len(train_loader))\n # print('Validation Loss :', loss_test_total.item()/len(test_loader))\n print(\"accuracy train\", accuracy_train.item() / len(train_loader))\n print(\"accuracy test\", accuracy_test.item() / len(test_loader))\n\ntorch.save(model.state_dict(), saver_path + \"model_1_c.pth\")\n","sub_path":"Machine Learning in Graphics and Vision/Assignment_03/task_3_1_c.py","file_name":"task_3_1_c.py","file_ext":"py","file_size_in_byte":5493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"104621800","text":"from sklearn.metrics import accuracy_score,f1_score,recall_score,precision_score,confusion_matrix,matthews_corrcoef\r\nfrom helpers import *\r\nfrom keras.layers.core import Activation, Flatten\r\nfrom keras.layers import Dense, Dropout, Input, merge\r\nfrom keras.layers.convolutional import Convolution1D, MaxPooling1D\r\nfrom keras.constraints import maxnorm\r\nfrom sklearn.metrics import roc_auc_score\r\nfrom keras.models import Model\r\nfrom keras import backend as K\r\nfrom keras.engine.topology import Layer\r\nfrom keras import activations, initializers, regularizers, constraints\r\n\r\n\r\n# Variable\r\nmaxlen = 100\r\nbatch_size = 10\r\nepochs = 25\r\nseq_rows, seq_cols =200,20\r\nnum_classes = 2\r\nnp.set_printoptions(threshold=np.inf)\r\n\r\n#build Attention model\r\nclass Attention(Layer):\r\n\r\n\tdef __init__(self,hidden,init='glorot_uniform',activation='linear',W_regularizer=None,b_regularizer=None,W_constraint=None,**kwargs):\r\n\t self.init = initializers.get(init)\r\n\t self.activation = activations.get(activation)\r\n\t self.W_regularizer = regularizers.get(W_regularizer)\r\n\t self.b_regularizer = regularizers.get(b_regularizer)\r\n\t self.W_constraint = constraints.get(W_constraint)\r\n\t self.hidden=hidden\r\n\t super(Attention, self).__init__(**kwargs)\r\n\r\n\tdef build(self, input_shape):\r\n\t input_dim = input_shape[-1]\r\n\t self.input_length = input_shape[1]\r\n\t self.W0 = self.add_weight(name ='{}_W1'.format(self.name), shape = (input_dim, self.hidden), initializer = 'glorot_uniform', trainable=True) # Keras 2 API\r\n\t self.W = self.add_weight( name ='{}_W'.format(self.name), shape = (self.hidden, 1), initializer = 'glorot_uniform', trainable=True)\r\n\t self.b0 = K.zeros((self.hidden,), name='{}_b0'.format(self.name))\r\n\t self.b = K.zeros((1,), name='{}_b'.format(self.name))\r\n\t self.trainable_weights = [self.W0,self.W,self.b,self.b0]\r\n\r\n\t self.regularizers = []\r\n\t if self.W_regularizer:\r\n\t self.W_regularizer.set_param(self.W)\r\n\t self.regularizers.append(self.W_regularizer)\r\n\r\n\t if self.b_regularizer:\r\n\t self.b_regularizer.set_param(self.b)\r\n\t self.regularizers.append(self.b_regularizer)\r\n\r\n\t self.constraints = {}\r\n\t if self.W_constraint:\r\n\t self.constraints[self.W0] = self.W_constraint\r\n\t self.constraints[self.W] = self.W_constraint\r\n\r\n\t super(Attention, self).build(input_shape)\r\n\r\n\tdef call(self,x,mask=None):\r\n\t attmap = self.activation(K.dot(x, self.W0)+self.b0)\r\n\t attmap = K.dot(attmap, self.W) + self.b\r\n\t attmap = K.reshape(attmap, (-1, self.input_length)) # Softmax needs one dimension\r\n\t attmap = K.softmax(attmap)\r\n\t dense_representation = K.batch_dot(attmap, x, axes=(1, 1))\r\n\t out = K.concatenate([dense_representation, attmap]) # Output the attention maps but do not pass it to the next layer by DIY flatten layer\r\n\t return out\r\n\r\n\r\n\tdef compute_output_shape(self, input_shape):\r\n\t return (input_shape[0], input_shape[-1] + input_shape[1])\r\n\r\n\tdef get_config(self):\r\n\t config = {'init': 'glorot_uniform',\r\n\t 'activation': self.activation.__name__,\r\n\t 'W_constraint': self.W_constraint.get_config() if self.W_constraint else None,\r\n\t 'W_regularizer': self.W_regularizer.get_config() if self.W_regularizer else None,\r\n\t 'b_regularizer': self.b_regularizer.get_config() if self.b_regularizer else None,\r\n\t 'hidden': self.hidden if self.hidden else None}\r\n\t base_config = super(Attention, self).get_config()\r\n\t return dict(list(base_config.items()) + list(config.items()))\r\n\r\n\r\nclass attention_flatten(Layer): # Based on the source code of Keras flatten\r\n\tdef __init__(self, keep_dim, **kwargs):\r\n\t self.keep_dim = keep_dim\r\n\t super(attention_flatten, self).__init__(**kwargs)\r\n\r\n\tdef compute_output_shape(self, input_shape):\r\n\t if not all(input_shape[1:]):\r\n\t raise Exception('The shape of the input to \"Flatten\" '\r\n\t 'is not fully defined '\r\n\t '(got ' + str(input_shape[1:]) + '. '\r\n\t 'Make sure to pass a complete \"input_shape\" '\r\n\t 'or \"batch_input_shape\" argument to the first '\r\n\t 'layer in your model.')\r\n\t return (input_shape[0], self.keep_dim) # Remove the attention map\r\n\r\n\tdef call(self, x, mask=None):\r\n\t x=x[:,:self.keep_dim]\r\n\t return K.batch_flatten(x)\r\n\r\ndef set_up_model_up():\r\n\tprint('building model')\r\n\r\n\tseq_input_shape = (200,20)\r\n\tnb_filter = 64\r\n\tfilter_length = 6\r\n\t# input_shape = (200,20,1)\r\n\tattentionhidden = 256\r\n\r\n\tseq_input = Input(shape = seq_input_shape, name = 'seq_input')\r\n\tconvul1 = Convolution1D(filters = nb_filter,\r\n \t kernel_size = filter_length,\r\n \t padding = 'valid',\r\n \t activation = 'relu',\r\n \t kernel_constraint = maxnorm(3),\r\n \t subsample_length = 1)\r\n\r\n\tpool_ma1 = MaxPooling1D(pool_size = 3)\r\n\tdropout1 = Dropout(0.6)\r\n\tdropout2 = Dropout(0.3)\r\n\tdecoder = Attention(hidden = attentionhidden, activation = 'linear')\r\n\tdense1 = Dense(2)\r\n\tdense2 = Dense(2)\r\n\r\n\toutput_1 = pool_ma1(convul1(seq_input))\r\n\toutput_2 = dropout1(output_1)\r\n\tatt_decoder = decoder(output_2)\r\n\toutput_3 = attention_flatten(output_2._keras_shape[2])(att_decoder)\r\n\r\n\toutput_4 = dense1(dropout2(Flatten()(output_2)))\r\n\tall_outp = merge([output_3, output_4], mode = 'concat')\r\n\toutput_5 = dense2(all_outp)\r\n\toutput_f = Activation('sigmoid')(output_5)\r\n\r\n\tmodel = Model(inputs = seq_input, outputs = output_f)\r\n\tmodel.compile(loss = 'binary_crossentropy', optimizer = 'adam', metrics = ['accuracy'])\r\n\r\n\tprint (model.summary())\r\n\treturn model\r\n\r\nmodel = set_up_model_up()\r\n\r\nmodel.load_weights('./models_weights/ACNNT3-1.h5')\r\n# model.load_weights('./models_weights/ACNNT3-2.h5')\r\n\r\nprint('Loading test data...')\r\npos_Test = readFile(\"./data/pos_independent_test_dataset.txt\",maxlen)\r\nneg_Test = readFile(\"./data/neg_independent_test_dataset.txt\",maxlen)\r\n\r\n# pos_Test = readFile(\"./data/P.syringae_nr_effector.txt\",maxlen)\r\n# neg_Test = readFile(\"./data/neg_P.syringae_test_dataset.txt\",maxlen)\r\n\r\nprint('Generating labels and features...')\r\n(y_test, x_test)=createTestData(pos_Test,neg_Test,\"Onehot\")\r\nx_test = x_test.reshape(x_test.shape[0],seq_rows,seq_cols)\r\n\r\n\r\n\r\nprint('Evaluating the model')\r\npredicted_Probability = model.predict(x_test)\r\n# prediction = model.predict_class(x_test)\r\nprediction = model.predict(x_test)\r\nprediction=np.argmax(prediction,axis=1)\r\n\r\n\r\nprint('Showing the confusion matrix')\r\ncm=confusion_matrix(y_test,prediction)\r\nprint(cm)\r\nprint(\"ACC: %f \"%accuracy_score(y_test,prediction))\r\nprint(\"F1: %f \"%f1_score(y_test,prediction))\r\nprint(\"Recall: %f \"%recall_score(y_test,prediction))\r\nprint(\"Pre: %f \"%precision_score(y_test,prediction))\r\nprint(\"MCC: %f \"%matthews_corrcoef(y_test,prediction))\r\nprint(\"AUC: %f \"%roc_auc_score(y_test,prediction))\r\n# print('Plotting the ROC curve...')\r\n# plotROC(y_test,predicted_Probability[:,1])\r\n\r\n\r\nprint('saving the model...')\r\nmodel.save_weights('./models_weights/model_weights.h5')\r\nwith open('./models_weights/json_model.json', 'w') as f:\r\n f.write(model.to_json())\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"ourmodel_test.py","file_name":"ourmodel_test.py","file_ext":"py","file_size_in_byte":7271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"182141264","text":"import sqlite3\n\nconnection = sqlite3.connect(\"recipes.db\")\ncursor = connection.cursor()\ncursor.execute(\"SELECT Site.lat, Site.long FROM Site;\")\nresults = cursor.fetchall()\nfor r in results:\n print(r)\ncursor.close()\nconnection.close()","sub_path":"login.py","file_name":"login.py","file_ext":"py","file_size_in_byte":236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"314502974","text":"#----------------------------------------------------------\n# File hello.py\n#----------------------------------------------------------\nimport bpy\n\n#\n# Menu in window region, object context\n#\nclass ObjectPanel(bpy.types.Panel):\n bl_label = \"Maelstrom II Edit\"\n bl_space_type = \"PROPERTIES\"\n bl_region_type = \"WINDOW\"\n bl_context = \"object\"\n \n def draw(self, context):\n self.layout.operator(\"maelstrom2.edit\", text='unhide hidden').country = \"France\"\n self.layout.operator(\"maelstrom2.deletefontobjects\", text='deleteFontObjects').country = \"France\"\n self.layout.operator(\"maelstrom2.seq_2_text\", text='sequence to text').country = \"France\"\n \ndef unhideHidden():\n for obj in bpy.data.objects:\n print(\"Unhiding \",obj)\n obj.hide = False\n obj.hide_render = False\n\ndef deleteFontObjects():\n print(\"Setting context to OBJECT\")\n bpy.ops.object.mode_set(mode = 'OBJECT')\n print(\"Selecting all FONT objects\")\n bpy.ops.object.select_by_type(type='FONT')\n print(\"Deleting selected\")\n bpy.ops.object.delete(use_global=False)\n print(\"Removing Meshes\")\n for item in bpy.data.meshes:\n print(\"Removing MESH for item:\",item)\n try:\n bpy.data.meshes.remove(item)\n except:\n print (\"item mesh has owner:\",item)\n\ndef seq_to_text(seq_all):\n print(\"seq_to_text\")\n m = bpy.data.materials.new(\"test\")\n m.use_shadeless = True\n# seq_all = scenes['Scene'].sequence_editor.sequences_all\n y = 0\n t_o = []\n seq_all_len = len(seq_all)\n print(\"seq_all_len\",seq_all_len)\n# textScale = 1.0/((seq_all_len - 1)*10.0)\n textScale = 1.0/((seq_all_len - 1)*5.0)\n print(\"textScale:\",textScale)\n for s in seq_all:\n s_n = s.name\n if \"transform\" in s_n.lower():\n continue\n if \"wipe\" in s_n.lower():\n continue\n if s.mute == True:\n continue\n #bpy.ops.object.text_add(radius=1.0, view_align=False, enter_editmode=False, location=(s.frame_final_start*textScale*2, s.channel, -s.channel), rotation=(0, 0, 0))\n bpy.ops.object.text_add(radius=1.0, view_align=False, enter_editmode=False, location=(0, s.channel, 0), rotation=(0, 0, 0))\n ob = bpy.context.object\n print(\"ob\",ob)\n # set text resolution to lowest\n ob.data.resolution_u = 1\n #assign material\n ob.data.materials.append(m)\n ob.name = s_n\n t_o.append(ob)\n tcu = ob.data\n tcu.body = s_n\n print(\"s_n\",s_n)\n if s_n == 'Scene':\n print (\"s_n = 'Scene'\")\n ob.hide = True\n ob.hide_render = True\n else:\n print (\"s_n != 'Scene'\")\n y += 1\n return(t_o)\n# end of def seq_to_text(seq_all):\n\nclass OBJECT_OT_unhideHiddenButton(bpy.types.Operator):\n bl_idname = \"maelstrom2.edit\"\n bl_label = \"Say Hello\"\n country = bpy.props.StringProperty()\n \n def execute(self, context):\n print(\"unhideHidden()\")\n unhideHidden()\n# deleteFontObjects()\n return{'FINISHED'} \n\n\nclass OBJECT_OT_deleteFontObjects(bpy.types.Operator):\n bl_idname = \"maelstrom2.deletefontobjects\"\n bl_label = \"deleteFontObjects\"\n country = bpy.props.StringProperty()\n \n def execute(self, context):\n print(\"deleteFontObjects()\")\n deleteFontObjects()\n return{'FINISHED'} \n\nclass OBJECT_OT_seq_2_text(bpy.types.Operator):\n bl_idname = \"maelstrom2.seq_2_text\"\n bl_label = \"seq_2_text\"\n country = bpy.props.StringProperty()\n \n def execute(self, context):\n print(\"seq_2_text()\")\n # convert all sequences to text objects\n seq_all = bpy.data.scenes[\"Scene\"].sequence_editor.sequences_all\n t_o_a = seq_to_text(seq_all)\n return{'FINISHED'} \n\n#\tRegistration\n# All panels and operators must be registered with Blender; otherwise\n# they do not show up. The simplest way to register everything in the\n# file is with a call to bpy.utils.register_module(__name__).\n#\n \nbpy.utils.register_module(__name__)\n#bpy.utils.register_class(OBJECT_OT_unhideHiddenButton)\n#bpy.utils.register_class(OBJECT_OT_deleteFontObjects)\n#bpy.utils.unregister_module(__name__)","sub_path":"python/buttons_v007.py","file_name":"buttons_v007.py","file_ext":"py","file_size_in_byte":4072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"16238199","text":"import wae\nimport argparse\nimport config\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--experiment\",\n help='Default experiment configs to use: dsprites/fading_squares/celebA_mini/celebA_random/celebA_deterministic')\nparser.add_argument(\"--dataset\",\n help='Dataset to train on: dsprites/celebA/celebA_mini/fading_squares')\nparser.add_argument(\"--z_dim\", help='latent space dimensionality', type=int)\nparser.add_argument(\"--lambda_imq\", help='Lambda for WAE penalty', type=float)\nparser.add_argument(\"--experiment_path\",\n help=\"Relative path to where this experiment should save results\")\nparser.add_argument(\"--encoder_distribution\",\n help=\"Encoder distribution: deterministic/gaussian/uniform\")\nparser.add_argument(\"--z_prior\",\n help=\"Prior distribution over latent space: gaussian/uniform\")\nparser.add_argument(\"--loss_reconstruction\",\n help=\"Image reconstruction loss: bernoulli/L2_squared\")\nparser.add_argument(\"--loss_regulariser\",\n help=\"Model type: VAE/beta_VAE/WAE_MMD\")\nparser.add_argument(\"--beta\", type=float,\n help=\"beta parameter for beta_VAE\")\nparser.add_argument(\"--disentanglement_metric\", type=bool,\n help=\"Calculate disentanglement metric\")\nparser.add_argument(\"--make_pictures_every\", type=int,\n help=\"How often to plot random samples and reconstructions\")\nparser.add_argument(\"--save_every\", type=int,\n help=\"How often to save the model\")\nparser.add_argument(\"--batch_size\", type=int,\n help=\"Batch size. Default 100\")\nparser.add_argument(\"--encoder_architecture\",\n help=\"Architecture of encoder: FC_dsprites/small_convolutional_celebA\")\nparser.add_argument(\"--decoder_architecture\",\n help=\"Architecture of decoder: FC_dsprites/small_convolutional_celebA\")\nparser.add_argument(\"--z_logvar_regularisation\",\n help=\"Regularisation on log-variances: None/L1/L2_squared\")\nparser.add_argument(\"--lambda_logvar_regularisation\", type=float,\n help=\"Coefficient of logvariance regularisation\")\nparser.add_argument(\"--plot_losses\",\n help=\"Plot losses and least-gaussian-subspace: True/False:\")\nparser.add_argument(\"--adversarial_cost_n_filters\", type=int,\n help=\"Number of convolutional filters to use for adversarial cost\")\n\nFLAGS = parser.parse_args()\n\nif __name__ == \"__main__\":\n if FLAGS.experiment == 'dsprites':\n opts = config.dsprites_opts\n elif FLAGS.experiment == 'fading_squares':\n opts = config.fading_squares_opts\n elif FLAGS.experiment == 'celebA_random':\n opts = config.celebA_random_opts\n elif FLAGS.experiment == 'celebA_deterministic':\n opts = config.celebA_deterministic_opts\n elif FLAGS.experiment == 'celebA_mini':\n opts = config.celebA_mini_opts\n elif FLAGS.experiment == 'celebA_dcgan_deterministic':\n opts = config.celebA_dcgan_deterministic_opts\n elif FLAGS.experiment == 'grassli_VAE':\n opts = config.grassli_VAE_opts\n elif FLAGS.experiment == 'grassli_WAE':\n opts = config.grassli_WAE_opts\n elif FLAGS.experiment == 'celebA_dcgan_adv':\n opts = config.celebA_dcgan_adv_cost_opts\n else:\n assert False, \"Invalid experiment defaults\"\n\n if FLAGS.dataset:\n opts['dataset'] = FLAGS.dataset\n if FLAGS.z_dim:\n opts['z_dim'] = FLAGS.z_dim\n if FLAGS.lambda_imq:\n opts['lambda_imq'] = FLAGS.lambda_imq\n if FLAGS.experiment_path:\n opts['experiment_path'] = FLAGS.experiment_path\n if FLAGS.encoder_distribution:\n opts['encoder_distribution'] = FLAGS.encoder_distribution\n if FLAGS.z_prior:\n opts['z_prior'] = FLAGS.z_prior\n if FLAGS.loss_reconstruction:\n opts['loss_reconstruction'] = FLAGS.loss_reconstruction\n if FLAGS.disentanglement_metric:\n opts['disentanglement_metric'] = FLAGS.disentanglement_metric\n if FLAGS.make_pictures_every:\n opts['make_pictures_every'] = FLAGS.make_pictures_every\n if FLAGS.save_every:\n opts['save_every'] = FLAGS.save_every\n if FLAGS.batch_size:\n opts['batch_size'] = FLAGS.batch_size\n if FLAGS.encoder_architecture:\n opts['encoder_architecture'] = FLAGS.encoder_architecture\n if FLAGS.decoder_architecture:\n opts['decoder_architecture'] = FLAGS.decoder_architecture\n if FLAGS.z_logvar_regularisation:\n if FLAGS.z_logvar_regularisation == \"None\":\n opts['z_logvar_regularisation'] = None\n else:\n opts['z_logvar_regularisation'] = FLAGS.z_logvar_regularisation\n if FLAGS.lambda_logvar_regularisation:\n opts['lambda_logvar_regularisation'] = FLAGS.lambda_logvar_regularisation\n if FLAGS.loss_regulariser:\n opts['loss_regulariser'] = FLAGS.loss_regulariser\n if FLAGS.beta:\n opts['beta'] = FLAGS.beta\n if FLAGS.plot_losses:\n if FLAGS.plot_losses == \"True\":\n opts['plot_losses'] = True\n elif FLAGS.plot_losses == \"False\":\n opts['plot_losses'] = False\n if FLAGS.adversarial_cost_n_filters:\n opts['adversarial_cost_n_filters'] = FLAGS.adversarial_cost_n_filters\n\n\n model = wae.Model(opts)\n model.train()\n","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":5356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"536001053","text":"from nltk.tokenize import sent_tokenize, word_tokenize\nfrom collections import Counter\nimport pandas as pd\nfrom nltk.corpus import stopwords\nimport nltk\n\nFILENAME = 'movie-pang02.csv'\nclass NaiveBayes(object):\n\n def train(self, csv_file):\n data = pd.read_csv(csv_file)\n # data is a pandas DataFrame\n\n data_pos = data[data['class'] == 'Pos']\n data_neg = data[data['class'] == 'Neg']\n\n positive_words = []\n negative_words = []\n\n for text in data_pos['text']:\n sentences = sent_tokenize(text)\n for sentence in sentences:\n words = word_tokenize(sentence)\n positive_words.extend(words)\n for text in data_neg['text']:\n sentences = sent_tokenize(text)\n for sentence in sentences:\n words = word_tokenize(sentence)\n negative_words.extend(words)\n\n stop_words = set(nltk.corpus.stopwords.words('english'))\n filtered_pos = [w for w in positive_words if w not in stop_words]\n filtered_neg = [w for w in negative_words if w not in stop_words]\n\n #Counters\n self.positiveCount = Counter(filtered_pos)\n self.negativeCount = Counter(filtered_neg)\n\n total_positive_words = len(positive_words)\n total_negative_words = len(negative_words)\n total_words = total_negative_words + total_positive_words\n self.total_positive_prob = total_positive_words/total_words\n self.total_negative_prob = total_negative_words/total_words\n\n for key in self.positiveCount:\n self.positiveCount[key] = self.positiveCount[key]/total_positive_words\n for key in self.negativeCount:\n self.negativeCount[key] = self.negativeCount[key]/total_negative_words\n","sub_path":"make.py","file_name":"make.py","file_ext":"py","file_size_in_byte":1784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"299981710","text":"from datetime import datetime\nimport re\nfrom django.utils import timezone\nfrom celery.utils.log import get_task_logger\nfrom celery.contrib import rdb\nfrom django.core.files.storage import default_storage as storage\nfrom uuid import uuid4\n\nfrom celery.decorators import task\nfrom crawler.celery import app\nfrom crawler.constants import STATES, RESOURCE_TYPES\n\n# Scrapers \nfrom .scrapers import HTMLScraper\n\nlogger = get_task_logger(__name__)\n\ndef save_resource(article, resource, use_tdir=True, uniq_fn=True):\n fn = resource['filename']\n content = resource['content']\n path = article.resource_path(fn, use_tdir=use_tdir, uniq_fn=uniq_fn)\n f = storage.open(path)\n f.write(content)\n f.close()\n resource['hosted_url'] = path\n return resource\n\n@task\ndef delete_resource_dir(path):\n storage.deletedir(path)\n\ndef delete_articles_resources(articles):\n delete_resource_dir.map(map(lambda a: a.resources_dir(), articles))\n\ndef scrape_article_resources(url):\n scraper = HTMLScraper(url)\n html_content = scraper.html_content()\n html_resources = scraper.static_resources()\n css_resources = scraper.css_resources()\n # logger.info(\"sraped article\")\n return [ html_content, html_resources, css_resources ]\n\ndef as_hosted_content(content, resources):\n def multiple_replace(txt, _dict):\n rx = re.compile('|'.join(map(re.escape, _dict)))\n def one_xlat(match):\n return _dict[match.group(0)]\n return rx.sub(one_xlat, txt)\n\n content = content.decode()\n if len(resources) > 0:\n mapped_urls = {\n resource['url']: mediaurl(resource['hosted_url']) for resource in resources\n }\n content = multiple_replace(content, mapped_urls)\n return bytes(content, 'utf-8')\n\ndef process_css(css, resources):\n content = css['content']\n resources_dict = resources[css['url']]\n resources_list = list()\n for rtype, sub_resources in resources_dict.items():\n sub_resources_list += map(\n lambda res: save_resource(article, res, rtype=rtype),\n sub_resources\n )\n return as_hosted_content(content, resources_list)\n\ndef save_resources(article, resources_dict, css_resources):\n article_resources = list()\n for ressource_type, resources in resources_dict.items():\n for resource_dict in resources:\n if rtype == RESOURCE_TYPES.STYLE:\n resource_dict['content'] = process_css(resource_dict, css_resources)\n article_resources.append(\n save_resource(article, resource_dict, rtype=rtype)\n )\n return article_resources\n\ndef crawl_article_resources(article):\n [ html_content, resources, css_resources ] = scrape_article_resources(\n article.url\n )\n resources = save_resources(article, resources, css_resources)\n save_resource(\n article,\n {\n 'filename': 'index.html',\n 'content': as_hoted_content(html_content, resources),\n },\n use_tdir=False,\n uniq_fn=False\n )\n article.preservation_state = STATES.PRESERVATION.STORED\n article.save()\n return pk\n\n@task\ndef crawl_resources(ids):\n logger.info('recieved ids %s' % ids)\n from crawler.utils import pickattr\n from crawler.core import tasks_utils\n from crawler.constants import STATES\n articles = tasks_utils.articles(\n pickattr(tasks_utils.should_be_preserved(ids), 'pk')\n )\n articles.update(preservation_state=STATES.PRESERVATION.PRESERVING)\n map(crawl_article_resources, articles)\n return ids\n\n","sub_path":"crawler/crawler/storing/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":3551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"438306444","text":"import sys\n\nread = sys.stdin.readline\nINF = int(1e9)\n\ndef bellman() : \n\n dist[1] = 0\n isCycle = False\n for i in range(1,N+1):\n for j in range(M) :\n f = adj[j][0]\n t = adj[j][1]\n c = adj[j][2]\n\n if dist[f] == INF : continue\n if dist[t] > dist[f] + c :\n if i == N : \n isCycle = True\n dist[t] = dist[f] + c \n return isCycle\n\nN,M = map(int,read().split())\ndist = [INF for _ in range(N+1)]\nadj = []\nfor _ in range(M) :\n x,y,c = map(int,read().split())\n adj.append((x,y,c))\n\nif bellman() :\n print(-1)\nelse :\n for i in range(2,N+1) :\n if dist[i] >= INF : \n print(-1)\n else :\n print(dist[i])\n","sub_path":"BOJ/25_최단경로/11657_타임머신.py","file_name":"11657_타임머신.py","file_ext":"py","file_size_in_byte":756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"250201422","text":"#!/usr/bin/env python\n# encoding: utf-8\n\n\"\"\"\nGiven an integer array nums, return the number of range sums that lie in [lower, upper] inclusive.\nRange sum S(i, j) is defined as the sum of the elements in nums between indices i and j (i ≤ j), inclusive.\n\nNote:\nA naive algorithm of O(n2) is trivial. You MUST do better than that.\n\nExample:\nGiven nums = [-2, 5, -1], lower = -2, upper = 2,\nReturn 3.\nThe three ranges are : [0, 0], [2, 2], [0, 2] and their respective sums are: -2, -1, 2.\n\"\"\"\n\n\n# T(n) = T(n/2) + nlgn = O(n(lgn^2))\nclass Solution(object):\n def countRangeSum(self, nums, lower, upper):\n \"\"\"\n :type nums: List[int]\n :type lower: int\n :type upper: int\n :rtype: int\n \"\"\"\n if not nums:\n return 0\n if len(nums) == 1:\n return 1 if lower <= nums[0] <= upper else 0\n result = 0\n mid = len(nums) / 2\n rightSums = []\n sum = 0\n for i in xrange(mid, len(nums)):\n sum += nums[i]\n rightSums.append(sum)\n rightSums.sort()\n sum = 0\n for i in xrange(mid - 1, -1, -1):\n sum += nums[i]\n l = bisect.bisect_left(rightSums, lower - sum)\n r = bisect.bisect(rightSums, upper - sum)\n result += r - l\n return result + self.countRangeSum(nums[:mid], lower, upper) + self.countRangeSum(nums[mid:], lower, upper)\n\n","sub_path":"Python/327-CountOfRangeSum/countRangeSum.py","file_name":"countRangeSum.py","file_ext":"py","file_size_in_byte":1409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"568387110","text":"import matplotlib.pyplot as plt\nimport numpy as np\nfrom sys import argv\n\nblock_convo = np.zeros((137,))\nfull_convo = np.zeros((137,))\n\nblock_list = ['task001_run001_conv001.txt', 'task001_run001_conv004.txt', 'task001_run001_conv005.txt']\nfull_list = ['task001_run001_conv001.txt', 'task001_run001_conv002.txt', 'task001_run001_conv003.txt', 'task001_run001_conv004.txt', 'task001_run001_conv005.txt', 'task001_run001_conv006.txt']\n\nfor i in block_list:\n\tblock_convo = block_convo + np.loadtxt('../../../data/convo/' + i)\n\nfor i in full_list:\n\tfull_convo = full_convo + np.loadtxt('../../../data/convo/' + i)\n\nplt.figure(0)\nplt.plot(block_convo)\nplt.title(\"Combination of block convo response\")\nplt.savefig('../../../data/convo/combine_block_convo.png')\n\nplt.figure(1)\nplt.plot(full_convo)\nplt.title(\"Combination of all convo response\")\nplt.savefig('../../../data/convo/combine_all_convo.png')\nplt.show()","sub_path":"code/utils/conv_response/combine_convo.py","file_name":"combine_convo.py","file_ext":"py","file_size_in_byte":904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"466033342","text":"from time import sleep\nfrom ina219 import INA219\n\nina = INA219(shunt_ohms=0.1,\n max_expected_amps = 0.2,\n address=0x40)\n\nina.configure(voltage_range=ina.RANGE_32V,\n gain=ina.GAIN_AUTO,\n bus_adc=ina.ADC_128SAMP,\n shunt_adc=ina.ADC_128SAMP)\n\n\ndef get_readings():\n v = ina.voltage()\n i = ina.current()\n p = ina.power()\n# print('{0:0.1f}V\\n{1:0.1f}mA'.format(v, i))\n# print('\\n{0:0.1f} Watts'.format(p/1000))\n return i, v, p\n","sub_path":"scripts/measure.py","file_name":"measure.py","file_ext":"py","file_size_in_byte":502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"317582793","text":"# -*- coding: utf-8 -*-\nimport scrapy\nfrom scrapy001.items import Scrapy001Item\n\n\nclass QsbkSpiderSpider(scrapy.Spider):\n name = 'qsbk_spider'\n allowed_domains = ['qiushibaike.com']\n start_urls = ['https://www.qiushibaike.com/text/page/1/']\n base_domain = 'https://www.qiushibaike.com'\n def parse(self, response):\n\n duanzis = response.xpath('//div[@id=\"content-left\"]/div')\n for duanzi in duanzis:\n # 段子作者\n author = duanzi.xpath('.//div[@class=\"author clearfix\"]//a[2]/h2/text() | .//span/h2/text()').get().strip()\n # 段子内容\n content = duanzi.xpath('.//div[@class=\"content\"]//span[1]').get()\n content = content.replace('', '').replace('', '').replace('
', '').replace('', '').strip()\n item = Scrapy001Item(author = author, content = content)\n yield item\n next_url = response.xpath('//ul[@class=\"pagination\"]/li[last()]/a/@href').get()\n if next_url:\n yield scrapy.Request(self.base_domain+next_url, callback=self.parse)\n else:\n return\n","sub_path":"scrapy001/spiders/qsbk_spider.py","file_name":"qsbk_spider.py","file_ext":"py","file_size_in_byte":1117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"285816094","text":"import time\n\nfrom .helpers import audience\nfrom .helpers import experiment\nfrom . import version\n\n\n# Attribute mapping format\nATTRIBUTE_PARAM_FORMAT = '{segment_prefix}{segment_id}'\n\n# Experiment mapping format\nEXPERIMENT_PARAM_FORMAT = '{experiment_prefix}{experiment_id}'\n\n# Event API format\nOFFLINE_API_PATH = 'https://{project_id}.log.optimizely.com/event'\n\n\nclass Params(object):\n ACCOUNT_ID = 'd'\n PROJECT_ID = 'a'\n EXPERIMENT_PREFIX = 'x'\n GOAL_ID = 'g'\n GOAL_NAME = 'n'\n END_USER_ID = 'u'\n EVENT_VALUE = 'v'\n SEGMENT_PREFIX = 's'\n SOURCE = 'src'\n TIME = 'time'\n\n\nclass Event(object):\n \"\"\" Representation of an event which can be sent to the Optimizely logging endpoint. \"\"\"\n\n def __init__(self, params):\n self.params = params\n\n def get_url(self):\n \"\"\" Get URL for sending impression/conversion event.\n\n Returns:\n URL for the event API.\n \"\"\"\n\n return OFFLINE_API_PATH.format(project_id=self.params[Params.PROJECT_ID])\n\n def get_params(self):\n \"\"\" Get params to be sent along to the event endpoint.\n\n Returns:\n Dict of params representing the impression/conversion event.\n \"\"\"\n\n return self.params\n\n\nclass EventBuilder(object):\n \"\"\" Class which encapsulates methods to build events for tracking impressions and conversions. \"\"\"\n\n def __init__(self, config, bucketer):\n self.config = config\n self.bucketer = bucketer\n self.params = {}\n\n def _add_project_id(self):\n \"\"\" Add project ID to the event. \"\"\"\n\n self.params[Params.PROJECT_ID] = self.config.get_project_id()\n\n def _add_account_id(self):\n \"\"\" Add account ID to the event. \"\"\"\n\n self.params[Params.ACCOUNT_ID] = self.config.get_account_id()\n\n def _add_user_id(self, user_id):\n \"\"\" Add user ID to the event. \"\"\"\n\n self.params[Params.END_USER_ID] = user_id\n\n def _add_attributes(self, attributes):\n \"\"\" Add attribute(s) information to the event.\n\n Args:\n attributes: Dict representing user attributes and values which need to be recorded.\n \"\"\"\n\n if not attributes:\n return\n\n for attribute_key in list(attributes.keys()):\n attribute_value = attributes[attribute_key]\n # Omit falsy attribute values\n if attribute_value:\n segment_id = self.config.get_segment_id(attribute_key)\n if segment_id:\n self.params[ATTRIBUTE_PARAM_FORMAT.format(\n segment_prefix=Params.SEGMENT_PREFIX, segment_id=segment_id)] = attribute_value\n\n def _add_source(self):\n \"\"\" Add source information to the event. \"\"\"\n\n self.params[Params.SOURCE] = 'python-sdk-{version}'.format(version=version.__version__)\n\n def _add_time(self):\n \"\"\" Add time information to the event. \"\"\"\n\n self.params[Params.TIME] = int(time.time())\n\n def _add_common_params(self, user_id, attributes):\n \"\"\" Add params which are used same in both conversion and impression events.\n\n Args:\n user_id: ID for user.\n attributes: Dict representing user attributes and values which need to be recorded.\n \"\"\"\n\n self._add_project_id()\n self._add_account_id()\n self._add_user_id(user_id)\n self._add_attributes(attributes)\n self._add_source()\n self._add_time()\n\n def _add_impression_goal(self, experiment_key):\n \"\"\" Add impression goal information to the event.\n\n Args:\n experiment_key: Experiment which is being activated.\n \"\"\"\n\n # For tracking impressions, goal ID is set equal to experiment ID of experiment being activated\n self.params[Params.GOAL_ID] = self.config.get_experiment_id(experiment_key)\n self.params[Params.GOAL_NAME] = 'visitor-event'\n\n def _add_experiment(self, experiment_key, variation_id):\n \"\"\" Add experiment to variation mapping to the impression event.\n\n Args:\n experiment_key: Experiment which is being activated.\n variation_id: ID for variation which would be presented to user.\n \"\"\"\n\n experiment_id = self.config.get_experiment_id(experiment_key)\n self.params[EXPERIMENT_PARAM_FORMAT.format(experiment_prefix=Params.EXPERIMENT_PREFIX,\n experiment_id=experiment_id)] = variation_id\n\n def _add_experiment_variation_params(self, event_key, user_id, valid_experiments):\n \"\"\" Maps experiment and corresponding variation as parameters to be used in the event tracking call.\n\n Args:\n event_key: Goal key representing the event which needs to be recorded.\n user_id: ID for user.\n valid_experiments: List of tuples representing valid experiments for the event.\n \"\"\"\n\n for experiment in valid_experiments:\n variation_id = self.bucketer.bucket(experiment[1], user_id)\n if variation_id:\n self.params[EXPERIMENT_PARAM_FORMAT.format(experiment_prefix=Params.EXPERIMENT_PREFIX,\n experiment_id=experiment[0])] = variation_id\n\n def _add_conversion_goal(self, event_key, event_value):\n \"\"\" Add conversion goal information to the event.\n\n Args:\n event_key: Goal key representing the event which needs to be recorded.\n event_value: Value associated with the event. Can be used to represent revenue in cents.\n \"\"\"\n\n goal_id = self.config.get_goal_id(event_key)\n event_ids = goal_id\n\n if event_value:\n event_ids = '{goal_id},{revenue_goal_id}'.format(goal_id=goal_id,\n revenue_goal_id=self.config.get_revenue_goal_id())\n self.params[Params.EVENT_VALUE] = event_value\n\n self.params[Params.GOAL_ID] = event_ids\n self.params[Params.GOAL_NAME] = event_key\n\n def create_impression_event(self, experiment_key, variation_id, user_id, attributes):\n \"\"\" Create impression Event to be sent to the logging endpoint.\n\n Args:\n experiment_key: Experiment for which impression needs to be recorded.\n variation_id: ID for variation which would be presented to user.\n user_id: ID for user.\n attributes: Dict representing user attributes and values which need to be recorded.\n\n Returns:\n Event object encapsulating the impression event.\n \"\"\"\n\n self.params = {}\n self._add_common_params(user_id, attributes)\n self._add_impression_goal(experiment_key)\n self._add_experiment(experiment_key, variation_id)\n return Event(self.params)\n\n def create_conversion_event(self, event_key, user_id, attributes, event_value, valid_experiments):\n \"\"\" Create conversion Event to be sent to the logging endpoint.\n\n Args:\n event_key: Goal key representing the event which needs to be recorded.\n user_id: ID for user.\n event_value: Value associated with the event. Can be used to represent revenue in cents.\n valid_experiments: List of tuples representing valid experiments for the event.\n\n Returns:\n Event object encapsulating the conversion event.\n \"\"\"\n\n self.params = {}\n self._add_common_params(user_id, attributes)\n self._add_conversion_goal(event_key, event_value)\n self._add_experiment_variation_params(event_key, user_id, valid_experiments)\n return Event(self.params)\n","sub_path":"optimizely/event_builder.py","file_name":"event_builder.py","file_ext":"py","file_size_in_byte":7046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"288079296","text":"import random\nimport time\nimport Classes\nfrom seleniumwire import webdriver, request as selenium_request\nfrom selenium.webdriver.common.keys import Keys\nfrom bs4 import BeautifulSoup\nimport json\n\n\n# ------------- Constants -----------------\nCHECK_STRING = \"Check\"\nCHANGING_SIGN = \"X1Y\"\nWAITING_TIME = 10\nTEXT_TYPES = [\"text\", \"password\"]\n\n\n# ------------------------- Webdriver methods -------------------------\ndef new_browser(data: Classes.Data, page: Classes.Page = None, debug: bool = False,\n interceptor=None, remove_alerts: bool = True):\n \"\"\"\n This function creates a new browser instance with a new session.\n\n @param data: The data object of the program.\n @type data: Classes.Data\n @param page: The page to be opened with the new browser to initialize cookies and get page (optional).\n @type page: Classes.Page\n @param debug: In case of debugging, in case of True the chrome window will appear.\n @type debug: bool\n @param interceptor: A pointer to an interceptor function.\n @type interceptor: a function\n @param remove_alerts: If True, the browser will remove every alert on `get` and `refresh` methods.\n @type remove_alerts: bool\n @return: Chrome web driver object.\n @rtype: Classes.Browser\n \"\"\"\n if not data.driver:\n # There is no driver file path.\n raise Exception(\"There is no driver file path\", \"\\t\")\n options = webdriver.ChromeOptions()\n if not debug:\n # If it's not debug, the browser will be headless.\n options.headless = True\n options.add_experimental_option(\"excludeSwitches\", [\"enable-logging\"])\n try:\n browser = Classes.Browser(data.driver, options, remove_alerts)\n except Exception as e:\n # In case of failure, we need to try again\n return new_browser(data, page, debug, interceptor)\n\n def default_interceptor(request: selenium_request.Request):\n \"\"\"\n Inner function that acts like a proxy, it removes any requests we don't want.\n\n @param request: The current request\n @type request: selenium_request.Request\n @return: None\n \"\"\"\n # Block PNG, JPEG and GIF images.\n if request.path.endswith(('.png', '.jpg', '.gif')):\n request.abort() # Abort the unwanted request.\n \n # Setting up request interceptor.\n if interceptor:\n browser.request_interceptor = interceptor\n else:\n browser.request_interceptor = default_interceptor\n # Setting long timeout.\n browser.set_page_load_timeout(60)\n if page:\n # If a page was specified.\n if page.parent:\n browser.get(page.parent.url) # Getting parent URL.\n else:\n browser.get(page.url) # Getting current URL.\n for cookie in page.cookies: # Adding cookies.\n browser.add_cookie(cookie)\n # Getting the page again, with the loaded cookies.\n browser.get(page.url)\n return browser\n\n\ndef submit_form(data: Classes.Data, browser: Classes.Browser, inputs: list):\n \"\"\"\n Function submits the specified form.\n \n @param data: The data object of the program.\n @type data: Classes.Data\n @param browser: The webdriver object.\n @type browser: Classes.Browser\n @param inputs: A list of inputs that belong to a form, already filled with their desired values to submit.\n @type inputs: list\n @return: The time the action took.\n @rtype: float\n \"\"\"\n # In case of multi-threading, we need to make sure that no one is interrupting anyone.\n data.mutex.acquire()\n # Getting time of normal input.\n start = time.time()\n # The elements we want to submit.\n elements = list()\n if browser.requests:\n del browser.requests\n before_submit = browser.page_source # There are action forms that use js instead of requests.\n for input_tag in inputs:\n if \"type\" in input_tag.keys() and input_tag['type'] == \"hidden\":\n continue\n # Using the inserted value.\n if \"name\" in input_tag.keys():\n # Only if the input has a name attribute.\n try:\n element = browser.find_element_by_name(input_tag[\"name\"])\n if input_tag in get_text_inputs(inputs):\n # You can only send a key to text inputs.\n element.send_keys(input_tag[\"value\"])\n elements.append({\"element\": element,\n \"name\": input_tag[\"name\"],\n \"type\": input_tag[\"type\"]})\n except:\n # Could not send keys to the form for some reason.\n continue\n try:\n for element in elements[::-1]:\n if element[\"type\"] in TEXT_TYPES:\n element[\"element\"].send_keys(Keys.ENTER) # Sending the form.\n else:\n element[\"element\"].click()\n try:\n # Check if page has somehow loaded an alert, if so we know the form was submitted.\n browser.switch_to.alert\n except:\n continue\n else:\n break\n if not len(browser.requests) and before_submit == browser.page_source:\n # Did not do anything.\n elements[0][\"element\"].submit() # Sending the form.\n except Exception as e:\n if not len(browser.requests) and before_submit == browser.page_source:\n # Did not do anything.\n raise e\n finally:\n data.mutex.release()\n return time.time() - start\n\n\ndef enter_cookies(data: Classes.Data, browser: Classes.Browser, url: str):\n \"\"\"\n This function adds the specified cookies to the browser instance.\n \n @param data: The data object of the program.\n @type data: Classes.Data\n @param browser: The webdriver object.\n @type browser: Classes.Browser\n @param url: The URL to get after inserting the cookies.\n @type url: str\n @return: True - The cookies were added, False - The cookies were not added.\n @rtype: bool\n \"\"\"\n def add_cookie(a_cookies: dict):\n \"\"\"\n Inner function that receives one cookie dictionary and checks\n if it already exists in the browser, if not it adds it.\n \n @param a_cookies: The cookie to check.\n @type a_cookies: dict\n @return: None\n \"\"\"\n for existing_cookie in browser.get_cookies():\n if a_cookies[\"name\"] == existing_cookie[\"name\"]:\n # The cookie is already in the browser.\n for key in a_cookies.keys():\n existing_cookie[key] = a_cookies[key]\n else:\n # The cookie is not in the browser.\n browser.add_cookie(a_cookies)\n\n browser.get(url)\n before = list(browser.get_cookies()) # Cookies before adding our cookies.\n if data.cookies:\n # If a cookies file was specified.\n try:\n with open(data.cookies) as json_file:\n cookies = json.load(json_file) # Load cookies json as a python object.\n\n # Try to add every cookie that was found.\n if type(cookies) is list:\n for cookie in cookies:\n add_cookie(cookie)\n if type(cookies) is dict:\n add_cookie(cookies)\n \n except Exception:\n # We could not add the cookies.\n return False\n \n # Get page with new cookies.\n browser.get(url)\n if before != browser.get_cookies():\n # The cookies were modified.\n return True\n \n # No changes were made to the cookies.\n return False\n\n\n# ------------------------------ Helper methods ------------------------------\ndef get_random_str(content: str):\n \"\"\"\n This function generates a random string and ensures does not exist in the current page source.\n \n @param content: The content of the current page.\n @type content: str\n @return: The random string.\n @rtype: str\n \"\"\"\n string = CHECK_STRING\n while True:\n string += str(random.randint(0, 10))\n if string not in content:\n return string\n\n\ndef get_text_inputs(inputs: list):\n \"\"\"\n This function receives a list of form inputs and extracts all the text inputs from them.\n \n @param inputs: A list of inputs from a form.\n @type inputs: list\n @return: The list of all the text inputs.\n @rtype: list\n \"\"\"\n text_inputs = list()\n for input_tag in inputs:\n # Using the specified value.\n if \"name\" and \"type\" in input_tag.keys():\n # Only if the input has a name.\n if input_tag[\"type\"] and any(input_tag[\"type\"] == input_type for input_type in TEXT_TYPES):\n # It is a text input tag.\n text_inputs.append(input_tag)\n return text_inputs\n\n\ndef get_forms(content: str):\n \"\"\"\n This function gets all the forms from a page source html.\n\n @param content: The page content.\n @type content: str\n @return: List of all the forms.\n @rtype: list\n \"\"\"\n forms = list()\n for form in BeautifulSoup(content, \"html.parser\").find_all(\"form\"):\n try:\n # Get the form action (requested URL).\n action = form.attrs.get(\"action\", \"\").lower()\n # Get the form method (POST, GET, DELETE, etc).\n # If not specified, GET is the default in HTML.\n method = form.attrs.get(\"method\", \"get\").lower()\n # Get all form inputs.\n inputs = []\n for input_tag in form.find_all(\"input\"):\n input_dict = dict()\n # Get type of input form control.\n input_type = input_tag.attrs.get(\"type\")\n # Get name attribute.\n input_name = input_tag.attrs.get(\"name\")\n # Get the default value of that input tag.\n input_dict[\"value\"] = input_tag.attrs.get(\"value\", \"\")\n # Add all the attributes to the input dictionary.\n if input_type:\n input_dict[\"type\"] = input_type\n if input_name:\n input_dict[\"name\"] = input_name\n \n # Add the input dictionary object to the list of inputs.\n inputs.append(input_dict)\n # Adding the form to the list.\n forms.append({\"action\": action, \"method\": method, \"inputs\": inputs, \"form\": form})\n except:\n continue\n return forms\n\n\ndef remove_forms(content: str):\n \"\"\"\n This function removes all the form tag blocks from the HTML content.\n\n @param content: The HTML page content.\n @type content: str\n @return: The content without the forms.\n @rtype: str\n \"\"\"\n content = str(BeautifulSoup(content, \"html.parser\")) # The bs4 object changes the HTML tags.\n for form in get_forms(content):\n content = content.replace(str(form[\"form\"]), \"\")\n return content\n\n\ndef inject(data: Classes.Data, page: Classes.Page, form: dict, interceptor=None):\n \"\"\"\n This function injects a string into a text box and submits the form.\n\n @param data: The data object of the program.\n @type data: Classes.Data\n @param page: The current page.\n @type page: Classes.Page\n @param form: A dictionary of inputs of action form.\n @type form: dict\n @param interceptor: A function pointer to an interceptor function.\n @type interceptor: function\n @return: Tuple of (The content of the page, The time it took submit the form, The random string that was used)\n @rtype: tuple\n \"\"\"\n check_string = \"\"\n # Creating new browser.\n browser = new_browser(data, page, interceptor=interceptor)\n # The arguments body we want to submit.\n inputs = list()\n for new_form in get_forms(browser.page_source):\n # Getting the updated forms, in case of CSRF tokens.\n if new_form[\"action\"] != form[\"action\"] or new_form[\"method\"] != form[\"method\"]:\n # It is not the right form.\n continue\n new_inputs = new_form[\"inputs\"]\n inputs = form[\"inputs\"]\n check_string = get_random_str(browser.page_source)\n for index in range(len(new_inputs)):\n if not new_inputs[index][\"value\"]:\n # If there is no string specified.\n if inputs[index][\"value\"]:\n # If there is a value in the old input tag.\n if CHANGING_SIGN in inputs[index][\"value\"]:\n # If there is a changing sign in the string.\n # Replacing the CHANGING SIGN.\n inputs[index][\"value\"] = inputs[index][\"value\"].replace(CHANGING_SIGN, check_string)\n else:\n # If there is not, generate a random value.\n inputs[index][\"value\"] = get_random_str(browser.page_source)\n else:\n # There is a specified value, may be a CSRF token.\n inputs[index][\"value\"] = new_inputs[index][\"value\"]\n break # We found the form we were looking for.\n # Submitting the new form.\n run_time = submit_form(data, browser, inputs)\n content = browser.page_source\n browser.quit()\n return content, run_time, check_string\n\n\ndef fill_input(form: dict, curr_text_input: dict, string: str):\n \"\"\"\n This function makes a deep copy of a form and fills the specified text input with the specified string.\n \n @param form: The current form.\n @type form: dict\n @param curr_text_input: The current text input tag.\n @type curr_text_input: dict\n @param string: the string we want to use.\n @type string: str\n @return: A deep copy of the form.\n @rtype: dict\n \"\"\"\n new_form = dict()\n new_form[\"action\"] = str(form[\"action\"]) # Same action.\n new_form[\"method\"] = str(form[\"method\"]) # Same method.\n new_form[\"form\"] = form[\"form\"] # Same form.\n new_form[\"inputs\"] = list()\n for input_tag in form[\"inputs\"]:\n new_input_tag = dict(input_tag) # Deep copy to the input tag.\n if curr_text_input == new_input_tag:\n # This is the input we are looking for.\n new_input_tag[\"value\"] = string\n new_form[\"inputs\"].append(new_input_tag)\n return new_form\n","sub_path":"Methods.py","file_name":"Methods.py","file_ext":"py","file_size_in_byte":14251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"225110869","text":"\n\nfrom xai.brain.wordbase.nouns._mileage import _MILEAGE\n\n#calss header\nclass _MILEAGES(_MILEAGE, ):\n\tdef __init__(self,): \n\t\t_MILEAGE.__init__(self)\n\t\tself.name = \"MILEAGES\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"mileage\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_mileages.py","file_name":"_mileages.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"460992174","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\n\njordan= [\"Ajlun\", \"Amman\", \"Aqaba\", \"Balqa\",\"Irbid\", \"Jarash\", \"Karak\" , \"Ma`an\" \"Madaba\", \"Mafraq\", \"Tafilah\", \"Zarqa\"]\nx=0\nwhile int(x)<11:\n if jordan [x][0] =='A':\n print (jordan [x])\n x=int(x)+1\n else:\n x=int(x)+1\n\n","sub_path":"Week 2/Practice 2-D.py","file_name":"Practice 2-D.py","file_ext":"py","file_size_in_byte":297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"415161679","text":"import yaml \nimport shutil\nimport numpy as np\nimport copy\n\n# subpackage for reading yaml files that describe simulations and absorbance data\nclass Parser(object):\n def __init__(self,original_experimental_conditions=None):\n self.original_experimental_conditions = original_experimental_conditions\n \n\n #config is a dict containing the yaml information\n def load_to_obj(self, path:str = ''):\n with open(path) as f:\n config = yaml.load(f)\n return config\n \n def parse_shock_tube_obj(self,loaded_exp:dict={}, loaded_absorption:dict={}):\n simulation_type = loaded_exp['apparatus']['kind']\n pressure = loaded_exp['common-properties']['pressure']['value']\n temperature = loaded_exp['common-properties']['temperature']['value']\n mole_fractions = [((concentration['mole-fraction'])) for concentration in loaded_exp['common-properties']['composition']]\n mole_fractions = [float(elm) for elm in mole_fractions]\n species_names = [(species['species']) for species in loaded_exp['common-properties']['composition']]\n conditions = dict(zip(species_names,mole_fractions))\n thermal_boundary = loaded_exp['common-properties']['assumptions']['thermal-boundary']\n mechanical_boundary = loaded_exp['common-properties']['assumptions']['mechanical-boundary']\n \n mole_fraction_observables = [point['targets'][0]['name'] for point in loaded_exp['datapoints']['mole-fraction']]\n species_uncertainties = [uncert['relative-uncertainty'] for uncert in loaded_exp['common-properties']['composition']]\n species_uncertainties = [float(elm) for elm in species_uncertainties]\n species_uncertainties = dict(zip(species_names,species_uncertainties))\n \n \n concentration_observables = [datapoint['targets'][0]['name'] for datapoint in loaded_exp['datapoints']['concentration']] \n observables = [x for x in (mole_fraction_observables + concentration_observables) if x is not None]\n \n initial_time = loaded_exp['common-properties']['time']['initial-time']['value']\n #eventually going to get this from a csv file \n final_time = loaded_exp['common-properties']['time']['final-time']['value']\n \n \n mole_fraction_csv_files = [csvfile['csvfile'] for csvfile in loaded_exp['datapoints']['mole-fraction']]\n concentration_csv_files = [csvfile['csvfile'] for csvfile in loaded_exp['datapoints']['concentration']]\n path_length = loaded_exp['apparatus']['inner-diameter']['value']\n csv_files = [x for x in (mole_fraction_csv_files + concentration_csv_files) if x is not None]\n\n\n #importing unceratinty values \n temp_relative_uncertainty = loaded_exp['common-properties']['temperature']['relative-uncertainty']\n temp_relative_uncertainty = float(temp_relative_uncertainty)\n pressure_relative_uncertainty = loaded_exp['common-properties']['pressure']['relative-uncertainty']\n pressure_relative_uncertainty = float(pressure_relative_uncertainty)\n time_shift_uncertainty = loaded_exp['common-properties']['time-shift']['absolute-uncertainty']['value']\n concentration_absolute_uncertainty = [point['targets'][0]['absolute-uncertainty'] for point in loaded_exp['datapoints']['concentration']]\n concentration_relative_uncertainity = [point['targets'][0]['relative-uncertainty'] for point in loaded_exp['datapoints']['concentration']]\n\n mole_fraction_absolute_uncertainty = [point['targets'][0]['absolute-uncertainty'] for point in loaded_exp['datapoints']['mole-fraction']]\n\n mole_fraction_relative_uncertainty = [point['targets'][0]['relative-uncertainty'] for point in loaded_exp['datapoints']['mole-fraction']] \n\n if loaded_absorption == {}:\n return{\n 'pressure':pressure,\n 'temperature':temperature,\n 'conditions':conditions,\n 'speciesUncertaintys':species_uncertainties,\n 'thermalBoundary':thermal_boundary,\n 'mechanicalBoundary':mechanical_boundary,\n 'moleFractionObservables':mole_fraction_observables,\n 'concentrationObservables': concentration_observables, \n 'observables':observables,\n 'initialTime':initial_time,\n 'finalTime':final_time,\n 'speciesNames':species_names,\n 'pathLength':path_length,\n 'MoleFractions':mole_fractions,\n 'moleFractionCsvFiles':mole_fraction_csv_files,\n 'concentrationCsvFiles':concentration_csv_files,\n 'tempRelativeUncertainty':temp_relative_uncertainty,\n 'pressureRelativeUncertainty': pressure_relative_uncertainty,\n 'timeShiftUncertainty':time_shift_uncertainty,\n 'concentrationAbsoluteUncertainty':concentration_absolute_uncertainty,\n 'concentrationRelativeUncertainity':concentration_relative_uncertainity,\n 'moleFractionAbsoluteUncertainty':mole_fraction_absolute_uncertainty,\n 'moleFractionRelativeUncertainty':mole_fraction_relative_uncertainty,\n 'csvFiles': csv_files,\n 'simulationType': simulation_type\n }\n \n else: #absorbtion file given\n absorbance_absolute_uncertainty = [point['absolute-uncertainty'] for point in loaded_exp['datapoints']['absorbance']]\n absorbance_relative_uncertainty = [point['relative-uncertainty'] for point in loaded_exp['datapoints']['absorbance']]\n #importing absorbance uncertainty \n\n absorbance_csv_files = [csvfile['csvfile'] for csvfile in loaded_exp['datapoints']['absorbance']]\n absorbance_csv_wavelengths = [csvfile['wavelength']['value'] for csvfile in loaded_exp['datapoints']['absorbance']]\n absorption_observables = [species['species'] for species in loaded_absorption['Absorption-coefficients']]\n\n observables = [x for x in (mole_fraction_observables + concentration_observables + absorption_observables) if x is not None]\n\n\n uncertainty_parameter_ones = [[] for i in range(len(loaded_absorption['Absorption-coefficients']))]\n for uncertainty in range(len(loaded_absorption['Absorption-coefficients'])):\n temp = [wavelength['parameter-one']['absolute-uncertainty']['value'] for wavelength in loaded_absorption['Absorption-coefficients'][uncertainty]['wave-lengths']]\n uncertainty_parameter_ones[uncertainty] = temp\n \n uncertainty_parameter_twos = [[] for i in range(len(loaded_absorption['Absorption-coefficients']))]\n for uncertainty in range(len(loaded_absorption['Absorption-coefficients'])):\n temp = [wavelength['parameter-two']['absolute-uncertainty']['value'] for wavelength in loaded_absorption['Absorption-coefficients'][uncertainty]['wave-lengths']]\n uncertainty_parameter_twos[uncertainty] = temp \n \n \n # add the function which will return the coupled paramters here \n parameter_ones = []\n for p1 in range(len(loaded_absorption['Absorption-coefficients'])):\n temp = [wl['parameter-one']['value'] for wl in loaded_absorption['Absorption-coefficients'][p1]['wave-lengths']]\n parameter_ones.append(temp)\n\n parameter_twos = [] \n for p2 in range(len(loaded_absorption['Absorption-coefficients'])):\n temp = [wl['parameter-two']['value'] for wl in loaded_absorption['Absorption-coefficients'][p2]['wave-lengths']]\n parameter_twos.append(temp)\n \n coupledCoefficients = [list(zip(parameter_ones[x],parameter_twos[x])) for x in range(len(parameter_ones))]\n functional_form = []\n for form in range(len(loaded_absorption['Absorption-coefficients'])):\n temp = [wl['functional-form'] for wl in loaded_absorption['Absorption-coefficients'][form]['wave-lengths']]\n functional_form.append(temp)\n\n \n return {\n 'pressure':pressure,\n 'temperature':temperature,\n 'conditions':conditions,\n 'thermalBoundary':thermal_boundary,\n 'mechanicalBoundary':mechanical_boundary,\n 'speciesNames': species_names,\n 'observables': observables,\n 'moleFractionObservables':mole_fraction_observables,\n 'concentrationObservables':concentration_observables, \n 'absorbanceObservables':absorption_observables,\n 'initialTime': initial_time,\n 'finalTime':final_time,\n 'speciesNames': species_names,\n 'MoleFractions':mole_fractions,\n 'absorbanceCsvFiles': absorbance_csv_files,\n 'moleFractionCsvFiles':mole_fraction_csv_files,\n 'concentrationCsvFiles':concentration_csv_files,\n 'absorbanceCsvWavelengths': absorbance_csv_wavelengths,\n 'pathLength':path_length,\n 'tempRelativeUncertainty': temp_relative_uncertainty,\n 'pressureRelativeUncertainty': pressure_relative_uncertainty,\n 'speciesUncertaintys': species_uncertainties,\n 'timeShiftUncertainty': time_shift_uncertainty,\n 'concentrationAbsoluteUncertainty': concentration_absolute_uncertainty,\n 'concentrationRelativeUncertainity': concentration_relative_uncertainity,\n 'moleFractionAbsoluteUncertainty': mole_fraction_absolute_uncertainty,\n 'moleFractionRelativeUncertainty': mole_fraction_relative_uncertainty,\n 'absorbanceAbsoluteUncertainty': absorbance_absolute_uncertainty,\n 'absorbanceRelativeUncertainty': absorbance_relative_uncertainty,\n 'uncertaintyParameterOnes':uncertainty_parameter_ones,\n 'uncertaintyParameterTwos':uncertainty_parameter_twos,\n 'coupledCoefficients':coupledCoefficients,\n 'simulationType': simulation_type,\n 'parameterOnes':parameter_ones,\n 'parameterTwos':parameter_twos,\n 'functionalForm':functional_form\n }\n \n def load_yaml_list(self, yaml_list:list = []):\n list_of_yaml_objects = []\n for tup in yaml_list:\n temp = []\n for file in tup:\n temp.append(self.load_to_obj(file))\n list_of_yaml_objects.append(temp) \n list_of_yaml_objects = [tuple(lst) for lst in list_of_yaml_objects ] \n return list_of_yaml_objects\n \n def parsing_multiple_dictonaries(self,list_of_yaml_objects:list = [],loop_counter=0):\n experiment_dictonaries = []\n for tup in list_of_yaml_objects:\n if len(tup)>1:\n experiment_dictonaries.append(self.parse_shock_tube_obj(loaded_exp = tup[0],\n loaded_absorption = tup[1]))\n\n else:\n experiment_dictonaries.append(self.parse_shock_tube_obj(loaded_exp = tup[0]))\n if loop_counter == 0 : \n self.original_experimental_conditions = experiment_dictonaries\n \n return experiment_dictonaries\n \n def assemble_dicts_for_master_equation(self,experiment_dictonaries:list=[],\n master_equation_reactions:list=[],\n additional_parameters:dict={}):\n temperatures = []\n pressures = []\n conditions = []\n master_equation_parameters = []\n for exp in experiment_dictonaries:\n temperatures.append(exp['temperature'])\n pressures.append(exp['pressure'])\n conditions.append(exp['conditions'])\n \n if bool(additional_parameters) == False:\n parameters = {'W':['Energy','Frequencies','SymmetryFactor'],\n 'B':['ImaginaryFrequency']}\n \n for reaction in range(len(master_equation_reactions)):\n temp_dict = {}\n for key in parameters.keys():\n for param in parameters[key]:\n string = str(key+str(reaction)+'_'+param)\n temp_dict[string] = [temperatures,pressures,conditions]\n master_equation_parameters.append(temp_dict)\n \n return master_equation_parameters\n \n \n def yaml_file_copy(self,fileName):\n \n tempName = fileName[0:(len(fileName)-5)]\n yamlExtention = fileName[(len(fileName)-5):]\n NewName = tempName +'_updated'+yamlExtention\n shutil.copy2(fileName, NewName) \n \n return NewName\n \n def yaml_file_updates(self,file_name_list,\n parsed_yaml_list,\n experiment_dict_list,\n physical_observables_updates_list,\n loop_counter=0):\n \n #always pass in the updated file name list except for the first run of the code\n if loop_counter == 0:\n updated_file_name_list = []\n \n for yaml_file in range(len(file_name_list)):\n temp = []\n if loop_counter == 0: \n new_file_name = self.yaml_file_copy(file_name_list[yaml_file][0]) \n temp.append(new_file_name)\n updated_file_name_list.append(temp)\n if len(file_name_list[yaml_file])>1:\n temp.append(file_name_list[yaml_file][1])\n \n else: \n new_file_name = file_name_list[yaml_file][0]\n \n if experiment_dict_list[0]['simulation'].physicalSens ==1 :\n temp = self.original_experimental_conditions[yaml_file]['temperature']\n press = self.original_experimental_conditions[yaml_file]['pressure']\n mole_fractions = self.original_experimental_conditions[yaml_file]['MoleFractions']\n conditions = self.original_experimental_conditions[yaml_file]['conditions']\n \n print('__________________________________________________________________________')\n print('loop:',loop_counter)\n print(temp)\n print(press)\n print(conditions)\n print('__________________________________________________________________________')\n \n \n updatedTemp = np.exp(physical_observables_updates_list[yaml_file]['T_experiment_'+str(yaml_file)]) * temp\n updatedTemp = round(updatedTemp,9)\n updatedPress = np.exp(physical_observables_updates_list[yaml_file]['P_experiment_'+str(yaml_file)]) * press\n updatedPress = round(updatedPress,9)\n \n \n\n species_to_loop = experiment_dict_list[yaml_file]['uncertainty']['species_relative_uncertainty']['species']\n dilluant = ['Ar','AR','ar','HE','He','he','Kr','KR','kr','Xe','XE','xe','NE','Ne','ne']\n updated_mole_fractions = {}\n count = 0\n for specie in species_to_loop:\n if specie in dilluant:\n continue\n updated = np.exp(physical_observables_updates_list[yaml_file]['X_'+str(count)+'_experiment_'+str(yaml_file)])*conditions[specie]\n updated = round(updated,9)\n updated_mole_fractions[specie] = updated\n count+=1\n\n for specie in species_to_loop:\n if specie in dilluant:\n updated_mole_fractions[specie] = conditions[specie]\n \n updated_mole_fraction_list = []\n for specie in species_to_loop:\n updated_mole_fraction_list.append(updated_mole_fractions[specie])\n # starting to do file updates here \n \n with open(new_file_name) as f:\n config2 = yaml.safe_load(f)\n \n config2['common-properties']['pressure']['value']=float(updatedPress)\n config2['common-properties']['temperature']['value']=float(updatedTemp)\n \n for i,moleFraction in enumerate(updated_mole_fraction_list):\n config2['common-properties']['composition'][i]['mole-fraction']=float(moleFraction)\n \n with open(new_file_name,'w') as f:\n yaml.safe_dump(config2, f,default_flow_style=False)\n \n # make a list of updated yaml files here that we return from this and then use these names \n if loop_counter ==0: \n return updated_file_name_list\n else:\n return file_name_list\n \n def absorption_file_updates(self,file_name_list,\n parsed_yaml_list,\n experiment_dict_list,\n absorption_observables_updates_dict,\n loop_counter=0):\n \n \n \n \n #change is happening somewhere after here \n for yaml_file in range(len(file_name_list)):\n if len(file_name_list[yaml_file])<2:\n continue\n \n if loop_counter ==0:\n new_absorption_file_name = self.yaml_file_copy(file_name_list[yaml_file][1])\n file_name_list[yaml_file][1] = new_absorption_file_name\n \n \n else:\n new_absorption_file_name = file_name_list[yaml_file][1]\n \n \n coupledCoefficients = self.original_experimental_conditions[yaml_file]['coupledCoefficients']\n coupledCoefficentsUpdated = copy.deepcopy(coupledCoefficients)\n ########changes somewhere down there\n \n for species in range(len(coupledCoefficients)):\n for wavelength in range(len(coupledCoefficients[species])):\n lst = list(coupledCoefficients[species][wavelength])\n tup = tuple(lst)\n\n temp = []\n for i,values in enumerate(absorption_observables_updates_dict[tup]):\n \n temp.append(np.exp(values)*lst[i])\n\n coupledCoefficentsUpdated[species][wavelength] = tuple(temp)\n \n combinationOfNewParameters = list(map(list, list(zip(*(list(map(list, list(zip(*x)))) for x in coupledCoefficentsUpdated)))))\n parameterOnesUpdated = combinationOfNewParameters[0]\n \n\n for x in range(len(parameterOnesUpdated)):\n for y in range(len(parameterOnesUpdated[x])):\n parameterOnesUpdated[x][y] = round(parameterOnesUpdated[x][y], 8)\n\n \n\n parameterTwosUpdated = combinationOfNewParameters[1]\n for x in range(len(parameterTwosUpdated)):\n for y in range(len(parameterTwosUpdated[x])):\n parameterTwosUpdated[x][y] = round(parameterTwosUpdated[x][y], 8)\n \n\n with open(new_absorption_file_name)as f:\n config3 = yaml.safe_load(f)\n \n \n \n for parameterOne in range(len(config3['Absorption-coefficients'])):\n for wavelength in range(len(config3['Absorption-coefficients'][parameterOne]['wave-lengths'])): \n config3['Absorption-coefficients'][parameterOne]['wave-lengths'][wavelength]['parameter-one']['value'] = float(parameterOnesUpdated[parameterOne][0])\n\n \n \n\n for parameterTwo in range(len(config3['Absorption-coefficients'])):\n for wavelength in range(len(config3['Absorption-coefficients'][parameterTwo]['wave-lengths'])):\n config3['Absorption-coefficients'][parameterTwo]['wave-lengths'][wavelength]['parameter-two']['value'] = float(parameterTwosUpdated[parameterTwo][0])\n \n with open(new_absorption_file_name,'w') as f:\n yaml.safe_dump(config3, f,default_flow_style=False)\n \n return file_name_list\n \n \n \n \n \n \n ","sub_path":"simulations/yaml_parser.py","file_name":"yaml_parser.py","file_ext":"py","file_size_in_byte":20676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"629852040","text":"from plugins.aws_configuration_parser import *\nimport boto3\nimport json\nimport time\nimport zipfile\n\nif __name__ == '__main__':\n\n # creating aws configuration object\n aws_configs = AwsConfigs('credentials/credentials.csv', 'credentials/resources.cfg')\n\n #---------------------------- Creating clients----------------------------------------------------------------------\n # Creating ec2 resource\n ec2 = boto3.resource('ec2',\n region_name=aws_configs.REGION,\n aws_access_key_id=aws_configs.ACCESS_KEY,\n aws_secret_access_key=aws_configs.SECRET_KEY\n )\n\n # Creating s3 resource\n s3 = boto3.resource('s3',\n region_name=aws_configs.REGION,\n aws_access_key_id=aws_configs.ACCESS_KEY,\n aws_secret_access_key=aws_configs.SECRET_KEY\n )\n\n # Creating kinesis client\n kinesis = boto3.client('kinesis',\n region_name=aws_configs.REGION,\n aws_access_key_id=aws_configs.ACCESS_KEY,\n aws_secret_access_key=aws_configs.SECRET_KEY\n )\n\n # Creating iam\n iam = boto3.client('iam',\n region_name=aws_configs.REGION,\n aws_access_key_id=aws_configs.ACCESS_KEY,\n aws_secret_access_key=aws_configs.SECRET_KEY\n )\n\n # Creating cloudwatch client\n cloud_watch = boto3.client('logs',\n region_name=aws_configs.REGION,\n aws_access_key_id=aws_configs.ACCESS_KEY,\n aws_secret_access_key=aws_configs.SECRET_KEY\n )\n\n # Creating firehose client\n firehose = boto3.client('firehose',\n region_name=aws_configs.REGION,\n aws_access_key_id=aws_configs.ACCESS_KEY,\n aws_secret_access_key=aws_configs.SECRET_KEY\n )\n\n # Creating Lambda client\n lambda_client = boto3.client('lambda',\n region_name=aws_configs.REGION,\n aws_access_key_id=aws_configs.ACCESS_KEY,\n aws_secret_access_key=aws_configs.SECRET_KEY\n )\n # Creating redshift client\n redshift = boto3.client('redshift',\n region_name=aws_configs.REGION,\n aws_access_key_id=aws_configs.ACCESS_KEY,\n aws_secret_access_key=aws_configs.SECRET_KEY\n )\n\n #-------------------------------------------------------------------------------------------------------------------\n #----------------------------------- Creating Roles-------------------------------------------------------------\n try:\n # creating firehose delivery role\n iam.create_role(Path='/',\n RoleName=aws_configs.FIREHOSE['ROLE_NAME'],\n Description='Allows Redshift clusters to call AWS services on your behalf.',\n AssumeRolePolicyDocument=json.dumps({\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Effect\": \"Allow\",\n \"Principal\": {\n \"Service\": \"firehose.amazonaws.com\"\n },\n \"Action\": \"sts:AssumeRole\",\n }\n ]\n }))\n print(f\"Firehose IAM Role {aws_configs.FIREHOSE['ROLE_NAME']} is created\")\n except Exception as e:\n print(e)\n\n # Get Account ID\n ACCOUNT_ID = boto3.client('sts',\n region_name=aws_configs.REGION,\n aws_access_key_id=aws_configs.ACCESS_KEY,\n aws_secret_access_key=aws_configs.SECRET_KEY\n ).get_caller_identity().get('Account')\n\n # creating firehose policy\n firehose_policy = {\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Sid\": \"\",\n \"Effect\": \"Allow\",\n \"Action\": [\n \"glue:GetTable\",\n \"glue:GetTableVersion\",\n \"glue:GetTableVersions\"\n ],\n \"Resource\": \"*\"\n },\n {\n \"Sid\": \"\",\n \"Effect\": \"Allow\",\n \"Action\": [\n \"s3:AbortMultipartUpload\",\n \"s3:GetBucketLocation\",\n \"s3:GetObject\",\n \"s3:ListBucket\",\n \"s3:ListBucketMultipartUploads\",\n \"s3:PutObject\"\n ],\n \"Resource\": [\n f\"arn:aws:s3:::{aws_configs.S3['BUCKET']}\",\n f\"arn:aws:s3:::{aws_configs.S3['BUCKET']}/*\",\n \"arn:aws:s3:::%FIREHOSE_BUCKET_NAME%\",\n \"arn:aws:s3:::%FIREHOSE_BUCKET_NAME%/*\"\n ]\n },\n {\n \"Sid\": \"\",\n \"Effect\": \"Allow\",\n \"Action\": [\n \"lambda:InvokeFunction\",\n \"lambda:GetFunctionConfiguration\"\n ],\n \"Resource\": f\"arn:aws:lambda:{aws_configs.REGION}:{ACCOUNT_ID}:function:%FIREHOSE_DEFAULT_FUNCTION%:%FIREHOSE_DEFAULT_VERSION%\"\n },\n {\n \"Sid\": \"\",\n \"Effect\": \"Allow\",\n \"Action\": [\n \"logs:PutLogEvents\"\n ],\n \"Resource\": [\n f\"arn:aws:logs:{aws_configs.REGION}:{ACCOUNT_ID}:log-group:/aws/kinesisfirehose/{aws_configs.FIREHOSE['DELIVERY_STREAM_NAME']}:log-stream:*\"\n ]\n },\n {\n \"Sid\": \"\",\n \"Effect\": \"Allow\",\n \"Action\": [\n \"kinesis:DescribeStream\",\n \"kinesis:GetShardIterator\",\n \"kinesis:GetRecords\"\n ],\n \"Resource\": f\"arn:aws:kinesis:{aws_configs.REGION}:{ACCOUNT_ID}:stream/{aws_configs.KINESIS['STREAM_NAME']}\"\n },\n {\n \"Effect\": \"Allow\",\n \"Action\": [\n \"kms:Decrypt\"\n ],\n \"Resource\": [\n f\"arn:aws:kms:{aws_configs.REGION}:{ACCOUNT_ID}:key/%SSE_KEY_ID%\"\n ],\n \"Condition\": {\n \"StringEquals\": {\n \"kms:ViaService\": f\"kinesis.{aws_configs.REGION}.amazonaws.com\"\n },\n \"StringLike\": {\n \"kms:EncryptionContext:aws:kinesis:arn\": f\"arn:aws:kinesis:{aws_configs.REGION}:{ACCOUNT_ID}:stream/{aws_configs.KINESIS['STREAM_NAME']}\"\n }\n }\n }\n ]\n }\n\n # Attaching policy to firehose role\n iam.put_role_policy(RoleName=aws_configs.FIREHOSE['ROLE_NAME'],\n PolicyName=aws_configs.FIREHOSE['POLICY'],\n PolicyDocument=json.dumps(firehose_policy))\n\n try:\n # Creating Lambda Role\n iam.create_role(Path='/',\n RoleName=aws_configs.LAMBDA['ROLE_NAME'],\n AssumeRolePolicyDocument=json.dumps({\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Sid\": \"\",\n \"Effect\": \"Allow\",\n \"Principal\": {\n \"Service\": \"lambda.amazonaws.com\"\n },\n \"Action\": \"sts:AssumeRole\"\n }\n ]\n }\n )\n )\n print(f\"Lambda IAM Role {aws_configs.LAMBDA['ROLE_NAME']} is created\")\n except Exception as e:\n print(e)\n\n # Attaching the policy to lambda role\n iam.put_role_policy(RoleName=aws_configs.LAMBDA['ROLE_NAME'],\n PolicyName=aws_configs.LAMBDA['POLICY'],\n PolicyDocument=json.dumps({\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Effect\": \"Allow\",\n \"Action\": [\n \"kinesis:DescribeStream\",\n \"kinesis:DescribeStreamSummary\",\n \"kinesis:GetRecords\",\n \"kinesis:GetShardIterator\",\n \"kinesis:ListShards\",\n \"kinesis:ListStreams\",\n \"kinesis:SubscribeToShard\",\n \"logs:CreateLogGroup\",\n \"logs:CreateLogStream\",\n \"logs:PutLogEvents\",\n \"lambda:InvokeFunction\",\n \"s3:*\"\n ],\n \"Resource\": \"*\"\n }\n ]\n })\n )\n\n try:\n # Creating Redshift role\n iam.create_role(\n Path='/',\n RoleName=aws_configs.REDSHIFT['ROLE_NAME'],\n Description='Allows Redshift clusters to call AWS services on your behalf.',\n AssumeRolePolicyDocument=json.dumps(\n {'Statement': [{'Action': 'sts:AssumeRole',\n 'Effect': 'Allow',\n 'Principal': {'Service': 'redshift.amazonaws.com'}}],\n 'Version': '2012-10-17'})\n )\n print(f\"Redshift IAM Role {aws_configs.REDSHIFT['ROLE_NAME']} is created\")\n except Exception as e:\n print(e)\n\n # Attaching policy to redshift role\n iam.attach_role_policy(RoleName=aws_configs.REDSHIFT['ROLE_NAME'],\n PolicyArn=\"arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess\"\n )\n\n #------------------------------------------------------------------------------------------------------------------\n #------------------------------------------------Creating S3 Bucket------------------------------------------------\n try:\n # Creates s3 bucket\n s3.create_bucket(Bucket=aws_configs.S3['BUCKET'],\n CreateBucketConfiguration={\n 'LocationConstraint': aws_configs.REGION}\n )\n print(f\"S3 Bucket {aws_configs.S3['BUCKET']} is created\")\n except Exception as e:\n print(e)\n #-------------------------------------------------------------------------------------------------------------------\n #------------------------------------------------Creating Kinesis data stream---------------------------------------\n try:\n # Creating kinesis data streams\n kinesis.create_stream(StreamName=aws_configs.KINESIS['STREAM_NAME'],\n ShardCount=int(aws_configs.KINESIS['SHARD_COUNT']))\n print(f\"Kinesis Stream {aws_configs.KINESIS['STREAM_NAME']} is created\")\n except Exception as e:\n print(e)\n #-------------------------------------------------------------------------------------------------------------------\n #------------------------------------------Creating Cloud Watch logs------------------------------------------------\n try:\n # Creating cloudwatch group\n cloud_watch.create_log_group(logGroupName=f\"/aws/kinesisfirehose/{aws_configs.FIREHOSE['DELIVERY_STREAM_NAME']}\")\n\n # Creating cloudwatch stream\n cloud_watch.create_log_stream(\n logGroupName=f\"/aws/kinesisfirehose/{aws_configs.FIREHOSE['DELIVERY_STREAM_NAME']}\",\n logStreamName='S3Stream'\n )\n print(f\"Cloudwatch group /aws/kinesisfirehose/{aws_configs.FIREHOSE['DELIVERY_STREAM_NAME']} is created\")\n except Exception as e:\n print(e)\n #-------------------------------------------------------------------------------------------------------------------\n #----------------------------------------Creating Firehose Delivery Stream------------------------------------------\n # Putting a delay of 30 secs in order to propagate the role successfully\n time.sleep(30)\n\n # Getting the ARN for firehose role\n firehose_role_arn = iam.get_role(RoleName=aws_configs.FIREHOSE['ROLE_NAME'])['Role']['Arn']\n #\n # # Getting the ARN of kinesis stream\n kinesis_stream_arn = kinesis.describe_stream(StreamName=aws_configs.KINESIS['STREAM_NAME'])['StreamDescription']['StreamARN']\n try:\n firehose.create_delivery_stream(\n DeliveryStreamName=aws_configs.FIREHOSE['DELIVERY_STREAM_NAME'],\n DeliveryStreamType='KinesisStreamAsSource',\n KinesisStreamSourceConfiguration={\n 'KinesisStreamARN': kinesis_stream_arn,\n 'RoleARN': firehose_role_arn\n },\n S3DestinationConfiguration={\n 'RoleARN': firehose_role_arn,\n 'BucketARN': f\"arn:aws:s3:::{aws_configs.S3['BUCKET']}\",\n 'Prefix': 'streamed_data-',\n 'BufferingHints': {\n 'SizeInMBs': 5,\n 'IntervalInSeconds': 60\n },\n 'CompressionFormat': 'UNCOMPRESSED',\n 'EncryptionConfiguration': {\n 'NoEncryptionConfig': 'NoEncryption'\n },\n 'CloudWatchLoggingOptions': {\n 'Enabled': True,\n 'LogGroupName': f\"/aws/kinesisfirehose/{aws_configs.FIREHOSE['DELIVERY_STREAM_NAME']}\",\n 'LogStreamName': 'S3Stream'\n\n }\n },\n\n )\n print(f\"Firehose Delivery Stream {aws_configs.FIREHOSE['DELIVERY_STREAM_NAME']} is created\")\n except Exception as e:\n print(e)\n #-------------------------------------------------------------------------------------------------------------------\n #-------------------------------------------Creating Lambda Function------------------------------------------------\n # Creating zip file for lambda function\n zf = zipfile.ZipFile('lambda.zip',mode='w')\n try:\n zf.write('lambda_function.py')\n finally:\n zf.close()\n\n # Getting the role\n lambda_role_arn = iam.get_role(RoleName=aws_configs.LAMBDA['ROLE_NAME'])['Role']['Arn']\n\n with open('lambda.zip', 'rb') as f:\n zipped_code = f.read()\n try:\n # Creating Lambda function\n lambda_client.create_function(\n FunctionName=aws_configs.LAMBDA['FUNCTION_NAME'],\n Runtime='python3.7',\n Role=lambda_role_arn,\n Handler='lambda_function.lambda_handler',\n Code=dict(ZipFile=zipped_code),\n Timeout=300, # Maximum allowable timeout\n Environment={\n 'Variables': {\n 'S3Bucket': aws_configs.S3['Bucket'],\n 'output_key_prefix' : aws_configs.S3['real_processed_key']\n }\n }\n )\n\n # Creating Kinesis Trigger\n lambda_client.create_event_source_mapping(\n EventSourceArn=kinesis_stream_arn,\n FunctionName=aws_configs.LAMBDA['FUNCTION_NAME'],\n Enabled=True,\n BatchSize=100,\n StartingPosition='LATEST',\n MaximumRetryAttempts=123\n )\n print(f\"Lambda function {aws_configs.LAMBDA['FUNCTION_NAME']} is created\")\n except Exception as e:\n print(e)\n #-------------------------------------------------------------------------------------------------------------------\n #-----------------------------------------Creating RedShift Cluster-------------------------------------------------\n redshift_role_arn = iam.get_role(RoleName=aws_configs.REDSHIFT['ROLE_NAME'])['Role']['Arn']\n\n try:\n\n # creating rdshift cluster\n response = redshift.create_cluster(\n # HW\n ClusterType=aws_configs.REDSHIFT['CLUSTER_TYPE'],\n NodeType=aws_configs.REDSHIFT['NODE_TYPE'],\n NumberOfNodes=int(aws_configs.REDSHIFT['NUM_NODES']),\n\n # Identifiers & Credentials\n DBName=aws_configs.REDSHIFT['DB_NAME'],\n ClusterIdentifier=aws_configs.REDSHIFT['CLUSTER_IDENTIFIER'],\n MasterUsername=aws_configs.REDSHIFT['DB_USER'],\n MasterUserPassword=aws_configs.REDSHIFT['DB_PASSWORD'],\n\n # Roles (for s3 access)\n IamRoles=[redshift_role_arn]\n )\n except Exception as e:\n print(e)\n\n # Checking if redshift cluster becomes available or not\n myClusterProps = redshift.describe_clusters(ClusterIdentifier=aws_configs.REDSHIFT['CLUSTER_IDENTIFIER'])['Clusters'][0]\n while myClusterProps['ClusterAvailabilityStatus'] != 'Available':\n myClusterProps = redshift.describe_clusters(ClusterIdentifier=aws_configs.REDSHIFT['CLUSTER_IDENTIFIER'])['Clusters'][0]\n time.sleep(10)\n print(f\"Redshift cluster {aws_configs.REDSHIFT['CLUSTER_IDENTIFIER']} is created\")\n # Open an incoming TCP port to access the cluster endpoint\n try:\n vpc = ec2.Vpc(id=myClusterProps['VpcId'])\n defaultSg = list(vpc.security_groups.all())[0]\n defaultSg.authorize_ingress(\n GroupName=defaultSg.group_name,\n CidrIp='0.0.0.0/0',\n IpProtocol='TCP',\n FromPort=int(aws_configs.REDSHIFT['PORT']),\n ToPort=int(aws_configs.REDSHIFT['PORT'])\n )\n except Exception as e:\n print(e)\n\n # Adding end point configuration of the cluster to the configuration file\n config = configparser.ConfigParser()\n config.read('credentials/resources.cfg')\n\n config['REDSHIFT']['ENDPOINT'] = myClusterProps['Endpoint']['Address']\n config['REDSHIFT']['ROLE_ARN'] = redshift_role_arn\n\n # writing to the configuration file\n with open('credentials/resources.cfg', 'w') as config_file:\n config.write(config_file)\n","sub_path":"capstone-project/create_aws_resources.py","file_name":"create_aws_resources.py","file_ext":"py","file_size_in_byte":18726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"172237380","text":"from ..base.twilltestcase import (\n common,\n ShedTwillTestCase,\n)\n\ncolumn_maker_repository_name = \"column_maker_0110\"\ncolumn_maker_repository_description = \"A flexible aligner.\"\ncolumn_maker_repository_long_description = \"A flexible aligner and methylation caller for Bisulfite-Seq applications.\"\n\nemboss_repository_name = \"emboss_0110\"\nemboss_repository_description = \"Galaxy wrappers for Emboss version 5.0.0 tools\"\nemboss_repository_long_description = \"Galaxy wrappers for Emboss version 5.0.0 tools\"\n\ncategory_name = \"Test 0110 Invalid Repository Dependencies\"\ncategory_desc = \"Test 0110 Invalid Repository Dependencies\"\nrunning_standalone = False\n\n\nclass TestBasicRepositoryDependencies(ShedTwillTestCase):\n \"\"\"Testing emboss 5 with repository dependencies.\"\"\"\n\n def test_0000_initiate_users(self):\n \"\"\"Create necessary user accounts and login as an admin user.\"\"\"\n self.login(email=common.test_user_1_email, username=common.test_user_1_name)\n self.login(email=common.admin_email, username=common.admin_username)\n\n def test_0005_create_category(self):\n \"\"\"Create a category for this test suite\"\"\"\n self.create_category(name=category_name, description=category_desc)\n\n def test_0010_create_emboss_dependendent_column_maker_repository_and_upload_tarball(self):\n \"\"\"Create and populate the column_maker repository.\"\"\"\n global running_standalone\n self.login(email=common.test_user_1_email, username=common.test_user_1_name)\n category = self.populator.get_category_with_name(category_name)\n column_maker_repository = self.get_or_create_repository(\n name=column_maker_repository_name,\n description=column_maker_repository_description,\n long_description=column_maker_repository_long_description,\n owner=common.test_user_1_name,\n category=category,\n strings_displayed=[],\n )\n if self.repository_is_new(column_maker_repository):\n running_standalone = True\n self.upload_file(\n column_maker_repository,\n filename=\"column_maker/column_maker.tar\",\n filepath=None,\n valid_tools_only=True,\n uncompress_file=True,\n remove_repo_files_not_in_tar=False,\n commit_message=\"Uploaded column_maker tarball.\",\n strings_displayed=[],\n strings_not_displayed=[],\n )\n\n def test_0020_create_emboss_5_repository_and_upload_files(self):\n \"\"\"Create and populate the emboss_5_0110 repository.\"\"\"\n global running_standalone\n if running_standalone:\n category = self.populator.get_category_with_name(category_name)\n repository = self.get_or_create_repository(\n name=emboss_repository_name,\n description=emboss_repository_description,\n long_description=emboss_repository_long_description,\n owner=common.test_user_1_name,\n category=category,\n strings_displayed=[],\n )\n self.upload_file(\n repository,\n filename=\"emboss/emboss.tar\",\n filepath=None,\n valid_tools_only=True,\n uncompress_file=True,\n remove_repo_files_not_in_tar=False,\n commit_message=\"Uploaded emboss tool tarball.\",\n strings_displayed=[],\n strings_not_displayed=[],\n )\n\n def test_0025_generate_repository_dependency_with_invalid_url(self):\n \"\"\"Generate a repository dependency for emboss 5 with an invalid URL.\"\"\"\n global running_standalone\n if running_standalone:\n dependency_path = self.generate_temp_path(\"test_1110\", additional_paths=[\"simple\"])\n column_maker_repository = self._get_repository_by_name_and_owner(\n column_maker_repository_name, common.test_user_1_name\n )\n emboss_repository = self._get_repository_by_name_and_owner(emboss_repository_name, common.test_user_1_name)\n url = \"http://http://this is not an url!\"\n name = column_maker_repository.name\n owner = column_maker_repository.owner\n changeset_revision = self.get_repository_tip(column_maker_repository)\n strings_displayed = [\"Repository dependencies are currently supported only within the same tool shed\"]\n repository_tuple = (url, name, owner, changeset_revision)\n self.create_repository_dependency(\n repository=emboss_repository,\n filepath=dependency_path,\n repository_tuples=[repository_tuple],\n strings_displayed=strings_displayed,\n complex=False,\n )\n\n def test_0030_generate_repository_dependency_with_invalid_name(self):\n \"\"\"Generate a repository dependency for emboss 5 with an invalid name.\"\"\"\n global running_standalone\n if running_standalone:\n dependency_path = self.generate_temp_path(\"test_1110\", additional_paths=[\"simple\"])\n repository = self._get_repository_by_name_and_owner(column_maker_repository_name, common.test_user_1_name)\n emboss_repository = self._get_repository_by_name_and_owner(emboss_repository_name, common.test_user_1_name)\n url = self.url\n name = \"!?invalid?!\"\n owner = repository.owner\n changeset_revision = self.get_repository_tip(repository)\n strings_displayed = [\"because the name is invalid.\"]\n repository_tuple = (url, name, owner, changeset_revision)\n self.create_repository_dependency(\n repository=emboss_repository,\n filepath=dependency_path,\n repository_tuples=[repository_tuple],\n strings_displayed=strings_displayed,\n complex=False,\n )\n\n def test_0035_generate_repository_dependency_with_invalid_owner(self):\n \"\"\"Generate a repository dependency for emboss 5 with an invalid owner.\"\"\"\n global running_standalone\n if running_standalone:\n dependency_path = self.generate_temp_path(\"test_1110\", additional_paths=[\"simple\"])\n repository = self._get_repository_by_name_and_owner(column_maker_repository_name, common.test_user_1_name)\n emboss_repository = self._get_repository_by_name_and_owner(emboss_repository_name, common.test_user_1_name)\n url = self.url\n name = repository.name\n owner = \"!?invalid?!\"\n changeset_revision = self.get_repository_tip(repository)\n strings_displayed = [\"because the owner is invalid.\"]\n repository_tuple = (url, name, owner, changeset_revision)\n self.create_repository_dependency(\n repository=emboss_repository,\n filepath=dependency_path,\n repository_tuples=[repository_tuple],\n strings_displayed=strings_displayed,\n complex=False,\n )\n\n def test_0040_generate_repository_dependency_with_invalid_changeset_revision(self):\n \"\"\"Generate a repository dependency for emboss 5 with an invalid changeset revision.\"\"\"\n global running_standalone\n if running_standalone:\n dependency_path = self.generate_temp_path(\"test_1110\", additional_paths=[\"simple\", \"invalid\"])\n repository = self._get_repository_by_name_and_owner(column_maker_repository_name, common.test_user_1_name)\n emboss_repository = self._get_repository_by_name_and_owner(emboss_repository_name, common.test_user_1_name)\n url = self.url\n name = repository.name\n owner = repository.owner\n changeset_revision = \"!?invalid?!\"\n strings_displayed = [\"because the changeset revision is invalid.\"]\n repository_tuple = (url, name, owner, changeset_revision)\n self.create_repository_dependency(\n repository=emboss_repository,\n filepath=dependency_path,\n repository_tuples=[repository_tuple],\n strings_displayed=strings_displayed,\n complex=False,\n )\n\n def test_0045_install_repository_with_invalid_repository_dependency(self):\n \"\"\"Install the repository and verify that galaxy detects invalid repository dependencies.\"\"\"\n self.galaxy_login(email=common.admin_email, username=common.admin_username)\n repository = self._get_repository_by_name_and_owner(emboss_repository_name, common.test_user_1_name)\n preview_strings_displayed = [\n \"emboss_0110\",\n self.get_repository_tip(repository),\n \"Ignoring repository dependency definition\",\n ]\n self._install_repository(\n emboss_repository_name,\n common.test_user_1_name,\n category_name,\n install_tool_dependencies=False,\n install_repository_dependencies=True,\n preview_strings_displayed=preview_strings_displayed,\n )\n installed_repository = self.test_db_util.get_installed_repository_by_name_owner(\n emboss_repository_name, common.test_user_1_name\n )\n json = self.display_installed_repository_manage_json(installed_repository)\n assert \"repository_dependencies\" not in json\n","sub_path":"lib/tool_shed/test/functional/test_1130_install_repository_with_invalid_repository_dependency.py","file_name":"test_1130_install_repository_with_invalid_repository_dependency.py","file_ext":"py","file_size_in_byte":9467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"54690876","text":"import logging\r\nfrom RPi import GPIO\r\nimport time\r\n\r\n\r\nclass DisplayPcf:\r\n # dit is een klasse voor een display waarvan de channels aan een pcf8574 hangen\r\n\r\n def __init__(self, rs_d_param, e_d_param, sda_p_param, scl_p_param, is_p_param):\r\n GPIO.setmode(GPIO.BCM)\r\n # display\r\n self.__rs = rs_d_param\r\n self.__e = e_d_param\r\n GPIO.setup(self.__e, GPIO.OUT)\r\n GPIO.setup(self.__rs, GPIO.OUT)\r\n GPIO.output(self.__e, 1)\r\n # pcf\r\n self.__sda = sda_p_param\r\n self.__scl = scl_p_param\r\n self.__id = is_p_param\r\n GPIO.setup(self.__sda, GPIO.OUT)\r\n GPIO.setup(self.__scl, GPIO.OUT)\r\n\r\n self.start_display()\r\n\r\n @property\r\n def rs(self):\r\n return self.__rs\r\n\r\n @property\r\n def e(self):\r\n return self.__e\r\n\r\n @property\r\n def sda(self):\r\n return self.__sda\r\n\r\n @property\r\n def scl(self):\r\n return self.__scl\r\n\r\n @property\r\n def id(self):\r\n return self.__id\r\n\r\n def __str__(self):\r\n returnen = \"display met pcf\\n\"\r\n returnen += \"rs: %s\\n\" % self.rs\r\n returnen += \"e: %s\\n\" % self.e\r\n returnen += \"sda: %s\\n\" % self.sda\r\n returnen += \"scl: %s\\n\" % self.scl\r\n returnen += \"id: %s\\n\" % self.id\r\n\r\n # display funcites\r\n def clock_display(self):\r\n GPIO.output(self.e, 0)\r\n time.sleep(0)\r\n GPIO.output(self.e, 1)\r\n\r\n def start_display(self):\r\n GPIO.output(self.rs, 0)\r\n startcommando_display = [0x38, 0xc, 0x1]\r\n for instructie in startcommando_display:\r\n self.write_to_item_pcf(self.id, instructie)\r\n self.clock_display()\r\n GPIO.output(self.rs, 1)\r\n\r\n def schrijf_naar_display(self, woord):\r\n print(woord)\r\n GPIO.setmode(GPIO.BCM)\r\n clean_display = 0x1\r\n start_new_line_display = 0xc0\r\n GPIO.output(self.rs, 0)\r\n self.write_to_item_pcf(self.id, clean_display)\r\n self.clock_display()\r\n GPIO.output(self.rs, 1)\r\n teller = 0\r\n al_verzet = 0\r\n for letter in woord:\r\n if ((teller > 15) and (al_verzet == 0)) or letter == \"#\":\r\n GPIO.output(self.rs, 0)\r\n self.write_to_item_pcf(self.id, start_new_line_display)\r\n self.clock_display()\r\n GPIO.output(self.rs, 1)\r\n teller = 0\r\n al_verzet = 1\r\n if letter != \"#\":\r\n instructie = ord(letter)\r\n self.write_to_item_pcf(self.id, instructie)\r\n self.clock_display()\r\n teller += 1\r\n\r\n\r\n # pcf functies\r\n def write_one_bit(self, bit):\r\n GPIO.output(self.sda, bit)\r\n time.sleep(0)\r\n GPIO.output(self.scl, 1)\r\n time.sleep(0)\r\n GPIO.output(self.scl, 0)\r\n time.sleep(0)\r\n\r\n def write_one_byte(self, data_byte):\r\n mask = 0x80\r\n for i in range(0, 8):\r\n if (data_byte & mask) == 0:\r\n self.write_one_bit(0)\r\n else:\r\n self.write_one_bit(1)\r\n time.sleep(0)\r\n mask = mask >> 1\r\n\r\n def starten_pcf(self, id):\r\n GPIO.output(self.scl, 1)\r\n GPIO.output(self.sda, 1)\r\n time.sleep(0)\r\n GPIO.output(self.sda, 0)\r\n time.sleep(0)\r\n GPIO.output(self.scl, 0)\r\n # id en r of w\r\n rw = 0\r\n id_rw = id | rw\r\n self.write_one_byte(id_rw)\r\n\r\n def stoppen_pcf(self):\r\n GPIO.output(self.scl, 0)\r\n GPIO.output(self.sda, 0)\r\n time.sleep(0)\r\n GPIO.output(self.scl, 1)\r\n time.sleep(0)\r\n GPIO.output(self.sda, 1)\r\n\r\n def ack_pcf(self):\r\n GPIO.setmode(GPIO.BCM)\r\n GPIO.setup(self.sda, GPIO.IN, pull_up_down=GPIO.PUD_UP)\r\n GPIO.output(self.scl, 1)\r\n time.sleep(0.01)\r\n status = GPIO.input(self.sda)\r\n GPIO.output(self.scl, 0)\r\n GPIO.setup(self.sda, GPIO.OUT)\r\n return status\r\n\r\n def write_to_item_pcf(self, id, data_byte):\r\n GPIO.setmode(GPIO.BCM)\r\n self.starten_pcf(id)\r\n status = self.ack_pcf()\r\n if not status:\r\n self.write_one_byte(data_byte)\r\n status = self.ack_pcf()\r\n if status:\r\n logging.error(\"geen acknowledge op de data\")\r\n else:\r\n logging.error(\"geen acknowledge op het address\")\r\n self.stoppen_pcf()","sub_path":"backend/GPIOMCT/DisplayPcf.py","file_name":"DisplayPcf.py","file_ext":"py","file_size_in_byte":4457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"626101000","text":"import cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nversion=0.1\n\n# list 2 images (or image frame from video)\nimg1 = cv2.imread('./hatch.jpeg',0)\nimg2 = cv2.imread('./findin.jpg',0)\n\n# similarity detector\norb = cv2.ORB_create()\n\n# key points for each img\nkp1, des1 = orb.detectAndCompute(img1,None)\nkp2, des2 = orb.detectAndCompute(img2,None)\n\nbf= cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck= True)\n\n# sort matches\nmatches = bf.match(des1, des2)\nmatches = sorted(matches, key = lambda x:x.distance)\n\nimg3= cv2.drawMatches(img1, kp2, img2,kp2, matches[:10], None, flags=2 )\nplt.imshow(img3)\nplt.show()\n","sub_path":"image_rec.py","file_name":"image_rec.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"624917428","text":"import numpy as np\n\nclass NN(object):\n def __init__(self, layers = [10 , 20, 1], activations=['sigmoid', 'relu'], usage = 'regression'):\n #my model is very sensitive to initial value sometimes\n #maybe the gradient descent method is too naive\n assert(len(layers) == len(activations)+1)\n self.layers = layers\n self.activations = activations\n self.weights = []\n self.biases = []\n self.usage = usage\n for i in range(len(layers)-1):\n if self.activations[i] in ['relu', 'selu', 'elu']:\n self.weights.append(np.random.randn(layers[i+1], layers[i])*np.sqrt(2./layers[i])) #heuristic\n self.biases.append(np.random.randn(layers[i+1], 1)*0.1) #can be 0\n else:\n self.weights.append(np.random.randn(layers[i+1], layers[i])*np.sqrt(1./layers[i])) #heuristic\n self.biases.append(np.random.randn(layers[i+1], 1)*0.1) #can be 0\n\n\n def feedforward(self, x): #x = dim*num\n ai = np.copy(x)\n z_s = []\n a_s = [ai]\n for i in range(len(self.weights)):\n z_s.append(self.weights[i].dot(ai) + self.biases[i])\n ai = self.AF(self.activations[i])(z_s[-1])\n a_s.append(ai)\n return z_s, a_s\n\n def backpropagation(self,y, z_s, a_s): #y = 1*num\n dw = [] # dJ/dW\n db = [] # dJ/dB\n deltas = [None] * len(self.weights) # delta = dJ/dZ, error for each layer\n\n #delta out(dJ/dOut)\n delta_out = self.dJ(self.usage)(a_s[-1], y)\n #last layer delta\n deltas[-1] = delta_out*(self.dAF(self.activations[-1]))(z_s[-1])\n #backpro\n for i in reversed(range(len(deltas)-1)):\n deltas[i] = self.weights[i+1].T.dot(deltas[i+1])*(self.dAF(self.activations[i])(z_s[i]))\n batch_size = y.shape[1]\n db = [d.dot(np.ones((batch_size,1)))/float(batch_size) for d in deltas]\n dw = [d.dot(a_s[i].T)/float(batch_size) for i,d in enumerate(deltas)]\n #eps = 0.001\n #for i in range(len(dw)):\n # assert(np.linalg.norm(dw[i]) > eps)\n return dw, db\n\n def train(self, x, y, batch_size=10, epochs=100, lr = 0.1): #x = num*dim #y = num*dim\n #record cost by epchos\n learning_curve = []\n #mini batch + shuffle\n #epcho = dataset is used epcho times\n #iteration*batchsize ~= dataset size\n indices = np.arange(x.shape[0])#debug if 0\n np.random.shuffle(indices)\n x = x[indices]\n y = y[indices]\n\n for e in range(epochs):\n cur = 0\n while(cur < len(y)):\n nxt = cur + batch_size\n x_batch, y_batch = x[cur:nxt], y[cur:nxt] #if nxt>len(y)=>just the last segment\n x_batch, y_batch = x_batch.T, y_batch.T #print(y_batch.shape)\n cur = nxt\n z_s, a_s = self.feedforward(x_batch)\n dw, db = self.backpropagation(y_batch, z_s, a_s)\n self.weights = [wi+lr*dwi for wi,dwi in zip(self.weights, dw)]\n self.biases = [bi+lr*dbi for bi,dbi in zip(self.biases, db)]\n loss = self.J(self.usage)(a_s[-1],y_batch)\n learning_curve.append(loss) #learning_curve update per epoch\n\n return learning_curve\n\n\n def calc_error(self, test_X, test_y): #num*dim\n _, a_s = self.feedforward(test_X.T)\n return self.J(self.usage)(a_s[-1], test_y.T)\n\n def prediction(self, X): #num*dim\n _, a_s = self.feedforward(X.T)\n return a_s[-1]\n\n def calc_accuracy(self, test_X, test_y): #num*dim\n _, a_s = self.feedforward(test_X.T)\n n = a_s[-1].shape[1]\n total = 0.\n correct = 0.\n for i in range(n):\n total += 1\n if (a_s[-1][0][i] >= 0.5) == bool(test_y[i]):\n correct += 1\n return correct/total\n\n @staticmethod\n def AF(name):\n if(name == 'sigmoid'):\n def sig(x):\n x = np.clip(x , -10., 10.)\n return np.exp(x)/(1+np.exp(x))\n return sig\n elif(name == 'linear'):\n return lambda x : x\n elif(name == 'relu'):\n def relu(x):\n return np.where(x<0,0,x)\n return relu\n elif(name == 'selu'):\n def selu(x,lamb=1.0507009873554804934193349852946, alpha=1.6732632423543772848170429916717):\n x = np.clip(x , -10., 10.)\n return lamb*np.where(x<0,alpha*(np.exp(x) - 1),x)\n return selu\n else:\n print('unknown activation function => linear')\n return lambda x: x\n\n @staticmethod\n def dAF(name):\n if(name == 'sigmoid'):\n def dsig(x):\n x = np.clip(x , -10., 10.)\n sigx = np.exp(x)/(1+np.exp(x))\n return sigx*(1-sigx)\n return dsig\n elif(name == 'linear'):\n return lambda x: 1\n elif(name == 'relu'):\n def drelu(x):\n return np.where(x<0,0,1)\n return drelu\n elif(name == 'selu'):\n def dselu(x,lamb=1.0507009873554804934193349852946, alpha=1.6732632423543772848170429916717):\n x = np.clip(x , -10., 10.)\n return lamb*np.where(x<0,alpha*np.exp(x),1)\n return dselu\n else:\n print('unknown activation function => linear derivative')\n return lambda x: 1\n\n @staticmethod\n def dJ(name):\n if(name == 'regression'):\n return lambda x, y: y-x\n if(name == 'classification'):\n def dCE(yhat, y):\n epsilon=1e-12\n yhat = np.clip(yhat, epsilon, 1. - epsilon)\n return np.divide(y, yhat) - np.divide(1 - y, 1 - yhat)\n return dCE\n else:\n print('unknown usage => regression')\n return lambda x, y: y-x\n\n @staticmethod\n def J(name):\n if(name == 'regression'):\n return lambda x, y: np.linalg.norm(y-x)/np.sqrt(max(y.shape[0], y.shape[1])) #RMS\n if(name == 'classification'):\n def cross_entropy(yhat, y):\n epsilon=1e-12\n yhat = np.clip(yhat, epsilon, 1. - epsilon)\n n = yhat.shape[1]\n ce = -np.sum(y*np.log(yhat))/n\n return ce\n return cross_entropy\n else:\n print('unknown usage => regression')\n return lambda x, y: np.linalg.norm(y-x)/np.sqrt(max(y.shape[0], y.shape[1])) #RMS\n","sub_path":"HW1/HW1_0712238/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":6540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"25216493","text":"from django.db import models\nfrom django.utils import timezone\nfrom django.contrib.auth.models import User\nfrom django.conf import settings\nimport uuid\n\n# Create your models here.\n\n# Each individual piece is a MenuItem that staff can add to a daily meal menu\n# Breakfast will be the same every day. This will be reflected in the views/templates.\nclass MenuItem(models.Model):\n types = (\n (\"Breakfast\", \"Breakfast\"),\n (\"Lunch\", \"Lunch\"),\n (\"Dinner\", \"Dinner\")\n ) \n price = models.FloatField()\n item = models.CharField(max_length=30)\n type = models.CharField(max_length=30, choices=types)\n quantity = models.IntegerField(default=99) \n \n def __str__(self):\n return self.item\n \n# This will be an order \"summary\" relating to an individual member detailing the total\n# price of the order and when it was placed\nclass MealOrder(models.Model):\n types = (\n (\"Breakfast\", \"Breakfast\"),\n (\"Lunch\", \"Lunch\"),\n (\"Dinner\", \"Dinner\")\n ) \n total_price = models.FloatField()\n member = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)\n type = models.CharField(max_length=30, choices=types)\n time_placed = models.DateTimeField(default=timezone.localtime(timezone.now())) # apparently remove the () after timezone.now otherwise we get the time the server loaded instead of time model is made (as the parentheses CALL the function!)\n notes = models.CharField(max_length=50)\n acknowledged = models.BooleanField(default=False) # the staff will set this to TRUE when they receive the order\n\n class Meta:\n ordering = ['-time_placed']\n \n def __str__(self):\n return self.member.surname + \" \" + str(self.id)\n \n \n# This model represents each individual item that will be added to a meal\n# Therefore the MealOrder model has multiple of these \"items\" that build up to\n# represent the entire order\nclass MealOrderItem(models.Model):\n item = models.CharField(max_length=30)\n order = models.ForeignKey(MealOrder, on_delete=models.CASCADE, null=True, related_name=\"items\") \n price = models.FloatField() \n \n def __str__(self):\n return self.item + \": \" + str(self.price)\n\n ","sub_path":"main/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"369727107","text":"import numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nimport seaborn as sns\r\nimport streamlit as st\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.svm import SVC\r\nfrom sklearn.linear_model import LogisticRegression \r\nfrom sklearn.ensemble import RandomForestClassifier\r\n\r\n# Loading the dataset.\r\niris_df = pd.read_csv(\"iris-species.csv\")\r\n\r\n# Adding a column in the Iris DataFrame to resemble the non-numeric 'Species' column as numeric using the 'map()' function.\r\n# Creating the numeric target column 'Label' to 'iris_df' using the 'map()' function.\r\niris_df['Label'] = iris_df['Species'].map({'Iris-setosa': 0, 'Iris-virginica': 1, 'Iris-versicolor':2})\r\n\r\n# Creating features and target DataFrames.\r\nX = iris_df[['SepalLengthCm','SepalWidthCm', 'PetalLengthCm', 'PetalWidthCm']]\r\ny = iris_df['Label']\r\n\r\n# Splitting the dataset into train and test sets.\r\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.33, random_state = 42)\r\n\r\n# Creating an SVC model. \r\nsvc_model = SVC(kernel = 'linear')\r\nsvc_model.fit(X_train, y_train)\r\n\r\n# Creating a Logistic Regression model. \r\nrf_clf = RandomForestClassifier(n_jobs = -1, n_estimators = 100)\r\nrf_clf.fit(X_train, y_train)\r\n\r\n# Creating a Random Forest Classifier model.\r\nlog_reg = LogisticRegression(n_jobs = -1)\r\nlog_reg.fit(X_train, y_train)\r\n\r\n\r\n\r\n\r\n@st.cache()\r\ndef prediction(model, sepal_length, sepal_width, petal_length, petal_width):\r\n species = model.predict([[sepal_length, sepal_width, petal_length, petal_width]])\r\n species = species[0]\r\n if species == 0:\r\n return \"Iris-setosa\"\r\n elif species == 1:\r\n return \"Iris-virginica\"\r\n else:\r\n return \"Iris-versicolor\"\r\n\r\n\r\n\r\n\r\n\r\nst.sidebar.title('Iris Flower Species Prediction')\r\nsep_l = st.sidebar.slider('Sepal Length',float(iris_df['SepalLengthCm'].min()),float(iris_df['SepalLengthCm'].max()))\r\nsep_w = st.sidebar.slider('Sepal Width',float(iris_df['SepalWidthCm'].min()),float(iris_df['SepalWidthCm'].max()))\r\npet_l = st.sidebar.slider('Petal Length',float(iris_df['PetalLengthCm'].min()),float(iris_df['PetalLengthCm'].max()))\r\npet_w = st.sidebar.slider('Petal Width',float(iris_df['PetalWidthCm'].min()),float(iris_df['PetalWidthCm'].max()))\r\nst.sidebar.title('Choose Classifier')\r\nclss = st.sidebar.selectbox('Classifier',('Logistic Regression','RFC','SVM'))\r\nif st.sidebar.button('Predict') :\r\n\tif clss == 'Logistic Regression':\r\n\t\tpred = prediction(log_reg,sep_l,sep_w,pet_l,pet_w)\r\n\t\tscore = log_reg.score(X_train,y_train)\r\n\telif clss == 'SVC':\r\n\t\tpred = prediction(svc_model,sep_l,sep_w,pet_l,pet_w)\r\n\t\tscore = svc_model.score(X_train,y_train)\r\n\telse :\r\n\t\tpred = prediction(rf_clf,sep_l,sep_w,pet_l,pet_w)\r\n\t\tscore = rf_clf.score(X_train,y_train)\r\n\tst.write('Predicted result : ',pred)\r\n\tst.write('Score of Algorithm : ',score)","sub_path":"iris_improved.py","file_name":"iris_improved.py","file_ext":"py","file_size_in_byte":2822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"567879141","text":"# -*- coding: utf-8 -*-\n# @Time : 2017/10/14\n# @Author : ywh\n# @Email : yipwinghong@outlook.com\n# @File : String\n# @Software: PyCharm\n\n\nMAXSIZE = 100\n\n\nclass SqString(object):\n \"\"\" 顺序串 \"\"\"\n\n def __init__(self, elem=None, max_size=MAXSIZE):\n \"\"\" 初始化 \"\"\"\n\n self.elem = elem if elem else [0]\n self.length = max_size + 1\n\n\nclass Chunk(object):\n \"\"\" 链串节点(块) \"\"\"\n\n def __init__(self, elem=None, next=None):\n \"\"\" 初始化 \"\"\"\n\n self.elem = elem\n self.next = next\n\n\nclass LinkString(object):\n \"\"\" 链串 \"\"\"\n\n def __init__(self):\n \"\"\" 初始化 \"\"\"\n\n self.head = self.tail = Chunk()\n self.length = 0\n\n\n\"\"\" \n 串的模式匹配算法:\n 在主串中查找pos个字符后子串第一次出现的位置\n\"\"\"\n\ndef bf(main, sub, pos=1):\n \"\"\" BF算法(朴素串匹配算法) \"\"\"\n\n sub_length = len(sub)\n main_length = len(main)\n\n # 设字符串第0位为串长度,第1~n位为串\n i, j = pos, 1\n\n while i < main_length and j < sub_length:\n\n # 如匹配则把子串指针和主串指针都移动到后一位\n if main[i] == sub[j]:\n i, j = i + 1, j + 1\n\n # 不匹配则把子串指针回溯到\n else:\n i, j = i - j + 2, 1\n\n return i - sub_length if j == sub_length else -1\n\n\ndef kmp(main, sub, pos=1):\n\n sub_length = len(sub)\n main_length = len(main)\n\n # j从最左端开始向前移动\n # k标��为-1,表示在KMP算法中默认从第一个字符开始子串就与主串不匹配\n # 此时主串指针向前移动一位,子串指针回到第一位(从头开始匹配)\n j, k = 0, -1\n next_arr = [-1] * sub_length\n while j < sub_length - 1:\n\n # 当子串中j指针的值与k指针的值相等,表示KMP中匹配到第j位时失败,子串指针应退回到第k位\n if k == -1 or sub[j] == sub[k]:\n j, k = j + 1, k + 1\n # next_arr[i] = j\n\n # next修正:当sub中第0~k位都与j-k~j位对应地相等,直接使用next数组中已有的值\n if sub[j] != sub[k]:\n next_arr[j] = k\n # 当sub中第0~k-1位都与j-k~j-1位对应地相等、但第k位与第j位不相等,表示需返回到第k位\n else:\n next_arr[j] = next_arr[k]\n\n # 当j指针的值与k指针的值不相等,表示此时k指针左边(不含)有最长子串,与j指针左边最长子串长度相等\n # 相当于在子串中求子串,把k回溯到“当匹配到位置k时失败,应回溯到的位置”\n else:\n k = next_arr[k]\n\n # 使用next数组求子串位置:与bf算法类似\n i, j = pos, 0\n while i < main_length and j < sub_length:\n if j == 0 or main[i] == sub[j]:\n i, j = i + 1, j + 1\n else:\n next_j = next_arr[j]\n j = 0 if next_j == -1 else next_j\n\n return i - sub_length if j == sub_length else -1\n\n\n\"\"\"\n 修正next数组:\n j 1 2 3 4 5\n 子串 a a a a b\n next[j] 0 1 2 3 4\n nextval[j] 0 0 0 0 4\n\n 主串:abaaaaab\n\"\"\"\n\n\n# TODO BUG...\ndef regex_match(regex, text):\n \"\"\" \n 简化的正则表达式 \n . 匹配任意单个字符\n ^ 匹配串开头字符\n $ 匹配串结尾字符\n * 匹配任意多个字符\n \"\"\"\n\n def match(regex, regex_index, text, text_index):\n \"\"\" 检查模式与正文是否匹配 \"\"\"\n\n while 1:\n # 匹配到模式的尽头\n if regex_index == len(regex):\n return True\n\n # 在模式中匹配到下一个字符为$\n if regex[regex_index] == \"$\":\n return regex_index + 1 == len(regex) and text_index == len(text)\n\n # 在模式中匹配到下一个字符为*,则在后面的正文中匹配任意多个当前字符\n if regex_index + 1 < len(regex) and regex[regex_index + 1] == \"*\":\n return match_sub(regex[regex_index], regex, regex_index+2, text, text_index)\n\n # 模式字符与正文字符不匹配,且模式字符不为“.”\n if regex[regex_index] != \".\" and regex[regex_index] != text[text_index]:\n return False\n\n # 匹配到正文的尽头但还没匹配到完整的模式\n if text_index == len(text):\n return False\n\n regex_index, text_index = regex_index + 1, text_index + 1\n\n def match_sub(char, regex, regex_index, text, text_index):\n \"\"\" 在正文中跳过0或多个char后再匹配 \"\"\"\n\n for sub_index in range(text_index, len(text)):\n if match(regex, regex_index, text, sub_index):\n return True\n if text[sub_index] != char and char != \".\":\n break\n return False\n\n # 模式的首个字符为^\n if regex[0] == \"^\" and match(regex, 1, text, 0): # 逐个匹配^之后的字符\n return 1\n\n for text_index in range(len(text)):\n if match(regex, 0, text, text_index): # 逐个匹配模式的字符\n return text_index\n\n return False\n\n\nt = \"aaaaaaaba\"\ns = \"aaaab\"\n\nprint(kmp(t, s))\n#\n# reg = \"gab\"\n# text = \"qagabbbbc\"\n# print(regex_match(reg, text))\n","sub_path":"data_structure/String.py","file_name":"String.py","file_ext":"py","file_size_in_byte":5343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"434682888","text":"from pyspark import SparkContext, SparkConf\n\n#create the spark context\nconf = SparkConf().setAppName(\"MIFE Application\").setMaster(\"local\")\nsc = SparkContext(conf=conf)\n\n#read all lines from the log file\nlines = sc.textFile(\"hdfs://sandbox:9000/user/root/bl/carbon.log\")\n\n#read INFO lines from all lines\ninfo_lines = lines.filter(lambda line: \"INFO\" in line)\n\n#========================== read request lines ==========================\n\n#read >>>> lines from INFO lines\nrequest_lines = info_lines.filter(lambda line: \">>>>\" in line)\n\n#split the >>>> lines in to columns\nrequest_rows =request_lines.map(lambda line : line.split(\" \"))\n\n#-----last update line 2018-12-28 ---------\nrequest_rows.select(regexp_extract('value', r'^([^\\s]+\\s)', 1).alias('host'))\n\n#create a list for requests\n#request_row_list=[]\n#i=0\n\n#for row in request_rows.take(request_rows.count()):\n#\trequest_row=[row[3],row[4],row[16],row[16],row[21]]\n#\trequest_row_list.insert(i,request_row)\n#\ti=i+1\n\nprint(\"============request list start =====\")\n\n#for i in range(len(request_row_list)):\n#\tprint(request_row_list[i])\n\nprint(\"============request list end =======\")\n\n#print(len(request_row_list))\n\nprint(\"====================================\")\n\n#========================== read response lines ==========================\n\n#read <<<< lines from INFO lines\n#response_lines=info_lines.filter(lambda line: \"<<<<\" in line)\n\n#split the <<<< lines in to columns\n#response_rows=response_lines.map(lambda line:line.split(\" \"))\n\n#create a list for responses\n#response_row_list=[]\n#i=0\n#for row in response_rows.take(response_rows.count()):\n#\tresponse_row=[row[3],row[4],row[16],row[16],row[21],row[26],row[30]]\n#\tresponse_row_list.insert(i,response_row)\n#\ti=i+1\n\t\n\n#print(\"============response list start =====\")\n\n#for i in range(len(response_row_list)):\n#\tprint(response_row_list[i])\n\n#print(\"============response list end =======\")\n\n#print(len(response_row_list))\n\n#print(\"=====================================\")\n\n","sub_path":"pyspark_scripts_logfiles/Python test scripts/2018-12-28/mife-copy5.py","file_name":"mife-copy5.py","file_ext":"py","file_size_in_byte":1971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"484426134","text":"\"\"\"\nprims.py\n\"\"\"\n\nclass Node():\n \"\"\"\n simple node class\n \"\"\"\n def __init__(self, name, seen=False):\n self.name = name\n self.edges = {}\n #Boolean flag if the node has been seen by the algorithm\n self.seen = seen\n \n def add_edge(self, end_point, weight):\n #This makes it easier to connect nodes, because you don't have to type node.name\n if str(type(end_point)) == \"\":\n end_point = end_point.name\n self.edges[end_point] = weight\n\n def remove_edge(self, end_point):\n #This function was only for debug purposes\n del self.edges[end_point]\n\nclass Graph():\n \"\"\"\n OO wrapper for an adjacency list graph using dictionaries\n \"\"\"\n def __init__(self):\n self.nodes = {}\n\n def add_node(self, node):\n self.nodes[node.name] = node.edges\n\n def add_edge(self, v0, v1, weight):\n v0.add_edge(v1, weight)\n v1.add_edge(v0, weight)\n\nif __name__ == \"__main__\":\n a = Node('a')\n b = Node('b')\n c = Node('c')\n d = Node('d')\n\n a.add_edge(b, 5)\n a.add_edge(c, 3)\n a.add_edge(d, 6)\n\n b.add_edge(a, 5)\n c.add_edge(a, 3)\n d.add_edge(a, 6)","sub_path":"Algorithms/prims-alg/failed/prims.py","file_name":"prims.py","file_ext":"py","file_size_in_byte":1200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"114009610","text":"#!/usr/bin/env python\n#\n# Configuration File Parser\n#\n# class AppConfig will override the original function: optionxform\n# which can keep the original option name (case sensitive)\n# for configuration dictionary.\n#\n\nimport ConfigParser\n\nclass AppConfig(ConfigParser.ConfigParser):\n def __init__(self):\n ConfigParser.ConfigParser.__init__(self)\n\n def optionxform(self, optionstr):\n \"\"\"\n re-define optionxform, in the release version, return optionstr.lower()\n \"\"\"\n return optionstr\n\ndef get_conf_options(conf_files, key_lower=True):\n conf_options = dict()\n if key_lower:\n conf_parser = ConfigParser.ConfigParser()\n else:\n conf_parser = AppConfig()\n conf_parser.read(conf_files)\n for section in conf_parser.sections():\n t_section = dict()\n for option in conf_parser.options(section):\n value = conf_parser.get(section, option)\n t_section[option] = value\n conf_options[section] = t_section\n return conf_options\n","sub_path":"tmp_client/doc/TMP_example/standard_suite/gui_flow/tst_case1/testmethod/check/check_lib/xConf.py","file_name":"xConf.py","file_ext":"py","file_size_in_byte":1034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"395056834","text":"import os\nimport glob\n#-----------------helper functions--------------------------------\ndef projectDict():\n with open('projects.txt', 'r') as myFile:\n line = myFile.readlines()[2:]\n i=0\n list =[]\n circuit=[]\n project=[]\n\n while(i 1:\n ret.pop()\n else:\n middle = False\n for i in ret:\n parse(g, i)\n count += 1\n curser += len(i)\n \n readfile.seek(curser)\n\n\nif __name__ == \"__main__\":\n pass","sub_path":"datacleaner/clean_tweets_wo_uid.py","file_name":"clean_tweets_wo_uid.py","file_ext":"py","file_size_in_byte":3262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"127694097","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Aug 25 22:42:13 2017\n\n@author: owen\n\"\"\"\n# https://discuss.leetcode.com/topic/79938/super-short-easy-java-o-n-solution/18\nclass Solution(object):\n def findMinMoves(self, machines):\n \"\"\"\n :type machines: List[int]\n :rtype: int\n \"\"\"\n sums=sum(machines)\n n=len(machines)\n if sums%n:\n return -1\n ave=sums//n\n total=0\n res=0\n for m in machines: # starts from the first machine\n total+=m-ave # gain/lose array: how many moves are needed to make it equal to average, positive means give them to right neighbor, negative means request them from right neighbor\n res=max(res, max(abs(total),m-ave)) # abs(total): previous accumulate moves, m-ave: current moves\n \n return res\n \n \n \nif __name__==\"__main__\":\n print(Solution().findMinMoves([1,0,5]))\n print(Solution().findMinMoves([0,3,0]))\n print(Solution().findMinMoves([0,2,0]))","sub_path":"517. Super Washing Machines.py","file_name":"517. Super Washing Machines.py","file_ext":"py","file_size_in_byte":1048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"58723428","text":"# Imports\nimport cv2\nimport numpy as np\n\n# Variables\nimagePath = \"Camera Inputs/Files/img.jpg\"\n\ndef captureImage():\n cap = cv2.VideoCapture(0)\n check, img = cap.read()\n cv2.imwrite(imagePath, img)\n\n return img\n\ncaptureImage()","sub_path":"CameraInputs/GetCameraInput.py","file_name":"GetCameraInput.py","file_ext":"py","file_size_in_byte":237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"14940546","text":"################################################################################\r\n# AoC_5-1.py\r\n# 2019-12-05\r\n# Mike Quigley\r\n#\r\n# https://adventofcode.com/2019/day/5\r\n#\r\n# This is an intcode emulator, like day 2.\r\n# The following features have been added:\r\n# *Parameter modes\r\n# Opcodes are treated as 5 digit numbers. Leading 0s are assumed.\r\n# The last two digits are the opcode. The remaining 3 determine if the\r\n# parameters are treated as values (1 for immediate mode),\r\n# or pointers (0 for position mode). It's right to left, so the first\r\n# digit refers to the third parameter.\r\n# Parameters that an instruction writes to must be in position mode\r\n# *New opcodes for input/output. These have only one parameter, not 3\r\n#\r\n# Opcode table:\r\n# 1: ADD A B DEST - Adds A + B, result in DEST.\r\n# 2: MUL A B DEST - Multiplies A * B, result in DEST\r\n# 3: INP DEST - Reads keyboard input to DEST\r\n# 4: OUT A - Print A\r\n# 99: HALT\r\n################################################################################\r\n\r\nram = []\r\n\r\ndef list():\r\n for i in range(0,len(ram),4):\r\n print(i, ':', ram[i:i+4])\r\n\r\ndef init(n):\r\n for i in range(0,n):\r\n ram.append(0)\r\n\r\ndef clear():\r\n for i in range(0,len(ram)):\r\n ram[i] = 0\r\n\r\ndef load(program):\r\n pL = program.split(',')\r\n for i in range(0,len(pL)):\r\n ram[i] = int(pL[i])\r\n\r\ndef loadfile(filename):\r\n file = open(filename,'r')\r\n load(file.readline())\r\n file.close()\r\n\r\ndef fetch(val, mode):\r\n if mode == 0:\r\n return ram[ram[val]]\r\n else:\r\n return ram[val]\r\n\r\ndef run():\r\n halt = False\r\n pc = 0\r\n op = 0\r\n pM = [0, 0, 0]\r\n while not halt:\r\n op = ram[pc] % 100\r\n pM[0] = (ram[pc] // 100) % 10\r\n pM[1] = (ram[pc] // 1000) % 10\r\n pM[2] = (ram[pc] // 10000) % 10\r\n if op == 1:\r\n ram[ram[pc+3]] = fetch(pc + 1, pM[0]) + fetch(pc + 2, pM[1])\r\n pc += 4\r\n elif op == 2:\r\n ram[ram[pc+3]] = fetch(pc + 1, pM[0]) * fetch(pc + 2, pM[1])\r\n pc += 4\r\n elif op == 3:\r\n ram[ram[pc+1]] = int(input(\"P> \"))\r\n pc += 2\r\n elif op == 4:\r\n print(fetch(pc + 1, pM[0]))\r\n pc += 2\r\n elif op == 99:\r\n print(\"END\")\r\n halt = True\r\n else:\r\n print(\"ERROR UNKNOWN OPCODE\", op, \"AT ADDR\", pc)\r\n halt = True\r\n\r\ninit(1024)\r\ninp = \"Input String\"\r\nwhile inp != \"EXIT\":\r\n inp = input(\"> \")\r\n if inp == \"LIST\":\r\n list()\r\n elif inp == \"CLEAR\":\r\n clear()\r\n elif inp == \"LOAD\":\r\n load(input(\"PROGRAM: \"))\r\n elif inp == \"LOADFILE\":\r\n loadfile(input(\"FILENAME: \"))\r\n elif inp == \"RUN\":\r\n run()\r\n","sub_path":"AoC_5-1.py","file_name":"AoC_5-1.py","file_ext":"py","file_size_in_byte":2766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"164698099","text":"import cv2\nimport xml.etree.ElementTree as et\nimport os\nfrom matplotlib.widgets import RectangleSelector\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n'''\n#============for in one image==========\n\nimg = cv2.imread('./images/002.png')\nfiles=os.listdir('./annotations/')\nx=(0,0)\ny=(0,0)\n\nfor file in files:\n doc = et.parse('./annotations/' + file)\n for i in doc.findall('object'):\n for j in i.findall('bndbox'):\n x = (int(j.find(\"xmin\").text), int(j.find(\"xmax\").text))\n y = (int(j.find('ymin').text), int(j.find('ymax').text))\n img=cv2.rectangle(img, (x[0], y[0]), (x[1], y[1]), (0, 255, 0), 2)\n\n\ncv2.imshow('img',img)\ncv2.waitKey()\ncv2.destroyAllWindows()\n# s=np.hstack(imgs)\n# cv2.imshow(s)\n'''\nn=20000\npath='./new_model_data/images/'\npath2='./new_model_data/annotations/'\nwhile True:\n img = cv2.imread(path+'{:06}.png'.format(n))\n img = cv2.resize(img,(1080,1920))\n # img2 = cv2.imread('./images/fist_blur/rot/-90/000000.png')\n\n x=(0,0)\n y=(0,0)\n\n doc = et.parse(path2+'{:06}.xml'.format(n))\n for i in doc.findall('object'):\n for j in i.findall('bndbox'):\n x = (int(j.find(\"xmin\").text), int(j.find(\"xmax\").text))\n y = (int(j.find('ymin').text), int(j.find('ymax').text))\n img = cv2.rectangle(img, (x[0], y[0]), (x[1], y[1]), (0, 255, 0), 2)\n\n # doc = et.parse('./images/fist_blur/rot/-90/000.xml')\n # for i in doc.findall('object'):\n # for j in i.findall('bndbox'):\n # x = (int(j.find(\"xmin\").text), int(j.find(\"xmax\").text))\n # y = (int(j.find('ymin').text), int(j.find('ymax').text))\n # img2 = cv2.rectangle(img2, (x[0], y[0]), (x[1], y[1]), (255, 0, 0), 2)\n\n\n cv2.imshow('img', img)\n # cv2.imshow('img2', img2)\n\n cv2.waitKey()\n n+=1\ncv2.destroyAllWindows()\n","sub_path":"check_box.py","file_name":"check_box.py","file_ext":"py","file_size_in_byte":1833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"356910929","text":"# 计算某个点到其它各点的最短路径,可以有负权值\n# 假设有5个顶点,就需要4次遍历,第一轮在对所有的边进行松弛后,得到的是从1号顶点“只能经过一条边”到达其余各顶点的最短路径长度。第二轮在对\n# 所有的边进行松弛后,得到的是从1号顶点“最多经过两条边”到达其余各顶点的最短路径长度。如果进行k轮的话,得到的就是1号顶点“最多经过k条边”\n# 到达其余各顶点的最短路径长度。\n# 核心代码是看能否通过u[i]-v[i](权值为w[i])这条边,使得起点到v[i]顶点的距离变短,即起点到u[i]的距离加上u[i]-v[i]的距离,是否会比原先起点到v[i]的距离小。\n\nmax = 9999\nshortRoot = [0, max, max, max, max] # 初始化\n\ndef dfs(start, roots):\n for i in range(len(roots) - 1):\n check = 0\n for root in roots:\n if shortRoot[root[1]] > shortRoot[root[0]] + root[2]:\n shortRoot[root[1]] = shortRoot[root[0]] + root[2]\n check = 1 # 标识本次发生了变化\n if check == 0:\n break\n # 判断是否有负回路,就是在进行完n-1次轮询后,再进行一次,如果有路径变短了,就说明有负回路,因为有负回路的路径没有最短,每一次轮询都会变短。\n flag = 0\n for root in roots:\n if shortRoot[root[1]] > shortRoot[root[0]] + root[2]:\n shortRoot[root[1]] = shortRoot[root[0]] + root[2]\n flag = 1\n if flag == 1:\n print(\"有负回路\")\n else:\n print(\"没有负回路\")\n\n\ndfs(0, [(1, 2, 2), (0, 1, -3), (0, 4, 5), (3, 4, 2), (2, 3, 3)]) # 没有负回路\n# dfs(0, [(1, 2, 2), (0, 1, -3), (0, 4, 5), (3, 4, 2), (2, 3, 3), (3, 0, -3)]) # 有负回路\n\nfor i in shortRoot:\n print(i, end=\", \")","sub_path":"啊哈!算法/最短路径/BellmanFord.py","file_name":"BellmanFord.py","file_ext":"py","file_size_in_byte":1839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"187772983","text":"from torch.utils.data.dataset import Dataset\nfrom torchvision import transforms\nfrom scipy.misc import imread, imresize\nimport numpy as np\nfrom PIL import Image\nimport cv2 as cv\nfrom utilities_general import histogram_eq\n\nclass ISIC_Dataset(Dataset):\n def __init__(self, file_path,imageSize, transform = None):\n\n self.height = imageSize\n self.width = imageSize\n self.transform = transform\n self.lines = [line.rstrip('\\n') for line in open(file_path)]\n self.paths = [line.split()[0] for line in self.lines]\n self.labels = []\n [self.labels.append(int(line.split()[1])) for line in self.lines]\n self.to_tensor = transforms.ToTensor()\n self.data_len = len(self.paths)\n\n def __getitem__(self, index):\n\n img = imread(self.paths[index])\n img = imresize(img, (self.height, self.width , 3))\n\n img[0] = img[0] - np.mean(img[0])\n img[1] = img[1] - np.mean(img[1])\n img[2] = img[2] - np.mean(img[2])\n img = histogram_eq(img)\n if self.transform is not None:\n img = self.transform(img)\n\n label = self.labels[index]\n return img, label\n\n def __len__(self):\n return self.data_len # of how many data(images?) you have\n\n","sub_path":"utils/ISIC_DataLoader.py","file_name":"ISIC_DataLoader.py","file_ext":"py","file_size_in_byte":1255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"64776495","text":"class Solution:\r\n def isMatch(self, s, p):\r\n \"\"\"\r\n 通配符匹配,动态规划\r\n :param s:给定字符串\r\n :param p:匹配规则\r\n :return:True匹配 False不匹配\r\n \"\"\"\r\n # 动态规划 dp[i][j] 表示s前i个和p的前j个匹配的状态\r\n dp = [[False for i in range(0, len(p) + 1)] for j in range(0, len(s) + 1)]\r\n dp[0][0] = True\r\n\r\n for j in range(1, len(p) + 1):\r\n # 当前为*,匹配任意字符串\r\n if p[j - 1] == \"*\":\r\n dp[0][j] = dp[0][j - 1]\r\n\r\n for i in range(1, len(s) + 1):\r\n for j in range(1, len(p) + 1):\r\n if s[i - 1] == p[j - 1] or p[j - 1] == \"?\":\r\n dp[i][j] = dp[i - 1][j - 1]\r\n elif p[j - 1] == \"*\":\r\n dp[i][j] = dp[i - 1][j] or dp[i][j - 1]\r\n\r\n return dp[-1][-1]\r\n\r\n\r\nif __name__ == \"__main__\":\r\n print(Solution().isMatch(\"aa\", \"a*\"))\r\n","sub_path":"LeetCode_Python/Test_44_isMatch_.py","file_name":"Test_44_isMatch_.py","file_ext":"py","file_size_in_byte":974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"608802487","text":"# Some of the code here is taken from \n# https://github.com/ilblackdragon/tf_examples/blob/master/seq2seq/seq2seq.py\n\nimport tensorflow as tf\nfrom tensorflow.contrib import layers\n\nclass Seq2seq:\n def __init__(self, FLAGS):\n self.FLAGS = FLAGS\n self.END_TOKEN = 1\n self.UNK_TOKEN = 2\n\n # create vocab and reverse vocab maps\n self.vocab = {}\n self.rev_vocab = {}\n with open(FLAGS.vocab_filename) as f:\n for idx, line in enumerate(f):\n self.vocab[line.strip()] = idx\n self.rev_vocab[idx] = line.strip()\n\n def make_graph(self,mode, features, labels, params):\n vocab_size = len(self.vocab)\n embed_dim = params.embed_dim\n num_units = params.num_units\n\n input,output = features['input'], features['output']\n batch_size = tf.shape(input)[0]\n start_tokens = tf.zeros([batch_size], dtype= tf.int64)\n train_output = tf.concat([tf.expand_dims(start_tokens, 1), output], 1)\n input_lengths = tf.reduce_sum(tf.to_int32(tf.not_equal(input, 1)), 1)\n output_lengths = tf.reduce_sum(tf.to_int32(tf.not_equal(train_output, 1)), 1)\n input_embed = layers.embed_sequence(input, vocab_size= vocab_size, embed_dim = embed_dim, scope = 'embed')\n output_embed = layers.embed_sequence(train_output, vocab_size= vocab_size, embed_dim = embed_dim, scope = 'embed', reuse = True)\n with tf.variable_scope('embed', reuse=True):\n embeddings = tf.get_variable('embeddings')\n cell = tf.contrib.rnn.GRUCell(num_units=num_units)\n if self.FLAGS.use_residual_lstm:\n cell = tf.contrib.rnn.ResidualWrapper(cell)\n encoder_outputs, encoder_final_state = tf.nn.dynamic_rnn(cell, input_embed, dtype=tf.float32)\n\n\n def decode(helper, scope, reuse=None):\n with tf.variable_scope(scope, reuse=reuse):\n attention_mechanism = tf.contrib.seq2seq.BahdanauAttention(\n num_units=num_units, memory=encoder_outputs,\n memory_sequence_length=input_lengths)\n cell = tf.contrib.rnn.GRUCell(num_units=num_units)\n attn_cell = tf.contrib.seq2seq.AttentionWrapper(cell, attention_mechanism, attention_layer_size=num_units / 2)\n out_cell = tf.contrib.rnn.OutputProjectionWrapper(attn_cell, vocab_size, reuse=reuse)\n decoder = tf.contrib.seq2seq.BasicDecoder(\n cell=out_cell, helper=helper,\n initial_state=out_cell.zero_state(\n dtype=tf.float32, batch_size=batch_size))\n outputs = tf.contrib.seq2seq.dynamic_decode(\n decoder=decoder, output_time_major=False,\n impute_finished=True, maximum_iterations=self.FLAGS.output_max_length\n )\n return outputs[0]\n\n train_helper = tf.contrib.seq2seq.TrainingHelper(output_embed, output_lengths)\n pred_helper = tf.contrib.seq2seq.GreedyEmbeddingHelper(embeddings, start_tokens=tf.to_int32(start_tokens), end_token=1)\n train_outputs = decode(train_helper, 'decode')\n pred_outputs = decode(pred_helper, 'decode', reuse=True)\n\n tf.identity(train_outputs.sample_id[0], name='train_pred')\n weights = tf.to_float(tf.not_equal(train_output[:, :-1], 1))\n loss = tf.contrib.seq2seq.sequence_loss(train_outputs.rnn_output, output, weights=weights)\n train_op = layers.optimize_loss(\n loss, tf.train.get_global_step(),\n optimizer=params.optimizer,\n learning_rate=params.learning_rate,\n summaries=['loss', 'learning_rate'])\n\n tf.identity(pred_outputs.sample_id[0], name='predict')\n return tf.estimator.EstimatorSpec(mode=mode, predictions=pred_outputs.sample_id, loss=loss, train_op=train_op)\n\n\n def tokenize_and_map(self,line):\n return [self.vocab.get(token, self.UNK_TOKEN) for token in line.split(' ')]\n\n\n def make_input_fn(self):\n def input_fn():\n inp = tf.placeholder(tf.int64, shape=[None, None], name='input')\n output = tf.placeholder(tf.int64, shape=[None, None], name='output')\n tf.identity(inp[0], 'source')\n tf.identity(output[0], 'target')\n return {\n 'input': inp,\n 'output': output,\n }, None\n\n def sampler():\n while True:\n with open(self.FLAGS.input_filename) as finput, open(self.FLAGS.output_filename) as foutput:\n for in_line in finput:\n out_line = foutput.readline()\n yield {\n 'input': self.tokenize_and_map(in_line)[:self.FLAGS.input_max_length - 1] + [self.END_TOKEN],\n 'output': self.tokenize_and_map(out_line)[:self.FLAGS.output_max_length - 1] + [self.END_TOKEN]\n }\n\n data_feed = sampler()\n def feed_fn():\n inputs, outputs = [], []\n input_length, output_length = 0, 0\n for i in range(self.FLAGS.batch_size):\n rec = data_feed.next()\n inputs.append(rec['input'])\n outputs.append(rec['output'])\n input_length = max(input_length, len(inputs[-1]))\n output_length = max(output_length, len(outputs[-1]))\n for i in range(self.FLAGS.batch_size):\n inputs[i] += [self.END_TOKEN] * (input_length - len(inputs[i]))\n outputs[i] += [self.END_TOKEN] * (output_length - len(outputs[i]))\n return { 'input:0': inputs, 'output:0': outputs }\n return input_fn, feed_fn\n\n def get_formatter(self,keys):\n def to_str(sequence):\n tokens = [\n self.rev_vocab.get(x, \"\") for x in sequence]\n return ' '.join(tokens)\n\n def format(values):\n res = []\n for key in keys:\n res.append(\"****%s == %s\" % (key, to_str(values[key])))\n return '\\n'+'\\n'.join(res)\n return format\n\n","sub_path":"seq2seq.py","file_name":"seq2seq.py","file_ext":"py","file_size_in_byte":6135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"133413663","text":"#!/usr/bin/env python\n\"\"\"Main training workflow\"\"\"\nfrom __future__ import division\n\nimport os, time, argparse, subprocess, shutil\nimport myBertSum.src.others.myPyrouge as myPyrouge\n\ndef process(temp_dir, cand, ref):\n candidates = [line.strip() for line in open(cand, encoding='utf-8')] # 标准系统摘要\n references = [line.strip() for line in open(ref, encoding='utf-8')] # 生成摘要\n print(len(candidates))\n print(len(references))\n\n assert len(candidates) == len(references)\n\n cnt = len(candidates)\n current_time = time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime())\n tmp_dir = os.path.join(temp_dir, \"rouge-tmp-{}\".format(current_time))\n if not os.path.isdir(tmp_dir):\n os.mkdir(tmp_dir)\n os.mkdir(tmp_dir + \"/candidate\")\n os.mkdir(tmp_dir + \"/reference\")\n\n for i in range(cnt):\n if len(references[i]) < 1:\n continue\n with open(tmp_dir + \"/candidate/cand.{}.txt\".format(i), \"w\",\n encoding=\"utf-8\") as f:\n f.write(candidates[i])\n with open(tmp_dir + \"/reference/ref.{}.txt\".format(i), \"w\",\n encoding=\"utf-8\") as f:\n f.write(references[i])\n # 获取Rouge对象\n r = myPyrouge.Rouge155(temp_dir=temp_dir)\n # model_dir: 表示标准摘要的路径[确定,因为可以取clone的pyrouge包里面看,所以以后首先考虑来源]\n # system_dir:表示生成摘要的路径\n r.model_dir = tmp_dir + \"/reference/\"\n r.system_dir = tmp_dir + \"/candidate/\"\n r.model_filename_pattern = 'ref.#ID#.txt'\n r.system_filename_pattern = r'cand.(\\d+).txt'\n\n # 评测\n rouge_cmd = r.convert_and_evaluate()\n ret = subprocess.call(\"perl \" + rouge_cmd, shell=True)\n print(ret)\n # # 结果规范化\n # results_dict = r.output_to_dict(rouge_results)\n #\n if os.path.isdir(tmp_dir):\n shutil.rmtree(tmp_dir) # 递归的删除文件\n return ret\n\ndef testRouge(args, step):\n # 候选摘要地址 result文件夹\n can_path = '%s_step%d.candidate' % (args.result_path, step)\n # 最佳摘要地址 result文件夹\n gold_path = '%s_step%d.gold' % (args.result_path, step)\n\n result = process(args.temp_dir, can_path, gold_path)\n return 0\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\"-model_path\", default='../models/')\n parser.add_argument(\"-result_path\", default='../results/cnndm')\n parser.add_argument(\"-temp_dir\", default='../temp')\n parser.add_argument(\"-test_from\", default=\"../models/\" + \"model_step_\") # 23000.pt\n parser.add_argument(\"-train_from\", default='')\n parser.add_argument(\"-report_rouge\", default=True)\n parser.add_argument(\"-block_trigram\", default=True)\n\n args = parser.parse_args()\n for step in [\"152500\", \"155000\", \"160000\", \"2500\"]:\n args.test_from += step + \".pt\"\n testRouge(args, int(step))\n\n\"\"\"\nXML文件中,两类摘要用modle和peer表示,显然model文件是生成的\npeer表示偷窥,即标准摘要\n\n \n ../temp\\tmpo8deww0p\\model\n ../temp\\tmpo8deww0p\\system\n \n \n \n

cand.0.txt

\n
\n \n ref.0.txt\n \n
\n \n需要 smart_common_words.txt的支持\n\"\"\"\n","sub_path":"BertSumRBX/temp/pyrougeTest.py","file_name":"pyrougeTest.py","file_ext":"py","file_size_in_byte":3422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"328315101","text":"# json_data_filer.py\n\nimport shutil\nimport os\nimport glob\nimport json\nimport uuid\n\ndef copy_file_if_modified(srcfile, dstfile):\n if ((not os.path.exists(dstfile)) or os.path.getsize(srcfile) != os.path.getsize(dstfile)):\n shutil.copy2(srcfile, dstfile)\n \ndef load_json_from_file(filename):\n with open(filename) as data_file:\n data = json.load(data_file)\n return data\n\ndef save_json_to_file(data, filename):\n with open(filename, 'w') as data_file:\n json.dump(data, data_file, sort_keys=True, indent=4, ensure_ascii=False)\n\ndef run_filer(src, incoming_dir='incoming', imported_dir='imported', db_file='db.json'):\n if not os.path.isdir(incoming_dir):\n os.mkdir(incoming_dir)\n if not os.path.isdir(imported_dir):\n os.mkdir(imported_dir)\n\n for filename in glob.glob(src):\n print('Moving ' + filename + ' -> ' + incoming_dir)\n shutil.move(filename, incoming_dir)\n \n recs = []\n merged_files = []\n\n if os.path.exists(db_file):\n print('Loading ' + db_file)\n recs.extend(load_json_from_file(db_file))\n \n imported_new_file = False\n\n for filename in glob.glob(os.path.join(incoming_dir, '*')):\n print('Importing ' + filename)\n recs.extend(load_json_from_file(filename))\n merged_files.append(filename)\n imported_new_file = True\n\n if imported_new_file:\n temp_file = db_file + '.tmp'\n save_json_to_file(recs, temp_file)\n if os.path.exists(db_file):\n os.remove(db_file)\n os.rename(temp_file, db_file)\n\n for filename in merged_files:\n dstfile = os.path.join(imported_dir, str(uuid.uuid4()) + '.json')\n shutil.move(filename, dstfile)\n \n print('Wrote ' + str(len(recs)) + ' records to ' + db_file + '.')\n \n return recs\n \n#recs = run_filer(src='c:\\\\temp\\\\test\\\\*.json', incoming_dir='incoming')\n","sub_path":"json_data_filer.py","file_name":"json_data_filer.py","file_ext":"py","file_size_in_byte":1905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"453494826","text":"# Standard imports\nimport io\nimport os\nimport sys\n\n# Local imports\nfrom oblivion.constants import (\n callback,\n HASH_LENGTH,\n)\nfrom oblivion.entities import (\n RSAPublicKey,\n)\nfrom oblivion.schemes import (\n rsa_encryption_scheme_with_oaep_padding,\n)\n\n\ndef put_subparser(subparsers):\n parser = subparsers.add_parser(\n 'encrypt',\n help='Encrypt a file read from standard input (/dev/stdin)',\n )\n parser.add_argument(\n '-k', '--key-name',\n help='file name of the key, defaults to \"rsa\"',\n required=False,\n default='rsa',\n )\n parser.set_defaults(subparser_handler=handler)\n\n\ndef handler(args):\n key = RSAPublicKey(modulus=0, exponent=0)\n\n path: str = \\\n os.path.abspath(\n os.path.join(\n os.getcwd(),\n f'{args.key_name}.{key.kind}.{key.extension}'))\n\n callback(f'reading {key.kind} key from: {path}')\n if not os.path.exists(path):\n callback(f'error: no such key')\n sys.exit(1)\n\n key.load_from_file(path)\n\n # We can encrypt at much this data octets per round\n block_size = key.modulus_octets - 2 * (HASH_LENGTH + 1)\n # Adjust the last octet\n block_size -= 1\n\n with io.BufferedReader(sys.stdin.buffer) as buffer:\n block = buffer.read(block_size)\n while block:\n encrypted_block = rsa_encryption_scheme_with_oaep_padding(\n public_key=key,\n message=block,\n label=b'oblivion',\n )\n print(encrypted_block.hex())\n block = buffer.read(block_size)\n","sub_path":"oblivion/cli/encrypt.py","file_name":"encrypt.py","file_ext":"py","file_size_in_byte":1597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"629171262","text":"\ndef InsertionSort(arr):\n size=len(arr)\n\n for i in range(size):\n temp=arr[i]\n j=i\n\n while (j>0 & temp bestScore):\n bestScore = score\n bestMove = pos\n \n \"\"\"Undo the move\"\"\"\n board.modifyPosition(pos, pos)\n \n return bestMove\n\n\ndef minimax(board, depth, isMax):\n #Base Cases\n if (len(board.availSpots()) == 0):\n return 0\n \n if board.playerWin():\n return -10\n\n if board.aiWin():\n return 10\n \n #Recursive Step(s)\n if (isMax):\n bestScore = -1000\n for pos in board.availSpots():\n \"\"\"Modify board and find score.\"\"\"\n board.modifyPosition(\"X\", pos)\n score = minimax(board, depth+1, False)\n \n \"\"\"If resulting score of move is better, modify.\"\"\"\n if (score > bestScore):\n bestScore = score\n \n \"\"\"Undo the move\"\"\"\n board.modifyPosition(pos, pos)\n \n \"\"\"Return the best score we encounter.\"\"\"\n return bestScore\n \n else:\n bestScore = 1000\n for pos in board.availSpots():\n \"\"\"Modify board and find score.\"\"\"\n board.modifyPosition(\"O\", pos)\n score = minimax(board, depth+1, True)\n \n \"\"\"If resulting score of move is better, modify.\"\"\"\n if (score < bestScore):\n bestScore = score\n \n \"\"\"Undo the move\"\"\"\n board.modifyPosition(pos, pos)\n \n \"\"\"Return the best score we encounter.\"\"\"\n return bestScore\n\ndef game():\n # create board\n gameBoard = Board()\n # denote players\n gameBoard.drawBoard()\n print()\n print(\"Player is denoted as O\")\n print(\"AI is denoted as X\")\n print()\n\n while gameBoard.movesLeft():\n # ask player to make move -> O\n player1Move = int(input(\"Enter move desired for player 1: \"))\n gameBoard.modifyPosition(\"O\", player1Move)\n print()\n gameBoard.drawBoard()\n\n # check for victory -> if yes, break\n if (gameBoard.playerWin()):\n print(\"Player has won the game!\")\n return\n \n # check for tie\n if (not gameBoard.movesLeft()):\n print(\"Draw! Neither player has won.\")\n return\n\n # perform AI move\n aiMove = findbestMove(gameBoard)\n gameBoard.modifyPosition(\"X\", aiMove)\n print()\n print(\"AI has moved to positon: \" + str(aiMove))\n gameBoard.drawBoard()\n\n # check for victory -> if yes, break\n if (gameBoard.aiWin()):\n print(\"AI has won the game!\")\n return\n \n # check for tie\n if (not gameBoard.movesLeft()):\n print(\"Draw! Neither player has won.\")\n return\n\n print(\"Draw! Neither player has won.\")\n\ndef play():\n game()\n\nplay()","sub_path":"minimax.py","file_name":"minimax.py","file_ext":"py","file_size_in_byte":3174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"343167406","text":"class Node: \r\n def __init__(self,key): \r\n self.left = None\r\n self.right = None\r\n self.val = key \r\n \r\n\r\ndef insert(root,node): \r\n if root is None: \r\n root = node \r\n else: \r\n if root.val < node.val: \r\n if root.right is None: \r\n root.right = node \r\n else: \r\n insert(root.right, node) \r\n else: \r\n if root.left is None: \r\n root.left = node \r\n else: \r\n insert(root.left, node)\r\n\r\ndef minValueNode( node): \r\n current = node \r\n # loop down to find the leftmost leaf \r\n while(current.left is not None): \r\n current = current.left \r\n return current \r\n\r\ndef deleteNode(root, key): \r\n \r\n # Base Case \r\n if root is None: \r\n return root \r\n \r\n # If the key to be deleted is smaller than the root's \r\n # key then it lies in left subtree \r\n if key < root.val: \r\n root.left = deleteNode(root.left, key) \r\n \r\n # If the kye to be delete is greater than the root's key \r\n # then it lies in right subtree \r\n elif(key > root.val): \r\n root.right = deleteNode(root.right, key) \r\n \r\n # If key is same as root's key, then this is the node \r\n # to be deleted \r\n else: \r\n \r\n # Node with only one child or no child \r\n if root.left is None : \r\n temp = root.right \r\n root = None \r\n return temp \r\n \r\n elif root.right is None : \r\n temp = root.left \r\n root = None\r\n return temp \r\n \r\n # Node with two children: Get the inorder successor \r\n # (smallest in the right subtree) \r\n temp = minValueNode(root.right) \r\n \r\n # Copy the inorder successor's content to this node \r\n root.val = temp.val\r\n \r\n # Delete the inorder successor \r\n root.right = deleteNode(root.right , temp.val) \r\n \r\n \r\n return root \r\n \r\n\r\ndef inorder(root): \r\n if root: \r\n inorder(root.left) \r\n print(root.val) \r\n inorder(root.right)\r\n \r\n\r\ndef preorder(root): \r\n if root:\r\n print(root.val) \r\n preorder(root.left) \r\n preorder(root.right)\r\n\r\ndef postorder(root): \r\n if root: \r\n postorder(root.left) \r\n postorder(root.right)\r\n print(root.val)\r\n \r\nr = Node(50) \r\ninsert(r,Node(30)) \r\ninsert(r,Node(20)) \r\ninsert(r,Node(40)) \r\ninsert(r,Node(70)) \r\ninsert(r,Node(60)) \r\ninsert(r,Node(80)) \r\n \r\n# Print inoder traversal of the BST \r\nprint(\"inorder traversal is:\")\r\ninorder(r)\r\nprint(\"preorder traversal is:\")\r\npreorder(r)\r\nprint(\"postorder traversal is:\")\r\npostorder(r)\r\ndeleteNode(r,30)\r\nprint(\"inorder traversal is:\")\r\ninorder(r)\r\n","sub_path":"BST.py","file_name":"BST.py","file_ext":"py","file_size_in_byte":2749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"512735875","text":"import json\nimport os\nfrom urllib.error import URLError\nfrom urllib.request import Request, urlopen\n\nimport boto3\nfrom botocore.config import Config\n\nREGION = os.environ.get(\"AWS_CURRENT_REGION\", \"us-east-1\")\nENV = os.environ.get(\"ENV\", \"\")\nWEBHOOK_SSM_PATH = os.environ.get(\"WEBHOOK_SSM_PATH\", \"\")\n\nboto_config = Config(region_name=REGION)\nssm_client = boto3.client(\"ssm\", config=boto_config)\n\n\ndef slack_escape_str(str_to_escape: str) -> str:\n \"\"\"Escapes a string such that Slack can properly display it.\n See https://api.slack.com/reference/surfaces/formatting#escaping\n\n Args:\n str_to_escape (str): The string to escape\n\n Returns:\n str: A string escaped such that Slack can properly display it\n \"\"\"\n return str_to_escape.replace(\"&\", \"&\").replace(\"<\", \"<\").replace(\">\", \">\")\n\n\ndef handler(event, context):\n if not ENV:\n print(\"ENV was not defined, exiting...\")\n return\n\n if not WEBHOOK_SSM_PATH:\n print(\"WEBHOOK_SSM_PATH was not defined, exiting...\")\n return\n\n # We take only the first record, if it exists\n try:\n record = event[\"Records\"][0]\n except IndexError:\n print(\"Invalid SNS notification, no records found\")\n return\n\n try:\n sns_message = record[\"Sns\"][\"Message\"]\n except KeyError as exc:\n print(f\"No message found in SNS notification: {exc}\")\n return\n\n try:\n alarm_info = json.loads(sns_message)\n except json.JSONDecodeError:\n print(\"SNS message body was not valid JSON\")\n return\n\n try:\n # We do not escape \"<\" or \">\" to allow for links to be embedded in the Alarm message\n unescaped_alarm_message: str = alarm_info[\"AlarmDescription\"]\n alarm_message = unescaped_alarm_message.replace(\"&\", \"&\")\n\n alarm_name = slack_escape_str(alarm_info[\"AlarmName\"])\n alarm_reason = slack_escape_str(alarm_info[\"NewStateReason\"])\n alarm_metric = slack_escape_str(alarm_info[\"Trigger\"][\"MetricName\"])\n except KeyError as exc:\n print(f\"Unable to retrieve alarm information from SNS message: {exc}\")\n return\n\n try:\n wehbook_url = ssm_client.get_parameter(\n Name=WEBHOOK_SSM_PATH,\n WithDecryption=True,\n )[\"Parameter\"][\"Value\"]\n except KeyError as exc:\n print(f\"SSM parameter {WEBHOOK_SSM_PATH} not found: {exc.reason}\")\n return\n\n slack_message = {\n \"blocks\": [\n {\n \"type\": \"section\",\n \"text\": {\n \"type\": \"mrkdwn\",\n \"text\": (\n f\"CloudWatch Alarm alert received from `{ENV}` environment:\\n\"\n f\"\\t*Alarm Name:* `{alarm_name}`\\n\"\n f\"\\t*Alarm Reason:* `{alarm_reason}`\\n\"\n f\"\\t*Alarm Metric:* `{alarm_metric}`\\n\"\n f\"\\t*Alarm Message:* {alarm_message}\\n\"\n ),\n },\n }\n ]\n }\n\n request = Request(wehbook_url, method=\"POST\")\n request.add_header(\"Content-Type\", \"application/json\")\n try:\n with urlopen(\n request, data=json.dumps(slack_message).encode(\"utf-8\")\n ) as response:\n if response.status == 200:\n print(f\"Message posted successfully\")\n else:\n print(f\"{response.status} response received from Slack\")\n except URLError as e:\n print(f\"Unable to connect to Slack: {e.reason}\")\n","sub_path":"ops/terraform/modules/resources/cw_alarms_slack_notifier/lambda-src/cw_alarms_slack_notifier.py","file_name":"cw_alarms_slack_notifier.py","file_ext":"py","file_size_in_byte":3500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"420887121","text":"import pydicom as dicom\nimport os\nimport numpy as np,sys\nfrom matplotlib import pyplot as plt, cm\nfrom collections import defaultdict\nfrom scipy import ndimage\nfrom PIL import Image, ImageSequence\n\n\n# read the pet data as well as the CT dicom images\nPathDicom = \"../../Dataset/LSTM_GAN/\"\nlstFilesDCM = [] # create an empty list\nfor dirName, subdirList, fileList in os.walk(PathDicom):\n for filename in fileList:\n if \".gif\" in filename.lower(): # check whether the file's DICOM\n lstFilesDCM.append(os.path.join(dirName,filename))\n\nall_data = []\nfor x in range(len(lstFilesDCM)):\n img = Image.open(lstFilesDCM[x])\n frames = np.array([np.array(frame.copy().convert('RGB').getdata(),dtype=np.uint8).reshape(frame.size[1],frame.size[0],3) for frame in ImageSequence.Iterator(img)])\n all_data.append(frames)\n print(frames.shape) \n print(len(all_data))\n\n# for xx in all_data:\n# for xxx in xx:\n# plt.imshow(xxx)\n# plt.pause(0.3)\n\n\nall_data = np.asarray(all_data)\nprint(all_data.shape) \nnp.save('gif.npy', all_data)\n\nsys.exit()\n\nlstFilesDCM = [] # create an empty list os.path.join(dirName,filename)\npet_scan_images = defaultdict(list);pet_scan_images_count = 0\nct_scan_images = defaultdict(list);ct_scan_images_count = 0\nfor dirName, subdirList, fileList in os.walk(PathDicom):\n if not len(fileList) == 0:\n \n if len(fileList) == 63:\n temp = []\n for filename in fileList:\n if \".dcm\" in filename.lower():\n temp.append(os.path.join(dirName,filename))\n ct_scan_images[ct_scan_images_count] = temp\n ct_scan_images_count = ct_scan_images_count + 1\n\n if len(fileList) == 47:\n temp = []\n for filename in fileList:\n if \".dcm\" in filename.lower():\n temp.append(os.path.join(dirName,filename))\n \n pet_scan_images[pet_scan_images_count] = temp\n pet_scan_images_count = pet_scan_images_count + 1\n\n\nprint(len(pet_scan_images))\nprint(len(pet_scan_images[0]))\n\nfor xx in pet_scan_images:\n current_pet = pet_scan_images[xx]\n for xxx in range(len(current_pet)):\n curren_pet_image = dicom.read_file(current_pet[xxx]).pixel_array\n plt.title(str(current_pet[xxx][-10:]))\n plt.imshow(curren_pet_image,cmap='gray')\n plt.pause(0.1)\n\n# read the dicom to numpy\n# ct_scan_numpys = np.zeros(20,)\n\nsys.exit()\n\nfor dirName, subdirList, fileList in os.walk(PathDicom):\n for filename in fileList:\n if \".dcm\" in filename.lower(): # check whether the file's DICOM\n lstFilesDCM.append(os.path.join(dirName,filename))\n\nprint(lstFilesDCM)\nsys.exit()\n\n# Get ref file\nRefDs = dicom.read_file(lstFilesDCM[0])\n\n# Load dimensions based on the number of rows, columns, and slices (along the Z axis)\nConstPixelDims = (int(RefDs.Rows), int(RefDs.Columns), len(lstFilesDCM))\n\n# Load spacing values (in mm)\nConstPixelSpacing = (float(RefDs.PixelSpacing[0]), float(RefDs.PixelSpacing[1]), \nfloat(RefDs.SliceThickness))\n\n# -- end code --","sub_path":"NeuralNetwork/LSTM-GAN/archieve/y_read_data.py","file_name":"y_read_data.py","file_ext":"py","file_size_in_byte":3094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"239444990","text":"# 01-First\n# Author : jeeho.hyun@gmail.com\n# Date : 2019-04-30\n# Python version : 3.6.5\n\nimport numpy as np\n\ndef _list_stack_push(arr, val) :\n\tif arr is None :\n\t\traise IOError('array not found')\n\n\tarr.append(val)\n\ndef _list_stack_pop(arr) :\n\tif arr is None :\n\t\traise IOError('array not found')\n\n\treturn arr.pop()\n\ndef list_stack_test() :\n\tarr = []\n\twhile True :\n\t\tprint('Push(1) / Pop(2) / View(3) or Quit(0) :')\n\t\tkey_input = int(input())\n\t\tif key_input is 0 or key_input < 0 :\n\t\t\tprint('Terminated')\n\t\t\tbreak\n\t\telse :\n\t\t\tif key_input is 1 :\n\t\t\t\tprint('Input value : ')\n\t\t\t\tval_input = input()\n\t\t\t\t_list_stack_push(arr, val_input)\n\t\t\telif key_input is 2 :\n\t\t\t\tval = _list_stack_pop(arr)\n\t\t\t\tprint('Popped! : ', val)\n\t\t\telif key_input is 3 :\n\t\t\t\tprint('Current Stack status : ', arr)\n\n\n\nif __name__ == '__main__' :\n\tlist_stack_test()\n\n","sub_path":"code/01-first.py","file_name":"01-first.py","file_ext":"py","file_size_in_byte":835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"528171993","text":"import warnings\nwarnings.filterwarnings('ignore')\nfrom mpl_toolkits.basemap import Basemap\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport folium\nimport math\nfrom contextlib import suppress\nfrom mpl_toolkits.mplot3d import Axes3D\nimport datahandler as dh\nimport readCSV as read\n\n\ndef haversine_location(dataframe):\n\n print('in haversine_location')\n\n return dataframe.apply(lambda row: haversine_distance(row), axis=1)\n\n\ndef haversine_distance(row):\n\n print('in haversine distance')\n\n lat_orig, lon_orig = (55.676111,12.568333)\n lat_dest = row['lat']\n lon_dest = row['lon']\n \n radius = 6371\n\n dlat = math.radians(lat_dest-lat_orig)\n dlon = math.radians(lon_dest-lon_orig)\n a = (math.sin(dlat / 2) * math.sin(dlat / 2) + math.cos(math.radians(lat_orig)) \n * math.cos(math.radians(lat_dest)) * math.sin(dlon / 2) * math.sin(dlon / 2))\n c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))\n d = radius * c\n\n return d\n\n\ndef dataframe_year(dataframe, year):\n\n print('in dataframe_year')\n\n return dataframe[dataframe['sell_date'].dt.year == year]\n\n\ndef dataframe_zipcode(dataframe, zipcodes):\n\n print('in dataframe_zipcode')\n \n return dataframe[dataframe['zip_int'].isin(zipcodes)]\n\n\ndef extended_zipcodes():\n\n zipcodes = []\n zipcodes.extend(range(1000,3670))\n zipcodes.extend(range(4000,4793))\n\n return zipcodes\n\ndef defined_city_plot(dataframe):\n\n dataframe = dataframe.assign(kilometer_defined_city = haversine_location(dataframe))\n\n y = dataframe['kilometer_defined_city'].values\n x = dataframe['price_per_sq_m'].values\n \n create_plot(x,y,'defined_city_sales')\n\n\ndef create_plot(x, y, name):\n\n fig = plt.figure()\n \n y[::-1].sort()\n x.sort()\n \n plt.plot(x,y,'ro')\n plt.gca().invert_yaxis()\n \n fig.savefig(name + '.png')\n\n\ndef create_defined_city_plot(dataframe):\n\n defined_year = dataframe_year(dataframe, 2005)\n defined_city_dataframe = dataframe_zipcode(dataframe, extended_zipcodes())\n defined_city_dataframe = defined_city_dataframe[defined_city_dataframe['price_per_sq_m'] >= 80.000]\n\n defined_city_plot(defined_city_dataframe)\n\n\ndef run():\n\n print ('Generate dataframe ')\n boliga_dataframe = read.read_csv_to_dataframe(\"boliga_all_loc.csv\",{'year_of_construction': str, 'no_rooms': str})\n boliga_dataframe = dh.createZipLabel(boliga_dataframe)\n\n create_defined_city_plot(boliga_dataframe)\n\n\nrun()","sub_path":"Assignment4/2D_model.py","file_name":"2D_model.py","file_ext":"py","file_size_in_byte":2468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"592033974","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jun 20 13:39:02 2021\n\n@author: SRI\n\nProblem 1\n10.0/10.0 points (graded)\nAssume s is a string of lower case characters.\n\nWrite a program that counts up the number of vowels contained in the string s.\n Valid vowels are: 'a', 'e', 'i', 'o', and 'u'.\n For example, if s = 'azcbobobegghakl', your program should print:\n Number of vowels: 5\n\"\"\"\ns = input('Enter the string: ')\nvowels = ['a','e','i','o','u']\ncount =0\n\nfor letter in s:\n if letter in vowels:\n count+=1\nprint(f'Number of vowels: {count}')\n ","sub_path":"Week_1--Python_Basics/Problem Set 1/Problem1.py","file_name":"Problem1.py","file_ext":"py","file_size_in_byte":562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"307113742","text":"# -*- coding:utf-8 -*-\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\nclass Solution:\n def TreeDepth(self, pRoot):\n # write code here\n if pRoot==None:\n return 0\n left = self.TreeDepth(pRoot.left)\n right = self.TreeDepth(pRoot.right)\n if left>right:\n return left+1\n else:\n return right+1\n\nif __name__ == '__main__':\n TreeNode1 = TreeNode(5)\n TreeNode2 = TreeNode(3)\n TreeNode3 = TreeNode(7)\n TreeNode4 = TreeNode(2)\n TreeNode5 = TreeNode(4)\n TreeNode6 = TreeNode(6)\n TreeNode7 = TreeNode(8)\n TreeNode1.left = TreeNode2\n TreeNode1.right = TreeNode3\n TreeNode2.left = TreeNode4\n TreeNode2.right = TreeNode5\n TreeNode3.left = TreeNode6\n TreeNode3.right = TreeNode7\n k = 3\n # print(len(l))\n solution1 = Solution()\n a = solution1.TreeDepth(TreeNode1)\n print(a.val)","sub_path":"py-project/Solution55-1 2.py","file_name":"Solution55-1 2.py","file_ext":"py","file_size_in_byte":959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"651278980","text":"#!/usr/bin/python\n# coding:utf-8\n\n\nimport math\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom modules.layers import mask_logits, Initialized_Conv1d, DepthwiseSeparableConv, SelfAttention\nfrom modules.position_encoding import PosEncoder2, PosEncoder\n\n\nclass EncoderBlock(nn.Module):\n def __init__(self, conv_num, d_model, num_head, k, dropout=0.1):\n super().__init__()\n self.convs = nn.ModuleList([DepthwiseSeparableConv(d_model, d_model, k) for _ in range(conv_num)])\n self.pe = PosEncoder2(d_model, dropout)\n self.self_att = SelfAttention(d_model, num_head, dropout=dropout)\n self.FFN_1 = Initialized_Conv1d(d_model, d_model, relu=True, bias=True)\n self.FFN_2 = Initialized_Conv1d(d_model, d_model, bias=True)\n self.norm_C = nn.ModuleList([nn.LayerNorm(d_model) for _ in range(conv_num)])\n self.norm_1 = nn.LayerNorm(d_model)\n self.norm_2 = nn.LayerNorm(d_model)\n self.conv_num = conv_num\n self.dropout = dropout\n\n def forward(self, x, mask, l, blks):\n total_layers = (self.conv_num + 1) * blks\n dropout = self.dropout\n out = self.pe(x)\n for i, conv in enumerate(self.convs):\n res = out\n out = self.norm_C[i](out.transpose(1,2)).transpose(1,2)\n if (i) % 2 == 0:\n out = F.dropout(out, p=dropout, training=self.training)\n out = conv(out)\n out = self.layer_dropout(out, res, dropout*float(l)/total_layers)\n l += 1\n res = out\n out = self.norm_1(out.transpose(1,2)).transpose(1,2)\n out = F.dropout(out, p=dropout, training=self.training)\n out = self.self_att(out, mask)\n out = self.layer_dropout(out, res, dropout*float(l)/total_layers)\n l += 1\n res = out\n\n out = self.norm_2(out.transpose(1,2)).transpose(1,2)\n out = F.dropout(out, p=dropout, training=self.training)\n out = self.FFN_1(out)\n out = self.FFN_2(out)\n out = self.layer_dropout(out, res, dropout*float(l)/total_layers)\n return out\n\n def layer_dropout(self, inputs, residual, dropout):\n if self.training == True:\n pred = torch.empty(1).uniform_(0,1) < dropout\n if pred:\n return residual\n else:\n return F.dropout(inputs, dropout, training=self.training) + residual\n else:\n return inputs + residual\n","sub_path":"modules/encoder_blocks.py","file_name":"encoder_blocks.py","file_ext":"py","file_size_in_byte":2453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"300662151","text":"import spacy\nimport os\nimport argparse\n\n\ndef pos_of_token(input_text):\n \"\"\"\n 打印词性标签\n \"\"\"\n nlp = spacy.load(\"en_core_web_md\")\n doc = nlp(input_text)\n for token in doc:\n print(\"Token: {}, POS:{}, TAG:{}\".format(token.text, token.pos_, token.tag_))\n\ndef LR_based_NER(input_text):\n \"\"\"\n 使用预训练语言模型的命名实体识别\n param: input_text\n return: None\n \"\"\"\n # 1. 加载预训练模型,生成nlp对象(即处理文本的管道pipeline)\n # 加载的模型名称以自己下载的为准\n nlp = spacy.load(\"en_core_web_md\")\n # 2. nlp对象解析文本,得到doc对象,此时doc对象已经包含了文本的诸多数据,包括识别的实体\n doc = nlp(input_text)\n \n # 3. 遍历doc.ents,它存放了识别的实体及其信息\n for ent in doc.ents:\n # 打印实体名称、类型和位置\n print(\"Entity: {}, Label: {}\".format(ent.text, ent.label_), (ent.start, ent.end))\n\ndef rule_based_NER(input_text):\n \"\"\"\n 基于规则的命名实体识别\n \"\"\"\n # 同上\n nlp = spacy.load(\"en_core_web_md\")\n # 1. 添加组件entity_ruler, 它允许我们通过自定义规则来抽取特定实体\n ruler = nlp.add_pipe(\"entity_ruler\", config={\"overwrite_ents\": True})\n\n # 2. 定义匹配模板\n # 一般而言,patterns格式:[{\"label\": , \"pattern\": }, ...]\n patterns = [\n # 针对前后类型不一致,使用精确字符串匹配并指定标签\n {\"label\":\"ORG\", \"pattern\":\"Nanhang\"},\n\n # 针对没有识别出特定实体,使用基于词性的正则匹配\n # 区分pos标签和tag标签的异同:https://spacy.io/api/annotation\n {\"label\":\"TITLE\", \"pattern\":[{\"POS\":\"PROPN\"}, {\"POS\":\"PROPN\"}, {\"POS\":\"PROPN\"}, {\"POS\":\"PROPN\"}, {\"POS\":\"PROPN\"}]},\n # {\"label\":\"TITLE\", \"pattern\":[{\"POS\":\"PROPN\"}, {\"POS\":\"PROPN\"}, {\"POS\":\"PROPN\"}, {\"POS\":\"PROPN\", \"OP\":\"+\"}]},\n # {\"label\":\"TITLE\", \"pattern\":[{\"TAG\":\"NNP\"}, {\"TAG\":\"NNP\"}, {\"TAG\":\"NNP\"}, {\"TAG\":\"NNP\"}, {\"TAG\":\"NNP\"}]}\n ] \n # 3. 添加模板\n ruler.add_patterns(patterns)\n # 4. 同上\n doc = nlp(input_text)\n for ent in doc.ents:\n print(\"Entity: {}, Label: {}\".format(ent.text, ent.label_), (ent.start, ent.end))\n \n\nif __name__ == \"__main__\":\n \n text = \"\"\"\n Nanjing University of Aeronautics and Astronautics (NUAA), known colloquially as Nanhang, is an elite Double First Class Discipline University. \n Located in Nanjing, Jiangsu province, it was established in 1952 and is now operated by the Chinese Ministry of Industry and Information Technology. \n Nanhang has three campuses: the Ming Palace Campus situated on the ruins of a Ming Palace, and the Jiangjun Road Campus situated in the Jiangning Economic and Technological Development Zone. \n \"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-m\", \"--method\", type=str, choices=[\"lr\", \"rule\"], help=\"choose method of NER\")\n parser.add_argument(\"-p\", \"--pos\", type=str, default=\"\", help=\"pos of token\")\n args = parser.parse_args()\n \n if args.method == \"lr\":\n LR_based_NER(text)\n elif args.method == \"rule\":\n rule_based_NER(text)\n \n if args.pos != \"\":\n pos_of_token(args.pos)\n ","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"240393147","text":"#!/usr/bin/python3\n\"\"\" City Module instances cities with ids \"\"\"\nfrom sqlalchemy import Column, Integer, String, ForeignKey\nfrom models.base_model import BaseModel, Base\nfrom os import getenv\nfrom sqlalchemy.orm import relationship\n\nSTORAGE = getenv(\"HBNB_TYPE_STORAGE\")\n\n\nclass City(BaseModel, Base):\n \"\"\" The city class, contains state ID and name \"\"\"\n __tablename__ = 'cities'\n if STORAGE == \"db\":\n state_id = Column(String(60), ForeignKey('states.id'), nullable=False)\n name = Column(String(128), nullable=False)\n places = relationship('Place',\n backref='cities',\n cascade=\"all, delete-orphan\")\n else:\n name = \"\"\n state_id = \"\"\n","sub_path":"models/city.py","file_name":"city.py","file_ext":"py","file_size_in_byte":737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"409180518","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nhmp2_workflows.tasks.common\n~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nThis module contains common functions that are used across the board in\nall HMP2 AnADAMA2 workflows.\n\nCopyright (c) 2017 Harvard School of Public Health\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n THE SOFTWARE.\n\"\"\"\n\nimport itertools\nimport os\nimport shutil\nimport tempfile\n\nfrom biobakery_workflows import utilities as bb_utils\nfrom hmp2_workflows import utils as hmp_utils\n\n\ndef verify_files(workflow, input_files, checksums_file):\n \"\"\"Verifies the integrity of all files found under the supplied directory \n using md5 checksums. In order for this function to work properly an file \n contanining md5 checksums must have been generated on the source side of \n the files and provided when these files were uploaded.\n\n Args:\n input_file_dir (string): Path to directory containing files to be \n checked.\n checksums_file (string): Path to file containing the source side md5 \n checksums.\n\n Requires:\n None\n\n Returns:\n list: A list of files that have passed integrity verification\n\n Example:\n from anadama2 import Workflow\n\n from hmp2_workflows.common import verify_files\n\n workflow = Workflow()\n valid_files = verify_files(workflow, \n ['/tmp/fooA.bam', '/tmp/fooB.bam'],\n '/tmp/foo_checksums.txt)\n \"\"\"\n checksums_dict = hmp_utils.misc.parse_checksums_file(checksums_file)\n\n for input_file in input_files:\n md5sum = checksums_dict.get(os.path.basename(input_file))\n \n if not md5sum:\n raise KeyError('MD5 checksum not found.', input_file)\n\n workflow.add_task_gridable('echo \"[args[0]] *[depends[0]]\" | md5sum -c -',\n depends = [input_file],\n args = [md5sum],\n time = 24*60,\n mem = 1024,\n cores = 1)\n\n ## Kind of wonky but if the workflow doesn't fail than the files we \n ## passed in should all be valid. Right?\n return input_files\n\n\ndef stage_files(workflow, input_files, target_dir, delete=False, \n preserve=False, symlink=False):\n \"\"\"Moves data files from the supplied origin directory to the supplied\n destination directory. In order to include a file verification check in\n the staging process rsync is used by default to copy files.\n\n If the symlink parameter is set to True this function will instead create\n symlinks from the origin directory to the target directory.\n\n An optional parameter may be provided to only stage files with the \n corresponding extension.\n\n Args:\n workflow (anadama2.Workflow): The workflow object.\n input_files: A collection of input files to be staged.\n dest_dir (string): Path to destination directory where files should \n be moved.\n preserve (boolean): If set to True preserve the source subdirectory \n structure on the target side.\n symlink (boolean): By default create symlinks from the origin \n directory to the destination directory. If set to \n False files will be copied using rsync.\n\n Requires:\n rsync v3.0.6+: A versatile file copying tool.\n\n Returns:\n list: A list of all files that were successfuly staged\n\n Example:\n from anadama2 import Workflow\n from hmp2_workflows.tasks import common\n\n workflow = anadama2.Workflow()\n\n staged_files = common.stage_files(workflow, \n ['/tmp/fooA.sam', '/tmp/fooB.sam'],\n '/tmp/out_dir')\n\n workflow.go()\n \"\"\"\n if not os.path.exists(target_dir):\n raise OSError(2, 'Target directory does not exist', target_dir)\n\n ## TODO: We need to preserve the file directory structure here because\n ## it tells when the files were received and is used by the website.\n target_files = bb_utils.name_files(input_files, target_dir)\n\n ## TODO: Figure out a better way to handle this rather than creating \n ## N rsync calls.\n stage_cmd = \"remove_if_exists.py [targets[0]] ; rsync -avz [depends[0]] [targets[0]]\"\n \n if preserve:\n stage_cmd = stage_cmd.replace('-avz', \n '--rsync-path=\\\"mkdir -p `dirname '\n '[depends[0]]`\\\" -avz')\n if symlink:\n stage_cmd = \"remove_if_exists.py [targets[0]] ; ln -s [depends[0]] [targets[0]]\"\n\n workflow.add_task_group(stage_cmd,\n depends = input_files,\n targets = target_files)\n\n return target_files\n\n\ndef make_files_web_visible(workflow, files):\n \"\"\"Receives a list of files to be disseminated and ensures that they are \n visible on the IBDMDB website.\n\n Args:\n files (list): A list of files that should be made visible on the \n IBDMDB website.\n\n Requires:\n None \n\n Returns:\n list: A list of all files that should now be publicly visible on the \n IBDMDB website.\n\n Example:\n from anadama2 import Workflow\n from hmp2_workflows.tasks import common\n\n workflow = anadama2.Workflow()\n\n visible_files = common.make_files_web_visible(workflow, \n ['/tmp/public/fooA.sam'])\n\n workflow.go()\n \"\"\"\n ## Making a group of files web visible is as simple as touching a file \n ## named complete.html in the directories containing the files we want \n ## to show up on the website\n public_files = itertools.chain.from_iterable(files)\n public_dirs = itertools.groupby(public_files, os.path.dirname)\n complete_files = [os.path.join(item[0], 'complete.html') for item\n in public_dirs]\n\n workflow.add_task_group('touch [targets[0]]',\n depends = map(os.path.dirname, complete_files),\n targets = complete_files)\n\n ## Again kinda lazy, but the files passed in will be the ones that are\n ## made public.\n return files\n\n\ndef tar_files(workflow, files, output_tarball, depends, compress=True):\n \"\"\"Creates a tarball package of the provided files with the given output\n tarball file path.\n\n Args:\n workflow (anadama2.Workflow): The workflow object.\n files (list): A list of files to package together into a tarball.\n output_tarball (string): The desired output tarball file.\n depends (list): A list of files that can be tied to the files to \n be tar'd. These dependencies are not tar'd but needed to make \n sure that this step in the workflow is not run out of order.\n compress (string): \n\n Requires:\n None\n\n Returns:\n string: Path to the newly created tarball file.\n\n Example:\n from anadama2 import Workflow\n from hmp2_workflows.tasks import common\n\n workflow = anadama2.Workflow()\n\n files_to_tar = ['/tmp/foo.txt', '/tmp/bar.txt']\n tar_file = '/tmp/foo_bar.tar'\n\n out_tar = common.tar_files(workflow, files_to_tar, tar_file)\n \"\"\"\n ## Though there may be a cleaner way of doing this we need to create \n ## a temporary folder to symlink all the files we want to package into \n ## a tarball to get rid of tar'ing the directory structure as well.\n tmp_dir = tempfile.mkdtemp()\n tar_args = \"-hcvf\"\n\n for target_file in files:\n symlink_path = os.path.join(tmp_dir, os.path.basename(target_file))\n os.symlink(target_file, symlink_path)\n \n depend_files = []\n if depends:\n depend_files.extend(depends)\n else:\n depend_files.extend(files)\n\n if compress:\n tar_args = tar_args + \"z\"\n \n workflow.add_task('tar -hcvzf [targets[0]] -C [args[0]] .; rm -rf [args[0]]',\n depends = depend_files,\n targets = [output_tarball],\n args = [tmp_dir])\n\n return output_tarball\n\n\ndef generate_md5_checksums(workflow, files):\n \"\"\"Generates MD5 checksums for the provided set of files. All checksums \n are written to a file containing the same name as the input but with the \n \"md5\" extension appended.\n\n Args:\n workflow (anadama2.Workflow): The workflow object.\n files (list): A list of files to package together into a tarball.\n output_tarball (string): The desired output tarball file.\n\n Requires:\n None\n\n Returns:\n list: A list of the generated md5 checksum files.\n\n Example:\n from anadama2 import Workflow\n from hmp2_workflows.tasks import common\n\n workflow = anadama2.Workflow()\n\n files = ['/tmp/foo.txt', '/tmp/bar.txt']\n\n md5sum_files = common.generate_md5_checksums(workflow, files)\n \"\"\"\n output_dir = os.path.dirname(files[0])\n checksum_files = bb_utils.name_files(bb_utils.sample_names(files),\n output_dir,\n extension=\".md5\")\n\n workflow.add_task_gridable('md5sum [depends[0]] > [targets[0]]',\n depends=files,\n targets=checksum_files)\n\n return checksum_files","sub_path":"hmp2_workflows/tasks/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":10429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"361018012","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jan 13 14:32:27 2019\n@author: Zhining Liu\nmailto: znliu19@mails.jlu.edu.cn / zhining.liu@outlook.com\n\nFive ensemble learning algorithms for imbalanced classification, including:\n'SMOTEBaggingClassifier', 'SMOTEBoostClassifier', 'RUSBoostClassifier', \n'UnderBaggingClassifier', and 'BalanceCascadeClassifier'.\n\nNote: the implementation of SMOTEBoost&RUSBoost was obtained from\nimbalanced-algorithms: https://github.com/dialnd/imbalanced-algorithms.\n\"\"\"\n\n# %%\n\nfrom collections import Counter\n\nimport numpy as np\nfrom sklearn.base import is_regressor\nfrom sklearn.base import ClassifierMixin\nfrom sklearn.ensemble import BaseEnsemble\nfrom sklearn.ensemble import AdaBoostClassifier\nfrom sklearn.ensemble import BaggingClassifier\nfrom sklearn.ensemble._forest import BaseForest\nfrom sklearn.neighbors import NearestNeighbors\nfrom sklearn.preprocessing import normalize\nfrom sklearn.tree import BaseDecisionTree\nfrom sklearn.utils import check_random_state\nfrom sklearn.utils import check_X_y\nfrom sklearn.utils import check_array\nfrom sklearn.preprocessing import binarize\n\nclass SMOTE(object):\n \"\"\"Implementation of Synthetic Minority Over-Sampling Technique (SMOTE).\n SMOTE performs oversampling of the minority class by picking target \n minority class samples and their nearest minority class neighbors and \n generating new samples that linearly combine features of each target \n sample with features of its selected minority class neighbors [1].\n Parameters\n ----------\n k_neighbors : int, optional (default=5)\n Number of nearest neighbors.\n random_state : int or None, optional (default=None)\n If int, random_state is the seed used by the random number generator.\n If None, the random number generator is the RandomState instance used\n by np.random.\n References\n ----------\n .. [1] N. V. Chawla, K. W. Bowyer, L. O. Hall, and P. Kegelmeyer. \"SMOTE:\n Synthetic Minority Over-Sampling Technique.\" Journal of Artificial\n Intelligence Research (JAIR), 2002.\n \"\"\"\n\n def __init__(self, k_neighbors=5, random_state=None):\n self.k = k_neighbors\n self.random_state = random_state\n\n def sample(self, n_samples):\n \"\"\"Generate samples.\n Parameters\n ----------\n n_samples : int\n Number of new synthetic samples.\n Returns\n -------\n S : array, shape = [n_samples, n_features]\n Returns synthetic samples.\n \"\"\"\n np.random.seed(seed=self.random_state)\n\n S = np.zeros(shape=(n_samples, self.n_features))\n # Calculate synthetic samples.\n for i in range(n_samples):\n j = np.random.randint(0, self.X.shape[0])\n\n # Find the NN for each sample.\n # Exclude the sample itself.\n nn = self.neigh.kneighbors(self.X[j].reshape(1, -1),\n return_distance=False)[:, 1:]\n nn_index = np.random.choice(nn[0])\n\n dif = self.X[nn_index] - self.X[j]\n gap = np.random.rand()\n\n S[i, :] = self.X[j, :] + gap * dif[:]\n\n return S\n\n def fit(self, X):\n \"\"\"Train model based on input data.\n Parameters\n ----------\n X : array-like, shape = [n_minority_samples, n_features]\n Holds the minority samples.\n \"\"\"\n self.X = X\n self.n_minority_samples, self.n_features = self.X.shape\n\n # Learn nearest neighbors.\n self.neigh = NearestNeighbors(n_neighbors=self.k + 1)\n self.neigh.fit(self.X)\n\n return self\n\nclass SMOTEBoostClassifier(AdaBoostClassifier):\n \"\"\"Implementation of SMOTEBoost.\n SMOTEBoost introduces data sampling into the AdaBoost algorithm by\n oversampling the minority class using SMOTE on each boosting iteration [1].\n This implementation inherits methods from the scikit-learn \n AdaBoostClassifier class, only modifying the `fit` method.\n Parameters\n ----------\n n_samples : int, optional (default=100)\n Number of new synthetic samples per boosting step.\n k_neighbors : int, optional (default=5)\n Number of nearest neighbors.\n base_estimator : object, optional (default=DecisionTreeClassifier)\n The base estimator from which the boosted ensemble is built.\n Support for sample weighting is required, as well as proper `classes_`\n and `n_classes_` attributes.\n n_estimators : int, optional (default=50)\n The maximum number of estimators at which boosting is terminated.\n In case of perfect fit, the learning procedure is stopped early.\n learning_rate : float, optional (default=1.)\n Learning rate shrinks the contribution of each classifier by\n ``learning_rate``. There is a trade-off between ``learning_rate`` and\n ``n_estimators``.\n algorithm : {'SAMME', 'SAMME.R'}, optional (default='SAMME.R')\n If 'SAMME.R' then use the SAMME.R real boosting algorithm.\n ``base_estimator`` must support calculation of class probabilities.\n If 'SAMME' then use the SAMME discrete boosting algorithm.\n The SAMME.R algorithm typically converges faster than SAMME,\n achieving a lower test error with fewer boosting iterations.\n random_state : int or None, optional (default=None)\n If int, random_state is the seed used by the random number generator.\n If None, the random number generator is the RandomState instance used\n by np.random.\n References\n ----------\n .. [1] N. V. Chawla, A. Lazarevic, L. O. Hall, and K. W. Bowyer.\n \"SMOTEBoost: Improving Prediction of the Minority Class in\n Boosting.\" European Conference on Principles of Data Mining and\n Knowledge Discovery (PKDD), 2003.\n \"\"\"\n\n def __init__(self,\n n_samples=100,\n k_neighbors=5,\n base_estimator=None,\n n_estimators=50,\n learning_rate=1.,\n algorithm='SAMME.R',\n random_state=None):\n\n self.n_samples = n_samples\n self.algorithm = algorithm\n self.k_neighbors = k_neighbors\n self.smote = SMOTE(k_neighbors=k_neighbors,\n random_state=random_state)\n\n super(SMOTEBoostClassifier, self).__init__(\n base_estimator=base_estimator,\n n_estimators=n_estimators,\n learning_rate=learning_rate,\n random_state=random_state)\n\n def fit(self, X, y, sample_weight=None, minority_target=None):\n \"\"\"Build a boosted classifier/regressor from the training set (X, y),\n performing SMOTE during each boosting step.\n Parameters\n ----------\n X : {array-like, sparse matrix} of shape = [n_samples, n_features]\n The training input samples. Sparse matrix can be CSC, CSR, COO,\n DOK, or LIL. COO, DOK, and LIL are converted to CSR. The dtype is\n forced to DTYPE from tree._tree if the base classifier of this\n ensemble weighted boosting classifier is a tree or forest.\n y : array-like of shape = [n_samples]\n The target values (class labels in classification, real numbers in\n regression).\n sample_weight : array-like of shape = [n_samples], optional\n Sample weights. If None, the sample weights are initialized to\n 1 / n_samples.\n minority_target : int\n Minority class label.\n Returns\n -------\n self : object\n Returns self.\n Notes\n -----\n Based on the scikit-learn v0.18 AdaBoostClassifier and\n BaseWeightBoosting `fit` methods.\n \"\"\"\n # Check that algorithm is supported.\n if self.algorithm not in ('SAMME', 'SAMME.R'):\n raise ValueError(\"algorithm %s is not supported\" % self.algorithm)\n\n # Check parameters.\n if self.learning_rate <= 0:\n raise ValueError(\"learning_rate must be greater than zero\")\n\n if (self.base_estimator is None or\n isinstance(self.base_estimator, (BaseDecisionTree,\n BaseForest))):\n DTYPE = np.float64 # from fast_dict.pxd\n dtype = DTYPE\n accept_sparse = 'csc'\n else:\n dtype = None\n accept_sparse = ['csr', 'csc']\n\n X, y = check_X_y(X, y, accept_sparse=accept_sparse, dtype=dtype,\n y_numeric=is_regressor(self))\n\n if sample_weight is None:\n # Initialize weights to 1 / n_samples.\n sample_weight = np.empty(X.shape[0], dtype=np.float64)\n sample_weight[:] = 1. / X.shape[0]\n else:\n sample_weight = check_array(sample_weight, ensure_2d=False)\n # Normalize existing weights.\n sample_weight = sample_weight / sample_weight.sum(dtype=np.float64)\n\n # Check that the sample weights sum is positive.\n if sample_weight.sum() <= 0:\n raise ValueError(\n \"Attempting to fit with a non-positive \"\n \"weighted number of samples.\")\n\n if minority_target is None:\n # Determine the minority class label.\n stats_c_ = Counter(y)\n maj_c_ = max(stats_c_, key=stats_c_.get)\n min_c_ = min(stats_c_, key=stats_c_.get)\n self.minority_target = min_c_\n else:\n self.minority_target = minority_target\n\n # Check parameters.\n self._validate_estimator()\n\n # Clear any previous fit results.\n self.estimators_ = []\n self.estimator_weights_ = np.zeros(self.n_estimators, dtype=np.float64)\n self.estimator_errors_ = np.ones(self.n_estimators, dtype=np.float64)\n\n random_state = check_random_state(self.random_state)\n\n for iboost in range(self.n_estimators):\n # SMOTE step.\n X_min = X[np.where(y == self.minority_target)]\n self.smote.fit(X_min)\n X_syn = self.smote.sample(self.n_samples)\n y_syn = np.full(X_syn.shape[0], fill_value=self.minority_target,\n dtype=np.int64)\n\n # Normalize synthetic sample weights based on current training set.\n sample_weight_syn = np.empty(X_syn.shape[0], dtype=np.float64)\n sample_weight_syn[:] = 1. / X.shape[0]\n\n # print ('Boosting Iter: {} n_train: {} n_smote: {}'.format(\n # iboost, len(X_min), len(y_syn)))\n\n # Combine the original and synthetic samples.\n X = np.vstack((X, X_syn))\n y = np.append(y, y_syn)\n\n # Combine the weights.\n sample_weight = \\\n np.append(sample_weight, sample_weight_syn).reshape(-1, 1)\n sample_weight = \\\n np.squeeze(normalize(sample_weight, axis=0, norm='l1'))\n\n # X, y, sample_weight = shuffle(X, y, sample_weight,\n # random_state=random_state)\n\n # Boosting step.\n sample_weight, estimator_weight, estimator_error = self._boost(\n iboost,\n X, y,\n sample_weight,\n random_state)\n\n # Early termination.\n if sample_weight is None:\n print('sample_weight: {}'.format(sample_weight))\n break\n\n self.estimator_weights_[iboost] = estimator_weight\n self.estimator_errors_[iboost] = estimator_error\n\n # Stop if error is zero.\n # if estimator_error == 0:\n # print('error: {}'.format(estimator_error))\n # break\n\n sample_weight_sum = np.sum(sample_weight)\n\n # Stop if the sum of sample weights has become non-positive.\n if sample_weight_sum <= 0:\n print('sample_weight_sum: {}'.format(sample_weight_sum))\n break\n\n if iboost < self.n_estimators - 1:\n # Normalize.\n sample_weight /= sample_weight_sum\n\n return self\n\nclass RandomUnderSampler(object):\n \"\"\"Implementation of random undersampling (RUS).\n Undersample the majority class(es) by randomly picking samples with or\n without replacement.\n Parameters\n ----------\n with_replacement : bool, optional (default=True)\n Undersample with replacement.\n return_indices : bool, optional (default=False)\n Whether or not to return the indices of the samples randomly selected\n from the majority class.\n random_state : int or None, optional (default=None)\n If int, random_state is the seed used by the random number generator.\n If None, the random number generator is the RandomState instance used\n by np.random.\n \"\"\"\n\n def __init__(self, with_replacement=True, return_indices=False,\n random_state=None):\n self.return_indices = return_indices\n self.with_replacement = with_replacement\n self.random_state = random_state\n\n def sample(self, n_samples):\n \"\"\"Perform undersampling.\n Parameters\n ----------\n n_samples : int\n Number of samples to remove.\n Returns\n -------\n S : array, shape = [n_majority_samples - n_samples, n_features]\n Returns synthetic samples.\n \"\"\"\n np.random.seed(seed=self.random_state)\n\n if self.n_majority_samples <= n_samples:\n n_samples = self.n_majority_samples\n\n idx = np.random.choice(self.n_majority_samples,\n # size=self.n_majority_samples - n_samples,\n size=self.n_minority_samples,\n replace=self.with_replacement)\n\n if self.return_indices:\n return (self.X_maj[idx], idx)\n else:\n return self.X_maj[idx]\n\n def fit(self, X_maj, X_min):\n \"\"\"Train model based on input data.\n Parameters\n ----------\n X : array-like, shape = [n_majority_samples, n_features]\n Holds the majority samples.\n \"\"\"\n self.X_maj = X_maj\n self.X_min = X_min\n self.n_majority_samples, self.n_features = self.X_maj.shape\n self.n_minority_samples = self.X_min.shape[0]\n\n return self\n\nimport pandas as pd\n\nclass RUSBoostClassifier(AdaBoostClassifier):\n \"\"\"Implementation of RUSBoost.\n RUSBoost introduces data sampling into the AdaBoost algorithm by\n undersampling the majority class using random undersampling (with or\n without replacement) on each boosting iteration [1].\n This implementation inherits methods from the scikit-learn \n AdaBoostClassifier class, only modifying the `fit` method.\n Parameters\n ----------\n n_samples : int, optional (default=100)\n Number of new synthetic samples per boosting step.\n min_ratio : float (default=1.0)\n Minimum ratio of majority to minority class samples to generate.\n with_replacement : bool, optional (default=True)\n Undersample with replacement.\n base_estimator : object, optional (default=DecisionTreeClassifier)\n The base estimator from which the boosted ensemble is built.\n Support for sample weighting is required, as well as proper `classes_`\n and `n_classes_` attributes.\n n_estimators : int, optional (default=50)\n The maximum number of estimators at which boosting is terminated.\n In case of perfect fit, the learning procedure is stopped early.\n learning_rate : float, optional (default=1.)\n Learning rate shrinks the contribution of each classifier by\n ``learning_rate``. There is a trade-off between ``learning_rate`` and\n ``n_estimators``.\n algorithm : {'SAMME', 'SAMME.R'}, optional (default='SAMME.R')\n If 'SAMME.R' then use the SAMME.R real boosting algorithm.\n ``base_estimator`` must support calculation of class probabilities.\n If 'SAMME' then use the SAMME discrete boosting algorithm.\n The SAMME.R algorithm typically converges faster than SAMME,\n achieving a lower test error with fewer boosting iterations.\n random_state : int or None, optional (default=None)\n If int, random_state is the seed used by the random number generator.\n If None, the random number generator is the RandomState instance used\n by np.random.\n References\n ----------\n .. [1] C. Seiffert, T. M. Khoshgoftaar, J. V. Hulse, and A. Napolitano.\n \"RUSBoost: Improving Classification Performance when Training Data\n is Skewed\". International Conference on Pattern Recognition\n (ICPR), 2008.\n \"\"\"\n\n def __init__(self,\n n_samples=100,\n min_ratio=1.0,\n with_replacement=True,\n base_estimator=None,\n n_estimators=10,\n learning_rate=1.,\n algorithm='SAMME.R',\n random_state=None):\n\n self.n_samples = n_samples\n self.min_ratio = min_ratio\n self.with_replacement = with_replacement\n self.algorithm = algorithm\n self.rus = RandomUnderSampler(with_replacement=with_replacement,\n return_indices=True,\n random_state=random_state)\n\n super(RUSBoostClassifier, self).__init__(\n base_estimator=base_estimator,\n n_estimators=n_estimators,\n learning_rate=learning_rate,\n random_state=random_state)\n\n def fit(self, X, y, sample_weight=None, minority_target=None):\n \"\"\"Build a boosted classifier/regressor from the training set (X, y),\n performing random undersampling during each boosting step.\n Parameters\n ----------\n X : {array-like, sparse matrix} of shape = [n_samples, n_features]\n The training input samples. Sparse matrix can be CSC, CSR, COO,\n DOK, or LIL. COO, DOK, and LIL are converted to CSR. The dtype is\n forced to DTYPE from tree._tree if the base classifier of this\n ensemble weighted boosting classifier is a tree or forest.\n y : array-like of shape = [n_samples]\n The target values (class labels in classification, real numbers in\n regression).\n sample_weight : array-like of shape = [n_samples], optional\n Sample weights. If None, the sample weights are initialized to\n 1 / n_samples.\n minority_target : int\n Minority class label.\n Returns\n -------\n self : object\n Returns self.\n Notes\n -----\n Based on the scikit-learn v0.18 AdaBoostClassifier and\n BaseWeightBoosting `fit` methods.\n \"\"\"\n # Check that algorithm is supported.\n if self.algorithm not in ('SAMME', 'SAMME.R'):\n raise ValueError(\"algorithm %s is not supported\" % self.algorithm)\n\n # Check parameters.\n if self.learning_rate <= 0:\n raise ValueError(\"learning_rate must be greater than zero\")\n\n if (self.base_estimator is None or\n isinstance(self.base_estimator, (BaseDecisionTree,\n BaseForest))):\n DTYPE = np.float64 # from fast_dict.pxd\n dtype = DTYPE\n accept_sparse = 'csc'\n else:\n dtype = None\n accept_sparse = ['csr', 'csc']\n\n X, y = check_X_y(X, y, accept_sparse=accept_sparse, dtype=dtype,\n y_numeric=is_regressor(self))\n\n if sample_weight is None:\n # Initialize weights to 1 / n_samples.\n sample_weight = np.empty(X.shape[0], dtype=np.float64)\n sample_weight[:] = 1. / X.shape[0]\n else:\n sample_weight = check_array(sample_weight, ensure_2d=False)\n # Normalize existing weights.\n sample_weight = sample_weight / sample_weight.sum(dtype=np.float64)\n\n # Check that the sample weights sum is positive.\n if sample_weight.sum() <= 0:\n raise ValueError(\n \"Attempting to fit with a non-positive \"\n \"weighted number of samples.\")\n\n if minority_target is None:\n # Determine the minority class label.\n stats_c_ = Counter(y)\n maj_c_ = max(stats_c_, key=stats_c_.get)\n min_c_ = min(stats_c_, key=stats_c_.get)\n self.minority_target = min_c_\n else:\n self.minority_target = minority_target\n\n # Check parameters.\n self._validate_estimator()\n\n # Clear any previous fit results.\n self.estimators_ = []\n self.estimator_weights_ = np.zeros(self.n_estimators, dtype=np.float64)\n self.estimator_errors_ = np.ones(self.n_estimators, dtype=np.float64)\n\n random_state = check_random_state(self.random_state)\n\n for iboost in range(self.n_estimators):\n # Random undersampling step.\n X_maj = X[np.where(y != self.minority_target)]\n X_min = X[np.where(y == self.minority_target)]\n self.rus.fit(X_maj, X_min)\n # self.rus.fit(X_maj)\n\n n_maj = X_maj.shape[0]\n n_min = X_min.shape[0]\n if n_maj - self.n_samples < int(n_min * self.min_ratio):\n self.n_samples = n_maj - int(n_min * self.min_ratio)\n X_rus, X_idx = self.rus.sample(self.n_samples)\n\n # print ('Boosting Iter: {} X_maj: {} X_rus: {} X_min: {}'.format(\n # iboost, len(X_maj), len(X_rus), len(X_min)))\n\n y_rus = y[np.where(y != self.minority_target)][X_idx]\n y_min = y[np.where(y == self.minority_target)]\n\n sample_weight_rus = \\\n sample_weight[np.where(y != self.minority_target)][X_idx]\n sample_weight_min = \\\n sample_weight[np.where(y == self.minority_target)]\n\n # Combine the minority and majority class samples.\n X_train = np.vstack((X_rus, X_min))\n y_train = np.append(y_rus, y_min)\n\n # Combine the weights.\n sample_weight_train = \\\n np.append(sample_weight_rus, sample_weight_min).reshape(-1, 1)\n sample_weight_train = \\\n np.squeeze(normalize(sample_weight_train, axis=0, norm='l1'))\n\n # Boosting step.\n _, estimator_weight_train, estimator_error = self._boost(\n iboost,\n X_train, y_train,\n sample_weight_train,\n random_state)\n \n # print(self.estimators_)\n y_predict_proba = self.estimators_[-1].predict_proba(X)\n y_predict = self.classes_.take(np.argmax(y_predict_proba, axis=1),\n axis=0)\n # Instances incorrectly classified\n incorrect = y_predict != y\n # Error fraction\n estimator_error = np.mean(\n np.average(incorrect, weights=sample_weight, axis=0))\n n_classes = self.n_classes_\n classes = self.classes_\n y_codes = np.array([-1. / (n_classes - 1), 1.])\n y_coding = y_codes.take(classes == y[:, np.newaxis])\n estimator_weight = (-1. * self.learning_rate\n * ((n_classes - 1.) / n_classes)\n * (y_coding * (y_predict_proba)).sum(axis=1))\n # print(y_predict_proba, y_coding, np.log(y_predict_proba))\n if not iboost == self.n_estimators - 1:\n # Only boost positive weights\n sample_weight *= np.exp(estimator_weight * ((sample_weight > 0) | (estimator_weight < 0)))\n # print (np.exp(estimator_weight * ((sample_weight > 0) | (estimator_weight < 0))))\n # Early termination.\n if sample_weight is None:\n print('sample_weight: {}'.format(sample_weight))\n break\n\n self.estimator_weights_[iboost] = estimator_weight_train\n self.estimator_errors_[iboost] = estimator_error\n\n # Stop if error is zero.\n # if estimator_error == 0:\n # print('error: {}'.format(estimator_error))\n # break\n\n sample_weight_sum = np.sum(sample_weight)\n\n # Stop if the sum of sample weights has become non-positive.\n if sample_weight_sum <= 0:\n print('sample_weight_sum: {}'.format(sample_weight_sum))\n break\n\n if iboost < self.n_estimators - 1:\n # Normalize.\n sample_weight /= sample_weight_sum\n\n return self\n\nimport pandas as pd\nfrom imblearn.over_sampling import SMOTE as SMOTE_IMB\nfrom sklearn.tree import DecisionTreeClassifier\n\nclass SMOTEBaggingClassifier(BaggingClassifier):\n def __init__(self,\n base_estimator=DecisionTreeClassifier(),\n n_estimators=10,\n random_state=None):\n\n super(SMOTEBaggingClassifier, self).__init__(\n base_estimator=base_estimator,\n n_estimators=n_estimators,\n random_state=random_state)\n\n def fit(self, X, y):\n\n self._validate_estimator()\n\n self.estimators_ = []\n\n df = pd.DataFrame(X); df['label'] = y\n df_maj = df[df['label']==0]; n_maj = len(df_maj)\n df_min = df[df['label']==1]; n_min = len(df_min)\n cols = df.columns.tolist(); cols.remove('label')\n for ibagging in range(self.n_estimators):\n b = min(0.1*((ibagging%10)+1), 1)\n train_maj = df_maj.sample(frac=b, replace=True)\n train_min = df_min.sample(frac=b, replace=True)\n # train_maj = df_maj.sample(frac=1/self.n_estimators, replace=True)\n # train_min = df_min.sample(frac=1/self.n_estimators, replace=True)\n # train_maj = df_maj.sample(n=n_min, replace=True)\n # train_min = df_min.sample(frac=1/self.n_estimators, replace=True)\n df_k = train_maj.append(train_min)\n X_train, y_train = SMOTE_IMB(k_neighbors=min(5, len(train_min)-1)).fit_resample(df_k[cols], df_k['label'])\n # print ('Bagging Iter: {} |b: {:.1f}|n_train: {}|n_smote: {}'.format(\n # ibagging, b, len(y_train), len(y_train)-len(df_k)))\n estimator = self._make_estimator(append=True, random_state=self.random_state)\n estimator.fit(X_train, y_train)\n\n return self\n \n def predict_proba(self, X):\n y_pred = np.array([model.predict(X) for model in self.estimators_]).mean(axis=0)\n if y_pred.ndim == 1:\n y_pred = y_pred[:, np.newaxis]\n if y_pred.shape[1] == 1:\n y_pred = np.append(1-y_pred, y_pred, axis=1)\n return y_pred\n \n def predict(self, X):\n y_pred_binarazed = binarize(self.predict_proba(X)[:,1].reshape(1,-1), threshold=0.5)[0]\n return y_pred_binarazed\n\nimport pandas as pd\nfrom sklearn.tree import DecisionTreeClassifier\n\nclass UnderBaggingClassifier(BaggingClassifier):\n def __init__(self,\n base_estimator=DecisionTreeClassifier(),\n n_estimators=10,\n random_state=None):\n\n super(UnderBaggingClassifier, self).__init__(\n base_estimator=base_estimator,\n n_estimators=n_estimators,\n random_state=random_state)\n \n def fit(self, X, y):\n\n self._validate_estimator()\n\n self.estimators_ = []\n\n df = pd.DataFrame(X); df['label'] = y\n df_maj = df[df['label']==0]; n_maj = len(df_maj)\n df_min = df[df['label']==1]; n_min = len(df_min)\n cols = df.columns.tolist(); cols.remove('label')\n for ibagging in range(self.n_estimators):\n train_maj = df_maj.sample(n=n_min, replace=True)\n train_min = df_min\n # print ('Bagging Iter: {} X_maj: {} X_rus: {} X_min: {}'.format(\n # ibagging, len(df_maj), len(train_maj), len(train_min)))\n df_k = train_maj.append(train_min)\n X_train, y_train = df_k[cols], df_k['label']\n estimator = self._make_estimator(append=True, random_state=self.random_state)\n estimator.fit(X_train, y_train)\n\n return self\n \n def predict_proba(self, X):\n y_pred = np.array([model.predict(X) for model in self.estimators_]).mean(axis=0)\n if y_pred.ndim == 1:\n y_pred = y_pred[:, np.newaxis]\n if y_pred.shape[1] == 1:\n y_pred = np.append(1-y_pred, y_pred, axis=1)\n return y_pred\n \n def predict(self, X):\n y_pred_binarazed = binarize(self.predict_proba(X)[:,1].reshape(1,-1), threshold=0.5)[0]\n return y_pred_binarazed\n\n\nfrom sklearn.base import clone\nclass BalanceCascadeClassifier(BaggingClassifier):\n \"\"\"\n The implementation of BalanceCascade.\n Hyper-parameters:\n base_estimator : scikit-learn classifier object\n optional (default=DecisionTreeClassifier)\n The base estimator from which the ensemble is built.\n n_estimators: Number of iterations / estimators\n k_bins: Number of hardness bins\n \"\"\"\n def __init__(self, \n base_estimator=DecisionTreeClassifier(), \n n_estimators=10, \n random_state=None):\n\n super(BalanceCascadeClassifier, self).__init__(\n base_estimator=base_estimator,\n n_estimators=n_estimators,\n random_state=random_state)\n\n def fit(self, X, y, print_log=False, visualize=False):\n\n self._validate_estimator()\n \n self.estimators_ = []\n self.estimators_features_ = []\n\n # Initialize majority & minority set\n df = pd.DataFrame(X); df['label'] = y\n df_maj = df[y==0]; n_maj = df_maj.shape[0]\n df_min = df[y==1]; n_min = df_min.shape[0]\n self.features_ = df.columns.tolist()\n self.features_.remove('label')\n\n ir = n_min / n_maj\n keep_fp_rate = np.power(ir, 1/(self.n_estimators-1))\n\n # Algorithm start\n for ibagging in range(1, self.n_estimators):\n df_train = df_maj.sample(n=n_min).append(df_min)\n if visualize:\n df_train.plot.scatter(x=0, y=1, s=3, c='label', colormap='coolwarm', title='Iter {} training set'.format(ibagging))\n # print ('Cascade Iter: {} X_maj: {} X_rus: {} X_min: {}'.format(\n # ibagging, len(df_maj), len(df_min), len(df_min)))\n estimator = self._make_estimator(append=True, random_state=self.random_state)\n estimator.fit(df_train[self.features_], df_train['label'])\n # drop \"easy\" majority samples\n df_maj['pred_proba'] = self.predict(df_maj[self.features_])\n df_maj = df_maj.sort_values(by='pred_proba', ascending=False)[:int(keep_fp_rate*len(df_maj)+1)]\n return self\n \n def predict_proba(self, X):\n y_pred = np.array([model.predict(X) for model in self.estimators_]).mean(axis=0)\n if y_pred.ndim == 1:\n y_pred = y_pred[:, np.newaxis]\n if y_pred.shape[1] == 1:\n y_pred = np.append(1-y_pred, y_pred, axis=1)\n return y_pred\n \n def predict(self, X):\n y_pred_binarazed = binarize(self.predict_proba(X)[:,1].reshape(1,-1), threshold=0.5)[0]\n return y_pred_binarazed","sub_path":"self_paced_ensemble/canonical_ensemble/canonical_ensemble.py","file_name":"canonical_ensemble.py","file_ext":"py","file_size_in_byte":31498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"279312333","text":"'''\n mean squared error (MSE) or mean squared deviation (MSD)\n\n'''\n\nimport numpy as np\n\n\nclass LinearRegressor:\n def __init__(self, num_iteration, learning_rate, initial_m, initial_b):\n self.num_iteration = num_iteration\n self.learning_rate = learning_rate\n self.m = initial_m\n self.b = initial_b\n\n def train(self, data):\n for i in range(self.num_iteration):\n gradient_m, gradient_b = self.computGradient(data)\n self.m -= gradient_m * self.learning_rate\n self.b -= gradient_m * self.learning_rate\n\n def computGradient(self, data):\n total_gradient_m = 0\n total_gradient_b = 0\n for i in range(len(data)):\n x, y = data[i]\n predict_y = self.predict(x)\n gradient_m = 2 * x * (predict_y - y)\n gradient_b = 2 * (predict_y - y)\n\n total_gradient_m += gradient_m\n average_gradient_m = total_gradient_m / float(len(data))\n average_gradient_b = total_gradient_b / float(len(data))\n\n return average_gradient_m, average_gradient_b\n\n def predict(self, x):\n return self.m * x + self.b\n\n def computeMSE(self, data):\n total_error = 0\n for i in range(len(data)):\n x, y = data[i]\n predict_y = self.predict(x)\n error = (y - predict_y)**2\n total_error = error + total_error\n average_err = total_error / float(len(data))\n return average_err\n\n\ndef run():\n data = np.genfromtxt('../data/salary.csv', delimiter=',')\n\n # parameter\n num_iteration = 1000\n learning_rate = 0.0001\n initial_m = 0\n initial_b = 0\n\n model = LinearRegressor(num_iteration, learning_rate, initial_m, initial_b)\n print('MSE before training: ', model.computeMSE(data))\n\n model.train(data)\n print('MSE after training: ', model.computeMSE(data))\n print(\"m and b after training:\", model.m, model.b)\n\nif __name__ == '__main__':\n run()\n","sub_path":"Regression/linear_regression/linear_regression_simple.py","file_name":"linear_regression_simple.py","file_ext":"py","file_size_in_byte":1971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"642051975","text":"from django import forms\nfrom django.forms import ModelForm, Textarea\nimport datetime\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.contrib.admin import widgets \n\nfrom .models import Alarm, Setting, Event, Homework\n\n\nclass AlarmForm(forms.ModelForm):\n\tclass Meta:\n\t\tmodel = Alarm\n\t\tfields = ('date_alarm', 'time_alarm',)\n\t\tlabels = {\n 'date_alarm': _('Dia'),\n 'time_alarm': _('Hora'),\n }\n\n\n\nclass SettingForm(forms.ModelForm):\n\tclass Meta:\n\t\tmodel = Setting\n\t\tfields = ('title_setting', 'volumen_setting', 'vibration_setting',)\n\t\tlabels = {\n 'title_setting': _('Configuracion'),\n 'volumen_setting': _('Volumen'),\n 'vibration_setting': _('Vibracion'),\n }\n\nclass EventForm(forms.ModelForm):\n\tclass Meta:\n\t\tmodel = Event\n\t\tfields = ('title_event', 'date_event', 'time_event', 'duration_event', \n\t\t\t\t 'place_event', 'setting_event', )\n\t\tlabels = {\n 'title_event': _('Evento'),\n 'date_event': _('Fecha'),\n 'time_event': _('Hora'),\n 'duration_event': _('Duracion'),\n 'place_event': _('Lugar'),\n 'setting_event': _('Configuracion'),\n }\n\nclass HomeworkForm(forms.ModelForm):\n\tclass Meta:\n\t\tmodel = Homework\n\t\tfields = ('title_homework', 'description_homework', 'date_homework', 'time_homework', \n\t\t\t\t 'priority_homework', 'event_homework')\n\t\tlabels = {\n 'title_homework': _('Tarea'),\n 'description_homework': _('Descripcion'),\n 'date_homework': _('Fecha'),\n 'time_homework': _('Hora'),\n 'priority_homework': _('Prioridad'),\n 'event_homework': _('Evento relacionado'),\n }","sub_path":"smartime/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"13563431","text":"from .repeated_word import repeated_word\nimport pytest\n\n\ndef test_repeated_word1():\n tmp = repeated_word(\"Once upon a time, there was a brave princess who...\")\n assert tmp == 'a'\n\n\ndef test_repeated_word2():\n tmp = repeated_word(\"It was the best of times, it was the worst of times, \\\n it was the age of wisdom, it was the age of foolishness, it was the epoch \\\n of belief, it was the epoch of incredulity, it was the season of Light, \\\n it was the season of Darkness, it was the spring of hope, it was the winter \\\n of despair, we had everything before us, we had nothing before us, we were \\\n all going direct to Heaven, we were all going direct the other way – in short,\\\n the period was so far like the present period, that some of its noisiest \\\n authorities insisted on its being received, for good or for evil, in the \\\n superlative degree of comparison only...\")\n assert tmp == 'it'\n\n\ndef test_repeated_word3():\n tmp = repeated_word(\"It was a queer, sultry summer, the summer they electrocuted \\\n the Rosenbergs, and I didn’t know what I was doing in New York...\")\n assert tmp == 'summer'\n\n\ndef test_bad_input():\n with pytest.raises(TypeError) as t:\n repeated_word(234)\n # import pdb; pdb.set_trace()\n assert 'please input in the type of string.' in str(t.value)\n","sub_path":"challenges/repeated_word/test_repeated_word.py","file_name":"test_repeated_word.py","file_ext":"py","file_size_in_byte":1347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"619325825","text":"# Standard PyTorch imports\nimport time\nimport math\nimport copy\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\n\nimport matplotlib.pyplot as plt\n\n\nclass EncoderDecoderP(nn.Module):\n \"\"\"\n A standard Encoder-Decoder architecture. Base for this and many\n other models.\n \"\"\"\n\n def __init__(self, encoder, decoder, src_embed, tgt_embed, generator):\n super(EncoderDecoderP, self).__init__()\n self.encoder = encoder\n self.decoder = decoder\n self.src_embed = src_embed\n self.tgt_embed = tgt_embed\n self.generator = generator\n\n def forward(self, src, tgt, src_mask, tgt_mask):\n \"\"\"Take in and process masked src and target sequences.\"\"\"\n memory = self.encoder(self.src_embed(src), src_mask)\n output = self.decoder(self.tgt_embed(tgt), memory,\n src_mask, tgt_mask)\n return output\n\n def encode(self, src, src_mask):\n return self.encoder(self.src_embed(src), src_mask)\n\n def decode(self, memory, src_mask, tgt, tgt_mask):\n return self.decoder(self.tgt_embed(tgt), memory, src_mask, tgt_mask)\n\n\nclass GeneratorP(nn.Module):\n \"\"\"\n Define standard linear + softmax generation step.\n\n ???\n \"\"\"\n\n def __init__(self, d_model, vocab):\n super(GeneratorP, self).__init__()\n self.proj = nn.Linear(d_model, vocab)\n\n def forward(self, x):\n return F.log_softmax(self.proj(x), dim=-1)\n\n\ndef clones_p(module, N):\n \"\"\"Produce N identical layers.\"\"\"\n return nn.ModuleList([copy.deepcopy(module) for _ in range(N)])\n\n\nclass EncoderP(nn.Module):\n \"\"\"Core encoder is a stack of N layers\"\"\"\n\n def __init__(self, layer, N):\n super(EncoderP, self).__init__()\n self.layers = clones_p(layer, N)\n self.norm = LayerNormP(layer.size)\n\n def forward(self, x, mask):\n \"\"\"Pass the input (and mask) through each layer in turn.\"\"\"\n for layer in self.layers:\n x = layer(x, mask)\n return self.norm(x)\n\n\nclass LayerNormP(nn.Module):\n \"\"\"\n Construct a layernorm module (See citation for details).\n\n ln = LayerNorm(10)\n x = torch.tensor([[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]).type(torch.float)\n ln.forward(x)\n\n\n \"\"\"\n\n def __init__(self, features, eps=1e-6):\n super(LayerNormP, self).__init__()\n self.a_2 = nn.Parameter(torch.ones(features))\n self.b_2 = nn.Parameter(torch.zeros(features))\n self.eps = eps\n\n def forward(self, x):\n mean = x.mean(-1, keepdim=True)\n # std = x.std(-1, keepdim=True)\n std = x.std(-1, keepdim=True, unbiased=False) # changed @@@\n \"\"\"\n default value of unbiased is True. because Keras only provide biased std. \n for comparison purpose, changed to use biased std.\n \"\"\"\n return self.a_2 * (x - mean) / (std + self.eps) + self.b_2\n\n\nclass SublayerConnectionP(nn.Module):\n \"\"\"\n A residual connection followed by a layer norm.\n Note for code simplicity the norm is first as opposed to last.\n \"\"\"\n\n def __init__(self, size, dropout):\n super(SublayerConnectionP, self).__init__()\n self.norm = LayerNormP(size)\n self.dropout = nn.Dropout(dropout)\n\n def forward(self, x, sublayer):\n \"\"\"\n Apply residual connection to any sublayer with the same size.\n\n x : input to sublayer\n sublayer: {multi-head attention or position-wise feed-forward}\n Following original paper,\n this should be norm(x + dropout(sublayer(x)))\n\n\n But according to below comment\n https://github.com/tensorflow/tensor2tensor/blob/v1.6.5/tensor2tensor/layers/common_hparams.py#L110-L112\n # TODO(noam): The current settings (\"\", \"dan\") are the published version\n # of the transformer. (\"n\", \"da\") seems better for harder-to-learn\n # models, so it should probably be the default.\n and comment below\n https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/layers/common_layers.py\n The sequence is specified as a string which may contain the following\n characters:\n a: add previous_value\n n: apply normalization\n d: apply dropout\n z: zero add\n original paper use only post process 'dan'\n which is doing dropout, add, norm for sublayer_output\n and it is norm(x + dropout(sublayer(x))\n\n enhanced version is doing norm on x and then dropout on sublayer_output and add.\n this is x + dropout(sublayer(norm(x)))\n \"\"\"\n\n return x + self.dropout(sublayer(self.norm(x)))\n\n\nclass EncoderLayerP(nn.Module):\n \"\"\"\n Encoder is made up of self-attn and feed forward (defined below)\n\n\n \"\"\"\n\n def __init__(self, size, self_attn, feed_forward, dropout):\n super(EncoderLayerP, self).__init__()\n self.self_attn = self_attn\n self.feed_forward = feed_forward\n self.sublayer = clones_p(SublayerConnectionP(size, dropout), 2)\n self.size = size\n\n def forward(self, x, mask):\n \"\"\"Follow Figure 1 (left) for connections.\"\"\"\n x = self.sublayer[0](x, lambda x: self.self_attn(x, x, x, mask))\n return self.sublayer[1](x, self.feed_forward)\n\n\nclass DecoderP(nn.Module):\n \"\"\"Generic N layer decoder with masking.\"\"\"\n\n def __init__(self, layer, N):\n super(DecoderP, self).__init__()\n self.layers = clones_p(layer, N)\n self.norm = LayerNormP(layer.size)\n\n def forward(self, x, memory, src_mask, tgt_mask):\n for layer in self.layers:\n x = layer(x, memory, src_mask, tgt_mask)\n return self.norm(x)\n\n\nclass DecoderLayerP(nn.Module):\n \"\"\"Decoder is made of self-attn, src-attn, and feed forward (defined below)\"\"\"\n\n def __init__(self, size, self_attn, src_attn, feed_forward, dropout):\n super(DecoderLayerP, self).__init__()\n self.size = size\n self.self_attn = self_attn\n self.src_attn = src_attn\n self.feed_forward = feed_forward\n self.sublayer = clones_p(SublayerConnectionP(size, dropout), 3)\n\n def forward(self, x, memory, src_mask, tgt_mask):\n \"\"\"Follow Figure 1 (right) for connections.\"\"\"\n m = memory\n x = self.sublayer[0](x, lambda x: self.self_attn(x, x, x, tgt_mask))\n x = self.sublayer[1](x, lambda x: self.src_attn(x, m, m, src_mask))\n return self.sublayer[2](x, self.feed_forward)\n\n\ndef subsequent_mask_p(size):\n \"\"\"\n Mask out subsequent positions.\n\n >>> subsequent_mask(3)\n tensor([\n [\n [1, 0, 0],\n [1, 1, 0],\n [1, 1, 1]\n ]], dtype=torch.uint8) # [1, 3, 3]\n\n This function gives mask for a sentence with 'size' words.\n\n \"\"\"\n attn_shape = (1, size, size)\n subsequent_mask = np.triu(np.ones(attn_shape), k=1).astype('uint8')\n return torch.from_numpy(subsequent_mask) == 0\n\n\ndef attention_p(q_w_q, k_w_k, v_w_v, mask=None, dropout=None):\n \"\"\"\n Compute 'Scaled Dot Product Attention'\n\n With settings\n d_model = 12\n num of word in sentence = 4\n num of sentences = nbatches = 5\n num of heads = self.h = 2\n self.d_k = d_model / self.h = 6\n\n shape of q_w_q, k_w_k, v_w_v: [5, 2, 4, 6]\n -> last dim is 6 because we divided d_model by num heads. (12/6)\n -> [num sentences, heads, num words, word info 'for this head']\n\n torch.matmul(q_w_q, k_w_k.transpose(-2, -1)) / math.sqrt(d_k)\n -> attention(QW^Q, KW^K, VW^V) = softmax( {QW^Q dot (KW^K)^T} / sqrt(d_k)} ) dot VW^V\n -> eq (1) of original paper\n\n shape of scores = torch.matmul(q_w_q, k_w_k.transpose(-2, -1)): [5, 2, 4, 4]\n -> dot product of [5, 2, 4, 6] and [5, 2, 6, 4]\n\n shape of mask: [5, 1, 1, 4]\n -> this mask shape will be extended as shape of scores, scores's shape is [5, 2, 4, 4]\n\n scores.masked_fill(mask == 0, -1e9)\n -> create new tensor with scores having original value if mask != 0 otherwise having -1e9 if mask == 0.\n \"\"\"\n d_k = q_w_q.size(-1)\n scores = torch.matmul(q_w_q, k_w_k.transpose(-2, -1)) / math.sqrt(d_k)\n if mask is not None:\n scores = scores.masked_fill(mask == 0, -1e9) # Fills scores where mask is zero\n p_attn = F.softmax(scores, dim=-1)\n if dropout is not None:\n p_attn = dropout(p_attn)\n return torch.matmul(p_attn, v_w_v), p_attn\n\n\nclass MultiHeadedAttentionP(nn.Module):\n \"\"\"\n\n \"\"\"\n def __init__(self, h, d_model, dropout=0.1, linears=None):\n \"\"\"Take in model size and number of heads.\n\n h: number of heads\n linears: added by kdw to test fixed weight linear.\n \"\"\"\n super(MultiHeadedAttentionP, self).__init__()\n assert d_model % h == 0\n # We assume d_v always equals d_k\n self.d_k = d_model // h # d_k = d_v = d_model/h\n self.h = h # number of heads\n\n if linears:\n assert len(linears) == 4\n self.linears = linears\n else:\n self.linears = clones_p(nn.Linear(d_model, d_model), 4)\n\n \"\"\"\n : 4 copies for W^Q, W^K, W^V and W^O (refers to page 5 of paper)\n : actually W^{Q, K, V} is for h heads, \n so it's dim is d_model, not d_model/h\n \"\"\"\n\n self.attn = None\n self.dropout = nn.Dropout(p=dropout)\n\n def forward(self, query, key, value, mask=None):\n \"\"\"\n Implements Figure 2\n\n With settings\n d_model = 12\n num of word in sentence = 4\n num of sentences = nbatches = 5\n num of heads = self.h = 2\n self.d_k = d_model / self.h = 6\n\n shape of query: [5, 4, 12]\n shape of key: [5, 4, 12]\n shape of value: [5, 4, 12]\n\n shape of w_q, w_k, w_v: [12, 12]\n\n shape of self.linears[0](query): [5, 4, 12]\n self.linears[1](key) : [5, 4, 12]\n self.linears[2](value): [5, 4, 12]\n\n ※ view function is similar to reshape of numpy\n\n shape of self.linears[0](query).view(5, -1, 2, 6): [5, 4, 2, 6]\n -> splitting last dim into 2\n\n shape of q_w_q = self.linears[0](query).view(5, -1, 2, 6).transpose(1, 2): [5, 2, 4, 6]\n k_w_k = self.linears[1](key ).view(5, -1, 2, 6).transpose(1, 2): [5, 2, 4, 6]\n v_w_v = self.linears[2](value).view(5, -1, 2, 6).transpose(1, 2): [5, 2, 4, 6]\n -> exchanging 1st and 2nd dim to ... ??? why???\n \"\"\"\n if mask is not None:\n # Same mask applied to all h heads.\n mask = mask.unsqueeze(1)\n\n nbatches = query.size(0)\n\n # 1) Do all the linear projections in batch from d_model => h x d_k\n q_w_q, k_w_k, v_w_v = \\\n [l(x).view(nbatches, -1, self.h, self.d_k).transpose(1, 2)\n for l, x in zip(self.linears, (query, key, value))]\n\n # 2) Apply attention on all the projected vectors in batch.\n x, self.attn = attention_p(q_w_q, k_w_k, v_w_v, mask=mask, dropout=self.dropout)\n\n # 3) \"Concat\" using a view and apply a final linear.\n \"\"\"\n shape of x: [5, 2, 4, 6] -> last two dim represent one sentence.\n x.transpose(1, 2): [5, 4, 2, 6] -> last two dim represent attentions(multiple heads) of one word.\n x.transpose(1, 2).contiguous().view(nbatches, -1, self.h * self.d_k): [5, 4, 12]\n -> concatenating attentions into one.\n \n self.linears[-1](x) -> concat(head1, head2, ...) dot W^O\n shape of W^O: d_model times d_K\n \"\"\"\n x = x.transpose(1, 2).contiguous().view(nbatches, -1, self.h * self.d_k)\n return self.linears[-1](x)\n\n\nclass PositionwiseFeedForwardP(nn.Module):\n \"\"\"Implements FFN equation.\"\"\"\n\n def __init__(self, d_model, d_ff, dropout=0.1):\n super(PositionwiseFeedForwardP, self).__init__()\n self.w_1 = nn.Linear(d_model, d_ff)\n self.w_2 = nn.Linear(d_ff, d_model)\n self.dropout = nn.Dropout(dropout)\n\n def forward(self, x):\n return self.w_2(self.dropout(F.relu(self.w_1(x))))\n\n\nclass EmbeddingsP(nn.Module):\n \"\"\"\n >>> np.random.seed(0)\n >>> emb_weight = np.random.rand(7, 12) # total 7 tokens and hidden size is 12\n >>> em = EmbeddingsP(d_model=12, vocab=7, weight=emb_weight)\n >>> test_emb_pytorch = em(torch.tensor([list(range(7))]))\n >>> test_emb_pytorch = test_emb_pytorch.numpy()[:]\n >>> print(test_emb_pytorch, test_emb_pytorch.shape)\n \"\"\"\n def __init__(self, d_model, vocab, weight=None):\n super(EmbeddingsP, self).__init__()\n self.d_model = d_model\n self.lut = nn.Embedding(num_embeddings=vocab, embedding_dim=d_model)\n\n if weight is None:\n pass\n elif isinstance(weight, np.ndarray):\n self.lut.weight.data.copy_(torch.from_numpy(weight))\n self.lut.weight.requires_grad = False\n else:\n raise ValueError('Invalid weight')\n\n def forward(self, x):\n \"\"\"Why multiply sqrt of d_model? maybe this is scaling factor\n that is sqrt of d_k in the eq1 of original paper.\n Btw d_k = d_v = d_model / h = 64,\n scaling factor is sqrt of length of vector itself.\n \"\"\"\n return self.lut(x) * math.sqrt(self.d_model)\n\n\nclass PositionalEncodingP(nn.Module):\n \"\"\"Implement the PE function.\n\n >>> # test implementation\n >>> max_len = 4\n >>> d_model = 12\n >>> pe = torch.zeros(max_len, d_model); print(pe, pe.shape)\n\n >>> # sentence number 0 to max_len-1\n >>> position = torch.arange(start=0.0, end=max_len).unsqueeze(1); print(position, position.shape)\n\n >>> # div term = exp{ -frac{2i}{d_model} * log(10000) }\n >>> # PE(pos, 2i) = sin(pos/10000^{frac{2i}{d_model}}\n >>> # i : index of 0 to d_model-1\n >>> div_term = torch.exp(torch.arange(0.0, d_model, 2) * -(math.log(10000.0) / d_model))\n >>> pe[:, 0::2] = torch.sin(position * div_term)\n >>> pe[:, 1::2] = torch.cos(position * div_term)\n >>> pe.shape # (4, 12)\n >>> pe = pe.unsqueeze(0)\n >>> pe.shape # (1, 4, 12)\n\n\n >>> # plotting\n >>> d_model = 12\n >>> num_sentences = 1\n >>> num_tokens_in_sentence = 100\n >>> plt.figure(figsize=(15, 5))\n >>> pe = PositionalEncodingP(d_model=d_model, dropout=0.)\n >>> y = pe.forward(Variable(torch.zeros(1, num_tokens_in_sentence, d_model)))\n >>> plt.plot(np.arange(num_tokens_in_sentence), y[0, :, 4:8].data.numpy())\n >>> plt.legend([\"dim %d\" % p for p in [4, 5, 6, 7]])\n >>> plt.show()\n \"\"\"\n def __init__(self, d_model, dropout, max_len=5000):\n super(PositionalEncodingP, self).__init__()\n self.dropout = nn.Dropout(p=dropout)\n\n # Compute the positional encodings once in log space.\n pe = torch.zeros(max_len, d_model)\n position = torch.arange(0.0, max_len).unsqueeze(1)\n div_term = torch.exp(torch.arange(0.0, d_model, 2) *\n -(math.log(10000.0) / d_model))\n pe[:, 0::2] = torch.sin(position * div_term)\n pe[:, 1::2] = torch.cos(position * div_term)\n pe = pe.unsqueeze(0)\n self.register_buffer('pe', pe)\n\n def forward(self, x):\n x = x + Variable(self.pe[:, :x.size(1)],\n requires_grad=False)\n return self.dropout(x)\n\n\ndef make_model_p(src_vocab, tgt_vocab, N=6, d_model=512, d_ff=2048, h=8, dropout=0.1):\n \"\"\"\n Helper: Construct a model from hyperparameters.\n\n :param src_vocab:\n :param tgt_vocab:\n :param N: # of transformer block\n :param d_model: size of embedding\n :param d_ff: hidden layer size of the 'Position wize feed forward' unit.\n :param h: # of heads\n :param dropout:\n :return:\n \"\"\"\n c = copy.deepcopy\n attn = MultiHeadedAttentionP(h, d_model)\n ff = PositionwiseFeedForwardP(d_model, d_ff, dropout)\n position = PositionalEncodingP(d_model, dropout)\n\n model = EncoderDecoderP(\n encoder=EncoderP( # 'encoder' is stack of N 'encoder layer'\n layer=EncoderLayerP( # 'encoder layer' has 2 sub-layers,\n size=d_model, # which are 'multi-attn' and 'position-wise fully connected feed-forward'\n self_attn=c(attn),\n feed_forward=c(ff),\n dropout=dropout\n ),\n N=N\n ),\n decoder=DecoderP( # stack of N 'decoder layer'\n layer=DecoderLayerP(\n size=d_model,\n self_attn=c(attn),\n src_attn=c(attn),\n feed_forward=c(ff),\n dropout=dropout\n ),\n N=N\n ),\n src_embed=nn.Sequential(\n EmbeddingsP(\n d_model=d_model, vocab=src_vocab\n ),\n c(position) # positional encoding\n ),\n tgt_embed=nn.Sequential( # Sequential(f1(x), f2) means y = f2(f1(x))\n EmbeddingsP(\n d_model=d_model,\n vocab=tgt_vocab\n ),\n c(position) # positional encoding\n ),\n generator=GeneratorP(d_model=d_model, vocab=tgt_vocab)\n )\n\n # This was important from their code.\n # Initialize parameters with Glorot / fan_avg.\n for p in model.parameters():\n if p.dim() > 1:\n # nn.init.xavier_uniform(p)\n nn.init.xavier_uniform_(p) # fixed by kdw\n return model\n\n\nclass BatchP:\n \"\"\"Object for holding a batch of data with mask during training.\"\"\"\n\n def __init__(self, src, trg=None, pad=0):\n self.src = src\n self.src_mask = (src != pad).unsqueeze(-2)\n \"\"\"\n >>> trg = src = torch.tensor([[1, 2, 3, 2],\n [1, 2, 1, 4],\n [1, 2, 4, 5],\n [1, 1, 2, 1],\n [1, 2, 5, 5]]) # [5, 4]\n >>> pad = 0\n \n >>> src.unsqueeze(0).shape # (1, 5, 10)\n >>> src.unsqueeze(1).shape # (5, 1, 10)\n >>> src.unsqueeze(-1).shape # (5, 10, 1)\n >>> src.unsqueeze(-2).shape # (5, 1, 10)\n \"\"\"\n if trg is not None:\n self.trg = trg[:, :-1] # without last column, why???\n self.trg_y = trg[:, 1:] # without first column, why???\n self.trg_mask = self.make_std_mask(self.trg, pad)\n self.ntokens = (self.trg_y != pad).data.sum() # where this used for???\n\n @staticmethod\n def make_std_mask(trg, pad):\n \"\"\"\n Create a mask to hide padding and future words.\n\n >>> trg = src = torch.tensor([[1, 2, 3, 2],\n [1, 2, 1, 4],\n [1, 2, 4, 5],\n [1, 1, 2, 1],\n [1, 2, 5, 5]]) # (5, 4), number of sentence in this batch is 5, size of embedding is 4.\n\n >>> tgt = trg[:, :-1]\n >>> pad = 0\n \"\"\"\n tgt_mask = (trg != pad).unsqueeze(-2) # for example, turn [5, 3] to [5, 1, 3]\n \"\"\"\n >>> (tgt != pad).shape # (5, 3)\n >>> tgt_mask = (tgt != pad).unsqueeze(-2) # [5, 1, 3]\n >>> tgt_mask\n tensor([[[1, 1, 1]], # mask for 1st sentence\n [[1, 1, 1]], # 2nd\n [[1, 1, 1]], # 3rd\n [[1, 1, 1]], # 4th\n [[1, 1, 1]]], # 5th\n dtype=torch.uint8) # [5, 1, 3] \n \"\"\"\n tgt_mask = tgt_mask & Variable(\n subsequent_mask_p(size=trg.size(-1)).type_as(tgt_mask.data)\n )\n \"\"\"\n >>> tgt.size(-1) # 3\n \n >>> v = Variable(subsequent_mask(size=tgt.size(-1)).type_as(tgt_mask.data))\n >>> v \n tensor([[[1, 0, 0],\n [1, 1, 0],\n [1, 1, 1]]], dtype=torch.uint8) # [1, 3, 3]\n \n >>> tgt_mask & v\n tensor([[[1, 0, 0], # mask for 1st sentence\n [1, 1, 0],\n [1, 1, 1]],\n [[1, 0, 0], # mask for 2nd sentence\n [1, 1, 0],\n [1, 1, 1]],\n [[1, 0, 0], # mask for 3rd sentence\n [1, 1, 0],\n [1, 1, 1]],\n [[1, 0, 0], # mask for 4th sentence\n [1, 1, 0],\n [1, 1, 1]],\n [[1, 0, 0], # mask for 5th sentence\n [1, 1, 0],\n [1, 1, 1]]], dtype=torch.uint8) # [5, 3, 3]\n \"\"\"\n return tgt_mask\n\n\ndef run_epoch_p(data_iter, model, loss_compute):\n \"\"\"Standard Training and Logging Function\"\"\"\n start = time.time()\n total_tokens = 0\n total_loss = 0\n tokens = 0\n for i, batch in enumerate(data_iter):\n out = model.forward(batch.src, batch.trg,\n batch.src_mask, batch.trg_mask)\n loss = loss_compute(out, batch.trg_y, batch.ntokens)\n total_loss += loss\n total_tokens += batch.ntokens\n tokens += batch.ntokens\n if i % 50 == 1:\n elapsed = time.time() - start\n # print(\"Epoch Step: %d Loss: %f Tokens per Sec: %f\" % (i, loss / batch.ntokens, tokens / elapsed))\n print(\"Epoch Step: %d Loss: %f Tokens per Sec: %f\"\n % (i, loss / batch.ntokens.type(torch.FloatTensor), tokens.type(torch.FloatTensor) / elapsed))\n start = time.time()\n tokens = 0\n # return total_loss / total_tokens\n return total_loss / total_tokens.type(torch.FloatTensor) # fixed by kdw\n\n\nglobal max_src_in_batch, max_tgt_in_batch\n\n\ndef batch_size_fn_p(new, count, sofar):\n \"\"\"Keep augmenting batch and calculate total number of tokens + padding.\"\"\"\n global max_src_in_batch, max_tgt_in_batch\n if count == 1:\n max_src_in_batch = 0\n max_tgt_in_batch = 0\n max_src_in_batch = max(max_src_in_batch, len(new.src))\n max_tgt_in_batch = max(max_tgt_in_batch, len(new.trg) + 2)\n src_elements = count * max_src_in_batch\n tgt_elements = count * max_tgt_in_batch\n return max(src_elements, tgt_elements)\n\n\nclass NoamOptP:\n \"\"\"Optim wrapper that implements rate.\n\n from paper 5.3 Optimizer.\n We used the Adam optimizer with β1 = 0:9, β2 = 0:98 and epsilon = 10−9.\n We varied the learning rate over the course of training, according to the formula: (3)\n \n This corresponds to increasing the learning rate linearly \n for the first warmup_steps training steps,\n and decreasing it thereafter proportionally \n to the inverse square root of the step number. \n We used warmup_steps = 4000\n\n ex)\n >>> opts = [NoamOptP(512, 1, 4000, None),\n NoamOpt(512, 1, 8000, None),\n NoamOpt(256, 1, 4000, None)]\n >>> plt.plot(np.arange(1, 20000), [[opt.rate(i) for opt in opts] for i in range(1, 20000)])\n >>> plt.legend([\"512:4000\", \"512:8000\", \"256:4000\"])\n >>> plt.show()\n \"\"\"\n\n def __init__(self, model_size, factor, warmup, optimizer):\n self.optimizer = optimizer\n self._step = 0\n self.warmup = warmup # before this steps, lr increase | after then lr decrease.\n self.factor = factor # ???\n self.model_size = model_size\n self._rate = 0\n\n def step(self):\n \"\"\"Update parameters and rate\"\"\"\n self._step += 1\n rate = self.rate() # learning rate actually we use.\n for p in self.optimizer.param_groups:\n p['lr'] = rate\n self._rate = rate # save to be used for calculating lr in the next step.\n self.optimizer.step()\n\n def rate(self, step=None):\n \"\"\"Implement `lrate` above\"\"\"\n if step is None:\n step = self._step\n\n # formula (3) of the original paper.\n return self.factor * (self.model_size ** (-0.5) * min(step ** (-0.5), step * self.warmup ** (-1.5)))\n\n\ndef get_std_opt_p(model):\n return NoamOptP(model.src_embed[0].d_model, 2, 4000,\n torch.optim.Adam(model.parameters(), lr=0, betas=(0.9, 0.98), eps=1e-9))\n\n\nclass LabelSmoothingP(nn.Module):\n \"\"\"Implement label smoothing.\"\"\"\n\n def __init__(self, size, padding_idx, smoothing=0.0):\n super(LabelSmoothingP, self).__init__()\n # self.criterion = nn.KLDivLoss(size_average=False)\n self.criterion = nn.KLDivLoss(reduction='sum') # fixed by kdw\n self.padding_idx = padding_idx\n self.confidence = 1.0 - smoothing\n self.smoothing = smoothing\n self.size = size\n self.true_dist = None\n\n def forward(self, x, target):\n assert x.size(1) == self.size\n true_dist = x.data.clone()\n true_dist.fill_(self.smoothing / (self.size - 2))\n true_dist.scatter_(1, target.data.unsqueeze(1), self.confidence)\n true_dist[:, self.padding_idx] = 0\n mask = torch.nonzero(target.data == self.padding_idx)\n if mask.dim() > 1: # fixed 0 to 1 by kew.\n true_dist.index_fill_(0, mask.squeeze(), 0.0)\n self.true_dist = true_dist\n return self.criterion(x, Variable(true_dist, requires_grad=False))\n\n\ndef greedy_decode_p(model, src, src_mask, max_len, start_symbol):\n memory = model.encode(src, src_mask)\n ys = torch.ones(1, 1).fill_(start_symbol).type_as(src.data)\n for i in range(max_len-1):\n out = model.decode(memory, src_mask,\n Variable(ys),\n Variable(subsequent_mask_p(ys.size(1))\n .type_as(src.data)))\n prob = model.generator(out[:, -1])\n _, next_word = torch.max(prob, dim = 1)\n next_word = next_word.data[0]\n ys = torch.cat([ys,\n torch.ones(1, 1).type_as(src.data).fill_(next_word)], dim=1)\n return ys\n\n\ndef data_gen_p(V, batch, nbatches, max_words_in_sentence):\n \"\"\"\n Generate random data for a src-tgt copy task.\n\n # 5: # of sentences per batch == batch(2nd arg)\n # 4: # of words in each sentence\n # 7: size of word dictionary\n np.random.randint(low=1, high=7, size=(5, 4)) # 5 by 4 matrix\n\n >>> gen = data_gen(7, 5, 2, 4)\n >>> batch0 = next(gen)\n >>> batch0.src\n >>> batch0.trg\n >>> batch0.src.shape # [5, 4]\n >>> batch0.ntokens # 15\n tensor([[1, 2, 3, 2],\n [1, 2, 1, 4],\n [1, 2, 4, 5],\n [1, 1, 2, 1],\n [1, 2, 5, 5]]) # [5, 4]\n >>> batch0.src_mask\n tensor([[[1, 1, 1, 1]],\n [[1, 1, 1, 1]],\n [[1, 1, 1, 1]],\n [[1, 1, 1, 1]],\n [[1, 1, 1, 1]]], dtype=torch.uint8) # [5, 1, 4]\n >>> batch0.trg\n tensor([[1, 2, 3],\n [1, 2, 1],\n [1, 2, 4],\n [1, 1, 2],\n [1, 2, 5]]) # [5, 3]\n >>> batch0.trg_y\n tensor([[2, 3, 2],\n [2, 1, 4],\n [2, 4, 5],\n [1, 2, 1],\n [2, 5, 5]]) # [5, 3]\n >>> batch0.trg_mask\n tensor([[[1, 0, 0],\n [1, 1, 0],\n [1, 1, 1]],\n [[1, 0, 0],\n [1, 1, 0],\n [1, 1, 1]],\n [[1, 0, 0],\n [1, 1, 0],\n [1, 1, 1]],\n [[1, 0, 0],\n [1, 1, 0],\n [1, 1, 1]],\n [[1, 0, 0],\n [1, 1, 0],\n [1, 1, 1]]], dtype=torch.uint8) # [5, 3, 3]\n\n >>> batch0.ntokens # 15\n\n >>> batch0.src.shape # (5, 4)\n \"\"\"\n for _ in range(nbatches):\n data = torch.from_numpy(np.random.randint(low=1, high=V, size=(batch, max_words_in_sentence)))\n data[:, 0] = 1 # 1 for first column\n src = Variable(data, requires_grad=False).type(torch.long)\n tgt = Variable(data, requires_grad=False).type(torch.long)\n yield BatchP(src, tgt, 0)\n","sub_path":"my/transformer_test/harvardnlp_transformer.py","file_name":"harvardnlp_transformer.py","file_ext":"py","file_size_in_byte":27751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"546177057","text":"\"\"\"\nCommands\n\nCommands describe the input the player can do to the game.\n\n\"\"\"\nimport time, evennia\nfrom evennia import Command as BaseCommand\nfrom evennia.server.sessionhandler import SESSIONS\nfrom evennia.utils import utils, create, search, evtable\n# from evennia import default_cmds\n\nclass Command(BaseCommand):\n \"\"\"\n Inherit from this if you want to create your own command styles\n from scratch. Note that Evennia's default commands inherits from\n MuxCommand instead.\n\n Note that the class's `__doc__` string (this text) is\n used by Evennia to create the automatic help entry for\n the command, so make sure to document consistently here.\n\n Each Command implements the following methods, called\n in this order (only func() is actually required):\n - at_pre_command(): If this returns True, execution is aborted.\n - parse(): Should perform any extra parsing needed on self.args\n and store the result on self.\n - func(): Performs the actual work.\n - at_post_command(): Extra actions, often things done after\n every command, like prompts.\n\n \"\"\"\n def at_post_cmd(self):\n \"called after self.func().\"\n caller = self.caller\n prompt = \"\\n|C[Health %s/%s, Moves %s/%s]|n\\n\" % (caller.db.curhealth, \n caller.db.maxhealth,\n caller.db.curmoves,\n caller.db.maxmoves)\n caller.msg(\"\", prompt=prompt) \n pass\n\n#------------------------------------------------------------\n#\n# The default commands inherit from\n#\n# evennia.commands.default.muxcommand.MuxCommand.\n#\n# If you want to make sweeping changes to default commands you can\n# uncomment this copy of the MuxCommand parent and add\n#\n# COMMAND_DEFAULT_CLASS = \"commands.command.MuxCommand\"\n#\n# to your settings file. Be warned that the default commands expect\n# the functionality implemented in the parse() method, so be\n# careful with what you change.\n#\n#------------------------------------------------------------\n\n#from evennia.utils import utils\n#class MuxCommand(Command):\n# \"\"\"\n# This sets up the basis for a MUX command. The idea\n# is that most other Mux-related commands should just\n# inherit from this and don't have to implement much\n# parsing of their own unless they do something particularly\n# advanced.\n#\n# Note that the class's __doc__ string (this text) is\n# used by Evennia to create the automatic help entry for\n# the command, so make sure to document consistently here.\n# \"\"\"\n# def has_perm(self, srcobj):\n# \"\"\"\n# This is called by the cmdhandler to determine\n# if srcobj is allowed to execute this command.\n# We just show it here for completeness - we\n# are satisfied using the default check in Command.\n# \"\"\"\n# return super(MuxCommand, self).has_perm(srcobj)\n#\n# def at_pre_cmd(self):\n# \"\"\"\n# This hook is called before self.parse() on all commands\n# \"\"\"\n# pass\n#\n# def at_post_cmd(self):\n# \"\"\"\n# This hook is called after the command has finished executing\n# (after self.func()).\n# \"\"\"\n# pass\n#\n# def parse(self):\n# \"\"\"\n# This method is called by the cmdhandler once the command name\n# has been identified. It creates a new set of member variables\n# that can be later accessed from self.func() (see below)\n#\n# The following variables are available for our use when entering this\n# method (from the command definition, and assigned on the fly by the\n# cmdhandler):\n# self.key - the name of this command ('look')\n# self.aliases - the aliases of this cmd ('l')\n# self.permissions - permission string for this command\n# self.help_category - overall category of command\n#\n# self.caller - the object calling this command\n# self.cmdstring - the actual command name used to call this\n# (this allows you to know which alias was used,\n# for example)\n# self.args - the raw input; everything following self.cmdstring.\n# self.cmdset - the cmdset from which this command was picked. Not\n# often used (useful for commands like 'help' or to\n# list all available commands etc)\n# self.obj - the object on which this command was defined. It is often\n# the same as self.caller.\n#\n# A MUX command has the following possible syntax:\n#\n# name[ with several words][/switch[/switch..]] arg1[,arg2,...] [[=|,] arg[,..]]\n#\n# The 'name[ with several words]' part is already dealt with by the\n# cmdhandler at this point, and stored in self.cmdname (we don't use\n# it here). The rest of the command is stored in self.args, which can\n# start with the switch indicator /.\n#\n# This parser breaks self.args into its constituents and stores them in the\n# following variables:\n# self.switches = [list of /switches (without the /)]\n# self.raw = This is the raw argument input, including switches\n# self.args = This is re-defined to be everything *except* the switches\n# self.lhs = Everything to the left of = (lhs:'left-hand side'). If\n# no = is found, this is identical to self.args.\n# self.rhs: Everything to the right of = (rhs:'right-hand side').\n# If no '=' is found, this is None.\n# self.lhslist - [self.lhs split into a list by comma]\n# self.rhslist - [list of self.rhs split into a list by comma]\n# self.arglist = [list of space-separated args (stripped, including '=' if it exists)]\n#\n# All args and list members are stripped of excess whitespace around the\n# strings, but case is preserved.\n# \"\"\"\n# raw = self.args\n# args = raw.strip()\n#\n# # split out switches\n# switches = []\n# if args and len(args) > 1 and args[0] == \"/\":\n# # we have a switch, or a set of switches. These end with a space.\n# switches = args[1:].split(None, 1)\n# if len(switches) > 1:\n# switches, args = switches\n# switches = switches.split('/')\n# else:\n# args = \"\"\n# switches = switches[0].split('/')\n# arglist = [arg.strip() for arg in args.split()]\n#\n# # check for arg1, arg2, ... = argA, argB, ... constructs\n# lhs, rhs = args, None\n# lhslist, rhslist = [arg.strip() for arg in args.split(',')], []\n# if args and '=' in args:\n# lhs, rhs = [arg.strip() for arg in args.split('=', 1)]\n# lhslist = [arg.strip() for arg in lhs.split(',')]\n# rhslist = [arg.strip() for arg in rhs.split(',')]\n#\n# # save to object properties:\n# self.raw = raw\n# self.switches = switches\n# self.args = args.strip()\n# self.arglist = arglist\n# self.lhs = lhs\n# self.lhslist = lhslist\n# self.rhs = rhs\n# self.rhslist = rhslist\n#\n# # if the class has the player_caller property set on itself, we make\n# # sure that self.caller is always the player if possible. We also create\n# # a special property \"character\" for the puppeted object, if any. This\n# # is convenient for commands defined on the Player only.\n# if hasattr(self, \"player_caller\") and self.player_caller:\n# if utils.inherits_from(self.caller, \"evennia.objects.objects.DefaultObject\"):\n# # caller is an Object/Character\n# self.character = self.caller\n# self.caller = self.caller.player\n# elif utils.inherits_from(self.caller, \"evennia.players.players.DefaultPlayer\"):\n# # caller was already a Player\n# self.character = self.caller.get_puppet(self.session)\n# else:\n# self.character = None\n#\n\nclass CmdWho(Command):\n \"\"\"\n list who is currently online\n Usage:\n who\n doing\n Shows who is currently online. Doing is an alias that limits info\n also for those with all permissions.\n \"\"\"\n\n def sessions():\n \"\"\"\n Simple shortcut to retrieving all connected sessions.\n Returns:\n list\n \"\"\"\n session_list = SESSIONS.get_sessions()\n\n session_list = sorted(session_list, key=lambda o: o.player.key)\n return evennia.SESSION_HANDLER.values()\n \n key = \"who\"\n aliases = \"twho\"\n locks = \"cmd:all()\"\n\n # this is used by the parent\n player_caller = True\n\n def sessions(self):\n \"\"\"\n Simple shortcut to retrieving all connected sessions.\n Returns:\n list\n \"\"\"\n return sorted([session for session in evennia.SESSION_HANDLER.values() if session.logged_in], key=lambda o: o.player.key)\n \n def func(self):\n \"\"\"\n Get all connected players by polling session.\n \"\"\"\n \n message = list() \n for session in self.sessions(): \n character = session.get_puppet() \n if not character: \n continue \n nam = character.get_display_name(self.caller) \n sur = character.get_names() \n line = \"|n %s %s\" % (nam, sur) \n message.append(line) \n combined = \"\\n\".join(message) \n self.caller.msg(combined)\n \npass\n\nclass CmdScore(Command):\n \"\"\"\n Display score sheet\n\n Usage:\n score\n \n Displays your character sheet.\n \"\"\"\n key = \"score\"\n aliases = [\"sc\"]\n lock = \"cmd:all()\"\n help_category = \"General\"\n\n def func(self):\n \"implements the actual functionality\"\n\n character = self.caller\n nam = character.get_display_name(self.caller)\n sur = self.caller.get_names()\n sex = self.caller.db.gender\n string = \"|C Name |R:|n %s %-37s |CGender |R:|n %s\" % (nam, sur, sex)\n self.caller.msg(string)\n \n sdesc = self.caller.attributes.get(\"_sdesc\", default=\"\")\n string = \"|C Intro |R:|n %s\" % (sdesc)\n self.caller.msg(string)\n \n age, hei, wei = self.caller.get_traits() \n string = \"|C Age |R:|n %-17s |CHeight |R:|n %-22s |CWeight |R:|n %skg|n\" % (age, hei, wei)\n self.caller.msg(string)\n \n xp, sxp, qp = self.caller.get_spends() \n string = \"|C XP |R:|n %-15s |CSpent XP |R:|n %-26s |CQP|R :|n %s\" % (xp, sxp, qp)\n self.caller.msg(string)\n \n hp, mhp, mv, mmv = self.caller.get_pools() \n string = \"|C Toughness |R:|n %s/%-12s |CFitness |R:|n %s/%s energy|n\\n\" % (hp, mhp, mv, mmv)\n self.caller.msg(string)\n\n str, dex, con, int, wis, cha = self.caller.get_abilities() \n string = \"|C Stats |R:|w Strength |C[|c%s|C]|w Dexterity |C[|c%s|C]{w Constitution |C[|c%s|C]{w\\n|w Intelligence |C[|c%s|C]|w Wisdom |C[|c%s|C]|w Charisma |C[|c%s|C]|n\\n\" % (str, dex, con, int, wis, cha)\n self.caller.msg(string)\n\n ","sub_path":"mygame/commands/command.py","file_name":"command.py","file_ext":"py","file_size_in_byte":11496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"162967224","text":"from PIL import Image, ImageTk\nfrom tkinter import *\nimport time\n\n\n\nclass Levels:\n\tdef __init__(self):\n\t\tpass\n\tdef get_(self):\n\t\tself.lvls={}\n\t\twith open(f'data\\\\levels.txt','r') as f:\n\t\t\tidx=0\n\t\t\tfor l in f:\n\t\t\t\tif not l.startswith('#'):\n\t\t\t\t\tmap_=[]\n\t\t\t\t\tl=l.replace('\\n','').split('&')\n\t\t\t\t\tfor y in range(len(l[0].split(';'))):\n\t\t\t\t\t\tmap_.append([11]*len(l[0].split(';')[y].split(',')))\n\t\t\t\t\tfor y in range(len(l[0].split(';'))):\n\t\t\t\t\t\tfor x in range(len(l[0].split(';')[y].split(','))):\n\t\t\t\t\t\t\tmap_[y][x]=int(l[0].split(';')[y].split(',')[x])\n\t\t\t\t\tself.lvls[idx]=[map_,[int(l[1].split(',')[0]),int(l[1].split(',')[1])],int(l[2])]\n\t\t\t\t\tidx+=1\n\tdef get(self,idx):\n\t\tself.get_()\n\t\treturn self.lvls[idx]\n\tdef next_lvl(self,idx):return idx+1\nclass Level:\n\tdef __init__(self,tk,cnv,tiles,ar,re,slf,lvl_id=0,lvl_map=[[[13,13,13,13,13],[32,31,44,41,34],[32,21,22,21,34],[32,33,43,42,34],[22,22,22,22,22],[22,22,22,22,22],[11,11,11,11,11]],[3,3],5]):\n\t\tself.tk,self.cnv,self.l_m,self.l_m_o,self.l_s_p,self.t_l,self.p_d,self.p_f,self.m_m,self.lvl_id,self.ar,self.re,self.t_s,self.m,self.slf,self.m_m_=tk,cnv,list(lvl_map[0]),[],lvl_map[1],tiles,{11:'u',12:'r',13:'d',14:'l',21:'rl',22:'ud',31:'url',32:'urd',33:'rdl',34:'udl',41:'ur',42:'rd',43:'dl',44:'lu'},{'u':'d','r':'l','d':'u','l':'r'},{'u':(-1,0),'r':(0,1),'d':(1,0),'l':(0,-1)},lvl_id,ar,re,time.time(),0,slf,lvl_map[2]\n\t\tself.cnv.bind_all('',func=self.turn_tile)\n\t\tself.arr=self.cnv.create_image(10,10,image=self.ar,anchor='nw')\n\t\tself.res=self.cnv.create_image(1860,10,image=self.re,anchor='nw')\n\t\tself.prepare()\n\tdef prepare(self):\n\t\tself.l_h,self.l_w=len(self.l_m),len(self.l_m[0])\n\t\tself.l_pos_c=[952.5-(self.l_w*25),502.5-(self.l_h*25)]\n\t\tfor y in range(self.l_h):\n\t\t\tself.l_m_o.append([None]*self.l_w)\n\t\tfor y in range(self.l_h):\n\t\t\tfor x in range(self.l_w):\n\t\t\t\tself.l_m_o[y][x]=self.cnv.create_image(x*50+self.l_pos_c[0],y*50+self.l_pos_c[1],image=self.t_l['off'][int(str(self.l_m[y][x])[0])-1][f'@{(int(str(self.l_m[y][x])[1])-1)*90}'],anchor='nw')\n\t\tself.marker=self.cnv.create_image(self.l_s_p[0]*50+self.l_pos_c[0]+16,self.l_s_p[1]*50+self.l_pos_c[1]+16,image=self.t_l['marker'],anchor='nw')\n\t\tself.update_power()\n\tdef turn_tile(self,arg):\n\t\tx_,y_,x,y=self.l_pos_c[0],self.l_pos_c[1],-1,-1\n\t\tfor xp in range(self.l_w):\n\t\t\tif xp<((arg.x-x_)/50)<(xp+1):\n\t\t\t\tx=xp\n\t\tfor yp in range(self.l_h):\n\t\t\tif yp<((arg.y-y_)/50)<(yp+1):\n\t\t\t\ty=yp\n\t\tif x>-1 and y>-1:\n\t\t\tself.m+=1\n\t\t\tself.cnv.delete(self.l_m_o[y][x])\n\t\t\tif str(self.l_m[y][x])[0] in ['1','3','4'] and str(self.l_m[y][x])[1]=='4':self.l_m[y][x]-=3\n\t\t\telif str(self.l_m[y][x])[0] in ['1','3','4'] and not str(self.l_m[y][x])[1]=='4':self.l_m[y][x]+=1\n\t\t\telif str(self.l_m[y][x])[0]=='2' and str(self.l_m[y][x])[1]=='2':self.l_m[y][x]-=1\n\t\t\telif str(self.l_m[y][x])[0]=='2' and not str(self.l_m[y][x])[1]=='4':self.l_m[y][x]+=1\n\t\t\tself.l_m_o[y][x]=self.cnv.create_image(x*50+self.l_pos_c[0],y*50+self.l_pos_c[1],image=self.t_l['off'][int(str(self.l_m[y][x])[0])-1][f'@{(int(str(self.l_m[y][x])[1])-1)*90}'],anchor='nw')\n\t\t\tself.update_power()\n\t\tif 9')\n\t\t\tMain.open_lvl_tab(Main,self.lvl_id)\n\t\tif 1859-1 and y_>-1:\n\t\t\t\t\tif self.p_f[d] in list(self.p_d[self.l_m[y_][x_]]):\n\t\t\t\t\t\tself.l_p_c.append([x_,y_])\n\t\t\t\t\t\tself.l_p_t_l+=1\n\t\t\t\t\t\tif len(list(self.p_d[self.l_m[y_][x_]]))>1:\n\t\t\t\t\t\t\td__=list(self.p_d[self.l_m[y_][x_]])\n\t\t\t\t\t\t\td__.remove(self.p_f[d])\n\t\t\t\t\t\t\tself._update_p(d__,x_,y_,x_,y_)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tself.cnv.delete(self.l_m_o[y_][x_])\n\t\t\t\t\t\t\tself.l_m_o[y_][x_]=self.cnv.create_image(x_*50+self.l_pos_c[0],y_*50+self.l_pos_c[1],image=self.t_l['on'][int(str(self.l_m[y_][x_])[0])-1][f'@{(int(str(self.l_m[y_][x_])[1])-1)*90}'],anchor='nw')\n\t\t\texcept Exception as er:\n\t\t\t\tpass\n\tdef end(self):\n\t\tself.t_e=time.time()\n\t\tself.cnv.unbind_all('')\n\t\tself.cnv.delete(self.arr)\n\t\tself.cnv.delete(self.res)\n\t\tself.click_=self.cnv.create_text(15,15,text='Tap anywhere to continue...',font=('Tempus Sans ITC',20),anchor='nw')\n\t\tself.cnv.bind_all('',func=self.end_)\n\tdef end_(self,arg):\n\t\tself.cnv.unbind_all('')\n\t\tself.cnv.delete(self.click_)\n\t\tMain.finish_lvl(self.slf,self.lvl_id,round((self.t_e-self.t_s)),self.m,self.m_m_)\n\tdef reset_lvl(self):\n\t\tself.cnv.unbind_all('')\n\t\tself.cnv.delete(self.arr)\n\t\tself.cnv.delete(self.res)\n\t\tfor y in range(self.l_h):\n\t\t\t\tfor x in range(self.l_w):\n\t\t\t\t\tself.cnv.delete(self.l_m_o[y][x])\n\t\tself.cnv.delete(self.marker)\n\t\tLevel(self.tk,self.cnv,self.t_l,self.ar,self.re,self.slf,lvl_id=self.lvl_id,lvl_map=list(self.slf.level_manager.get(self.lvl_id)))\nclass Main:\n\tdef __init__ (self):\n\t\tself.tk=Tk()\n\t\tself.tk.title('')\n\t\tself.tk['background']='white'\n\t\tself.tk.resizable(0,0)\n\t\tself.tk.minsize(width=100,height=100)\n\t\tself.tk.geometry('1910x1030+-5+-25')\n\t\tself.make()\n\tdef make(self):\n\t\tself.all_tiles,self.other_img={'on':[{},{},{},{}],'off':[{},{},{},{}],'marker':None},{'arrows':{},'other':{}}\n\t\tself.all_tiles['marker']=ImageTk.PhotoImage(Image.open('data\\\\img\\\\tiles\\\\tile_marker.bmp'))\n\t\tfor st in ['on','off']:\n\t\t\tfor n in range(1,5):\n\t\t\t\trot=['@0','@90','@180','@270']\n\t\t\t\tif n==2:rot=['@0','@90']\n\t\t\t\tfor r in rot:\n\t\t\t\t\tself.all_tiles[st][n-1][r]=ImageTk.PhotoImage(Image.open(f'data\\\\img\\\\tiles\\\\tile_{n}_{st}_{r}.bmp'))\n\t\tself.other_img['arrows']['left_arrow']=ImageTk.PhotoImage(Image.open('data\\\\img\\\\other\\\\arrow_left.bmp'))\n\t\tself.other_img['arrows']['right_arrow']=ImageTk.PhotoImage(Image.open('data\\\\img\\\\other\\\\arrow_right.bmp'))\n\t\tself.other_img['arrows']['reset_arrow']=ImageTk.PhotoImage(Image.open('data\\\\img\\\\other\\\\arrow_reset.bmp'))\n\t\tself.other_img['other']['diamond1']=ImageTk.PhotoImage(Image.open('data\\\\img\\\\other\\\\diamond1.bmp'))\n\t\tself.other_img['other']['diamond2']=ImageTk.PhotoImage(Image.open('data\\\\img\\\\other\\\\diamond2.bmp'))\n\t\tself.canvas=Canvas(self.tk,bg='white',width=10,height=10,borderwidth=0,highlightbackgroun='white',highlightthickness=0,highlightcolor='white')\n\t\tself.canvas.pack(padx=0,pady=0)\n\t\tself.canvas['height']=1005\n\t\tself.canvas['width']=1905\n\t\tself.canvas.bind_all('',func=self.kill)#temp\n\t\tself.level_manager=Levels()\n\t\tLevel(self.tk,self.canvas,self.all_tiles,self.other_img['arrows']['left_arrow'],self.other_img['arrows']['reset_arrow'],self,lvl_id=0,lvl_map=list(self.level_manager.get(0)))\n\tdef kill(self,arg):\n\t\tself.tk.destroy()\n\t\tquit()\n\tdef test_img(self):\n\t\tfor x in range(4):\n\t\t\tfor y in range(len(list(self.all_tiles['on'][x].keys()))):\n\t\t\t\tself.canvas.create_image(x*51,y*51,image=self.all_tiles['off'][x][f'@{y*90}'],anchor='nw')\n\t\t\t\tself.canvas.create_image((x*51)+150,y*51,image=self.all_tiles['on'][x][f'@{y*90}'],anchor='nw')\n\t\t\t\tself.canvas.create_image((x*51)+300,y*51,image=self.all_tiles['on'][x][f'@{y*90}'],anchor='nw')\n\t\t\t\tself.canvas.create_image((x*51)+300+15,y*51+15,image=self.all_tiles['marker'],anchor='nw')\n\tdef open_lvl_tab(self,idx_start):\n\t\tself.canvas.delete('all')\n\tdef finish_lvl_btn(self,arg):\n\t\tif 90:\n\t\t\tif p>=1:\n\t\t\t\tp-=1\n\t\t\t\tl_d.append(2)\n\t\t\telse:\n\t\t\t\tp-=0.5\n\t\t\t\tl_d.append(1)\n\t\tcr=952.5-((len(l_d)-1)/2)*50\n\t\ttime.sleep(0.5)\n\t\tself.diamonds=[]\n\t\tfor d in l_d:\n\t\t\td_=self.canvas.create_image(cr+950,225,image=self.other_img['other'][f'diamond{d}'],anchor='center')\n\t\t\twhile self.canvas.coords(d_)[0]!=cr:\n\t\t\t\tself.canvas.move(d_,-25,0)\n\t\t\t\tself.tk.update()\n\t\t\t\tself.tk.update_idletasks()\n\t\t\t\ttime.sleep(0.01)\n\t\t\tcr+=50\n\t\t\tself.diamonds.append(d_)\n\t\tself.canvas.create_image(10,10,image=self.other_img['arrows']['left_arrow'],anchor='nw')\n\t\tself.b_txt=self.canvas.create_text(950,1005,text=f'Try Agein\\t\\tNext Level',font=('Tempus Sans ITC',75),anchor='center')\n\t\twhile self.canvas.coords(self.b_txt)[1]>925:\n\t\t\tself.canvas.move(self.b_txt,0,-5)\n\t\t\tself.tk.update()\n\t\t\tself.tk.update_idletasks()\n\t\t\ttime.sleep(0.02)\n\t\tself.data_lvl=int(lvl_id)+1\n\t\tself.data_lvl-=1\n\t\tself.canvas.bind_all('',func=self.finish_lvl_btn)\n\tdef calculate_points(self,t,m,m_m_):\n\t\tp=0\n\t\tif m<=m_m_:p+=2\n\t\telif m_m_*2>m:p+=1\n\t\telse:p+=0\n\t\tif m_m_<=10:a=1\n\t\telif m_m_<=25:a=2\n\t\telif m_m_<=40:a=3\n\t\telif m_m_<=65:a=4\n\t\telse:a=5\n\t\tif t<=15:b=1\n\t\telif 152 and a>2:p+=(a-b+4)/2\n\t\telif (a-b+4)/2>2 and a<=2:p+=2\n\t\telse:p+=(a-b+4)/2\n\t\treturn p\nMain()\n\n","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":10491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"149305223","text":"# Search properties according to criteria then sort by nearness to Dublin Castle\nfrom daftlistings import Daft, RentType\n\ndaft = Daft()\n\ndaft.set_county(\"Dublin City\")\ndaft.set_listing_type(RentType.APARTMENTS)\ndaft.set_min_price(1000)\ndaft.set_max_price(1500)\n\nlistings = daft.search(fetch_all=False)\n\ndublin_castle_coords = [53.3429, -6.2674]\nlistings.sort(key=lambda x: x.distance_to(dublin_castle_coords))\n\nfor l in listings:\n print(f'{l}\\n\\tDistance to Dublin Castle: '\n f'{l.distance_to(dublin_castle_coords):.3} km')","sub_path":"examples/search_nearest_properties.py","file_name":"search_nearest_properties.py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"451776415","text":"\"\"\"\nDjango settings for Viewer project.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/1.6/topics/settings/\n\nFor the full list of settings and their values, see\nhttps://docs.djangoproject.com/en/1.6/ref/settings/\n\"\"\"\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nimport os\nBASE_DIR = os.path.dirname(os.path.dirname(__file__))\n\n\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = '%!frnxk7pe7+c#2e625ya9@md#(ogh(xunr(loi1w^$nmcc%3&'\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = True\n\nTEMPLATE_DEBUG = True\nTEMPLATE_DIRS = (os.path.join(BASE_DIR, 'templates'),)\n\nALLOWED_HOSTS = []\n\n\n# Application definition\n\nINSTALLED_APPS = (\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n)\n\nMIDDLEWARE_CLASSES = (\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n)\n\nTEMPLATE_CONTEXT_PROCESSORS = (\n \"django.contrib.auth.context_processors.auth\",\n \"django.core.context_processors.debug\",\n \"django.core.context_processors.i18n\",\n \"django.core.context_processors.media\",\n \"django.core.context_processors.static\",\n \"django.core.context_processors.tz\",\n \"django.contrib.messages.context_processors.messages\",\n \"core.context_processors.process_globals\",\n)\n\n\nROOT_URLCONF = 'Viewer.urls'\n\nWSGI_APPLICATION = 'Viewer.wsgi.application'\n\n\n# Database\n# https://docs.djangoproject.com/en/1.6/ref/settings/#databases\n\nDATABASES = {\n}\n\n#SESSION_ENGINE = 'django.contrib.sessions.backends.signed_cookies'\nSESSION_ENGINE = 'django.contrib.sessions.backends.file'\nSESSION_COOKIE_HTTPONLY = True\n\n# Internationalization\n# https://docs.djangoproject.com/en/1.6/topics/i18n/\n\nLANGUAGE_CODE = 'en-us'\n\nTIME_ZONE = 'UTC'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/1.6/howto/static-files/\n\nSTATIC_URL = '/static/'\n\nSTATICFILES_DIRS = (\n 'static',\n)\n\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'formatters': {\n 'verbose': {\n 'format' : \"[%(asctime)s] %(levelname)-8s [%(name)s:%(lineno)s] %(message)s\",\n 'datefmt' : \"%d/%b/%Y %H:%M:%S\"\n },\n 'simple': {\n 'format': '%(levelname)s %(message)s'\n },\n },\n 'handlers': {\n 'console': {\n 'level': 'DEBUG',\n 'class': 'logging.StreamHandler',\n 'formatter': 'verbose'\n },\n },\n 'loggers': {\n 'django': {\n 'handlers':['console'],\n 'propagate': True,\n 'level':'DEBUG',\n },\n 'telemetry': {\n 'handlers': ['console'],\n 'level': 'DEBUG',\n },\n }\n}\n\nLOGIN_URL=\"/login/\"\n","sub_path":"T3Viewer/Viewer/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":3293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"342130965","text":"# The most comfortable imports\nfrom django.shortcuts import render, get_object_or_404, redirect\n# messages\nfrom django.contrib import messages\n# Work with HTTP\nfrom django.http import HttpResponseRedirect, Http404\n# CBView\nfrom django.views import View\n# For draftchecking\nfrom django.utils import timezone\n# For searching\nfrom django.db.models import Q\n# paginators import\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\n\nfrom .models import Post\nfrom .forms import PostForm\n\n# ----------------------------------------------------------------------\n\n\n# Views live here\n# First is home view\n# For all posts\ndef home(request):\t\n\t# global unpaged queryset\n # if statement pull all posts\n # for site stuff and only\n # undrafted posts for users\n\tif not(request.user.is_staff) or not(request.user.is_superuser):\n\t\t# Comment below showing sorting\n\t\t# by using base filtering\n\t\t# queryset_list = Post.objects.exclude(late_publish__gt=timezone.now())\n\t\tqueryset_list = Post.objects.actual()\n\telse:\n\t\tqueryset_list = Post.objects.all()\n\t\n\t# Getting actual search stuff\n\t# From search input with name q\n\t# And using Q searching system\n\t# .distinct() prevents repeating\n\tquery = request.GET.get('q')\n\tif query:\n\t\tqueryset_list = queryset_list.filter(\n\t\t\tQ(title__icontains=query) |\n\t\t\tQ(content__icontains=query) |\n\t\t\tQ(user__first_name__icontains=query) |\n\t\t\tQ(user__last_name__icontains=query)\n\t\t).distinct()\n\t# It is refreshing cicle for\n\t# returning drafted posts in the\n\t# right order with other posts\n\t# and it works!!!\n\tfor post in [query for query in queryset_list if not query.late_publish is None]:\n\t\tif post.late_publish < timezone.now():\n\t\t\tpost.timestamp = post.late_publish\n\t\t\tpost.late_publish = None\n\t\t\tpost.save()\n\t\n\t\n\t# creating Paginator\n\tpaginator = Paginator(queryset_list, 5) # Show 5 contacts per page\n\t# getting request from User\n\tpage = request.GET.get('page')\n\t\n\ttry:\n\t\tqueryset = paginator.page(page)\n\texcept PageNotAnInteger:\n\t\t# If page is not an integer, deliver first page.\n\t\tqueryset = paginator.page(1)\n\texcept EmptyPage:\n\t\t# If page is out of range (e.g. 9999), deliver last page of results.\n\t\tqueryset = paginator.page(paginator.num_pages)\n\tcontext={\n\t\t\"actual_datetime\": timezone.now(),\n\t\t\"title\": 'Best coffee blog ever',\n\t\t\"post_list\": queryset,\n\t}\n\treturn render(request, 'home.html', context)\n\n# Detail view in\n# Function based view\n# Representing\ndef detail(request, slug=None):\n\t# Return 404 error if user\n\t# wants to look post, that\n\t# is in draft\n\tpost = get_object_or_404(Post, slug=slug)\n\tif not(post.late_publish is None) and(post.late_publish > timezone.now()) and (not(request.user.is_staff) or not(request.user.is_superuser)):\n\t\traise Http404\n\tcontext = {\n\t\t\"actual_datetime\": timezone.now(),\n\t\t'post': post,\n\t}\n\treturn render(request, 'detail.html', context)\n\n\n# Create view in\n# Class based view\n# Representing\nclass CreateView(View):\n\t\n\tdef get(self, request, *args, **kwargs):\n\t\tif not(request.user.is_staff) or not(request.user.is_superuser):\n\t\t\traise Http404\n\t\tform = PostForm()\n\t\tcontext = {\n\t\t\t'form': form,\n\t\t}\n\t\treturn render(request, 'post_form.html', context)\n\t\n\tdef post(self, request, *args, **kwargs):\n\t\tif not(request.user.is_staff) or not(request.user.is_superuser):\n\t\t\traise Http404\n\t\tform = PostForm(request.POST or None, request.FILES or None)\n\t\tif form.is_valid():\n\t\t\tinstance = form.save(commit=False)\n\t\t\t# The user which creates Post\n\t\t\t# Become it's author\n\t\t\tinstance.user = request.user\n\t\t\tinstance.save()\n\t\t\t# Message success\n\t\t\tmessages.success(request, \"Successfully Created\", extra_tags='test_extra_tag')\t\t\t\n\t\t\treturn HttpResponseRedirect(instance.get_absolute_url())\n\t\t# Message invalid input\n\t\tmessages.error(request, \"Not successfully Created\")\n\t\tcontext = {\n\t\t\t'form': form,\n\t\t}\n\t\treturn render(request, 'post_form.html', context)\n\n\n# Update view in\n# Function based view\n# Representing\nclass UpdateView(View):\n\t\n\tdef get(self, request, slug=None, *args, **kwargs):\n\t\tif not(request.user.is_staff) or not(request.user.is_superuser):\n\t\t\traise Http404\n\t\tpost = get_object_or_404(Post, slug=slug)\n\t\tform = PostForm(request.FILES or None, instance=post)\n\t\tcontext = {\n\t\t\t'post': post,\n\t\t\t'form': form,\n\t\t}\n\t\treturn render(request, 'post_form.html', context)\n\t\n\tdef post(self, request, slug=None, *args, **kwargs):\n\t\tif not(request.user.is_staff) or not(request.user.is_superuser):\n\t\t\traise Http404\n\t\tpost = get_object_or_404(Post, slug=slug)\n\t\tform = PostForm(request.POST or None, request.FILES or None, instance=post)\n\t\tif form.is_valid():\n\t\t\tinstance = form.save(commit=False)\n\t\t\tinstance.save()\n\t\t\t# Message success\n\t\t\tmessages.success(request, \"Successfully Updated\")\n\t\t\treturn HttpResponseRedirect(instance.get_absolute_url())\n\t\t# Message success\n\t\tmessages.success(request, \"Not successfully Updated\")\n\t\tcontext = {\n\t\t\t'form': form,\n\t\t}\n\t\treturn render(request, 'post_form.html', context)\n\n\n# Delete view in\n# Function based view\n# Representing\ndef delete(request, slug=None):\n\tif not(request.user.is_staff) or not(request.user.is_superuser):\n\t\traise Http404\n\tpost = get_object_or_404(Post, slug=slug)\n\t# Deleting posts image goes\n\t# From models signals and this\n\t# Function is not required now\n\t# post.image.delete(save=False)\n\t\n\tpost.delete()\n\t# Message success deletind\n\tmessages.success(request, \"Successfully Deleted\")\n\treturn redirect('blog:home')","sub_path":"blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"596926020","text":"class Cell:\n def __init__(self, v, s = None):\n self.valeur = v \n self.suivante = s\n\n\nclass Pile:\n def __init__(self):\n self.contenu = None \n self.compteur = 0\n \n def estVide(self):\n return self.contenu == None \n \n def empiler(self, v):\n self.contenu = Cell(v, self.contenu)\n self.compteur += 1\n\n def depiler(self):\n if self.estVide():\n raise IndexError(\"Impossible de dépiler une pile vide\") \n else:\n v = self.contenu.valeur\n self.contenu = self.contenu.suivante\n self.compteur -= 1 \n return v\n \n def __str__(self):\n affichage = 'T T\\n' \n i = 0\n p = self.contenu\n while i < self.compteur:\n affichage += \"|-----------------|\\n\" \n affichage += f\"| {p.valeur:^15} |\\n\" \n p = p.suivante\n i += 1\n affichage += \"\\_________________/\" \n return affichage\n\n","sub_path":"exo/nsi terminal/cours/chap 9 - arbres binaire/classPile.py","file_name":"classPile.py","file_ext":"py","file_size_in_byte":992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"257901669","text":"from django.views.generic.base import RedirectView\nfrom django.urls import reverse_lazy\nfrom django.contrib.auth import login\nfrom django.contrib import messages\nfrom .conf import settings\nfrom django.apps import apps\n\n# Get the app that contains the auth profile model\napp = apps.get_app_config(settings.UNICAMP_AUTH_APP_NAME)\n# Get it's model by name\nAUTH_MODEL = app.get_model(settings.UNICAMP_AUTH_MODEL_NAME)\n# Authenticator class used to process the login flow\nAUTHENTICATOR_CLASS = settings.UNICAMP_AUTHENTICATOR_CLASS\n# Validator class used to validate new users\nVALIDATOR_CLASS = settings.UNICAMP_VALIDATOR_CLASS\n\n\nclass Authorize(RedirectView):\n auth_class = AUTHENTICATOR_CLASS\n validator = VALIDATOR_CLASS\n\n def get_redirect_url(self):\n redirect_url = self.auth_class().get_authorization_url()\n return redirect_url\n\n\nclass ExchangeCode(RedirectView):\n auth_class = AUTHENTICATOR_CLASS\n validator = VALIDATOR_CLASS\n auth_model = AUTH_MODEL\n\n def get_redirect_url(self):\n # Instantiate the auth class\n auth_class = self.auth_class()\n # Get authorization code from request url\n code = auth_class.response_code_or_false(self.request)\n # If no code was provided\n if not code:\n # Add error message\n messages.error(self.request, settings.UNICAMP_AUTH_FAIL_MESSAGE)\n # If successful\n else:\n # Exchange code with provider\n auth_class.exchange_auth_code(code)\n # Get the data related to the auth profile model\n data = auth_class.get_data()\n # Use the provided validator to validate the data\n if not self.validator().validate(data):\n # If the data was invalid, add error message\n messages.error(self.request, settings.UNICAMP_AUTH_FAIL_MESSAGE)\n else:\n # If it was valid, register or update the auth profile model\n profile = self.auth_model.register_or_update_user(\n auth_class.credentials.access_token,\n auth_class.credentials.refresh_token,\n **data\n )\n # Login the user\n login(self.request, profile.user)\n # Finish by returning to the index\n return reverse_lazy(settings.INDEX_URL_NAME)\n","sub_path":"unicampauth/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"226937057","text":"#!/usr/bin/env python3\nimport sys\nimport os\nimport re\n\nfile_regex = \"\"\n\ndef load_settings():\n with open(\"/lib/cleanscript/cleanscript_settings.txt\",\"r\") as file:\n content = file.read()\n file_regex = content.split(\"\\n\")[1]\n\nload_settings()\n\nfile_regex = re.compile(file_regex)\n\nhow_many_times_we_should_clean = 0\ndeleted_files = []\n\nclass FileCache:\n def __init__(self, _dir):\n self._dir = _dir\n self.file_cache = []\n def cache(self, filename):\n #Assume the file is in the _dir\n with open( self._dir + \"/\" + filename, \"r\" ) as file:\n self.file_cache.append( file.read() )\n def file_is_in_cache(self, filename):\n file_content = \"\"\n with open(self._dir + \"/\" + filename, \"r\" ) as file:\n file_content = file.read()\n if file_content in self.file_cache:\n return True\n return False\n\n\ndef is_heavy_or_useless(filename):\n #If the file matches the regex, delete it\n if file_regex.match(filename) != None:\n return True\n \n #Put more cases here if needed\n \n return False\n\n\ndef delete_file_or_folder(filename):\n if os.path.isdir(filename):\n os.rmdir(filename)\n else:\n os.remove(filename)\n #For convenience, we'll log all our deleted files and folders and show them to the user\n deleted_files.append(filename)\n \ndef scan_and_clean(_dir):\n global how_many_times_we_should_clean\n \n print(_dir)\n how_many_times_we_should_clean += 1\n file_cache = FileCache( _dir )\n for i in os.listdir(_dir):\n #Make sure not to get stuck in recursion or overstep our boundaries\n if i in [\".\",\"..\"]:\n continue\n \n path_to_file = _dir + \"/\" + i\n \n #If it is a _directory\n if os.path.isdir(path_to_file):\n if len( os.listdir(path_to_file) ) == 0:\n delete_file_or_folder(path_to_file)\n else:\n scan_and_clean(path_to_file)\n \n #Otherwise, it's a file\n else:\n #Is it a duplicate or a \"heavy or useless\" file?\n is_duplicate = file_cache.file_is_in_cache( i )\n is_hev_or_usels = is_heavy_or_useless( i )\n #Delete if it is\n if is_duplicate or is_hev_or_usels:\n delete_file_or_folder( path_to_file )\n #Otherwise, just cache it and continue\n else:\n file_cache.cache( i )\n return\n\n\n#Finally, run the program on all the given directories\nfor i in range( 1, len(sys.argv) ):\n scan_and_clean(i)\n for j in range(how_many_times_we_should_clean):\n scan_and_clean(i)\n how_many_times_we_should_clean = 0\n","sub_path":"bash/cleanscript.py","file_name":"cleanscript.py","file_ext":"py","file_size_in_byte":2437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"302166997","text":"import datetime\nimport time\nimport random\nodds = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33,\n 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59]\n\nright_this_minute = datetime.datetime.today().minute\n\nfor i in range (4):\n if right_this_minute in odds:\n print (\"Odd minute\")\n else:\n print (\"Not an Odd minute\")\n wait_time = random.randint (1, 60)\n print(wait_time)\n time.sleep(wait_time)\n","sub_path":"P001.py","file_name":"P001.py","file_ext":"py","file_size_in_byte":442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"509904365","text":"from django import forms\n\n\nclass DynamicArrayWidget(forms.TextInput):\n\n template_name = \"django_better_admin_arrayfield/forms/widgets/dynamic_array.html\"\n\n def get_context(self, name, value, attrs):\n context_value = value or [\"\"]\n context = super().get_context(name, context_value, attrs)\n final_attrs = context[\"widget\"][\"attrs\"]\n id_ = context[\"widget\"][\"attrs\"].get(\"id\")\n context[\"widget\"][\"is_none\"] = value is None\n\n subwidgets = []\n for index, item in enumerate(context[\"widget\"][\"value\"]):\n print(index, item)\n widget_attrs = final_attrs.copy()\n if id_:\n widget_attrs[\"id\"] = \"{id_}_{index}\".format(id_=id_, index=index)\n widget = forms.Select(choices=final_attrs[\"choices\"])\n widget.is_required = self.is_required\n subwidgets.append(widget.get_context(name, item, widget_attrs)[\"widget\"])\n\n context[\"widget\"][\"subwidgets\"] = subwidgets\n return context\n\n def value_from_datadict(self, data, files, name):\n try:\n getter = data.getlist\n return [value for value in getter(name) if value]\n except AttributeError:\n return data.get(name)\n\n def format_value(self, value):\n return value or []\n","sub_path":"django_better_admin_arrayfield/forms/widgets.py","file_name":"widgets.py","file_ext":"py","file_size_in_byte":1303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"369750874","text":"# TouchAction\nfrom appium.webdriver.common.touch_action import TouchAction\nfrom appium import webdriver\ncaps = {}\ncaps[\"platformName\"] = \"android\"\ncaps[\"deviceName\"] = \"emulator-5554\"\ncaps[\"appPackage\"] = \"com.tencent.wework\"\ncaps[\"appActivity\"] = \".launch.LaunchSplashActivity\"\ncaps[\"noReset\"] = \"true\"\ncaps['settings[waitForIdleTimeout]'] = 1\n# 客户端与appium 服务器建立连接的代码\ndriver = webdriver.Remote(\"http://127.0.0.1:4723/wd/hub\", caps)\n\naction = TouchAction(driver)\n\n\nwindow_rect = driver.get_window_rect() # 获取屏幕尺寸\nwidth = window_rect[\"width\"]\nheight = window_rect[\"height\"]\nx1 = int(width/2)\ny_start = int(height * 0.8)\ny_end = int(height * 0.2)\n# 从下往上滑动页面\naction.press(x=x1, y=y_start).wait(200).move_to(x=x1 ,y=y_end).release().perform()\n\n\n","sub_path":"test_android/test_touch_action.py","file_name":"test_touch_action.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"465872535","text":"#-*- coding:utf-8 -*-\n\"\"\"listls3_abnormal.py\n\"\"\"\nfrom __future__ import print_function\nimport sys, re,codecs\nfrom parseheadline import parseheadline\n\nclass Entry(object):\n Ldict = {}\n def __init__(self,lines,linenum1,linenum2):\n # linenum1,2 are int\n self.metaline = lines[0]\n self.lend = lines[-1] # the line\n self.datalines = lines[1:-1] # the non-meta lines\n # parse the meta line into a dictionary\n #self.meta = Hwmeta(self.metaline)\n self.metad = parseheadline(self.metaline)\n self.linenum1 = linenum1\n self.linenum2 = linenum2\n #L = self.meta.L\n L = self.metad['L']\n if L in self.Ldict:\n print(\"Entry init error: duplicate L\",L,linenum1)\n exit(1)\n self.Ldict[L] = self\n self.lsarr = []\n \ndef init_entries(filein):\n # slurp lines\n with codecs.open(filein,encoding='utf-8',mode='r') as f:\n lines = [line.rstrip('\\r\\n') for line in f]\n recs=[] # list of Entry objects\n inentry = False \n idx1 = None\n idx2 = None\n for idx,line in enumerate(lines):\n if inentry:\n if line.startswith(''):\n idx2 = idx\n entrylines = lines[idx1:idx2+1]\n linenum1 = idx1 + 1\n linenum2 = idx2 + 1\n entry = Entry(entrylines,linenum1,linenum2)\n recs.append(entry)\n # prepare for next entry\n idx1 = None\n idx2 = None\n inentry = False\n elif line.startswith(''): # error\n print('init_entries Error 1. Not expecting ')\n print(\"line # \",idx+1)\n print(line.encode('utf-8'))\n exit(1)\n else: \n # keep looking for \n continue\n else:\n # inentry = False. Looking for ''\n if line.startswith(''):\n idx1 = idx\n inentry = True\n elif line.startswith(''): # error\n print('init_entries Error 2. Not expecting ')\n print(\"line # \",idx+1)\n print(line.encode('utf-8'))\n exit(1)\n else: \n # keep looking for \n continue\n # when all lines are read, we should have inentry = False\n if inentry:\n print('init_entries Error 3. Last entry not closed')\n print('Open entry starts at line',idx1+1)\n exit(1)\n\n print(len(lines),\"lines read from\",filein)\n print(len(recs),\"entries found\")\n return recs\n\nclass LSinstance(object):\n def __init__(self,entry,ls,iline,lstype=None):\n self.entry = entry\n self.ls = ls\n self.iline = iline\n self.type = lstype # type of \n\ndef regexdata_extra1(ls,tmp):\n if (ls == \"MBH.\"):\n return [(r'%s[^<]*ed[.] Bomb[.].*?'%tmp , '1xa')]\n if (ls == 'ṚV.'):\n return [\n ('ṚV. ANUKRAMAṆIKĀ\\.?','ṚV. ANUKRAMAṆIKĀ.'),\n ('ṚV. ANUKR\\.','ṚV. ANUKR.'),\n ('ṚV. PRĀT\\.','ṚV. PRĀT.'),\n ('ṚV. PRĀT\\. ([0-9]+), ([0-9]+[.]?)','ṚV. PRĀT. #, #.'),\n ('ṚV. PRĀTIŚ\\.','ṚV. PRĀTIŚ.'),\n ('ṚV. PRĀTIŚ\\. ([0-9]+), ([0-9]+[.]?)','ṚV. PRĀTIŚ. #, #.'),\n ]\n if (ls == 'AV.'):\n return [\n ('AV. ANUKR\\.','AV. ANUKR.'),\n ('AV. ANUKR\\. ([0-9]+), ([0-9]+[.]?)','AV. ANUKR. #, #.'),\n\n ('AV. PRĀT\\.','AV. PRĀT\\.'),\n ('AV. PRĀT\\. ([0-9]+), ([0-9]+[.]?)','AV. PRĀT. #, #.'),\n\n ('AV. PARIŚ\\.','AV. PARIŚ.'),\n ('AV. PARIŚ\\. ([0-9]+[.]?)','AV. PARIŚ. #.'),\n ('AV. PARIŚ\\. ([0-9]+), ([0-9]+[.]?)','AV. PARIŚ. #, #.'),\n ('AV. PARIŚ\\. ([0-9]+), ([0-9]+), ([0-9]+[.]?)','AV. PARIŚ. #, #, #.'),\n ('AV. PAR\\.','AV. PAR.'),\n ]\n return []\n\ndef regexdata_extra2(ls,tmp):\n if (ls == 'ṚV.'):\n return [\n ('([0-9]+), ([0-9]+[.]?)',\n '#, #.'),\n ('([0-9]+[.]?)',\n '#.'),\n ('([0-9]+), ([0-9]+[.]?)',\n '#, #.'),\n ('([0-9]+[.]?)',\n '#.'),\n ]\n if (ls == 'AV.'):\n return [\n ('([0-9]+), ([0-9]+[.]?)',\n '#, #.'),\n ('([0-9]+[.]?)',\n '#.'),\n ]\n return []\n\ndef get_regexdata(lspfx):\n replacements = (('.','[.]'), ('(','\\('), (')','\\)'))\n tmp = lspfx\n for old,new in replacements:\n tmp = tmp.replace(old,new)\n regexdata = [\n [r'%s.*?'%tmp,\n [(r'%s ([0-9]+), ([0-9]+), ([0-9]+[.]?)'%tmp , \n '%s #, #, #.' % tmp),\n (r'%s ([0-9]+), ([0-9]+), ([0-9]+[.]?) fgg?[.]' % tmp,\n '%s #, #, #. fgg.' % tmp),\n (r'%s ([0-9]+), ([0-9]+), ([0-9]+[.,]?) v[.] l[.]' % tmp,\n '%s #, #, #. v. l.' % tmp),\n (r'%s'%tmp ,\n '%s' % tmp),\n ] + regexdata_extra1(lspfx,tmp)\n ],\n [r'.*?'%tmp,\n [(r'([0-9]+), ([0-9]+), ([0-9]+[.]?)'%tmp ,\n '#, #, #.' % tmp),\n\n (r'([0-9]+), ([0-9]+), ([0-9]+[.]?) fgg?[.]' % tmp,\n '#, #, #. fgg.' % tmp),\n \n (r'([0-9]+), ([0-9]+), ([0-9]+[.,]?) v[.] l[.]' % tmp,\n '#, #, #. v. l.' % tmp),\n\n (r'([0-9]+), ([0-9]+[.]?)'%tmp ,\n '#, #.' % tmp),\n\n (r'([0-9]+), ([0-9]+[.]?) fgg?[.]' % tmp,\n '#, #. fgg.' % tmp),\n\n (r'([0-9]+), ([0-9]+[.,]?) v[.] l[.]' % tmp,\n '#, #. v. l.' % tmp),\n\n (r'([0-9]+[.]?)'%tmp ,\n '#.' % tmp),\n\n (r'([0-9]+[.]?) fgg?[.]' % tmp,\n '#. fgg.' % tmp),\n\n (r'([0-9]+[.,]?) v[.] l[.]' % tmp,\n '#. v. l.' % tmp),\n\n \n ] + regexdata_extra2(lspfx,tmp)\n ]\n ]\n return regexdata\n\ndef find_abnormals3(lspfx,entries):\n regexdata = get_regexdata(lspfx)\n if False:\n regexnorms = regexdata[1][1]\n for regex1a,regextype in regexnorms:\n print('%s %s' %(regextype,regex1a))\n abnormals = []\n normals = []\n for entry in entries:\n #text = '\\n'.join(entry.datalines)\n for iline,line in enumerate(entry.datalines):\n text = line\n for regex1,regexnorms in regexdata:\n lsarr = re.findall(regex1,text,flags=re.DOTALL)\n for ls in lsarr:\n normal = None\n for regex1a,regextype in regexnorms:\n if re.search(regex1a,ls):\n normal = LSinstance(entry,ls,iline,regextype)\n normals.append(normal)\n break\n if normal == None:\n abnormal = LSinstance(entry,ls,iline)\n abnormals.append(abnormal)\n return abnormals,normals\n\ndef normals_summary(normals):\n d = {} \n for lsinstance in normals:\n t = lsinstance.type\n if t not in d:\n d[t] = 0\n d[t] = d[t] + 1\n types = sorted(d.keys())\n tot = 0\n for t in types:\n print('%6d' %d[t],t)\n tot = tot + d[t]\n print('totals=',tot)\n \ndef write_abnormals(fileout,abnormals):\n with codecs.open(fileout,\"w\",\"utf-8\") as f:\n for x in abnormals:\n entry = x.entry\n ls = x.ls\n L = entry.metad['L']\n k1 = entry.metad['k1']\n out = '%s %s %s' %(ls,k1,L)\n f.write(out+'\\n')\n print(len(abnormals),'abnormal ls written to',fileout)\n\ndef skip_abnormals(abnormals,lsabr):\n regexdict = {\n 'ṚV.': [\n 'ṚV\\. [0-9]+, [0-9]+\\.?',\n '[0-9]+, [0-9]+\\.?',\n '[0-9]+\\.?',\n ],\n 'AV.': [\n 'AV\\. [0-9]+, [0-9]+\\.?',\n '[0-9]+, [0-9]+\\.?',\n '[0-9]+\\.?',\n ],\n }\n if lsabr in regexdict:\n regexes = regexdict[lsabr]\n else:\n regexes = []\n\n ans = [] # abnormals that are not skipped\n for x in abnormals:\n ls = x.ls # the abnormal ls\n skip = False\n for regex in regexes:\n if re.search(regex,ls):\n skip = True\n break\n if not skip:\n ans.append(x)\n return ans\n \ndef write_abnormals_change(fileout,abnormals,lsabr):\n dbg = False\n if dbg:\n abnormals = skip_abnormals(abnormals,lsabr)\n print('WARNING DBG: write_abnormals_change skipping some')\n with codecs.open(fileout,\"w\",\"utf-8\") as f:\n for x in abnormals:\n entry = x.entry\n iline = x.iline\n ls = x.ls # the abnormal ls\n lnum = entry.linenum1+iline+1\n metaline = re.sub(r'.*$','',entry.metaline)\n line = entry.datalines[iline]\n outarr = []\n outarr.append('; --------------------------------')\n outarr.append('; %s' % metaline)\n outarr.append('; Abnormal ls: %s' %ls)\n outarr.append('%s old %s' %(lnum,line))\n outarr.append(';')\n outarr.append('%s new %s' %(lnum,line))\n for out in outarr:\n f.write(out+'\\n')\n print(len(abnormals),'change transactions',fileout)\n\nif __name__==\"__main__\":\n lspfx = sys.argv[1]\n filein = sys.argv[2] # xxx.txt (path to digitization of xxx)\n fileout = sys.argv[3] #\n fileoutchg = sys.argv[4]\n entries = init_entries(filein)\n abnormals,normals = find_abnormals3(lspfx,entries)\n write_abnormals(fileout,abnormals)\n write_abnormals_change(fileoutchg,abnormals,lspfx)\n normals_summary(normals)\n \n","sub_path":"pwg_ls2/av/listls3_abnormal.py","file_name":"listls3_abnormal.py","file_ext":"py","file_size_in_byte":9063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"372098885","text":"import re\nfrom xraydb import XrayDB\nimport sys\nimport numpy as np\ntry:\n from mendeleev.fetch import fetch_table\nexcept:\n from mendeleev import get_table\n\n\nclass Chemical_Formula:\n def __init__(self, formula=None):\n self.formula = formula\n self.xdb = XrayDB()\n cols = ['symbol', 'covalent_radius_cordero']\n try:\n ptable=fetch_table('elements')\n except:\n ptable = get_table('elements')\n x = ptable[cols]\n self.covalent_radius = x.set_index('symbol').T.to_dict('index')['covalent_radius_cordero']\n if formula is not None:\n self.parse(self.formula)\n\n def parse(self, formula):\n parsed = re.findall(r'([A-Z][a-z]*)([-+]?\\d*\\.*\\d*)', formula)\n self.formula_dict = {}\n for a, b in parsed:\n if b != '':\n self.formula_dict[a] = float(b)\n else:\n self.formula_dict[a] = 1.0\n return self.formula_dict\n\n def elements(self):\n \"\"\"\n Provides a list of all the elements in the formula\n :return:\n \"\"\"\n return list(self.formula_dict.keys())\n\n def element_mole_ratio(self):\n \"\"\"\n Provides a dictionary of mole ratio of all the elements in the formula\n :return:\n \"\"\"\n return self.formula_dict\n\n def molar_mass(self):\n \"\"\"\n Provides the total Molar-mass of the compound represented by the formula\n :return:\n \"\"\"\n return np.sum([self.xdb.molar_mass(ele) * num for ele, num in self.formula_dict.items()])\n\n def molecular_weight(self):\n \"\"\"\n Provides the Molecular-Weight of the compound represented by the formula\n :return:\n \"\"\"\n return self.molar_mass()\n\n def molar_mass_ratio(self, element):\n \"\"\"\n Provides the molecular-mass-ratio of the element in the chemical formula\n :param element: Symbol of the element\n :return:\n \"\"\"\n if element in self.formula_dict.keys():\n tot = self.molar_mass()\n return self.xdb.molar_mass(element) * self.formula_dict[element] / tot\n else:\n return 0.0\n\n def molar_volume(self):\n \"\"\"Returns molar volumes in cm^3 or ml\"\"\"\n volume=0.0\n for ele,moles in self.formula_dict.items():\n volume+=moles*4*np.pi*self.covalent_radius[ele]**3/3\n return 6.023e23*volume*1e-30\n\n\n\nif __name__=='__main__':\n t=Chemical_Formula('NaCl0.27000000402331353')\n elements=t.elements\n element_mole_ratio=t.element_mole_ratio()\n molar_mass=t.molar_mass()\n molar_volume=t.molar_volume()\n print('Elements:',elements())\n print('Element moles:',element_mole_ratio)\n print('Molecular Weight (gms):',molar_mass)\n print('Molar Volume (ml):',molar_volume)\n density=(17.11*molar_mass/1000+(1-17.11*molar_volume/1000))\n print('Density of 17.11M NaCl (gms/ml):',density)\n\n\n","sub_path":"Chemical_Formula.py","file_name":"Chemical_Formula.py","file_ext":"py","file_size_in_byte":2936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"621955684","text":"# day 14 - more lists, then tuples\r\n\r\n# list method\r\n\r\nmylist = [1,2,3]\r\nmylist.insert(1,999)\r\nmylist.insert(10,999) #position, value\r\n# if position >= len puts it at end\r\n\r\nprint(mylist)\r\nmylist.insert(-2,8888)\r\nprint(mylist)\r\n\r\n# a string method split creates a list\r\n\r\nmoby = \"a book about whales with a guy named Ishma\"\r\nmobylist = moby.split()\r\nprint(mobylist)\r\n\r\nphone = \"404-444-3333\"\r\nphonelist = phone.split(\"3\")\r\nprint(phonelist)\r\n\r\n\r\n#tuples - like a list, but it is mutable \r\nmytup = (\"John\",18,4.0,\"Comp E\")\r\nmytup2 = (\"Melinda\",24,4.1,\"CS\")\r\n\r\n\r\nmytup = (\"Johnny\",) + mytup[1:] # like a string \r\n#need a comma to identify a tuple\r\n# cannot do mytup[0] = \"Johnny\" because tuples are mutable\r\n\r\n#creating tuples\r\ntup1 =() # no data, no need a comma \r\ntup2 = (3, ) # if one data must use a comma to \r\ntup3 =(1,2)\r\n# comma, comma, comma, comma, comma, comma\r\nprint(type(tup1))\r\n\r\nif ():\r\n print(\"WoW!\")\r\n\r\n#empty tuple --> False\r\n\r\nalist = \"a,b,ccc\".split(\",\")\r\n\r\nprint(alist[2][2])\r\n\r\n\r\nalist = \"yellow jackets\".split(\" \")\r\n\r\nprint(alist[1])\r\n\r\nalist = \"yellow jackets\".split()\r\n\r\n\r\nprint(alist)\r\n\r\nalist = \"yellow jackets\".split()\r\n\r\nfor item in alist:\r\n\r\n for item2 in item:\r\n\r\n print(item2,end=\"\")\r\n\r\n break\r\n\r\n break\r\n\r\n\r\n\r\npets = [(\"cat\",\"fluffy\",\"gray\"),(\"dog\",\"whitey\",\"black\")]\r\n\r\n# print out the last letter of the last string above\r\n\r\nprint(pets[1][2][-1])\r\n\r\n#write a nestes for loop to print out all the letters\r\n# of all the strings one letter per line\r\n\r\nfor atup in pets:\r\n print(type(atup))\r\n for astring in atup:\r\n print(type(astring))\r\n for letter in astring:\r\n print(letter)\r\n\r\n\r\n# count how many strings in pets have 4 or more letter\r\n\r\n\r\ncount = 0\r\nfor atup in pets:\r\n for astring in atup:\r\n if len(astring) >= 4:\r\n count += 1\r\nprint(count)\r\n\r\n#tuples can be multiplied\r\n#they can use slicing\r\n\r\npets = [(\"cat\",\"fluffy\",\"gray\"),(\"dog\",\"whitey\",\"black\")]\r\n\r\nprint(pets[1][:1]) # (\"dog\",)\r\nprint(pets[0][1:]) # (\"fluffy\",\"gray\")\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"september 23.py","file_name":"september 23.py","file_ext":"py","file_size_in_byte":2069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"337612123","text":"# Copyright (c) 2012 Web Notes Technologies Pvt Ltd (http://erpnext.com)\n# \n# MIT License (MIT)\n# \n# Permission is hereby granted, free of charge, to any person obtaining a \n# copy of this software and associated documentation files (the \"Software\"), \n# to deal in the Software without restriction, including without limitation \n# the rights to use, copy, modify, merge, publish, distribute, sublicense, \n# and/or sell copies of the Software, and to permit persons to whom the \n# Software is 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 IMPLIED, \n# INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A \n# PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT \n# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF \n# CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE \n# OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n# \n\n# Search\nfrom __future__ import unicode_literals\nimport webnotes\nimport webnotes.widgets.reportview\nimport webnotes.widgets.query_builder\nfrom webnotes.utils import cstr\nfrom startup.query_handlers import standard_queries\n\n# this is called by the Link Field\n@webnotes.whitelist()\ndef search_link(doctype, txt, query=None, filters=None):\n\tsearch_widget(doctype, txt, query, page_len=10, filters=filters)\n\twebnotes.response['results'] = build_for_autosuggest(webnotes.response[\"values\"])\n\n# this is called by the search box\n@webnotes.whitelist()\ndef search_widget(doctype, txt, query=None, searchfield=\"name\", start=0, \n\tpage_len=50, filters=None):\n\tif isinstance(filters, basestring):\n\t\timport json\n\t\tfilters = json.loads(filters)\n\n\tmeta = webnotes.get_doctype(doctype)\n\t\n\tif query and query.split()[0].lower()!=\"select\":\n\t\t# by method\n\t\twebnotes.response[\"values\"] = webnotes.get_method(query)(doctype, txt, \n\t\t\tsearchfield, start, page_len, filters)\n\telif not query and doctype in standard_queries:\n\t\t# from standard queries\n\t\tsearch_widget(doctype, txt, standard_queries[doctype], \n\t\t\tsearchfield, start, page_len, filters)\n\telse:\n\t\tif query:\n\t\t\t# custom query\n\t\t\twebnotes.response[\"values\"] = webnotes.conn.sql(scrub_custom_query(query, \n\t\t\t\tsearchfield, txt))\n\t\telse:\n\t\t\tif isinstance(filters, dict):\n\t\t\t\tfilters_items = filters.items()\n\t\t\t\tfilters = []\n\t\t\t\tfor f in filters_items:\n\t\t\t\t\tif isinstance(f[1], (list, tuple)):\n\t\t\t\t\t\tfilters.append([doctype, f[0], f[1][0], f[1][1]])\n\t\t\t\t\telse:\n\t\t\t\t\t\tfilters.append([doctype, f[0], \"=\", f[1]])\n\n\t\t\tif filters==None:\n\t\t\t\tfilters = []\n\t\t\t\n\t\t\t# build from doctype\n\t\t\tif txt:\n\t\t\t\tfilters.append([doctype, searchfield or \"name\", \"like\", txt + \"%\"])\n\t\t\tif meta.get({\"parent\":doctype, \"fieldname\":\"enabled\", \"fieldtype\":\"Check\"}):\n\t\t\t\tfilters.append([doctype, \"enabled\", \"=\", 1])\n\t\t\tif meta.get({\"parent\":doctype, \"fieldname\":\"disabled\", \"fieldtype\":\"Check\"}):\n\t\t\t\tfilters.append([doctype, \"disabled\", \"!=\", 1])\n\n\t\t\twebnotes.response[\"values\"] = webnotes.widgets.reportview.execute(doctype,\n\t\t\t\tfilters=filters, fields = get_std_fields_list(meta, searchfield or \"name\"), \n\t\t\t\tlimit_start = start, limit_page_length=page_len, as_list=True)\n\ndef get_std_fields_list(meta, key):\n\t# get additional search fields\n\tsflist = meta[0].search_fields and meta[0].search_fields.split(\",\") or []\n\tsflist = ['name'] + sflist\n\tif not key in sflist:\n\t\tsflist = sflist + [key]\n\n\treturn ['`tab%s`.`%s`' % (meta[0].name, f.strip()) for f in sflist]\n\ndef build_for_autosuggest(res):\n\tresults = []\n\tfor r in res:\n\t\tinfo = ''\n\t\tif len(r) > 1:\n\t\t\tinfo = ', '.join([cstr(t) for t in r[1:]])\n\t\t\tif len(info) > 50:\n\t\t\t\tinfo = \"%s...\" % (info, info[:50])\n\n\t\tresults.append({'label':r[0], 'value':r[0], 'info':info})\n\treturn results\n\ndef scrub_custom_query(query, key, txt):\n\tif '%(key)s' in query:\n\t\tquery = query.replace('%(key)s', key)\n\tif '%s' in query:\n\t\tquery = query.replace('%s', ((txt or '') + '%'))\n\treturn query","sub_path":"webnotes/widgets/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":4131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"86310387","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport seaborn as sns\r\nfrom cvxopt import matrix, solvers\r\nimport copy\r\n\r\n\r\n################################################################################################################################### \r\n# Helper functions for IRL\r\n###################################################################################################################################\r\ndef actions(w=0.1):\r\n\r\n # each action is a 10x10 that corresponds to each of the 100 states\r\n up = np.zeros((100, 100))\r\n left = np.zeros((100, 100))\r\n down = np.zeros((100, 100))\r\n right = np.zeros((100, 100))\r\n \r\n # define the transition probabilities\r\n for i in range(100):\r\n \r\n # left edge\r\n if i <= 9:\r\n\r\n # corner states\r\n if i == 0:\r\n\r\n # off grid moves\r\n up[i, i + 10], up[i, i + 1], up[i, i] = w / 4, w / 4, 1 - w + w / 2\r\n left[i, i + 10], left[i, i + 1], left[i, i] = w / 4, w / 4, 1 - w + w / 2\r\n\r\n # in grid moves\r\n down[i, i + 10], down[i, i + 1], down[i, i] = w / 4, 1 - w + w / 4, w / 2\r\n right[i, i + 10], right[i, i + 1], right[i, i] = 1 - w + w / 4, w / 4, w / 2\r\n\r\n elif i == 9:\r\n\r\n # off grid moves\r\n down[i, i + 10], down[i, i - 1], down[i, i] = w / 4, w / 4, 1 - w + w / 2\r\n left[i, i + 10], left[i, i - 1], left[i, i] = w / 4, w / 4, 1 - w + w / 2\r\n\r\n # in grid moves\r\n up[i, i + 10], up[i, i - 1], up[i, i] = w / 4, 1 - w + w / 4, w / 2\r\n right[i, i + 10], right[i, i - 1], right[i, i] = 1 - w + w / 4, w / 4, w / 2\r\n\r\n # edge states\r\n else:\r\n \r\n # off grid moves\r\n left[i, i], left[i, i + 1], left[i, i - 1], left[i, i + 10] = 1 - w + w / 4, w / 4, w / 4, w / 4\r\n\r\n # in grid moves\r\n right[i, i], right[i, i + 1], right[i, i - 1], right[i, i + 10] = w / 4, w / 4, w / 4, 1 - w + w / 4\r\n down[i, i], down[i, i + 1], down[i, i - 1], down[i, i + 10] = w / 4, 1 - w + w / 4, w / 4, w / 4\r\n up[i, i], up[i, i + 1], up[i, i - 1], up[i, i + 10] = w / 4, w / 4, 1 - w + w / 4, w / 4\r\n\r\n # right edge states:\r\n elif i >= 90:\r\n\r\n # corner states\r\n if i == 90:\r\n \r\n # off grid moves\r\n right[i, i - 10], right[i, i + 1], right[i, i] = w / 4, w / 4, 1 - w + w / 2\r\n up[i, i - 10], up[i, i + 1], up[i, i] = w / 4, w / 4, 1 - w + w / 2\r\n\r\n # in grid moves\r\n down[i, i - 10], down[i, i + 1], down[i, i] = w / 4, 1 - w + w / 4, w / 2\r\n left[i, i - 10], left[i, i + 1], left[i, i] = 1 - w + w / 4, w / 4, w / 2\r\n\r\n elif i == 99:\r\n\r\n # off grid moves\r\n right[i, i - 10], right[i, i - 1], right[i, i] = w / 4, w / 4, 1 - w + w / 2\r\n down[i, i - 10], down[i, i - 1], down[i, i] = w / 4, w / 4, 1 - w + w / 2\r\n \r\n # in grid moves\r\n up[i, i - 10], up[i, i - 1], up[i, i] = w / 4, 1 - w + w / 4, w / 2\r\n left[i, i - 10], left[i, i - 1], left[i, i] = 1 - w + w / 4, w / 4, w / 2\r\n\r\n # edge states\r\n else:\r\n \r\n # off grid moves\r\n right[i, i], right[i, i + 1], right[i, i - 1], left[i, i - 10] = 1 - w + w / 4, w / 4, w / 4, w / 4\r\n\r\n # in grid moves\r\n left[i, i], left[i, i + 1], left[i, i - 1], left[i, i - 10] = w / 4, w / 4, w / 4, 1 - w + w / 4\r\n down[i, i], down[i, i + 1], down[i, i - 1], down[i, i - 10] = w / 4, 1 - w + w / 4, w / 4, w / 4\r\n up[i, i], up[i, i + 1], up[i, i - 1], up[i, i - 10] = w / 4, w / 4, 1 - w + w / 4, w / 4\r\n\r\n # upper edge states:\r\n elif i % 10 == 0:\r\n \r\n # off grid moves\r\n up[i, i], up[i, i + 1], up[i, i - 10], up[i, i + 10] = 1 - w + w / 4, w / 4, w / 4, w / 4\r\n\r\n # in grid moves\r\n right[i, i], right[i, i + 1], right[i, i - 10], right[i, i + 10] = w / 4, w / 4, w / 4, 1 - w + w / 4\r\n left[i, i], left[i, i + 1], left[i, i - 10], left[i, i + 10] = w / 4, w / 4, 1 - w + w / 4, w / 4\r\n down[i, i], down[i, i + 1], down[i, i - 10], down[i, i + 10] = w / 4, 1 - w + w / 4, w / 4, w / 4\r\n\r\n # lower edge states:\r\n elif i % 10 == 9:\r\n \r\n # off grid moves\r\n down[i, i], down[i, i - 1], down[i, i - 10], down[i, i + 10] = 1 - w + w / 4, w / 4, w / 4, w / 4\r\n\r\n # in grid moves\r\n right[i, i], right[i, i - 1], right[i, i - 10], right[i, i + 10] = w / 4, w / 4, w / 4, 1 - w + w / 4\r\n left[i, i], left[i, i - 1], left[i, i - 10], left[i, i + 10] = w / 4, w / 4, 1 - w + w / 4, w / 4\r\n up[i, i], up[i, i - 1], up[i, i - 10], up[i, i + 10] = w / 4, 1 - w + w / 4, w / 4, w / 4\r\n\r\n # inner edges\r\n else:\r\n down[i, i + 1], down[i, i - 1], down[i, i - 10], down[i, i + 10] = 1 - w + w / 4, w / 4, w / 4, w / 4\r\n up[i, i + 1], up[i, i - 1], up[i, i - 10], up[i, i + 10] = w / 4, 1 - w + w / 4, w / 4, w / 4\r\n left[i, i + 1], left[i, i - 1], left[i, i - 10], left[i, i + 10] = w / 4, w / 4, 1 - w + w / 4, w / 4\r\n right[i, i + 1], right[i, i - 1], right[i, i - 10], right[i, i + 10] = w / 4, w / 4, w / 4, 1 - w + w / 4\r\n\r\n return up, down, left, right\r\n\r\n\r\ndef get_optimal_value(up, down, right, left, reward_func, gamma=0.8, snapshots=False):\r\n\r\n # initialization\r\n v = np.zeros(100)\r\n reward = reward_func.transpose().flatten()\r\n delta = np.inf\r\n iterations = 0\r\n snaps = []\r\n\r\n # policy evaluation\r\n while(delta>0.01):\r\n delta = 0\r\n v_copy = np.copy(v)\r\n for i in range(0,100):\r\n t = v_copy[i]\r\n u,d,r,l = np.sum(up[i]*(reward+gamma*v_copy)), np.sum(down[i]*(reward+gamma*v_copy)), np.sum(right[i]*(reward+gamma*v_copy)), np.sum(left[i]*(reward+gamma*v_copy))\r\n v[i] = max(u,d,r,l)\r\n delta = max(delta,abs(t-v[i]))\r\n iterations += 1\r\n snaps.append(v_copy.reshape(10,10))\r\n if snapshots:\r\n \tsteps = np.round(np.linspace(1,iterations,5))\r\n \tfor i in steps:\r\n \t\tt = np.round(snaps[int(i-1)],decimals=3)\r\n \t\tplt.table(cellText=t,loc=(0,0),cellLoc='center'); plt.title('Optimal State Value for Reward Function 1, Step Number = %i' %i); plt.show()\r\n \r\n return v.reshape(10,10).T\r\n\r\n\r\ndef get_value_and_opt_policy(up, down, right, left, reward_func, gamma=0.8):\r\n\r\n # intialization\r\n\tv, state_values, optimal_policies = np.zeros(100), np.zeros(100), np.zeros(100)\r\n\treward = reward_func.transpose().flatten()\r\n\tdelta = np.inf\r\n\r\n # policy evaluation\r\n\twhile(delta>0.01):\r\n\t delta = 0\r\n\t v_copy = np.copy(v)\r\n\r\n\t for i in range(100):\r\n\t t = v_copy[i]\r\n\t u,d,r,l = np.sum(up[i]*(reward+gamma*v_copy)), np.sum(down[i]*(reward+gamma*v_copy)), np.sum(right[i]*(reward+gamma*v_copy)), np.sum(left[i]*(reward+gamma*v_copy))\r\n\t v[i] = max(u,d,r,l)\r\n\t delta = max(delta,abs(t-v[i]))\r\n\r\n # policy improvement\r\n\tfor i in range(100):\r\n\t\tu,d,r,l = np.sum(up[i]*(reward+gamma*v)), np.sum(down[i]*(reward+gamma*v)), np.sum(right[i]*(reward+gamma*v)), np.sum(left[i]*(reward+gamma*v))\r\n\t\tarr = [r,l,u,d]\r\n\t\tstate_values[i] = np.amax(arr)\r\n\t\toptimal_policies[i] = arr.index(np.amax(arr))\r\n\r\n\treturn state_values, optimal_policies\r\n\r\n\r\ndef plot_arrows(arrows, title=''):\r\n\tarr = np.chararray((10,10),unicode=True)\r\n\tfor i in range(10):\r\n\t\tfor j in range(10):\r\n\t\t\tif arrows[i,j]==0: arr[i,j] = '\\u2192' # right\r\n\t\t\telif arrows[i,j]==1: arr[i,j] = '\\u2190' # left\r\n\t\t\telif arrows[i,j]==2: arr[i,j] = '\\u2191' # up\r\n\t\t\telif arrows[i,j]==3: arr[i,j] = '\\u2193' # down\r\n\tplt.table(cellText=arr,loc=(0,0),cellLoc='center')\r\n\tplt.title(title)\r\n\r\n\treturn\r\n\r\n\r\n################################################################################################################################### \r\n# Q11: finding the optimal penalty coefficient lambda (plot accuracy vs lambda) with reward function 1 as reference\r\n###################################################################################################################################\r\nsolvers.options['show_progress'] = False\r\nnum_states = 100\r\nnum_lambdas = 500\r\ngamma = 0.8\r\nlambda_vec = np.linspace(0, 5, num_lambdas)\r\nlen_lambda = len(lambda_vec)\r\nR_max = [1.0, 10.0]\r\n\r\n# define the optimal transitional probabilities of each action from the \"expert\" and list them in order\r\nup, down, left, right = actions()\r\naction_prob_list = [right, left, up, down]\r\n\r\n# define the reward functions\r\nreward_func_1 = np.zeros((10,10))\r\nreward_func_1[-1,-1] = 1\r\nreward_func_1[2:4,5:7], reward_func_1[4:6,1:3], reward_func_1[8:,2:4] = -10, -10, -10\r\n\r\nreward_func_2 = np.zeros((10,10))\r\nreward_func_2[-1,-1] = 10\r\nreward_func_2[8,6],reward_func_2[1:7,4],reward_func_2[1,4:7],reward_func_2[1:4,6],reward_func_2[3,6:9],reward_func_2[3:8,8],reward_func_2[7,6:9] = -100,-100,-100,-100,-100,-100,-100\r\n\r\n# get the optimal values of each state and optimal policies using reward functions 1 and 2\r\nstate_values_1, optimal_policies_1 = get_value_and_opt_policy(up, down, right, left, reward_func_1, gamma)\t\t# for reward function 1\r\nstate_values_2, optimal_policies_2 = get_value_and_opt_policy(up, down, right, left, reward_func_2, gamma)\t\t# for reward function 2\r\noptimal_policies_1_2 = [optimal_policies_1, optimal_policies_2]\r\n\r\n# initialize matrices for the LP\r\nones_100x1 = matrix(np.ones(num_states))\r\nzeros_100x1 = matrix(np.zeros(num_states))\r\nzeros_400x1 = matrix(np.zeros(4 * num_states))\r\nzeros_100x100 = matrix(np.zeros((num_states, num_states)))\r\nzeros_200x100 = matrix(np.zeros((2 * num_states, num_states)))\r\nzeros_700x100 = matrix(np.zeros((7 * num_states, num_states)))\r\nidentity_100x100 = matrix(np.identity(num_states))\r\n\r\n# declare variables to store the estimated reward functions, policies, and accuracies\r\nreward_func_list = [[], []]\r\npolicy_list = [[], []]\r\naccuracy_list = [[], []]\r\nmax_lambda = []\r\nmax_lambda_idx = []\r\n\r\n# compute the variables c, b, and D\r\nc = matrix([[ones_100x1, ones_100x1 * -lambda_vec[i], zeros_100x1] for i in range(len_lambda)]) # each column is a corresponding lambda\r\nb = [[], []]\r\nD = [[], []]\r\n\r\n# iterate to find the third column of \r\nfor r_idx, r in enumerate(R_max):\r\n\r\n b[r_idx] = matrix([zeros_400x1, zeros_400x1, R_max[r_idx] * ones_100x1, R_max[r_idx] * ones_100x1])\r\n D[r_idx] = matrix([[identity_100x100, identity_100x100, identity_100x100, zeros_700x100], \\\r\n [zeros_200x100, zeros_200x100, zeros_200x100, -identity_100x100, -identity_100x100, zeros_200x100]])\r\n\r\n # compute the third column of D\r\n idx = 0\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# used to ignore the increment if the optimal policy is the same as the action of interest\r\n third_col = np.zeros((300, 100))\r\n\r\n for s in range(num_states):\r\n p_a1 = action_prob_list[int(optimal_policies_1_2[r_idx][s])]\t\t# for action 1\r\n for a in range(4):\r\n if(int(optimal_policies_1_2[r_idx][s]) == a):\r\n continue\r\n p_ax = action_prob_list[a]\t\t\t\t\t\t\t\t# for all other actions\r\n third_col[idx, :] = -np.dot(p_a1[s] - p_ax[s], np.linalg.inv(np.array(identity_100x100) - gamma * p_a1))\r\n idx += 1\r\n\r\n third_col = matrix(third_col)\r\n D[r_idx] = matrix([[D[r_idx]], [third_col, third_col, -identity_100x100, identity_100x100, identity_100x100, -identity_100x100]])\r\n\r\n # extract the reward function and policy from each lambda. get the accuracy of each policy compared with the optimal policy\r\n for i in range(num_lambdas):\r\n sol = solvers.lp(c[:, i], D[r_idx], b[r_idx])\r\n reward_func_list[r_idx].append(np.array(sol['x'])[200:]) #reshape(10, 10))\r\n\r\n v, p = get_value_and_opt_policy(up, down, right, left, reward_func_list[r_idx][i], gamma)\r\n policy_list[r_idx].append(p)\r\n\r\n accuracy_list[r_idx].append(np.sum(p == optimal_policies_1_2[r_idx]) / 100.0)\r\n\r\n max_lambda_idx.append(np.argmax(accuracy_list[0]))\r\n max_lambda.append(lambda_vec[max_lambda_idx[r_idx]])\r\n\r\nplt.figure(1)\r\nplt.xlabel(\"\\u03BB\")\r\nplt.ylabel(\"accuracy\")\r\nplt.title(\"Accuracy over \\u03BB for reward function 1\")\r\nplt.plot(lambda_vec, accuracy_list[0])\r\n\r\nplt.figure(2)\r\nplt.xlabel(\"\\u03BB\")\r\nplt.ylabel(\"accuracy\")\r\nplt.title(\"Accuracy over \\u03BB for reward function 2\")\r\nplt.plot(lambda_vec, accuracy_list[1])\r\n\r\n\r\n################################################################################################################################### \r\n# Q13, Q20: compare ground truth and max lambda for extracted reward function 1 and 2\r\n###################################################################################################################################\r\nplt.figure(3)\r\nplt.title(\"Heatmap for Ground Truth Reward Function 1\")\r\nsns.heatmap(reward_func_1)\r\n\r\nplt.figure(4)\r\nplt.title(\"Heatmap for Extracted Reward Function 1\")\r\nsns.heatmap(reward_func_list[0][int(max_lambda_idx[0])].reshape(10, 10).T)\r\n\r\nplt.figure(5)\r\nplt.title(\"Heatmap for Ground Truth Reward Function 2\")\r\nsns.heatmap(reward_func_2)\r\n\r\nplt.figure(6)\r\nplt.title(\"Heatmap for Extracted Reward Function 2\")\r\nsns.heatmap(reward_func_list[1][int(max_lambda_idx[1])].reshape(10, 10).T)\r\n\r\n\r\n################################################################################################################################### \r\n# Q14, Q21: plot state values for extracted reward 1 and 2\r\n###################################################################################################################################\r\nv1 = get_optimal_value(up, down, right, left, reward_func_list[0][max_lambda_idx[0]])\r\nv2 = get_optimal_value(up, down, right, left, reward_func_list[1][max_lambda_idx[1]])\r\n\r\nplt.figure(7)\r\nplt.title(\"State Values Heat Map for Extracted Reward Function 1\")\r\nsns.heatmap(v1)\r\n\r\nplt.figure(8)\r\nplt.title(\"State Values Heat Map for Extracted Reward Function 2\")\r\nsns.heatmap(v2)\r\n\r\n\r\n################################################################################################################################### \r\n# Q16, Q23: plot optimal policies for extracted reward 1 and 2\r\n###################################################################################################################################\r\nstate_values_1, optimal_policies_1 = get_value_and_opt_policy(up, down, right, left, reward_func_list[0][max_lambda_idx[0]], gamma)\r\nstate_values_2, optimal_policies_2 = get_value_and_opt_policy(up, down, right, left, reward_func_list[1][max_lambda_idx[1]], gamma)\r\n\r\nstate_values_1, optimal_policies_1 = state_values_1.reshape(10, 10).T, optimal_policies_1.reshape(10, 10).T\r\nstate_values_2, optimal_policies_2 = state_values_2.reshape(10, 10).T, optimal_policies_2.reshape(10, 10).T\r\n\r\nplt.figure(9)\r\nplot_arrows(optimal_policies_1, \"Optimal Policy for Extracted Reward Function 1\")\r\n\r\nplt.figure(10)\r\nplot_arrows(optimal_policies_2, \"Optimal Policy for Extracted Reward Function 2\")\r\n\r\n\r\n################################################################################################################################### \r\n# Q25: improving IRL\r\n###################################################################################################################################\r\n\r\n\r\nplt.show()","sub_path":"Project 3/irl.py","file_name":"irl.py","file_ext":"py","file_size_in_byte":15683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"72495592","text":"from django.shortcuts import render\nfrom django.views.generic import TemplateView, ListView, DetailView, UpdateView\nfrom django.db.models import Q\nfrom .models import Date, Event, Work, Author, Composer\nfrom .forms import AuthorForm, ComposerForm, WorkForm\n\n# Create your views here.\nclass Index(TemplateView):\n \"\"\"schletter_app home page \"\"\"\n context_object_name = 'index'\n template_name = 'schletter_app/index.html'\n\n# Calendar\nclass DateList(ListView):\n context_object_name = 'calendar'\n model = Date\n paginate_by = 40\n template_name = 'schletter_app/calendar.html'\n \n def get_queryset(self):\n date_min = self.request.GET.get('date_min')\n date_max = self.request.GET.get('date_max')\n if date_min is not None and date_max is not None:\n return Date.objects.all().filter(date__gte=date_min, date__lte=date_max)\n else:\n return Date.objects.all()\n \n# Events\nclass EventQueryMixin:\n def get_queryset(self):\n qs = Event.objects.all()\n theater = self.request.GET.get('theater')\n company = self.request.GET.getlist('company')\n event_type = self.request.GET.getlist('event_type')\n genre = self.request.GET.getlist('genre')\n if theater:\n qs = qs.filter(theater=theater)\n if company:\n qs = qs.filter(Q(company__in=company))\n if event_type:\n qs = qs.filter(Q(event_type__in=event_type))\n if genre:\n qs = qs.filter(Q(work__genre__in=genre) |\n Q(work__source_genre__in=genre))\n return qs\n\nclass EventList(EventQueryMixin, ListView):\n context_object_name = 'events'\n paginate_by = 50\n template_name = 'schletter_app/events.html'\n # Value lists for drop downs in Event search\n extra_context = {\n 'companies': Event.objects.all().exclude(company='NA').order_by('company').values_list('company', flat=True).distinct(),\n 'event_types': Event.objects.all().order_by('event_type').values_list('event_type', flat=True).distinct(),\n 'genres': Work.objects.all().order_by('genre').values_list('genre', flat=True).distinct()\n }\n\nclass EventDetail(EventQueryMixin, DetailView):\n context_object_name = 'event'\n model = Event\n template_name = 'schletter_app/event.html'\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n prev_pk = (\n self.get_queryset()\n .filter(pk__lt=self.object.pk)\n .reverse().values('pk')[:1]\n )\n # There may be no previous page\n if prev_pk:\n context['prev_pk'] = prev_pk[0]['pk']\n \n next_pk = (\n self.get_queryset()\n .filter(pk__gt=self.object.pk)\n .values('pk')[:1]\n )\n # There may be no next page\n if next_pk:\n context['next_pk'] = next_pk[0]['pk']\n \n return context\n\nclass EventEdit(UpdateView):\n model = Event\n template_name = 'schletter_app/event_edit.html'\n fields = ['notes']\n\n\n# Works\nclass WorkQueryMixin:\n def get_queryset(self):\n query = self.request.GET.get('q')\n if query is not None:\n return Work.objects.filter(Q(title__unaccent__icontains=query) | \n Q(source_title__icontains=query) | \n Q(genre__unaccent__icontains=query) |\n Q(source_genre__unaccent__icontains=query)) \n else:\n return Work.objects.all()\n\nclass WorkList(WorkQueryMixin, ListView):\n context_object_name = 'works'\n model = Work\n paginate_by = 50\n template_name = 'schletter_app/works.html'\n\nclass WorkDetail(WorkQueryMixin, DetailView):\n context_object_name = 'work'\n model = Work\n template_name = 'schletter_app/work.html'\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n prev_pk = (\n self.get_queryset()\n .filter(sort_title__lt=self.object.sort_title)\n .reverse().values('pk')[:1]\n )\n # There may be no previous page\n if prev_pk:\n context['prev_pk'] = prev_pk[0]['pk']\n \n next_pk = (\n self.get_queryset()\n .filter(sort_title__gt=self.object.sort_title).values('pk')[:1]\n )\n # There may be no next page\n if next_pk:\n context['next_pk'] = next_pk[0]['pk']\n \n return context\n\nclass WorkEdit(UpdateView):\n model = Work\n template_name = 'schletter_app/work_edit.html'\n form_class = WorkForm\n\n# Authors\nclass AuthorQueryMixin:\n def get_queryset(self):\n query = self.request.GET.get('q')\n if query is not None:\n return Author.objects.filter(Q(last_name__unaccent__icontains=query) | Q(first_names__unaccent__icontains=query) | Q(authorwork__role__icontains=query)).distinct()\n else:\n return Author.objects.all()\n\nclass AuthorList(AuthorQueryMixin, ListView):\n context_object_name = 'authors'\n model = Author\n paginate_by = 50\n template_name = 'schletter_app/authors.html'\n\nclass AuthorDetail(AuthorQueryMixin, DetailView):\n context_object_name = 'author'\n model = Author\n template_name = 'schletter_app/author.html'\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n prev_pk = (\n self.get_queryset()\n .filter(last_name__lt=self.object.last_name)\n .reverse().values('pk')[:1]\n )\n # There may be no previous page\n if prev_pk:\n context['prev_pk'] = prev_pk[0]['pk']\n \n next_pk = (\n self.get_queryset()\n .filter(last_name__gt=self.object.last_name)\n .values('pk')[:1]\n )\n # There may be no next page\n if next_pk:\n context['next_pk'] = next_pk[0]['pk']\n \n return context\n\nclass AuthorEdit(UpdateView):\n model = Author\n form_class = AuthorForm\n template_name = 'schletter_app/author_edit.html'\n\n# Composers\nclass ComposerQueryMixin:\n def get_queryset(self):\n query = self.request.GET.get('q')\n if query is not None:\n return Composer.objects.exclude(last_name=\"NA\").filter(Q(last_name__unaccent__icontains=query) | Q(first_names__unaccent__icontains=query))\n else:\n return Composer.objects.all().exclude(last_name=\"NA\")\n\nclass ComposerList(ComposerQueryMixin, ListView):\n context_object_name = 'composers'\n model = Composer\n paginate_by = 50\n template_name = 'schletter_app/composers.html'\n\nclass ComposerDetail(ComposerQueryMixin, DetailView):\n context_object_name = 'composer'\n model = Composer\n template_name = 'schletter_app/composer.html'\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n prev_pk = (\n self.get_queryset()\n .filter(last_name__lt=self.object.last_name)\n .reverse().values('pk')[:1]\n )\n # There may be no previous page\n if prev_pk:\n context['prev_pk'] = prev_pk[0]['pk']\n \n next_pk = (\n self.get_queryset()\n .filter(last_name__gt=self.object.last_name)\n .values('pk')[:1]\n )\n # There may be no next page\n if next_pk:\n context['next_pk'] = next_pk[0]['pk']\n \n return context\n\nclass ComposerEdit(UpdateView):\n model = Composer\n form_class = ComposerForm\n template_name = 'schletter_app/composer_edit.html'\n","sub_path":"schletter_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"324870418","text":"import tensorflow as tf\nimport CNN_interface\nimport DNN_interface\n\n\nINPUT_NODE = 64 # 输入节点\nOUTPUT_NODE = 32 # 输出节点\n\nsent_data_shape = None # 发射机的输出维度\nsent_dnn_DROP = 0.5 # 发射机的DNN的drop\nsent_dnn_REGULARIZER_RATE = 1e-4 # 发射机的DNN的正则率\n\nreceive_data_after_cnn_shape = None # 接收机通过CNN网络之后的数据维度\nreceive_cnn_DROP = 0.5 # 接收机的CNN的drop,CNN内的一个密集层的drop\nreceive_cnn_REGULARIZER_RATE = 1e-4 # 接收机中CNN的密集层的正则率\n\nreceive_data_shape = None # 接收机的输出维度\nreceive_dnn_DROP = 0.5 # 接收机的DNN的drop\nreceive_dnn_REGULARIZER_RATE = 1e-4 # 接收机的DNN的正则率\n\nLEARNING_RATE_BASE = 0.8 # 模型基础学习速率\nLEARNING_RATE_DECAY = 0.99 # 学习衰减速度\nBATCH_SIZE = 200 # 一批数据量\nTRAIN_NUM = 2E4 # 数据总量\nMOVING_AVERAGE_DECAY = 0.99 # 滑动平均衰减\nTRAINING_STEPS = 10000 # 训练多少次\n\nSNR = 0 # 信噪比\n\nE_x = 10 ** (0.1*SNR) #信号能量\n\nimport numpy as np\nimport pandas as pd\n#生成数据\nX = np.random.randint(0,2,[TRAIN_NUM,INPUT_NODE])\nY = pd.DataFrame(X).applymap(lambda x: 1 if x==1 else -1)\n\n\n# 定义整个模型的x和y\nx = tf.placeholder(tf.float32 ,[None,INPUT_NODE], name='x_input')\ny_ = tf.placeholder(tf.float32, [None,OUTPUT_NODE], name='y-input')\n\n# 发射机通过DNN输出的数据\n# dnn_interface(input_tensor, output_shape, regularizer_rate=None, drop=None)\nsent_data = DNN_interface.dnn_interface(input_tensor=x,\n output_shape=sent_data_shape,\n regularizer_rate=sent_dnn_REGULARIZER_RATE,\n drop=sent_dnn_DROP )\n\n# 过信道,加噪声\ndata_after_channle = sent_data * E_x + np.random.randn(TRAIN_NUM,32) # sigma * r + mu\n\n# 接收机的CNN网络\n# cnn_inference(input_tensor, output_shape, drop=None, regularizer_rate=None)\nreceive_data_after_cnn = CNN_interface.cnn_inference(input_tensor=data_after_channle,\n output_shape=receive_data_after_cnn_shape,\n drop=receive_cnn_DROP,\n regularizer_rate=receive_cnn_REGULARIZER_RATE)\n\n# 移除噪声\ndata_after_remove_voice = data_after_channle - receive_data_after_cnn\n\n# 接收机的DNN\n# dnn_interface(input_tensor, output_shape, regularizer_rate=None, drop=None)\ny = DNN_interface.dnn_interface(input_tensor=data_after_remove_voice,\n output_shape=OUTPUT_NODE,\n regularizer_rate=receive_dnn_REGULARIZER_RATE,\n drop=receive_dnn_DROP,\n )\n\n# 损失函数\ncross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=y,\n labels=y_) # 自动one-hot编码\ncross_entropy_mean = tf.reduce_mean(cross_entropy) # 平均交叉熵\n\nloss = cross_entropy_mean + tf.add_n(tf.get_collection('losses')) # 损失函数是交叉熵和正则化的和\n\n# 优化器\n# 定义当前迭代轮数的变量\nglobal_step = tf.get_variable('global_step', # 存储当前迭代的轮数\n dtype=tf.int32, # 整数\n initializer=0, # 初始化值\n trainable=False) # 不可训练\n# 定义学习速率\nlearning_rate = tf.train.exponential_decay(LEARNING_RATE_BASE, # 基础学习率\n global_step, # 当前迭代轮数\n TRAIN_NUM / BATCH_SIZE, # 迭代次数\n LEARNING_RATE_DECAY, # 学习衰减速度\n staircase=False) # 是否每步都改变速率\n\n# 定义优化函数\ntrain_step = tf.train.AdamOptimizer(learning_rate).minimize(loss, global_step)\n\n\"\"\"\n# 滑动平均类\nvariable_averages = tf.train.ExponentialMovingAverage(MOVING_AVERAGE_DECAY, global_step)\nvariables_averages_op = variable_averages.apply(tf.trainable_variables())\ntrain_op = tf.group(train_step, variables_averages_op)\n\"\"\"\n\n# 保存模型\nsaver = tf.train.Saver(max_to_keep=3)\nmin_loss = float('inf')\n\n#使用tensorboard\n#writer = tf.summary.FileWriter('/logs/log', tf.get_default_graph())\n#writer.close()\nmerged = tf.summary.merge_all()\n\nwith tf.Session() as sess:\n #初始化写日志的writer,并将当前Tensorflow计算图写入日志\n summary_writer = tf.summary.FileWriter('/logs/log', sess.graph)\n tf.global_variables_initializer().run() # 初始化\n for i in range(TRAINING_STEPS):\n # 设置批次\n start = (i * BATCH_SIZE) % TRAIN_NUM\n end = min(start+BATCH_SIZE, TRAIN_NUM)\n loss_entropy = sess.run(cross_entropy_mean,\n feed_dict={x: X[start:end], y_: Y[start:end]})\n compute_loss,summary = sess.run([train_step, merged],\n feed_dict={x:X[start:end], y_:Y[start:end]})\n # 保存模型\n if compute_loss < min_loss:\n min_loss = compute_loss\n saver.save(sess, '/ckpt/min_loss_model.ckpt', global_step=i)\n\n # 写入tensorboard日志\n summary_writer.add_summary(summary,i)\n\n # 输出\n if i % 100:\n print('训练了%d次后,交叉熵损失为%f,总损失为%f'%(i,loss_entropy,compute_loss))\n\nsess.close()","sub_path":"cnn_and_dnn.py","file_name":"cnn_and_dnn.py","file_ext":"py","file_size_in_byte":5532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"101105794","text":"#fn = input(\"Enter File name : \")\ntry:\n fh = open('words.txt')\nexcept:\n print('No file with that name!!')\n quit()\nfor line in fh :\n l = line.rstrip()\n lu = l.upper()\n print(lu)\n","sub_path":"programs/word/word.py","file_name":"word.py","file_ext":"py","file_size_in_byte":195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"207509508","text":"import argparse\nfrom spread_sheet import get_list\n\n\nclass Guest():\n def __init__(self, name, reserve_name):\n self.name = name\n self.reserve_name = reserve_name\n\n\nclass Guests():\n def __init__(self):\n self.update()\n\n def get_guests(self):\n return self.__guests\n\n def get_guest(self, name):\n for guest in self.get_guests():\n if guest.name == name:\n return guest\n return\n\n def is_exist(self, name):\n for guest in self.get_guests():\n if guest.name == name:\n return True\n return False\n\n def update(self):\n self.__guests = []\n for i, data in enumerate(get_list()):\n if len(data) == 2 and data[0] == '':\n print('null name. check name column where row = {}.'\n 'reserve_name is {}.'.format(i+2, data[1]))\n continue\n\n if len(data) == 1:\n self.__guests.append(Guest(data[0], ''))\n else:\n self.__guests.append(Guest(data[0], data[1]))\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n\n parser.add_argument('--name', type=str, help='name to confirm reservation')\n args = parser.parse_args()\n\n confirm_name = args.name\n guests = Guests()\n\n if confirm_name is not None:\n print('confirm guest name : {}'.format(confirm_name))\n if guests.is_exist(confirm_name):\n guest = guests.get_guest(confirm_name)\n print('exist. name: {}, reserve_name: {}'.format(\n guest.name, guest.reserve_name))\n else:\n print('no exist.')\n","sub_path":"guest.py","file_name":"guest.py","file_ext":"py","file_size_in_byte":1654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"209289129","text":"import pytest\n\n@pytest.fixture\ndef registrar(chain):\n return chain.registrar\n\n\ndef test_setting_bytes32(chain, web3, registrar):\n set_txn = registrar.transact().set('this-is-a-key', 'this-is-a-value')\n chain.wait.for_receipt(set_txn, timeout=30)\n\n value = registrar.call().get('this-is-a-key')\n\n assert len(value) == 32\n assert 'this-is-a-value' in value\n\n\ndef test_setting_address(chain, web3, registrar):\n set_txn = registrar.transact().setAddress('this-is-a-key', '0xd3cda913deb6f67967b99d67acdfa1712c293601')\n chain.wait.for_receipt(set_txn, timeout=30)\n\n value = registrar.call().getAddress('this-is-a-key')\n assert value == '0xd3cda913deb6f67967b99d67acdfa1712c293601'\n\n\n@pytest.mark.parametrize(\n 'value',\n (0, 1, 1234567890, 2**256 - 1),\n)\ndef test_setting_uint(chain, web3, registrar, value):\n set_txn = registrar.transact().setUInt('this-is-a-key', value)\n chain.wait.for_receipt(set_txn, timeout=30)\n\n chain_value = registrar.call().getUInt('this-is-a-key')\n\n assert chain_value == value\n\n\n@pytest.mark.parametrize(\n 'value',\n (0, 1, -1, 1234567890, 2**255 - 1),\n)\ndef test_setting_int(chain, web3, registrar, value):\n set_txn = registrar.transact().setInt('this-is-a-key', value)\n chain.wait.for_receipt(set_txn, timeout=30)\n\n chain_value = registrar.call().getInt('this-is-a-key')\n\n assert chain_value == value\n\n\n@pytest.mark.parametrize(\n 'value',\n ('', 'a', 'some-short-string', 'some-string-that-is-longer-than-32-bytes'),\n)\ndef test_setting_string(chain, web3, registrar, value):\n set_txn = registrar.transact().setString('this-is-a-key', value)\n chain.wait.for_receipt(set_txn, timeout=30)\n\n chain_value = registrar.call().getString('this-is-a-key')\n\n assert chain_value == value\n\n\ndef test_exists_query(chain, web3, registrar):\n assert registrar.call().exists('this-is-a-key') is False\n\n set_txn = registrar.transact().set('this-is-a-key', 'a-value')\n chain.wait.for_receipt(set_txn, timeout=30)\n\n assert registrar.call().exists('this-is-a-key') is True\n","sub_path":"tests/migrations/test_registrar_key_value_api.py","file_name":"test_registrar_key_value_api.py","file_ext":"py","file_size_in_byte":2069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"160175873","text":"import numpy as np\nimport cv2\n\n\"\"\"img = cv2.imread('watch.jpg', 1)\n\n#parameters: image, starting coordinate, end coordinate\n#parameters: rgb color, line thickness\nimg = cv2.line(img, (0,0), (255,255), (255, 0, 0), 10)\n\nimg = cv2.arrowedLine(img, (0,255), (255,255), (0, 0, 255), 10)\n\n#parameters: image, top corner coordinate, bottom corner coordinate,\n#paramters: rgb color, line thickness\nimg = cv2.rectangle(img, (255,0), (124,255), (0, 255, 0), 5)\n\n#More examples:\n# - cv2.circle\n# - cv2.putText\n\ncv2.imshow('image', img)\"\"\"\n\nimage = np.zeros((512, 512, 3), np.uint8)\nimage_bw = np.zeros((512, 512), np.uint8)\n\npts = np.array([[10, 50], [400, 50], [90, 200], [50, 500]], np.int32)\nprint(pts, pts.shape)\npts = pts.reshape((-1, 1, 2))\nprint(pts)\ncv2.polylines(image, [pts], True, (0, 0, 255), 3)\n\ncv2.circle(image, (256, 256), 50, (255, 0, 0), -1)\n\ncv2.putText(image, 'Hello World', (75, 290), cv2.FONT_HERSHEY_COMPLEX, 2, (100, 170, 3), 3)\n\n\ncv2.imshow(\"Black rectangle (Color)\", image)\n\ncv2.imshow(\"Black rectangle (B&W)\", image_bw)\n\n\ncv2.waitKey(0)\ncv2.destroyAllWindows()","sub_path":"DrawGeometricShapes.py","file_name":"DrawGeometricShapes.py","file_ext":"py","file_size_in_byte":1077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"303461508","text":"#\n# Copyright (c) 2016 GigaSpaces Technologies Ltd. All rights reserved.\n# \n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n# \n# http://www.apache.org/licenses/LICENSE-2.0\n# \n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n#\n\nfrom .elements import Element, Parameter\nfrom .utils import validate_dict_values, validate_list_values, coerce_dict_values, coerce_list_values, dump_list_values, dump_dict_values, dump_parameters, dump_interfaces\nfrom ..validation import Issue\nfrom ..utils import StrictList, StrictDict, FrozenList, puts, indent, as_raw, as_raw_list, as_raw_dict, as_agnostic, safe_repr \nfrom collections import OrderedDict\n\nclass ServiceInstance(Element):\n \"\"\"\n A service instance is an instance of a :class:`ServiceModel`.\n \n You will usually not create it programmatically, but instead instantiate\n it from the model.\n \n Properties:\n \n * :code:`description`: Human-readable description\n * :code:`metadata`: :class:`Metadata`\n * :code:`nodes`: Dict of :class:`Node`\n * :code:`groups`: Dict of :class:`Group`\n * :code:`policies`: Dict of :class:`Policy`\n * :code:`substitution`: :class:`Substituion`\n * :code:`inputs`: Dict of :class:`Parameter`\n * :code:`outputs`: Dict of :class:`Parameter`\n * :code:`operations`: Dict of :class:`Operation`\n \"\"\"\n \n def __init__(self):\n self.description = None\n self.metadata = None\n self.nodes = StrictDict(key_class=basestring, value_class=Node) \n self.groups = StrictDict(key_class=basestring, value_class=Group) \n self.policies = StrictDict(key_class=basestring, value_class=Policy)\n self.substitution = None\n self.inputs = StrictDict(key_class=basestring, value_class=Parameter)\n self.outputs = StrictDict(key_class=basestring, value_class=Parameter)\n self.operations = StrictDict(key_class=basestring, value_class=Operation)\n\n def satisfy_requirements(self, context):\n satisfied = True\n for node in self.nodes.itervalues():\n if not node.satisfy_requirements(context):\n satisfied = False\n return satisfied\n \n def validate_capabilities(self, context):\n satisfied = True\n for node in self.nodes.itervalues():\n if not node.validate_capabilities(context):\n satisfied = False\n return satisfied\n \n def find_nodes(self, node_template_name):\n nodes = []\n for node in self.nodes.itervalues():\n if node.template_name == node_template_name:\n nodes.append(node)\n return FrozenList(nodes)\n\n def get_node_ids(self, node_template_name):\n return FrozenList((node.id for node in self.find_nodes(node_template_name)))\n \n def find_groups(self, group_template_name):\n groups = []\n for group in self.groups.itervalues():\n if group.template_name == group_template_name:\n groups.append(group)\n return FrozenList(groups)\n\n def get_group_ids(self, group_template_name):\n return FrozenList((group.id for group in self.find_groups(group_template_name)))\n \n def is_node_a_target(self, context, target_node):\n for node in self.nodes.itervalues():\n if self._is_node_a_target(context, node, target_node):\n return True\n return False\n\n def _is_node_a_target(self, context, source_node, target_node):\n if source_node.relationships:\n for relationship in source_node.relationships:\n if relationship.target_node_id == target_node.id:\n return True\n else:\n node = context.modeling.instance.nodes.get(relationship.target_node_id)\n if node is not None:\n if self._is_node_a_target(context, node, target_node):\n return True\n return False\n\n @property\n def as_raw(self):\n return OrderedDict((\n ('description', self.description),\n ('metadata', as_raw(self.metadata)),\n ('nodes', as_raw_list(self.nodes)),\n ('groups', as_raw_list(self.groups)),\n ('policies', as_raw_list(self.policies)),\n ('substitution', as_raw(self.substitution)),\n ('inputs', as_raw_dict(self.inputs)),\n ('outputs', as_raw_dict(self.outputs)),\n ('operations', as_raw_list(self.operations))))\n \n def validate(self, context):\n if self.metadata is not None:\n self.metadata.validate(context)\n validate_dict_values(context, self.nodes)\n validate_dict_values(context, self.groups)\n validate_dict_values(context, self.policies)\n if self.substitution is not None:\n self.substitution.validate(context)\n validate_dict_values(context, self.inputs)\n validate_dict_values(context, self.outputs)\n validate_dict_values(context, self.operations)\n\n def coerce_values(self, context, container, report_issues):\n if self.metadata is not None:\n self.metadata.coerce_values(context, container, report_issues)\n coerce_dict_values(context, container, self.nodes, report_issues)\n coerce_dict_values(context, container, self.groups, report_issues)\n coerce_dict_values(context, container, self.policies, report_issues)\n if self.substitution is not None:\n self.substitution.coerce_values(context, container, report_issues)\n coerce_dict_values(context, container, self.inputs, report_issues)\n coerce_dict_values(context, container, self.outputs, report_issues)\n coerce_dict_values(context, container, self.operations, report_issues)\n\n def dump(self, context):\n if self.description is not None:\n puts(context.style.meta(self.description))\n if self.metadata is not None:\n self.metadata.dump(context)\n for node in self.nodes.itervalues():\n node.dump(context)\n for group in self.groups.itervalues():\n group.dump(context)\n for policy in self.policies.itervalues():\n policy.dump(context)\n if self.substitution is not None:\n self.substitution.dump(context)\n dump_parameters(context, self.inputs, 'Inputs')\n dump_parameters(context, self.outputs, 'Outputs')\n dump_dict_values(context, self.operations, 'Operations')\n\n def dump_graph(self, context):\n for node in self.nodes.itervalues():\n if not self.is_node_a_target(context, node):\n self._dump_graph_node(context, node)\n \n def _dump_graph_node(self, context, node):\n puts(context.style.node(node.id))\n if node.relationships:\n with context.style.indent:\n for relationship in node.relationships:\n relationship_name = context.style.node(relationship.template_name) if relationship.template_name is not None else context.style.type(relationship.type_name)\n capability_name = context.style.node(relationship.target_capability_name) if relationship.target_capability_name is not None else None\n if capability_name is not None:\n puts('-> %s %s' % (relationship_name, capability_name))\n else:\n puts('-> %s' % relationship_name)\n target_node = self.nodes.get(relationship.target_node_id)\n with indent(3):\n self._dump_graph_node(context, target_node)\n\nclass Node(Element):\n \"\"\"\n An instance of a :class:`NodeTemplate`.\n \n Nodes may have zero or more :class:`Relationship` instances to other nodes.\n \n Properties:\n \n * :code:`id`: Unique ID (prefixed with the template name)\n * :code:`type_name`: Must be represented in the :class:`ModelingContext`\n * :code:`template_name`: Must be represented in the :class:`ServiceModel`\n * :code:`properties`: Dict of :class:`Parameter`\n * :code:`interfaces`: Dict of :class:`Interface`\n * :code:`artifacts`: Dict of :class:`Artifact`\n * :code:`capabilities`: Dict of :class:`CapabilityTemplate`\n * :code:`relationship`: List of :class:`Relationship`\n \"\"\"\n \n def __init__(self, context, type_name, template_name):\n if not isinstance(type_name, basestring):\n raise ValueError('must set type_name (string)')\n if not isinstance(template_name, basestring):\n raise ValueError('must set template_name (string)')\n\n self.id = '%s_%s' % (template_name, context.modeling.generate_id())\n self.type_name = type_name\n self.template_name = template_name\n self.properties = StrictDict(key_class=basestring, value_class=Parameter)\n self.interfaces = StrictDict(key_class=basestring, value_class=Interface)\n self.artifacts = StrictDict(key_class=basestring, value_class=Artifact)\n self.capabilities = StrictDict(key_class=basestring, value_class=Capability)\n self.relationships = StrictList(value_class=Relationship)\n \n def satisfy_requirements(self, context):\n node_template = context.modeling.model.node_templates.get(self.template_name)\n satisfied = True\n for i in range(len(node_template.requirement_templates)):\n requirement_template = node_template.requirement_templates[i]\n \n # Find target template\n target_node_template, target_node_capability = requirement_template.find_target(context, node_template)\n if target_node_template is not None:\n # Find target nodes\n target_nodes = context.modeling.instance.find_nodes(target_node_template.name)\n if target_nodes:\n target_node = None\n target_capability = None\n \n if target_node_capability is not None:\n # Relate to the first target node that has capacity\n for node in target_nodes:\n target_capability = node.capabilities.get(target_node_capability.name)\n if target_capability.relate():\n target_node = node\n break\n else:\n # Use first target node\n target_node = target_nodes[0]\n \n if target_node is not None:\n if requirement_template.relationship_template is not None:\n relationship = requirement_template.relationship_template.instantiate(context, self)\n else:\n relationship = Relationship()\n relationship.name = requirement_template.name\n relationship.source_requirement_index = i\n relationship.target_node_id = target_node.id\n if target_capability is not None:\n relationship.target_capability_name = target_capability.name\n self.relationships.append(relationship)\n else:\n context.validation.report('requirement \"%s\" of node \"%s\" targets node template \"%s\" but its instantiated nodes do not have enough capacity' % (requirement_template.name, self.id, target_node_template.name), level=Issue.BETWEEN_INSTANCES)\n satisfied = False\n else:\n context.validation.report('requirement \"%s\" of node \"%s\" targets node template \"%s\" but it has no instantiated nodes' % (requirement_template.name, self.id, target_node_template.name), level=Issue.BETWEEN_INSTANCES)\n satisfied = False\n else:\n context.validation.report('requirement \"%s\" of node \"%s\" has no target node template' % (requirement_template.name, self.id), level=Issue.BETWEEN_INSTANCES)\n satisfied = False\n return satisfied\n\n def validate_capabilities(self, context):\n satisfied = False\n for capability in self.capabilities.itervalues():\n if not capability.has_enough_relationships:\n context.validation.report('capability \"%s\" of node \"%s\" requires at least %d relationships but has %d' % (capability.name, self.id, capability.min_occurrences, capability.occurrences), level=Issue.BETWEEN_INSTANCES)\n satisfied = False\n return satisfied\n\n @property\n def as_raw(self):\n return OrderedDict((\n ('id', self.id),\n ('type_name', self.type_name),\n ('template_name', self.template_name),\n ('properties', as_raw_dict(self.properties)),\n ('interfaces', as_raw_list(self.interfaces)),\n ('artifacts', as_raw_list(self.artifacts)),\n ('capabilities', as_raw_list(self.capabilities)),\n ('relationships', as_raw_list(self.relationships))))\n \n def validate(self, context):\n if len(self.id) > context.modeling.id_max_length:\n context.validation.report('\"%s\" has an ID longer than the limit of %d characters: %d' % (self.id, context.modeling.id_max_length, len(self.id)), level=Issue.BETWEEN_INSTANCES)\n \n # TODO: validate that node template is of type?\n \n validate_dict_values(context, self.properties)\n validate_dict_values(context, self.interfaces)\n validate_dict_values(context, self.artifacts)\n validate_dict_values(context, self.capabilities)\n validate_list_values(context, self.relationships)\n\n def coerce_values(self, context, container, report_issues):\n coerce_dict_values(context, self, self.properties, report_issues)\n coerce_dict_values(context, self, self.interfaces, report_issues)\n coerce_dict_values(context, self, self.artifacts, report_issues)\n coerce_dict_values(context, self, self.capabilities, report_issues)\n coerce_list_values(context, self, self.relationships, report_issues)\n\n def dump(self, context):\n puts('Node: %s' % context.style.node(self.id))\n with context.style.indent:\n puts('Template: %s' % context.style.node(self.template_name))\n puts('Type: %s' % context.style.type(self.type_name))\n dump_parameters(context, self.properties)\n dump_interfaces(context, self.interfaces)\n dump_dict_values(context, self.artifacts, 'Artifacts')\n dump_dict_values(context, self.capabilities, 'Capabilities')\n dump_list_values(context, self.relationships, 'Relationships')\n\nclass Capability(Element):\n \"\"\"\n A capability of a :class:`Node`.\n \n An instance of a :class:`CapabilityTemplate`.\n\n Properties:\n \n * :code:`name`: Name\n * :code:`type_name`: Must be represented in the :class:`ModelingContext`\n * :code:`min_occurrences`: Minimum number of requirement matches required\n * :code:`max_occurrences`: Maximum number of requirement matches allowed\n * :code:`properties`: Dict of :class:`Parameter`\n \"\"\"\n \n def __init__(self, name, type_name):\n if not isinstance(name, basestring):\n raise ValueError('name must be a string or None')\n if not isinstance(type_name, basestring):\n raise ValueError('type_name must be a string or None')\n \n self.name = name\n self.type_name = type_name\n self.properties = StrictDict(key_class=basestring, value_class=Parameter)\n \n self.min_occurrences = None # optional\n self.max_occurrences = None # optional\n self.occurrences = 0\n \n @property\n def has_enough_relationships(self):\n if self.min_occurrences is not None:\n return self.occurrences >= self.min_occurrences\n return True\n\n def relate(self):\n if self.max_occurrences is not None:\n if self.occurrences == self.max_occurrences:\n return False\n self.occurrences += 1\n return True \n\n @property\n def as_raw(self):\n return OrderedDict((\n ('name', self.name),\n ('type_name', self.type_name),\n ('properties', as_raw_dict(self.properties))))\n\n def validate(self, context):\n if context.modeling.capability_types.get_descendant(self.type_name) is None:\n context.validation.report('capability \"%s\" has an unknown type: %s' % (self.name, safe_repr(self.type_name)), level=Issue.BETWEEN_TYPES)\n \n validate_dict_values(context, self.properties)\n\n def coerce_values(self, context, container, report_issues):\n coerce_dict_values(context, container, self.properties, report_issues)\n \n def dump(self, context):\n puts(context.style.node(self.name))\n with context.style.indent:\n puts('Type: %s' % context.style.type(self.type_name))\n puts('Occurrences: %s (%s%s)' % (self.occurrences, self.min_occurrences or 0, (' to %d' % self.max_occurrences) if self.max_occurrences is not None else ' or more'))\n dump_parameters(context, self.properties)\n\nclass Relationship(Element):\n \"\"\"\n Connects :class:`Node` to another node.\n\n An instance of a :class:`RelationshipTemplate`.\n\n Properties:\n\n * :code:`name`: Name (usually the name of the requirement at the source node template)\n * :code:`source_requirement_index`: Must be represented in the source node template\n * :code:`target_node_id`: Must be represented in the :class:`ServiceInstance`\n * :code:`target_capability_name`: Matches the capability at the target node\n * :code:`type_name`: Must be represented in the :class:`ModelingContext`\n * :code:`template_name`: Must be represented in the :class:`ServiceModel`\n * :code:`properties`: Dict of :class:`Parameter`\n * :code:`source_interfaces`: Dict of :class:`Interface`\n * :code:`target_interfaces`: Dict of :class:`Interface`\n \"\"\"\n \n def __init__(self, name=None, source_requirement_index=None, type_name=None, template_name=None):\n if (name is not None) and (not isinstance(name, basestring)):\n raise ValueError('name must be a string or None')\n if (source_requirement_index is not None) and ((not isinstance(source_requirement_index, int)) or (source_requirement_index < 0)):\n raise ValueError('source_requirement_index must be int > 0')\n if (type_name is not None) and (not isinstance(type_name, basestring)):\n raise ValueError('type_name must be a string or None')\n if (template_name is not None) and (not isinstance(template_name, basestring)):\n raise ValueError('template_name must be a string or None')\n \n self.name = name\n self.source_requirement_index = source_requirement_index\n self.target_node_id = None\n self.target_capability_name = None\n self.type_name = type_name\n self.template_name = template_name\n self.properties = StrictDict(key_class=basestring, value_class=Parameter)\n self.source_interfaces = StrictDict(key_class=basestring, value_class=Interface)\n self.target_interfaces = StrictDict(key_class=basestring, value_class=Interface)\n\n @property\n def as_raw(self):\n return OrderedDict((\n ('name', self.name),\n ('source_requirement_index', self.source_requirement_index),\n ('target_node_id', self.target_node_id),\n ('target_capability_name', self.target_capability_name),\n ('type_name', self.type_name),\n ('template_name', self.template_name),\n ('properties', as_raw_dict(self.properties)),\n ('source_interfaces', as_raw_list(self.source_interfaces)), \n ('target_interfaces', as_raw_list(self.target_interfaces))))\n\n def validate(self, context):\n if self.type_name:\n if context.modeling.relationship_types.get_descendant(self.type_name) is None:\n context.validation.report('relationship \"%s\" has an unknown type: %s' % (self.name, safe_repr(self.type_name)), level=Issue.BETWEEN_TYPES) \n\n validate_dict_values(context, self.properties)\n validate_dict_values(context, self.source_interfaces)\n validate_dict_values(context, self.target_interfaces)\n\n def coerce_values(self, context, container, report_issues):\n coerce_dict_values(context, container, self.properties, report_issues)\n coerce_dict_values(context, container, self.source_interfaces, report_issues)\n coerce_dict_values(context, container, self.target_interfaces, report_issues)\n\n def dump(self, context):\n if self.name:\n if self.source_requirement_index is not None:\n puts('%s (%d) ->' % (context.style.node(self.name), self.source_requirement_index))\n else:\n puts('%s ->' % context.style.node(self.name))\n else:\n puts('->')\n with context.style.indent:\n puts('Node: %s' % context.style.node(self.target_node_id))\n if self.target_capability_name is not None:\n puts('Capability: %s' % context.style.node(self.target_capability_name))\n if self.type_name is not None:\n puts('Relationship type: %s' % context.style.type(self.type_name))\n if self.template_name is not None:\n puts('Relationship template: %s' % context.style.node(self.template_name))\n dump_parameters(context, self.properties)\n dump_interfaces(context, self.source_interfaces, 'Source interfaces')\n dump_interfaces(context, self.target_interfaces, 'Target interfaces')\n\n\nclass Artifact(Element):\n \"\"\"\n A file associated with a :class:`Node`.\n\n Properties:\n \n * :code:`name`: Name\n * :code:`description`: Description\n * :code:`type_name`: Must be represented in the :class:`ModelingContext`\n * :code:`source_path`: Source path (CSAR or repository)\n * :code:`target_path`: Path at destination machine\n * :code:`repository_url`: Repository URL\n * :code:`repository_credential`: Dict of string\n * :code:`properties`: Dict of :class:`Parameter`\n \"\"\"\n \n def __init__(self, name, type_name, source_path):\n if not isinstance(name, basestring):\n raise ValueError('must set name (string)')\n if not isinstance(type_name, basestring):\n raise ValueError('must set type_name (string)')\n if not isinstance(source_path, basestring):\n raise ValueError('must set source_path (string)')\n \n self.name = name\n self.description = None\n self.type_name = type_name\n self.source_path = source_path\n self.target_path = None\n self.repository_url = None\n self.repository_credential = StrictDict(key_class=basestring, value_class=basestring)\n self.properties = StrictDict(key_class=basestring, value_class=Parameter)\n\n @property\n def as_raw(self):\n return OrderedDict((\n ('name', self.name),\n ('description', self.description),\n ('type_name', self.type_name),\n ('source_path', self.source_path),\n ('target_path', self.target_path),\n ('repository_url', self.repository_url),\n ('repository_credential', as_agnostic(self.repository_credential)),\n ('properties', as_raw_dict(self.properties))))\n\n def validate(self, context):\n if context.modeling.artifact_types.get_descendant(self.type_name) is None:\n context.validation.report('artifact \"%s\" has an unknown type: %s' % (self.name, safe_repr(self.type_name)), level=Issue.BETWEEN_TYPES) \n\n validate_dict_values(context, self.properties)\n\n def coerce_values(self, context, container, report_issues):\n coerce_dict_values(context, container, self.properties, report_issues)\n\n def dump(self, context):\n puts(context.style.node(self.name))\n if self.description:\n puts(context.style.meta(self.description))\n with context.style.indent:\n puts('Artifact type: %s' % context.style.type(self.type_name))\n puts('Source path: %s' % context.style.literal(self.source_path))\n if self.target_path is not None:\n puts('Target path: %s' % context.style.literal(self.target_path))\n if self.repository_url is not None:\n puts('Repository URL: %s' % context.style.literal(self.repository_url))\n if self.repository_credential:\n puts('Repository credential: %s' % context.style.literal(self.repository_credential))\n dump_parameters(context, self.properties)\n\nclass Group(Element):\n \"\"\"\n An instance of a :class:`GroupTemplate`.\n\n Properties:\n \n * :code:`id`: Unique ID (prefixed with the template name)\n * :code:`type_name`: Must be represented in the :class:`ModelingContext`\n * :code:`template_name`: Must be represented in the :class:`ServiceModel`\n * :code:`properties`: Dict of :class:`Parameter`\n * :code:`interfaces`: Dict of :class:`Interface`\n * :code:`policies`: Dict of :class:`GroupPolicy`\n * :code:`member_node_ids`: Must be represented in the :class:`ServiceInstance`\n * :code:`member_group_ids`: Must be represented in the :class:`ServiceInstance`\n \"\"\" \n \n def __init__(self, context, type_name, template_name):\n if not isinstance(template_name, basestring):\n raise ValueError('must set template_name (string)')\n\n self.id = '%s_%s' % (template_name, context.modeling.generate_id())\n self.type_name = type_name\n self.template_name = template_name\n self.properties = StrictDict(key_class=basestring, value_class=Parameter)\n self.interfaces = StrictDict(key_class=basestring, value_class=Interface)\n self.policies = StrictDict(key_class=basestring, value_class=GroupPolicy)\n self.member_node_ids = StrictList(value_class=basestring)\n self.member_group_ids = StrictList(value_class=basestring)\n\n @property\n def as_raw(self):\n return OrderedDict((\n ('id', self.id),\n ('type_name', self.type_name),\n ('template_name', self.template_name),\n ('properties', as_raw_dict(self.properties)),\n ('interfaces', as_raw_list(self.interfaces)),\n ('policies', as_raw_list(self.policies)),\n ('member_node_ids', self.member_node_ids),\n ('member_group_ids', self.member_group_ids)))\n\n def validate(self, context):\n if context.modeling.group_types.get_descendant(self.type_name) is None:\n context.validation.report('group \"%s\" has an unknown type: %s' % (self.name, safe_repr(self.type_name)), level=Issue.BETWEEN_TYPES) \n\n validate_dict_values(context, self.properties)\n validate_dict_values(context, self.interfaces)\n validate_dict_values(context, self.policies)\n\n def coerce_values(self, context, container, report_issues):\n coerce_dict_values(context, container, self.properties, report_issues)\n coerce_dict_values(context, container, self.interfaces, report_issues)\n coerce_dict_values(context, container, self.policies, report_issues)\n\n def dump(self, context):\n puts('Group: %s' % context.style.node(self.id))\n with context.style.indent:\n puts('Type: %s' % context.style.type(self.type_name))\n puts('Template: %s' % context.style.type(self.template_name))\n dump_parameters(context, self.properties)\n dump_interfaces(context, self.interfaces)\n dump_dict_values(context, self.policies, 'Policies')\n if self.member_node_ids:\n puts('Member nodes:')\n with context.style.indent:\n for node_id in self.member_node_ids:\n puts(context.style.node(node_id))\n\nclass Policy(Element):\n \"\"\"\n An instance of a :class:`PolicyTemplate`.\n \n Properties:\n \n * :code:`name`: Name\n * :code:`type_name`: Must be represented in the :class:`ModelingContext`\n * :code:`properties`: Dict of :class:`Parameter`\n * :code:`target_node_ids`: Must be represented in the :class:`ServiceInstance`\n * :code:`target_group_ids`: Must be represented in the :class:`ServiceInstance`\n \"\"\"\n \n def __init__(self, name, type_name):\n if not isinstance(name, basestring):\n raise ValueError('must set name (string)')\n if not isinstance(type_name, basestring):\n raise ValueError('must set type_name (string)')\n \n self.name = name\n self.type_name = type_name\n self.properties = StrictDict(key_class=basestring, value_class=Parameter)\n self.target_node_ids = StrictList(value_class=basestring)\n self.target_group_ids = StrictList(value_class=basestring)\n\n @property\n def as_raw(self):\n return OrderedDict((\n ('name', self.name),\n ('type_name', self.type_name),\n ('properties', as_raw_dict(self.properties)),\n ('target_node_ids', self.target_node_ids),\n ('target_group_ids', self.target_group_ids)))\n\n def validate(self, context):\n if context.modeling.policy_types.get_descendant(self.type_name) is None:\n context.validation.report('policy \"%s\" has an unknown type: %s' % (self.name, safe_repr(self.type_name)), level=Issue.BETWEEN_TYPES) \n\n validate_dict_values(context, self.properties)\n\n def coerce_values(self, context, container, report_issues):\n coerce_dict_values(context, container, self.properties, report_issues)\n\n def dump(self, context):\n puts('Policy: %s' % context.style.node(self.name))\n with context.style.indent:\n puts('Type: %s' % context.style.type(self.type_name))\n dump_parameters(context, self.properties)\n if self.target_node_ids:\n puts('Target nodes:')\n with context.style.indent:\n for node_id in self.target_node_ids:\n puts(context.style.node(node_id))\n if self.target_group_ids:\n puts('Target groups:')\n with context.style.indent:\n for group_id in self.target_group_ids:\n puts(context.style.node(group_id))\n\nclass GroupPolicy(Element):\n \"\"\"\n Policies applied to groups.\n\n Properties:\n \n * :code:`name`: Name\n * :code:`description`: Description\n * :code:`type_name`: Must be represented in the :class:`ModelingContext`\n * :code:`properties`: Dict of :class:`Parameter`\n * :code:`triggers`: Dict of :class:`GroupPolicyTrigger`\n \"\"\"\n \n def __init__(self, name, type_name):\n if not isinstance(name, basestring):\n raise ValueError('must set name (string)')\n if not isinstance(type_name, basestring):\n raise ValueError('must set type_name (string)')\n\n self.name = name\n self.description = None\n self.type_name = type_name\n self.properties = StrictDict(key_class=basestring, value_class=Parameter)\n self.triggers = StrictDict(key_class=basestring, value_class=GroupPolicyTrigger)\n\n @property\n def as_raw(self):\n return OrderedDict((\n ('name', self.name),\n ('description', self.description),\n ('type_name', self.type_name),\n ('properties', as_raw_dict(self.properties)),\n ('triggers', as_raw_list(self.triggers))))\n\n def validate(self, context):\n if context.modeling.policy_types.get_descendant(self.type_name) is None:\n context.validation.report('group policy \"%s\" has an unknown type: %s' % (self.name, safe_repr(self.type_name)), level=Issue.BETWEEN_TYPES) \n\n validate_dict_values(context, self.properties)\n validate_dict_values(context, self.triggers)\n\n def coerce_values(self, context, container, report_issues):\n coerce_dict_values(context, container, self.properties, report_issues)\n coerce_dict_values(context, container, self.triggers, report_issues)\n\n def dump(self, context):\n puts(context.style.node(self.name))\n if self.description:\n puts(context.style.meta(self.description))\n with context.style.indent:\n puts('Group policy type: %s' % context.style.type(self.type_name))\n dump_parameters(context, self.properties)\n dump_dict_values(context, self.triggers, 'Triggers')\n\nclass GroupPolicyTrigger(Element):\n \"\"\"\n Triggers for :class:`GroupPolicy`.\n\n Properties:\n \n * :code:`name`: Name\n * :code:`description`: Description\n * :code:`implementation`: Implementation string (interpreted by the orchestrator)\n * :code:`properties`: Dict of :class:`Parameter`\n \"\"\"\n \n def __init__(self, name, implementation):\n if not isinstance(name, basestring):\n raise ValueError('must set name (string)')\n if not isinstance(implementation, basestring):\n raise ValueError('must set implementation (string)')\n \n self.name = name\n self.description = None\n self.implementation = implementation\n self.properties = StrictDict(key_class=basestring, value_class=Parameter)\n\n @property\n def as_raw(self):\n return OrderedDict((\n ('name', self.name),\n ('description', self.description),\n ('implementation', self.implementation),\n ('properties', as_raw_dict(self.properties))))\n\n def validate(self, context):\n validate_dict_values(context, self.properties)\n\n def coerce_values(self, context, container, report_issues):\n coerce_dict_values(context, container, self.properties, report_issues)\n\n def dump(self, context):\n puts(context.style.node(self.name))\n if self.description:\n puts(context.style.meta(self.description))\n with context.style.indent:\n puts('Implementation: %s' % context.style.literal(self.implementation))\n dump_parameters(context, self.properties)\n\nclass Mapping(Element):\n \"\"\"\n An instance of a :class:`MappingTemplate`.\n \n Properties:\n \n * :code:`mapped_name`: Exposed capability or requirement name\n * :code:`node_id`: Must be represented in the :class:`ServiceInstance`\n * :code:`name`: Name of capability or requirement at the node\n \"\"\"\n \n def __init__(self, mapped_name, node_id, name):\n if not isinstance(mapped_name, basestring):\n raise ValueError('must set mapped_name (string)')\n if not isinstance(node_id, basestring):\n raise ValueError('must set node_id (string)')\n if not isinstance(name, basestring):\n raise ValueError('must set name (string)')\n\n self.mapped_name = mapped_name\n self.node_id = node_id\n self.name = name\n\n @property\n def as_raw(self):\n return OrderedDict((\n ('mapped_name', self.mapped_name),\n ('node_id', self.node_id),\n ('name', self.name)))\n\n def dump(self, context):\n puts('%s -> %s.%s' % (context.style.node(self.mapped_name), context.style.node(self.node_id), context.style.node(self.name)))\n\nclass Substitution(Element):\n \"\"\"\n An instance of a :class:`SubstitutionTemplate`.\n \n Properties:\n \n * :code:`node_type_name`: Must be represented in the :class:`ModelingContext`\n * :code:`capabilities`: Dict of :class:`Mapping`\n * :code:`requirements`: Dict of :class:`Mapping`\n \"\"\"\n \n def __init__(self, node_type_name):\n if not isinstance(node_type_name, basestring):\n raise ValueError('must set node_type_name (string)')\n \n self.node_type_name = node_type_name\n self.capabilities = StrictDict(key_class=basestring, value_class=Mapping)\n self.requirements = StrictDict(key_class=basestring, value_class=Mapping)\n\n @property\n def as_raw(self):\n return OrderedDict((\n ('node_type_name', self.node_type_name),\n ('capabilities', as_raw_list(self.capabilities)),\n ('requirements', as_raw_list(self.requirements))))\n\n def validate(self, context):\n if context.modeling.node_types.get_descendant(self.node_type_name) is None:\n context.validation.report('substitution \"%s\" has an unknown type: %s' % (self.name, safe_repr(self.node_type_name)), level=Issue.BETWEEN_TYPES) \n\n validate_dict_values(context, self.capabilities)\n validate_dict_values(context, self.requirements)\n\n def coerce_values(self, context, container, report_issues):\n coerce_dict_values(context, container, self.capabilities, report_issues)\n coerce_dict_values(context, container, self.requirements, report_issues)\n\n def dump(self, context):\n puts('Substitution:')\n with context.style.indent:\n puts('Node type: %s' % context.style.type(self.node_type_name))\n dump_dict_values(context, self.capabilities, 'Capability mappings')\n dump_dict_values(context, self.requirements, 'Requirement mappings')\n\nclass Interface(Element):\n \"\"\"\n A typed set of :class:`Operation`.\n \n Properties:\n \n * :code:`name`: Name\n * :code:`description`: Description\n * :code:`type_name`: Must be represented in the :class:`ModelingContext`\n * :code:`inputs`: Dict of :class:`Parameter`\n * :code:`operations`: Dict of :class:`Operation`\n \"\"\"\n \n def __init__(self, name, type_name):\n if not isinstance(name, basestring):\n raise ValueError('must set name (string)')\n \n self.name = name\n self.description = None\n self.type_name = type_name\n self.inputs = StrictDict(key_class=basestring, value_class=Parameter)\n self.operations = StrictDict(key_class=basestring, value_class=Operation)\n\n @property\n def as_raw(self):\n return OrderedDict((\n ('name', self.name),\n ('description', self.description),\n ('type_name', self.type_name),\n ('inputs', as_raw_dict(self.inputs)),\n ('operations', as_raw_list(self.operations))))\n\n def validate(self, context):\n if self.type_name:\n if context.modeling.interface_types.get_descendant(self.type_name) is None:\n context.validation.report('interface \"%s\" has an unknown type: %s' % (self.name, safe_repr(self.type_name)), level=Issue.BETWEEN_TYPES) \n\n validate_dict_values(context, self.inputs)\n validate_dict_values(context, self.operations)\n\n def coerce_values(self, context, container, report_issues):\n coerce_dict_values(context, container, self.inputs, report_issues)\n coerce_dict_values(context, container, self.operations, report_issues)\n \n def dump(self, context):\n puts(context.style.node(self.name))\n if self.description:\n puts(context.style.meta(self.description))\n with context.style.indent:\n puts('Interface type: %s' % context.style.type(self.type_name))\n dump_parameters(context, self.inputs, 'Inputs')\n dump_dict_values(context, self.operations, 'Operations')\n\nclass Operation(Element):\n \"\"\"\n An operation in a :class:`Interface`.\n \n Properties:\n \n * :code:`name`: Name\n * :code:`description`: Description\n * :code:`implementation`: Implementation string (interpreted by the orchestrator)\n * :code:`dependencies`: List of strings (interpreted by the orchestrator)\n * :code:`executor`: Executor string (interpreted by the orchestrator)\n * :code:`max_retries`: Maximum number of retries allowed in case of failure\n * :code:`retry_interval`: Interval between retries\n * :code:`inputs`: Dict of :class:`Parameter`\n \"\"\"\n \n def __init__(self, name):\n if not isinstance(name, basestring):\n raise ValueError('must set name (string)')\n \n self.name = name\n self.description = None\n self.implementation = None\n self.dependencies = StrictList(value_class=basestring)\n self.executor = None # Cloudify\n self.max_retries = None # Cloudify\n self.retry_interval = None # Cloudify\n self.inputs = StrictDict(key_class=basestring, value_class=Parameter)\n\n @property\n def as_raw(self):\n return OrderedDict((\n ('name', self.name),\n ('description', self.description),\n ('implementation', self.implementation),\n ('dependencies', self.dependencies),\n ('executor', self.executor),\n ('max_retries', self.max_retries),\n ('retry_interval', self.retry_interval),\n ('inputs', as_raw_dict(self.inputs))))\n\n def validate(self, context):\n validate_dict_values(context, self.inputs)\n\n def coerce_values(self, context, container, report_issues):\n coerce_dict_values(context, container, self.inputs, report_issues)\n\n def dump(self, context):\n puts(context.style.node(self.name))\n if self.description:\n puts(context.style.meta(self.description))\n with context.style.indent:\n if self.implementation is not None:\n puts('Implementation: %s' % context.style.literal(self.implementation))\n if self.dependencies:\n puts('Dependencies: %s' % ', '.join((str(context.style.literal(v)) for v in self.dependencies)))\n if self.executor is not None:\n puts('Executor: %s' % context.style.literal(self.executor))\n if self.max_retries is not None:\n puts('Max retries: %s' % context.style.literal(self.max_retries))\n if self.retry_interval is not None:\n puts('Retry interval: %s' % context.style.literal(self.retry_interval))\n dump_parameters(context, self.inputs, 'Inputs')\n","sub_path":"src/aria/aria/modeling/instance_elements.py","file_name":"instance_elements.py","file_ext":"py","file_size_in_byte":42533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"222698278","text":"from Dataset import *\nfrom Model import *\nfrom Settings import *\nimport sys\n\ndataset = POSDataset.create_dataset(path_to_data=args.data_path)\nmodel = POSTagger(embedding_size=args.char_embedding_size, \n num_embeddings=len(dataset.vectorizer.word_vocab),\n num_classes=len(dataset.vectorizer.tag_vocab),\n hidden_size=args.rnn_hidden_size,\n padding_idx=dataset.vectorizer.word_vocab.mask_index,\n dropout_rate=args.dropout_rate)\n\ndef predict(sentence, model, vectorizer):\n checkpoint = torch.load(args.model_state_file)\n model.load_state_dict(checkpoint)\n \n words = sentence.rstrip('\\n').split(' ')\n vectorized_sentence, vec_length = vectorizer.vectorize_sentence(words)\n vectorized_sentence = torch.tensor(vectorized_sentence).unsqueeze(dim=0)\n\n result = model(vectorized_sentence, apply_softmax=True)\n \n pred_values, pred_ind = torch.max(result, dim=2)\n indices = pred_ind[0][1:-1]\n tokens = []\n for ind in indices:\n tokens.append(vectorizer.tag_vocab.find_token(ind.item()))\n \n print(words)\n print(tokens)\n\nif __name__ == '__main__':\n predict(sys.argv[1], model, dataset.vectorizer)\n","sub_path":"Python Project/Predict.py","file_name":"Predict.py","file_ext":"py","file_size_in_byte":1288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"2257790","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat May 18 11:54:28 2019\n\n@author: yolandatiao\n\"\"\"\n\n#################### Networkx pagerank ####################\n# Author: Huitian (Yolanda) Diao\n# May 17th, 2019\n\n#################### Import ####################\nimport networkx as nx\nimport os\nimport csv\nfrom astropy.io import ascii\nfrom astropy.table import Table, join, vstack\nimport math\n\n#################### Self-defined functions ####################\ndef prune_tree(inTab, pruneN):\n print(\"Table row number: %s\" %len(inTab))\n source_list = list(inTab[\"gene1\"])\n tgt_list = list(inTab[\"gene2\"])\n total_list = source_list + tgt_list\n source_list_app = [total_list.count(i) for i in source_list]\n tgt_list_app = [total_list.count(i) for i in tgt_list]\n \n del_rows = [index for index, x in enumerate(source_list_app) if x <= pruneN]\n del_rows = del_rows + [index for index, x in enumerate(tgt_list_app) if x <= pruneN]\n inTab.remove_rows(del_rows)\n print(\"Pruned table row number: %s\" %len(inTab))\n return(inTab)\n\ndef pageRankProtein(inFile, outFile, sCol, tCol, swCol, twCol):\n #inFile = \"/Volumes/Yolanda/CRF_Screen/InVivo/2_Protein/PageRank/Biogrid-interaction_CRF-ProteinAbundance_fltself.csv\"\n #outFile = \"protein_pr_0h.csv\"\n #sCol = \"gene1\"\n #tCol = \"gene2\"\n #swCol = \"0h_1\"\n #twCol = \"0h_2\"\n \n in_tab = ascii.read(inFile)\n source_list = list(in_tab[sCol])\n target_list = list(in_tab[tCol])\n source_wt_list = list(in_tab[swCol])\n target_wt_list = list(in_tab[twCol])\n \n source_wt_list = [(x**(1/2)) for x in source_wt_list]\n target_wt_list = [(x**(1/2)) for x in target_wt_list]\n source_and_wt = [\"%s::%s\"%(x, str(y)) for index, (x,y) in enumerate(zip(source_list, source_wt_list))]\n target_and_wt = [\"%s::%s\"%(x, str(y)) for index, (x,y) in enumerate(zip(target_list, target_wt_list))]\n name_wt_list = list(set(source_and_wt + target_and_wt))\n p_dict = {}\n for i in name_wt_list:\n p_dict[i.split(\"::\")[0]] = float(i.split(\"::\")[1]) \n \n DG = nx.DiGraph()\n for x in range(0, len(in_tab)):\n s_x = source_list[x]\n t_x = target_list[x]\n #sw_x = source_wt_list[x]\n #tw_x = target_wt_list[x]\n DG.add_edges_from([(s_x, t_x), (t_x, s_x)])\n \n pr = nx.pagerank(DG, personalization=p_dict, max_iter=10000)\n with open(outFile, \"w\") as fout:\n wfout = csv.writer(fout, delimiter=\",\")\n wfout.writerow([\"gene_name\", \"PageRankScore\"])\n for key, val in pr.items():\n wfout.writerow([key,val])\n \n\n#################### Main ####################\nwk_dir = \"/Volumes/Yolanda/CRF_Screen/InVivo/2_Protein/PageRank\"\nos.chdir(wk_dir)\n\n\n###----- PageRank\nin_file = \"/Volumes/Yolanda/CRF_Screen/InVivo/2_Protein/PageRank/Biogrid-interaction_CRF-ProteinAbundance_fltself.csv\"\n\nout_file = \"protein_pr_0h.csv\"\nsource_col = \"gene1\"\ntarget_col = \"gene2\"\nsource_weight = \"0h_1\"\ntarget_weight = \"0h_2\"\npageRankProtein(in_file, out_file, source_col, target_col, source_weight, target_weight)\n\nout_file = \"protein_pr_16h.csv\"\nsource_col = \"gene1\"\ntarget_col = \"gene2\"\nsource_weight = \"16h_1\"\ntarget_weight = \"16h_2\"\npageRankProtein(in_file, out_file, source_col, target_col, source_weight, target_weight)\n","sub_path":"0.1_Codes_Invivo/2_4_networkx_pagerank.py","file_name":"2_4_networkx_pagerank.py","file_ext":"py","file_size_in_byte":3281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"552393837","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@author: JulienWuthrich\n\"\"\"\nimport math\nimport glob\n\nfrom PIL import Image\nimport matplotlib.pyplot as plt\n\nimport numpy as np\n\nimport tensorflow as tf\n\n\nclass DCGan(object):\n \"\"\"Deep Convolutional Generative Adversarial Networks.\"\"\"\n\n def __init__(self, data_paths, batch_size=32, width=28, height=28, channels=3, beta1=.4, z_dim=100, alpha=.01, learning_rate=.005, mode='RGB', n_images=5):\n \"\"\"Init.\n\n :param width: (int) input image width\n :param height: (int) input image height\n :param channels: (int) number of channels\n :param beta1: (float) exponential decay rate for the 1st moment in the optimizer\n :param z_dim: (int) z dimension\n :param alpha: (float) factor for the leaky relu\n :param learning_rate: (float) factor to control how much we are adjusting weights due to the loss\n :param mode: (str) how to read picture ('RGB', 'L')\n :param n_images: (int) number of images to display\n :param data_paths: (list) all images path\n :param batch_size: (int) batch size\n \"\"\"\n self.width = width\n self.height = height\n self.channels = channels\n self.beta1 = beta1\n self.z_dim = z_dim\n self.alpha = alpha\n self.learning_rate = learning_rate\n self.mode = mode\n self.n_images = n_images\n self.data_paths = glob.glob(data_paths + \"*\")\n print(\"there are \", len(self. data_paths), \"files\")\n self.batch_size = batch_size\n self.out_shape = 4 * 4 * 256\n self.in_shape = 1 * 1 * 64\n\n def model_inputs(self):\n \"\"\"Create model inputs.\n\n :return: (tuple) tensor of real input images, tensor of z data, learning rate\n \"\"\"\n # placeholder is simply a variable that we will assign data to at a later date\n input_real = tf.placeholder(dtype=tf.float32, shape=[None, self.width, self.height, self.channels], name=\"input_real\")\n input_z = tf.placeholder(dtype=tf.float32, shape=[None, self.z_dim], name=\"input_z\")\n learning_rate = tf.placeholder(dtype=tf.float32, shape=None, name=\"learning_rate\")\n\n return input_real, input_z, learning_rate\n\n def discriminator(self, images, reuse=False):\n \"\"\"Model to check if the images is a real one or a fake.\n logits: vector of raw (non-normalized) predictions that a classification model generates\n out: prediction of the model\n\n :param images: (tensor) images\n :param reuse: (boolean) reuse the weights or not\n :return: (tuple) tensor out of the discriminator, tensor logits of the discriminator\n \"\"\"\n init = tf.contrib.layers.xavier_initializer()\n with tf.variable_scope(name_or_scope=\"discriminator\", reuse=reuse):\n # Block 1 featuring\n conv1 = tf.layers.conv2d(inputs=images, filters=64, kernel_size=5, strides=2, padding=\"same\", kernel_initializer=init)\n relu1 = tf.maximum(conv1 * self.alpha, conv1)\n\n # Block 2 featuring\n conv2 = tf.layers.conv2d(inputs=relu1, filters=128, kernel_size=5, strides=2, padding=\"same\", kernel_initializer=init)\n # Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift\n bn2 = tf.layers.batch_normalization(inputs=conv2, training=True)\n relu2 = tf.maximum(bn2 * self.alpha, bn2)\n drop2 = tf.nn.dropout(x=relu2, keep_prob=.8)\n\n # Block 3 featuring\n conv3 = tf.layers.conv2d(inputs=drop2, filters=256, kernel_size=5, strides=2, padding=\"same\", kernel_initializer=init)\n bn3 = tf.layers.batch_normalization(inputs=conv3, training=True)\n relu3 = tf.maximum(bn3 * self.alpha, bn3)\n drop3 = tf.nn.dropout(x=relu3, keep_prob=.8)\n\n # Last Block prediction\n shape = (-1, self.out_shape)\n flat = tf.reshape(tensor=drop3, shape=shape)\n logits = tf.layers.dense(inputs=flat, units=1) # units: dimensionality of the output space.\n out = tf.sigmoid(logits)\n\n return logits, out\n\n def generator(self, input_z, out_channel_dim, is_train=True):\n \"\"\"The goal of the generator is to generate passable hand-written digits, to lie without being caught.\n\n :param input_z: (tf.placeholder) input\n :param is_train: (boolean) use generator for the training\n :param out_channel_dim: (int) number of channel in output (data.shape[3])\n :return: (tensor) output of the generator\n \"\"\"\n reuse = not is_train\n init = tf.contrib.layers.xavier_initializer()\n with tf.variable_scope(name_or_scope=\"generator\", reuse=reuse):\n # Block 1 featuring\n dense1 = tf.layers.dense(inputs=input_z, units=self.out_shape)\n dense1 = tf.reshape(tensor=dense1, shape=(-1, 4, 4, 512))\n bn1 = tf.layers.batch_normalization(inputs=dense1, training=is_train)\n relu1 = tf.maximum(bn1 * self.alpha, bn1)\n\n # Block 2 featuring\n # conv2d_transpose: transform something that has the shape of the output of some convolution to something that has the shape of its input\n conv2_transpose = tf.layers.conv2d_transpose(inputs=relu1, filters=256, kernel_size=5, strides=2, padding=\"same\", kernel_initializer=init)\n bn2 = tf.layers.batch_normalization(inputs=conv2_transpose, training=is_train)\n relu2 = tf.maximum(bn2 * self.alpha, bn2)\n drop2 = tf.nn.dropout(x=relu2, keep_prob=.8)\n\n # Block 3 featuring\n conv3_transpose = tf.layers.conv2d_transpose(inputs=drop2, filters=128, kernel_size=5, strides=2, padding=\"same\", kernel_initializer=init)\n bn3 = tf.layers.batch_normalization(inputs=conv3_transpose, training=is_train)\n relu3 = tf.maximum(bn3 * self.alpha, bn3)\n drop3 = tf.nn.dropout(x=relu3, keep_prob=.8)\n\n # Last Block prediction\n logits = tf.layers.conv2d_transpose(inputs=drop3, filters=out_channel_dim, kernel_size=5, strides=1, padding=\"same\")\n out = tf.tanh(logits)\n\n return out\n\n @staticmethod\n def loss_function(z, x):\n \"\"\"Measures the probability error in discrete classification tasks\n in which each class is independent and not mutually exclusive.\n For instance, one could perform multilabels classification where\n a picture can contain both an elephant and a dog at the same time.\n\n :param z: labels\n :param x: logits\n :return: z * -log(sigmoid(x)) + (1 - z) * -log(1 - sigmoid(x))\n \"\"\"\n return tf.nn.sigmoid_cross_entropy_with_logits(logits=x, labels=z)\n\n def compute_loss(self, input_real, input_z, out_channel_dim):\n \"\"\"Loss function for the discriminator and the generator.\n\n :param input_real: (tf.placeholder) real picture from dataset\n :param input_z: (tf.placeholder) inout z\n :param out_channel_dim: (int) number of channel in output (data.shape[3])\n :return: (tuple) discriminator loss, generator loss\n \"\"\"\n gen = self.generator(input_z=input_z, out_channel_dim=out_channel_dim)\n disc_out_real, disc_logits_real = self.discriminator(images=input_real, reuse=False)\n disc_out_fake, disc_logits_fake = self.discriminator(images=gen, reuse=True)\n\n # measure the error\n # here wer use ones_like, cause the generated images, should be detect as real\n real_loss = self.loss_function(z=disc_out_real, x=tf.ones_like(tensor=disc_logits_real) * self.alpha)\n # here wer use zeros_like, cause the generated images, should be detect as fake\n fake_loss = self.loss_function(z=disc_out_fake, x=tf.zeros_like(tensor=disc_logits_fake) * self.alpha)\n # here wer use ones_like, cause this is real images\n gen_loss = self.loss_function(z=disc_out_fake, x=tf.ones_like(tensor=disc_logits_fake) * self.alpha)\n\n # tf.reduce_mean: Computes the mean of elements across dimensions of a tensor\n disc_loss_real = tf.reduce_mean(real_loss)\n disc_loss_fake = tf.reduce_mean(fake_loss)\n gen_loss = tf.reduce_mean(gen_loss)\n\n return gen_loss, sum([disc_loss_real, disc_loss_fake])\n\n def optimization(self, disc_loss, gen_loss):\n \"\"\"Optimize the loss.\n\n :param disc_loss: (tensor) discriminator loss\n :param gen_loss: (tensor) generator loss\n :return: (tuple) discriminator training operation, generator training operation\n \"\"\"\n tf_vars = tf.trainable_variables()\n disc_var = [var for var in tf_vars if var.name.startswith('discriminator')]\n gen_var = [var for var in tf_vars if var.name.startswith('generator')]\n\n operations = tf.get_collection(key=tf.GraphKeys.UPDATE_OPS)\n # control_dependencies: list of Operation or Tensor objects which must be executed or computed\n # before running the operations defined in the context\n with tf.control_dependencies(control_inputs=operations):\n disc_opt = tf.train.AdamOptimizer(learning_rate=self.learning_rate, beta1=self.beta1)\n disc_opt = disc_opt.minimize(loss=disc_loss, var_list=disc_var)\n gen_opt = tf.train.AdamOptimizer(learning_rate=self.learning_rate, beta1=self.beta1)\n gen_opt = gen_opt.minimize(loss=gen_loss, var_list=gen_var)\n\n return disc_opt, gen_opt\n\n def show_generator_output(self, sess, input_z):\n \"\"\"Show example output for the generator\n\n :param sess: (tf.session) tensorFlow session\n :param input_z: (tensor) input z\n \"\"\"\n cmap = None if self.mode == 'RGB' else 'gray'\n z_dim = input_z.get_shape().as_list()[-1]\n example_z = np.random.uniform(-1, 1, size=[self.n_images, z_dim])\n\n samples = sess.run(\n self.generator(input_z=input_z, out_channel_dim=self.channels, is_train=False),\n feed_dict={input_z: example_z}\n )\n\n images_grid = plot_images(samples, self.mode)\n plt.imshow(images_grid, cmap=cmap)\n plt.show()\n\n def get_batches(self):\n \"\"\"Generate batches.\n\n :return: (np.array) batches of data\n \"\"\"\n max_value = 255\n current_index = 0\n\n while current_index + self.batch_size <= len(self.data_paths):\n data_batch = get_images(\n self.data_paths[current_index:current_index + self.batch_size],\n self.width, self.height, self.mode\n )\n current_index += self.batch_size\n\n yield data_batch / max_value - 0.5\n\n @staticmethod\n def show_progression(epoch, epochs, steps, loss_disc, loss_gen):\n \"\"\"Show progression of the gan.\n\n :param epoch: (int) current epoch\n :param epochs: (int) max epochs\n :param steps: (int) which batch step\n :param loss_disc: (float) disc loss\n :param loss_gen: (float) gen loss\n \"\"\"\n print(\n \"Epoch {}/{}... \\n\".format(epoch + 1, epochs),\n \"Batch {}... \\n\".format(steps),\n \"Discriminator loss {}... \\n\".format(loss_disc),\n \"Generator loss {}... \\n\".format(loss_gen)\n )\n\n def train(self, epochs):\n \"\"\"Train the DCGan.\n\n :param epochs: (int) number of epochs\n :return: (tuple) list of discriminator loss, list of generator loss\n \"\"\"\n input_real, input_z, lr = self.model_inputs()\n disc_loss, gen_loss = self.compute_loss(input_real=input_real, input_z=input_z, out_channel_dim=self.channels)\n disc_opt, gen_opt = self.optimization(disc_loss=disc_loss, gen_loss=gen_loss)\n ldisc_loss, lgen_loss = list(), list()\n\n with tf.Session() as sess:\n sess.run(fetches=tf.global_variables_initializer())\n for epoch in range(epochs):\n steps = 0\n for batch in self.get_batches():\n steps += 1\n batch *= 2\n rdm_batch = np.random.uniform(low=-1, high=1, size=(self.batch_size, self.z_dim))\n # feed_dict = {input_real: batch, input_z: rdm_batch, lr: self.learning_rate}\n _ = sess.run(fetches=disc_opt, feed_dict={input_real: batch, input_z: rdm_batch, lr: self.learning_rate})\n _ = sess.run(fetches=gen_opt, feed_dict={input_real: batch, input_z: rdm_batch, lr: self.learning_rate})\n\n loss_disc = disc_loss.eval({input_real: batch, input_z: rdm_batch})\n loss_gen = gen_loss.eval({input_z: rdm_batch})\n\n ldisc_loss.append(loss_disc)\n lgen_loss.append(loss_gen)\n\n # show the gan progression\n if steps % 20 == 0:\n self.show_progression(epoch, epochs, steps, loss_disc, loss_gen)\n # plot some generated images\n if steps % 5 == 0:\n self.show_generator_output(sess, input_z)\n\n return ldisc_loss, lgen_loss\n\n\ndef read_image(path, width, height, mode=\"RGB\"):\n \"\"\"Read image as a numpy array.\n\n :param path: (str) path of the image\n :param width: (int) new width size\n :param height: (int) new height size\n :param mode: (str) 'RGB' or 'L' image in color or gray\n :return: (np.array) image as np.array\n \"\"\"\n image = Image.open(path)\n image = image.resize([width, height], Image.BILINEAR)\n\n return np.array(image.convert(mode))\n\n\ndef get_images(paths, width, height, mode=\"RGB\"):\n \"\"\"Read all images and store them into a numpy array.\n\n :param paths: (list) image_path\n :param width: (int) new width size\n :param height: (int) new height size\n :param mode: (str) 'RGB' or 'L' image in color or gray\n :return: (np.array) array of images\n \"\"\"\n images = [read_image(path, width, height, mode) for path in paths]\n images = np.array(images).astype(np.float32)\n # Be sure the images are in 4 dimensions\n if len(images.shape) < 4:\n images = images.reshape(images.shape + (1, ))\n\n return images\n\n\ndef plot_images(images, mode=\"RGB\"):\n \"\"\"Show the images in a square grid.\n\n :param images: (np.array) images to show in the grid\n :param mode: (str) 'RGB' or 'L' image in color or gray\n :return: (grid) grid square of images\n \"\"\"\n # Maximal size of the grid square\n max_size = math.floor(np.sqrt(images.shape[0]))\n # Scale images\n images_scaled = ((images - images.min()) * 255) / (images.max() - images.min())\n images_scaled = images_scaled.astype(np.uint8)\n # Arrange images in the grid\n a = images_scaled[:max_size * max_size]\n new_shape = (max_size, max_size, *images_scaled.shape[:3])\n images_squared = np.reshape(a, new_shape)\n # Remove single-dimensional entries from the shape of an array\n if mode == 'L':\n images_squared = np.squeeze(images_squared, 4)\n # Combine image into the grid\n size = (images[1] * max_size, images.shape[2] * max_size)\n grid = Image.new(mode, size)\n for col_i, col_images in enumerate(images_squared):\n for image_i, image in enumerate(col_images):\n img = Image.fromarray(image, mode)\n box = (col_i * images.shape[1], image_i * images.shape[2])\n grid.paste(img, box)\n\n return grid\n\n\nif __name__ == '__main__':\n gan = DCGan(data_paths=\"../../../../data/raw/dcgan/\")\n with tf.Graph().as_default():\n disc_loss, gen_loss = gan.train(epochs=100)\n","sub_path":"deep/computer_vision/DCGan/core/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":15537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"84205027","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport unittest\n\nfrom hwt.hdl.constants import Time\nfrom hwt.hdl.operatorDefs import AllOps\nfrom hwt.serializer.resourceAnalyzer.analyzer import ResourceAnalyzer\nfrom hwt.serializer.resourceAnalyzer.resourceTypes import ResourceMUX, \\\n ResourceFF\nfrom hwt.simulator.simTestCase import SimTestCase\nfrom hwt.synthesizer.utils import toRtl\nfrom hwtLib.examples.arithmetic.cntr import Cntr\n\n\nclass CntrTC(SimTestCase):\n def setUp(self):\n super(CntrTC, self).setUp()\n self.u = Cntr()\n self.prepareUnit(self.u)\n\n def test_overflow(self):\n u = self.u\n\n u.en._ag.data.append(1)\n self.runSim(90 * Time.ns)\n self.assertValSequenceEqual(u.val._ag.data,\n [0, 1, 2, 3, 0, 1, 2, 3])\n\n def test_contingWithStops(self):\n u = self.u\n\n u.en._ag.data.extend([1, 0, 1, 1, 0, 0, 0])\n self.runSim(90 * Time.ns)\n self.assertValSequenceEqual(u.val._ag.data,\n [0, 1, 1, 2, 3, 3, 3, 3])\n\n def test_resources_2b(self):\n u = Cntr()\n\n expected = {(AllOps.ADD, 2): 1,\n # 1 for reset, one for en\n (ResourceMUX, 2, 2): 2,\n ResourceFF: 2}\n\n s = ResourceAnalyzer()\n toRtl(u, serializer=s)\n r = s.report()\n self.assertDictEqual(r, expected)\n\n def test_resources_150b(self):\n u = Cntr()\n u.DATA_WIDTH.set(150)\n\n expected = {(AllOps.ADD, 150): 1,\n # 1 for reset, one for en\n (ResourceMUX, 150, 2): 2,\n ResourceFF: 150}\n\n s = ResourceAnalyzer()\n toRtl(u, serializer=s)\n r = s.report()\n self.assertDictEqual(r, expected)\n\n\nif __name__ == \"__main__\":\n suite = unittest.TestSuite()\n # suite.addTest(CntrTC('test_resources_150b'))\n suite.addTest(unittest.makeSuite(CntrTC))\n runner = unittest.TextTestRunner(verbosity=3)\n runner.run(suite)\n","sub_path":"hwtLib/examples/arithmetic/cntr_test.py","file_name":"cntr_test.py","file_ext":"py","file_size_in_byte":2031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"25406514","text":"#Calendar Final Version (Python 3.x)\r\n#Adam Suleman\r\n\r\nfrom datetime import datetime\r\nfrom time import strftime, sleep\r\n\r\n#main function, displays menu\r\ndef chooseFunction():\r\n while True:\r\n try:\r\n sleep(2)\r\n print(\"\\ni. Import entries from a file (will delete existing entries)\\nv. View all entries\\na. Add a new entry\\ne. Edit existing entries\\ns. Save entries to a file\")\r\n choice = input(\"Choose a character from above: \").strip().lower()\r\n if choice == \"i\":\r\n importFromFile() \r\n elif choice == \"v\":\r\n viewAllEntries()\r\n elif choice == \"a\":\r\n add()\r\n elif choice == \"e\":\r\n edit()\r\n elif choice == \"s\":\r\n saveToFile()\r\n else:\r\n pass\r\n except ValueError:\r\n pass\r\n\r\n#function to obtain date:\r\n#validates date to exist before accepting, loops until correct input received\r\ndef getDate():\r\n while True:\r\n try:\r\n dateInput = input(\"\\nPlease input a date (dd/mm/yyyy):\\n\")\r\n date = validateDate(dateInput)\r\n return(date)\r\n except ValueError:\r\n print(\"Invalid date, please try again\")\r\n\r\n#function which validates a given date\r\n#year must be four digits long, and the datetime module must be able to verify the date exists\r\ndef validateDate(dateInput):\r\n dd, mm, yyyy = dateInput.split(\"/\")\r\n if len(str(int(yyyy))) != 4:\r\n raise ValueError\r\n date = datetime(int(yyyy), int(mm), int(dd))\r\n return(date)\r\n\r\n#general function to get a string from the user (i.e. diary entry)\r\ndef getString(prompt):\r\n while True:\r\n stringInput = input(prompt).strip()\r\n if len(stringInput) != 0:\r\n return(stringInput)\r\n\r\n#display all entries to user\r\ndef viewAllEntries():\r\n print()\r\n for pair in entryList:\r\n date = pair[0]\r\n entry = pair[1]\r\n viewEntry(date, entry)\r\n\r\n#function to display an entry\r\n#string format function is used to display date objects as readable dates\r\ndef viewEntry(date, entry):\r\n print(date.strftime(\"\\n%d/%m/%Y:\\n\") + entry)\r\n\r\n#add function:\r\ndef add():\r\n date = getDate()\r\n entry = getString(\"\\nPlease input an entry:\\n\")\r\n addEntry(date, entry)\r\n\r\ndef addEntry(date, entry):\r\n\r\n #check if date entered by user is already in diary\r\n index = searchEntriesForDate(date)\r\n \r\n #if date is not in diary, create new entry\r\n if index is None: \r\n entryList.append([date,entry])\r\n entryList.sort()\r\n \r\n #if date already exists, append to the old entry\r\n else:\r\n oldEntry = entryList[index][1]\r\n entryList[index][1] = oldEntry + \";\" + entry\r\n\r\n#check if a date already exists in diary, return entry's index within entryList\r\ndef searchEntriesForDate(inputDate):\r\n for index, pair in enumerate(entryList):\r\n date = pair[0]\r\n if inputDate == date:\r\n return(index)\r\n return(None)\r\n\r\n#edit function:\r\n#allows user to edit an existing entry by date\r\ndef edit():\r\n inputDate = getDate()\r\n index = searchEntriesForDate(inputDate)\r\n\r\n #if no such entry for given date, alert user\r\n if index is None:\r\n print(\"Date not found in diary\")\r\n\r\n #if entry exists for given date, obtain previous date and entry from entryList:\r\n #display to previous entry to user and ask for a new entry to replace it\r\n else:\r\n pair = entryList[index]\r\n date = pair[0]\r\n entry = pair[1]\r\n viewEntry(date, entry)\r\n newEntry = getString(\"\\nPlease input a new entry for this date:\\n\")\r\n entryList[index][1] = newEntry\r\n viewAllEntries()\r\n\r\n#import function:\r\ndef importFromFile():\r\n\r\n #ask user for filename, store all lines from file in 'lines' list\r\n while True:\r\n try:\r\n filename = input(\"\\nEnter filename with extension:\\n\")\r\n with open(filename, 'r') as file:\r\n lines = file.readlines()\r\n break\r\n except FileNotFoundError:\r\n print(\"File does not exist\")\r\n\r\n #clear previous diary\r\n entryList.clear()\r\n\r\n #attempt to split each line at commas: (date,entry)\r\n #validate date and entry for each line:\r\n #if format is incorrect the line is skipped and not added to diary\r\n for line in lines:\r\n try:\r\n values = line.split(\",\")\r\n dateInput = values[0].strip()\r\n date = validateDate(dateInput)\r\n entry = values[1].strip()\r\n addEntry(date,entry)\r\n except ValueError:\r\n continue\r\n except IndexError:\r\n continue\r\n \r\n viewAllEntries()\r\n\r\n#save function:\r\n#ask user for output filename, write all values in entryList to this file\r\ndef saveToFile():\r\n filename = getString(\"\\nPlease input filename to save as:\\n\") + \".txt\"\r\n with open(filename, 'w') as file:\r\n for pair in entryList:\r\n date = pair[0]\r\n entry = pair[1]\r\n file.write(date.strftime(\"%d/%m/%Y\") + \",\" + entry + \"\\n\")\r\n\r\ndef main():\r\n chooseFunction()\r\n\r\n#create empty entryList which stores date, entry pairs in sublists\r\nentryList = []\r\nmain()\r\n","sub_path":"Calendar Final - Adam Suleman.py","file_name":"Calendar Final - Adam Suleman.py","file_ext":"py","file_size_in_byte":5291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"534680277","text":"import lzw\nimport argparse\n\ndef main():\n parser = argparse.ArgumentParser(description = 'Compress and decompress text files')\n parser.add_argument('-cf', type = str, help = 'Compress file, provide file path')\n parser.add_argument('-cs', type = str, help = 'Compress given string')\n parser.add_argument('-d', type = str, help = 'Decompress given file')\n parser.add_argument('--dictionary', type = str, help = 'Dictionary path for decompression')\n\n args = parser.parse_args()\n\n compress = lzw.Compress()\n\n if args.cf:\n compress.compress_file(args.cf)\n elif args.cs:\n compress.compress_str(args.cs)\n elif args.d:\n if args.dictionary:\n compress.decompress(args.d, args.dictionary)\n else:\n print('Please provide a dictionary')\n \n\nif __name__ == \"__main__\": main()\n","sub_path":"lzw/compress.py","file_name":"compress.py","file_ext":"py","file_size_in_byte":842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"384889604","text":"import os\nimport sys\nsys.path.append(os.path.join(os.path.dirname(__file__), '..'))\nsys.path.append(os.path.join(os.path.dirname(__file__), '../../'))\nimport random\nfrom common.logger import set_logger\nimport pandas as pd\nimport re\nimport time\nimport requests\nfrom bs4 import BeautifulSoup\nimport re\nimport urllib.parse\nfrom common.operation_csv import *\nlogger = set_logger(__name__)\n\n\n\n\ndef fetch_yamada_data(model_number_list):\n ua = \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6)\" \\\n \"AppleWebKit/537.36 (KHTML, like Gecko)\" \\\n \"Chrome/96.0.4664.45\"\n yamada_item_data = []\n for model_number in model_number_list:\n print(model_number)\n # 商品ページへ遷移\n if model_number != 'None':\n try:\n model_number = urllib.parse.quote(model_number)\n yamada_url = f'https://www.yamada-denkiweb.com/search/{model_number}/?path=&searchbox=1'\n res = requests.get(yamada_url,headers={\"User-Agent\": ua})\n time.sleep(2)\n soup = BeautifulSoup(res.content, \"html.parser\")\n name = soup.select(\"p.item-name\")[0].text\n price_elem = soup.select(\"p.subject-text\")[0].text\n price = re.sub(r'\\D', '', price_elem) \n url = soup.select(\"p.item-name > a\")[0].get('href')\n except Exception as e:\n logger.info(e)\n name = 'None'\n price = 999999\n url = 'None'\n else:\n name = 'None'\n price = 999999\n url = 'None'\n yamada_item_data.append([name,price,url]) \n \n return yamada_item_data\n\n\nif __name__ == \"__main__\":\n model_number_list = load_item_name()\n fetch_yamada_data(model_number_list)","sub_path":"engine/yamada.py","file_name":"yamada.py","file_ext":"py","file_size_in_byte":1790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"298497085","text":"from setuptools import find_packages, setup\n\nfrom rts import __version__\n\n\nEXCLUDE_FROM_PACKAGES = []\n\nsetup(\n name='django-rts',\n version=__version__,\n url='http://www.djangoproject.com/',\n author='Jos van Velzen',\n author_email='jos.vanvelzen@changer.nl',\n description=('A django app that provides building blocks to receive requests, transform data and send '\n 'the response .'),\n license='BSD',\n packages=find_packages(exclude=EXCLUDE_FROM_PACKAGES),\n include_package_data=True,\n classifiers=[\n 'Development Status :: 2 - Pre-Alpha',\n 'Environment :: Web Environment',\n 'Framework :: Django',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: BSD License',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.4',\n 'Topic :: Internet :: WWW/HTTP',\n 'Topic :: Internet :: WWW/HTTP :: Dynamic Content',\n 'Topic :: Internet :: WWW/HTTP :: WSGI',\n 'Topic :: Software Development :: Libraries :: Application Frameworks',\n 'Topic :: Software Development :: Libraries :: Python Modules',\n ],\n)\n","sub_path":"pypi_install_script/django-rts-0.1.1.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"186220031","text":"from bs4 import BeautifulSoup\n \nf=open('/home/cesargasca/Desktop/19-1/PLN/Corpus/e960401.htm', encoding='latin-1') #abre archivo html\nt=f.read() #lee de archivo\nf.close() #cierra archivo\n \nsoup = BeautifulSoup(t, 'lxml') #procesa texto\ntS = soup.get_text() #guarda texto en string -> sin etiquetas html\ntS = tS.replace('\\x97', ' ') #quita caracter especial\n \n#print(tS)\n \nf=open('/home/cesargasca/Desktop/test.txt', 'w') #abre archivo \nf.write(tS) #escribe en archivo\nf.close() #cierra archivo","sub_path":"Olga/SantoGrial/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"369937732","text":"from telegram.ext import Updater, CommandHandler, MessageHandler, Filters\nfrom .log import logger\nfrom .config import Config\n\nimport datetime\nimport pandas as pd\n\nfrom . import get_weather, \\\n db_tg\n\n\ndef university_schedule(updater, context):\n # try:\n schedule_df = pd.read_csv(\"schedule.csv\")\n schedule_request = schedule_df[schedule_df['Weekday'].isin([updater.message.text])]\n if not schedule_request.empty:\n db_tg.action2db(updater['message']['chat']['id'], updater['message']['chat']['username'], \"schedule\")\n updater.message.reply_text(f\"Here you are:\\n{schedule_request.to_string(index=False)}\\n\")\n if schedule_df.loc[datetime.datetime.today().weekday()][1] == updater.message.text:\n updater.message.reply_text(get_weather.get_weather())\n else:\n db_tg.action2db(updater['message']['chat']['id'], updater['message']['chat']['username'], \"invalid\")\n updater.message.reply_text(\"Invalid value.\")\n\n # except (FileNotFoundError, TypeError):\n # updater.message.reply_text(\"Can't find schedule. Sorry!\")\n\n\ndef start(updater, message):\n updater.message.reply_text('Hi! Bring some information about my commands by /help')\n db_tg.action2db(updater['message']['chat']['id'], updater['message']['chat']['username'], \"start\")\n\n\ndef command_help(updater, context):\n updater.message.reply_text(\"You can check my schedule for a different days. Type a week day\"\n \" and I will take you schedule for this one.\\nFor example: Monday\\n\"\n \"If you wanna know schedule for today I will send you weather as a bonus :)\"\n \"Use /remind to create new date event (date format: DD.MM.YYYY).\")\n db_tg.action2db(updater['message']['chat']['id'], updater['message']['chat']['username'], \"help\")\n\n\n# def command_remind(updater, context):\n# db_tg.action2db(updater['message']['chat']['id'], updater['message']['chat']['username'], \"remind\")\n# try:\n# message_text = updater.message.text[7:]\n# date = re.findall('(0[1-9]|[12][0-9]|3[01])[.](0[1-9]|1[012])[.](19\\d\\d|20\\d\\d)', message_text)[0]\n# message_text = message_text.replace(\".\".join(date), '')\n# if len(date) == 3:\n# user_event_handler.events_list.append((date, message_text))\n# schedule.every(5).seconds.do(user_event_handler.events_check, updater, context)\n# updater.message.reply_text(\"Ok!\")\n# else:\n# updater.message.reply_text(\"Invalid date.\")\n# except IndexError:\n# updater.message.reply_text(\"Invalid event.\")\n\n# def echo(updater, context):\n# updater.message.reply_text(updater.message.text)\n\n\ndef main():\n db_tg.db_table_create()\n\n Config.read_opts()\n updater = Updater(token=Config.TOKEN, use_context=True)\n dp = updater.dispatcher\n\n dp.add_handler(CommandHandler(\"start\", start))\n dp.add_handler(CommandHandler(\"help\", command_help))\n # dp.add_handler(CommandHandler(\"remind\", command_remind))\n dp.add_handler(MessageHandler(Filters.text, university_schedule))\n # dp.add_handler(MessageHandler(Filters.text & ~Filters.command, echo))\n updater.start_polling()\n\n # schedule_thread = Thread(target=user_event_handler.user_schedule)\n # schedule_thread.start()\n # schedule_thread.join()\n","sub_path":"schedule_bot/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"492587941","text":"import copy\n\nfrom anytree import findall_by_attr\n\nimport grammar\nfrom syntax_tree import MyNodeClass\nfrom lex import KEYWORD\n\n\nclass CppSemanticsAnalyzer:\n\n def __init__(self, tree):\n self.__tree = tree\n\n def start_find_by_term_value(self, value):\n res = []\n if self.__tree.term.value == value:\n res.append(self.__tree)\n children = self.__tree.children\n for ch in children:\n self.__find_by_value(ch, value, res)\n return res\n\n def __find_by_value(self, node, value, res):\n if node.term.value == value:\n res.append(node)\n children = node.children\n # print(\"children\", children)\n for ch in children:\n self.__find_by_value(ch, value, res)\n\n def __remove_values_from_list(self, the_list, val):\n return [value for value in the_list if value != val]\n\n def check_semantic(self):\n # собираем все объявления переменных\n initialization_node = self.start_find_by_term_value(\"объявление переменной\")\n init_id = []\n for node in initialization_node:\n leaves = node.leaves\n for l in leaves:\n if l.term.value == 'ID':\n init_id.append(copy.deepcopy(l.term.lex))\n # print(\"init id\", init_id)\n\n # проверим наличие объявления main\n if 'main' in init_id:\n print(\"Переобъявление имени main запрещено\")\n return False\n\n\n # проверим наличие повторяющихся объявлений\n is_repeatable = len(init_id) != len(set(init_id))\n if is_repeatable:\n d = {}\n # Составим словарь по кол-во повторений\n for i in init_id:\n if i in d:\n d[i] += 1\n else:\n d[i] = 1\n for k, v in d.items():\n if v > 1:\n print(f\"Переменная {k} объявлена {v} раз!\")\n return False\n\n\n # собираем все доступные id\n initialization_node = self.start_find_by_term_value(\"ID\")\n used_id = []\n for node in initialization_node:\n used_id.append(copy.deepcopy(node.term.lex))\n for id in init_id:\n used_id = self.__remove_values_from_list(used_id, id)\n used_id.remove('main')\n if used_id:\n print(\"Есть необъявленные переменные\")\n return False\n\n # проверяем, что переменные объявлены до использования\n initialization_node = self.start_find_by_term_value(\"объявление переменной\")\n init_id = []\n for node in initialization_node:\n leaves = node.leaves\n for l in leaves:\n if l.term.value == 'ID':\n init_id.append([copy.deepcopy(l.term.lex), copy.deepcopy(l.pi_stack_number)])\n initialization_node = self.start_find_by_term_value(\"ID\")\n used_id = []\n for node in initialization_node:\n used_id.append([copy.deepcopy(node.term.lex), copy.deepcopy(node.pi_stack_number)])\n\n for init in init_id:\n id = init[0]\n rule = init[1]\n for used in used_id:\n if used[0] == id and used[1] < rule:\n print(\"Переменная\", id, \"используется в программе до объявления\")\n return False\n return True\n\n def optimizer(self):\n # находим все математические выражения, которые надо свернуть\n math_value = self.start_find_by_term_value(\"мат выражение\")\n for m in math_value:\n leaves = m.leaves\n line = leaves[0].term.line\n id = False\n for l in leaves:\n if l.term.value == \"ID\":\n id = True\n break\n if not id:\n print(\"math\", m.term.value, m.pi_stack_number)\n math_start = m.children[0]\n res = self.do_math(math_start)\n math_start.parent = None\n if res[0] == 'int':\n MyNodeClass(grammar.Term(value='N', lex=res[1], line=line), None, None, None, m)\n else:\n s = str(res[1]).split('.')\n print(s)\n MyNodeClass(grammar.Term(value='N', lex=s[0], line=line), None, None, None, m)\n MyNodeClass(grammar.Term(value='D1', lex='.', line=line), None, None, None, m)\n MyNodeClass(grammar.Term(value='N', lex=s[1], line=line), None, None, None, m)\n\n\n __operations = {\n '+': lambda x, y: x + y,\n '-': lambda x, y: x - y,\n '*': lambda x, y: x * y,\n '/': lambda x, y: x / y,\n }\n\n def do_math(self, branch):\n children = branch.children\n print('curr branch', branch.term.value)\n if not children:\n if branch.term.value == \"N\":\n return [\"int\", branch.term.lex]\n elif branch.term.value[0] == 'O':\n return [\"operator\", branch.term.lex]\n else:\n return \"hehe\"\n else:\n l = len(children)\n t = branch.term.value\n if l == 3 and t == 'вещественное число':\n new_float = str(children[0].term.lex) + '.' + str(children[2].term.lex)\n print('new float', new_float)\n return [\"float\", new_float]\n elif len(children) == 3 and (t == \"E1\" or t == \"T1\"):\n btw = children[1].term.value\n if btw == \"мат знак типа сложения\" or btw == \"мат знак типа умножения\":\n operator = self.do_math(children[1])\n left = self.do_math(children[0])\n right = self.do_math(children[2])\n print(\"op\", operator, \"left\", left, \"right\", right)\n\n if left[0] == \"int\":\n left = int(left[1])\n elif left[0] == \"float\":\n left = float(left[1])\n\n if right[0] == \"int\":\n right = int(right[1])\n elif right[0] == \"float\":\n right = float(right[1])\n\n result = self.__operations[operator[1]](left, right)\n print(\"result\", result)\n print(\"type\", type(result).__name__)\n return [type(result).__name__, result]\n elif len(children) == 3 and t == \"F1\":\n return self.do_math(children[1])\n elif children:\n for ch in children:\n return self.do_math(ch)\n","sub_path":"semantics.py","file_name":"semantics.py","file_ext":"py","file_size_in_byte":7062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"475571894","text":"#!python\n\nfrom argparse import ArgumentParser, ArgumentDefaultsHelpFormatter\nfrom contextlib import closing\nfrom datetime import timedelta, datetime\n\nfrom rocky.process import log_exception\nfrom sqlalchemy.orm import sessionmaker\n\nfrom service.api_definition import SERVICE_USER_ID\nfrom service.config import get_mysql_config, config\nfrom service.db import create_mysql_engine\nfrom service.migrate import ensure_migrations_table\nfrom services import services\n\n\ndef clear_permission_cache(session_factory):\n \"\"\" Clear permisssion cache as a part of every db_init/restart. \"\"\"\n with closing(session_factory()) as session:\n session.execute(\"UPDATE access_tokens SET permissions = NULL\")\n session.commit()\n\n\ndef refresh_service_access_token(session_factory):\n \"\"\" Clear permisssion cache as a part of every db_init/restart. \"\"\"\n \n service_token = config.get('API_BEARER', log_value=False)\n assert service_token, \"API_BEARER not configured\"\n \n with closing(session_factory()) as session:\n ten_years = timedelta(days=365 * 10)\n session.execute(\"DELETE FROM access_tokens WHERE user_id = :user_id\", dict(user_id=SERVICE_USER_ID))\n session.execute(\"INSERT INTO access_tokens (user_id, access_token, expires, lifetime, browser, ip)\"\n \" VALUES (:user_id, :token, :expires, :lifetime, '', '')\",\n dict(user_id=SERVICE_USER_ID, token=service_token,\n expires=datetime.utcnow() + ten_years, lifetime=ten_years.total_seconds()))\n session.commit()\n\n\ndef init_db():\n engine = create_mysql_engine(**get_mysql_config())\n session_factory = sessionmaker(autocommit=False, autoflush=False, bind=engine)\n \n ensure_migrations_table(engine, session_factory)\n \n for path, service in services:\n service.migrate(session_factory)\n \n clear_permission_cache(session_factory)\n \n refresh_service_access_token(session_factory)\n\n\nif __name__ == '__main__':\n\n with log_exception(status=1):\n parser = ArgumentParser(description=\"Migrate all components.\", formatter_class=ArgumentDefaultsHelpFormatter)\n args = parser.parse_args()\n \n init_db()\n","sub_path":"api/src/init_db.py","file_name":"init_db.py","file_ext":"py","file_size_in_byte":2219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"615812098","text":"\n\nB = []\n\ndef spiral(matrix, level):\n\n\tm, n = len(matrix), len(matrix[0]) # MxN matrix\n\n\tleft, right, top, bottom = level, n - 1 - level, level, m - 1 - level\n\n\tif level >= m // 2 and level >= n // 2:\n\t return # no more layer to solve\n\t\n\tfor j in range(left, right):\n\t B.append(matrix[top][j])\n\t\n\tfor i in range(top, bottom):\n\t B.append(matrix[i][right])\n\t\n\tfor j in range(right, left, -1):\n\t B.append(matrix[bottom][j])\n\t\n\tfor i in range(bottom, top, -1):\n\t B.append(matrix[i][left])\n\t\n\tspiral(matrix, level=level + 1)\n\nA = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]\n\nspiral(A,0)\n\nprint(B)\n","sub_path":"Arrays/spiral_order_print_2.py","file_name":"spiral_order_print_2.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"379114696","text":"from datetime import timedelta\nfrom django.conf import settings\nfrom django.utils import timezone\nfrom json import dumps as json_dumps\nfrom models import (IntervalSchedule,\n Monitor,\n PeriodicTask)\nfrom rest_framework.serializers import ModelSerializer\nfrom scanner.serializers import ScanReportSerializer\n\n\nclass IntervalScheduleSerializer(ModelSerializer):\n\n class Meta:\n model = IntervalSchedule\n fields = ('every', 'period')\n\n\nclass PeriodicTaskSerializer(ModelSerializer):\n interval = IntervalScheduleSerializer()\n\n class Meta:\n model = PeriodicTask\n fields = ('interval',)\n\n\nclass MonitorSerializer(ModelSerializer):\n periodic_task = PeriodicTaskSerializer(required=False)\n report = ScanReportSerializer()\n\n class Meta:\n model = Monitor\n\n def create(self, validated_data):\n target_url = validated_data.get('report').get('target_url')\n scan_interval = validated_data.get('periodic_task', {}).get('interval', {})\n\n interval_schedule, interval_schedule_created = IntervalSchedule.objects.get_or_create(\n every=scan_interval.get('every', settings.WASPC['monitoring']['default']['every']),\n period=scan_interval.get('period', settings.WASPC['monitoring']['default']['period'])\n )\n\n expiration = timezone.now() + timedelta(interval_schedule.schedule.seconds)\n periodic_task = PeriodicTask.objects.create(\n name=target_url,\n task='monitoring.tasks.Monitoring',\n kwargs=json_dumps({'target_url': target_url}),\n interval=interval_schedule,\n expires=expiration,\n # last_run_at=expiration,\n )\n\n monitor = Monitor.objects.create(\n periodic_task=periodic_task\n )\n\n return monitor\n\n def update(self, instance, validated_data):\n scan_interval = validated_data.get('periodic_task', {}).get(\"interval\", {})\n\n if scan_interval:\n interval_schedule, interval_schedule_created = IntervalSchedule.objects.get_or_create(\n every=scan_interval.get('every', settings.WASPC['monitoring']['default']['every']),\n period=scan_interval.get('period', settings.WASPC['monitoring']['default']['period'])\n )\n\n instance_periodic_task = instance.periodic_task\n instance_periodic_task_old_interval = instance_periodic_task.interval\n instance_periodic_task.interval = interval_schedule\n\n if not PeriodicTask.objects.exclude(\n pk=instance_periodic_task.pk\n ).filter(\n interval=instance_periodic_task_old_interval\n ).exists():\n instance_periodic_task_old_interval.delete()\n\n instance_periodic_task.save()\n instance.save()\n\n return instance\n","sub_path":"monitoring/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":2881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"492682177","text":"from autumn.tools.project import Project, ParameterSet, TimeSeriesSet, build_rel_path\nfrom autumn.tools.calibration import Calibration, priors, targets\nfrom autumn.tools.calibration.priors import UniformPrior\nfrom autumn.tools.calibration.targets import NormalTarget\nfrom autumn.models.example import base_params, build_model\nfrom autumn.settings import Region, Models\n\n\n# Load and configure model parameters.\nbaseline_params = base_params.update(build_rel_path(\"params/baseline.yml\"))\nscenario_1_params = baseline_params.update(build_rel_path(\"params/scenario-1.yml\"))\nparam_set = ParameterSet(baseline=baseline_params, scenarios=[scenario_1_params])\n\n\n# Load and configure calibration settings.\nts_set = TimeSeriesSet.from_file(build_rel_path(\"timeseries.json\"))\npriors = [\n UniformPrior(\"contact_rate\", [0.025, 0.05]),\n UniformPrior(\"recovery_rate\", [0.9, 1.2]),\n]\ntargets = [\n NormalTarget(\n timeseries=ts_set[\"prevalence_infectious\"],\n time_weights=list(range(1, len(ts_set[\"prevalence_infectious\"].times) + 1)),\n )\n]\ncalibration = Calibration(priors=priors, targets=targets)\nproject = Project(Region.VICTORIA, Models.EXAMPLE, build_model, param_set, calibration)\n","sub_path":"autumn/projects/example/victoria/project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":1195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"192518306","text":"import os, h5py, re, time, json\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom scipy import optimize\r\nfrom camera.clients.data_tools.process_image import process_images_g\r\nfrom camera.clients.data_tools.process_image import process_images_g_fluorescence\r\n\r\nimport sys\r\nsys.path.insert(1, 'C:\\\\LabRad\\\\SrData\\\\data\\\\notebooks\\\\data_tools')\r\nfrom helper import process_units\r\n# from data.notebooks.helper.data_tools import process_camera\r\n\r\nPROJECT_DATA_PATH = os.path.join(os.getenv('LABRADDATA'), 'data')\r\n\r\nexp_name = 'lattice_lifetime'\r\n \r\ndef fit_Gaussian(x, x0, w, amp, const):\r\n return amp * np.exp(-pow(x - x0, 2)/(2*pow(w, 2))) + const\r\n\r\ndef fit_exp_decay(t, a, tau):\r\n return a* np.exp(-t/tau)\r\n\r\ndef process_lattice_lifetime_ccd(settings):\r\n shot = settings['shot']\r\n roi_center = settings['kwargs']['roi_center']\r\n roi_width = settings['kwargs']['roi_width']\r\n fit_width = settings['kwargs']['fit_width']\r\n x_key = settings['kwargs']['x_key']\r\n y_key = settings['kwargs']['y_key']\r\n method = settings['kwargs']['method']\r\n image = settings['kwargs']['image']\r\n \r\n if shot >= 0:\r\n data = []\r\n data_folder = os.path.join(PROJECT_DATA_PATH, settings['data_path'])\r\n save_folder = os.path.join(PROJECT_DATA_PATH, settings['data_path'], 'processed_data')\r\n save_path = os.path.join(save_folder, str(shot))\r\n if not os.path.isdir(save_folder):\r\n os.makedirs(save_folder)\r\n \r\n conductor_json_path = data_folder + '\\\\{}'.format(shot) + '.conductor.json'\r\n ccd_hdf5_path = data_folder + '\\\\{}'.format(shot) + '.{}.hdf5'.format(method)\r\n \r\n with open(conductor_json_path, 'r') as file:\r\n f1 = file.read()\r\n f2 = json.loads(f1)\r\n try:\r\n em_gain = f2['andor.record_path']['em_gain']\r\n except:\r\n em_gain = 1\r\n \r\n try: \r\n \r\n f = open(conductor_json_path, 'r')\r\n f1 = f.read()\r\n f2 = json.loads(f1)\r\n holdtime = f2['sequencer.DO_parameters.lattice_hold']\r\n \r\n images = {}\r\n with h5py.File(ccd_hdf5_path, 'r') as images_h5:\r\n for key in images_h5:\r\n images[key] = np.array(images_h5[key], dtype = 'float64')\r\n images_h5.close()\r\n \r\n if image == 'absorption':\r\n n0 = process_images_g(images, em_gain)\r\n \r\n xc = n0.shape[1] -roi_center[1]\r\n yc = roi_center[0]\r\n n = n0[yc - roi_width: yc + roi_width, xc - roi_width: xc + roi_width]\r\n x_trace0 = np.sum(n, axis = 0)\r\n y_trace0 = np.sum(n, axis = 1)\r\n X = range(n.shape[1])\r\n Y = range(n.shape[0])\r\n count = np.sum(n)\r\n \r\n count = round(float(count), 1)\r\n \r\n elif image == 'fluorescence':\r\n n0 = process_images_g_fluorescence(images)\r\n \r\n xc = n0.shape[1] -roi_center[1]\r\n yc = roi_center[0]\r\n n = n0[yc - roi_width: yc + roi_width, xc - roi_width: xc + roi_width]\r\n x_trace0 = np.sum(n, axis = 0)\r\n y_trace0 = np.sum(n, axis = 1)\r\n X = range(n.shape[1])\r\n Y = range(n.shape[0])\r\n count = np.sum(n)\r\n \r\n # fit Gaussian\r\n # try:\r\n # x_trace0 = np.sum(n0, axis = 0)\r\n # y_trace0 = np.sum(n0, axis = 1)\r\n # X = range(n0.shape[1])\r\n # Y = range(n0.shape[0])\r\n # p0x = (x_trace0.argmax(), fit_width, np.max(x_trace0), np.min(x_trace0))\r\n # p0y = (y_trace0.argmax(), fit_width, np.max(y_trace0), np.min(y_trace0))\r\n \r\n # poptx, pcovx = optimize.curve_fit(fit_Gaussian, X, x_trace0, p0 = p0x)\r\n # popty, pcovy = optimize.curve_fit(fit_Gaussian, Y, y_trace0, p0 = p0y)\r\n \r\n # countx = np.sum(x_trace0) - poptx[-1]*len(x_trace0)\r\n # county = np.sum(y_trace0) - poptx[-1]*len(y_trace0)\r\n # count = (countx+county)/2\r\n \r\n # # sum - bg\r\n # except Exception as e:\r\n # print(e)\r\n # (xc, yc) = np.unravel_index(np.argmax(n0, axis=None), n0.shape)\r\n # n = n0[xc - roi_width: xc + roi_width, yc - roi_width: yc + roi_width]\r\n \r\n # n_bg1 = n0[0: roi_width, 0:roi_width]\r\n # n_bg2 = np.mean(n_bg1)\r\n \r\n # count = np.sum(n) - n_bg2*np.size(n)\r\n \r\n count = round(float(count), 1)\r\n \r\n fig, ax = plt.subplots(1, 1)\r\n fig.set_size_inches(20, 8)\r\n \r\n cmap = plt.get_cmap('jet')\r\n ax.set_aspect('equal')\r\n plt.pcolormesh(X, Y, n, cmap = cmap)\r\n ax.set_xlim(0, n.shape[1])\r\n ax.set_ylim(0, n.shape[0])\r\n # plt.legend()\r\n plt.colorbar()\r\n plt.title('Atom number: {:.2e}'.format(count))\r\n \r\n plt.savefig(save_path + '.png', bbox_inches='tight')\r\n \r\n plt.clf()\r\n plt.close('all')\r\n \r\n except Exception as e2:\r\n print(e2)\r\n count = 0\r\n \r\n data.append({'shot': shot, x_key: holdtime, 'fit': {y_key: count}})\r\n return data\r\n\r\n else:\r\n return data\r\n\r\ndef plot_lattice_lifetime_ccd(data, settings):\r\n # print(data)\r\n\r\n units = settings['kwargs']['units']\r\n data_range = settings['kwargs']['data_range']\r\n x_label = settings['kwargs']['x_label']\r\n y_label = settings['kwargs']['y_label']\r\n x_key = settings['kwargs']['x_key']\r\n y_key = settings['kwargs']['y_key']\r\n \r\n result_folder = os.path.join(PROJECT_DATA_PATH, settings['data_path'], 'result')\r\n result_path = os.path.join(result_folder, os.path.split(settings['data_path'])[0] + '_' + os.path.split(settings['data_path'])[1])\r\n saved_data_path = os.path.join(result_folder, 'processed_data.txt')\r\n \r\n if not os.path.isdir(result_folder):\r\n os.makedirs(result_folder)\r\n \r\n # sort by shot number\r\n sorted_data = sorted(data, key = lambda k:k['shot'])\r\n x_data = [i[x_key] for i in sorted_data]\r\n y_data = [i['fit'][y_key] for i in sorted_data]\r\n \r\n with open(saved_data_path, 'w') as file:\r\n file.write(json.dumps(sorted_data))\r\n \r\n x_data = process_units(x_data, units)\r\n \r\n x_data = np.asarray(x_data)\r\n y_data = np.asarray(y_data)\r\n # y_data = y_data/(np.max(y_data)) # Normalize\r\n \r\n p0 = [np.max(y_data), 0.7*np.max(x_data)]\r\n \r\n try:\r\n popt, pcov = optimize.curve_fit(fit_exp_decay, x_data, y_data, p0 = p0)\r\n perr = np.sqrt(np.diag(pcov))\r\n \r\n except Exception as e:\r\n print(e)\r\n popt = p0\r\n\r\n t1 = np.arange(np.min(x_data) - 1, np.max(x_data)+ 1, 0.1)\r\n\r\n f, ax = plt.subplots(1,1)\r\n ax.scatter(x_data, y_data, c='red', marker = 's', s= 35)\r\n ax.plot(t1, fit_exp_decay(t1, popt[0], popt[1]), label= '{}({}) s'.format(str(round(popt[1], 2)), str(round(perr[1], 2))),\r\n c='red', linestyle='dashed')\r\n ax.set_xlabel(x_label+\" ({})\".format(units))\r\n ax.set_ylabel(y_label)\r\n ax.set_title('Lattice lifetime measurement')\r\n ax.set_yscale('log')\r\n plt.legend(loc='best')\r\n \r\n plt.savefig(result_path+'.svg', bbox_inches='tight')\r\n plt.savefig(result_path+'.png', bbox_inches='tight')\r\n \r\n plt.clf()\r\n plt.close('all')\r\n # plt.show()\r\n \r\ndef process_lattice_lifetime_pmt(settings):\r\n shot = settings['shot']\r\n x_key = settings['kwargs']['x_key']\r\n y_key = settings['kwargs']['y_key']\r\n count_key = settings['kwargs']['count_key']\r\n \r\n if shot >= 0:\r\n data = []\r\n data_folder = os.path.join(PROJECT_DATA_PATH, settings['data_path'])\r\n save_folder = os.path.join(PROJECT_DATA_PATH, settings['data_path'], 'processed_data')\r\n save_path = os.path.join(save_folder, str(shot))\r\n if not os.path.isdir(save_folder):\r\n os.makedirs(save_folder)\r\n \r\n conductor_json_path = data_folder + '\\\\{}'.format(shot) + '.conductor.json'\r\n blue_pmt_path = data_folder + '\\\\{}'.format(shot) + '.blue_pmt.json'\r\n\r\n f = open(conductor_json_path, 'r')\r\n f1 = f.read()\r\n f2 = json.loads(f1)\r\n holdtime = f2['sequencer.DO_parameters.lattice_hold']\r\n \r\n f = open(blue_pmt_path, 'r')\r\n f1 = f.read()\r\n f2 = json.loads(f1)\r\n count = f2[count_key]\r\n \r\n data.append({'shot': shot, x_key: holdtime, y_key: count})\r\n return data\r\n \r\n else:\r\n return data\r\n\r\ndef plot_lattice_lifetime_pmt(data, settings):\r\n\r\n units = settings['kwargs']['units']\r\n data_range = settings['kwargs']['data_range']\r\n x_label = settings['kwargs']['x_label']\r\n y_label = settings['kwargs']['y_label']\r\n x_key = settings['kwargs']['x_key']\r\n y_key = settings['kwargs']['y_key']\r\n \r\n result_folder = os.path.join(PROJECT_DATA_PATH, settings['data_path'], 'result')\r\n result_path = os.path.join(result_folder, os.path.split(settings['data_path'])[0] + '_' + os.path.split(settings['data_path'])[1])\r\n saved_data_path = os.path.join(result_folder, 'processed_data.txt')\r\n \r\n if not os.path.isdir(result_folder):\r\n os.makedirs(result_folder)\r\n \r\n # sort by shot number\r\n sorted_data = sorted(data, key = lambda k:k['shot'])\r\n x_data = [i[x_key] for i in sorted_data if min(data_range) Tools > Easy HDRI\",\r\n \"description\": \"Load and test your HDRIs easily.\", \r\n \"wiki_url\": \"http://codeofart.com/easy-hdri/‎\",\r\n \"tracker_url\": \"http://codeofart.com/easy-hdri/\", \r\n \"category\": \"3D View\"}\r\n\r\n\r\n# Preview collections\r\npreview_collections = {}\r\n# Addon path\r\naddon_dir = os.path.dirname(__file__)\r\n\r\n###########################################################################################\r\n################################### Functions #############################################\r\n###########################################################################################\r\n\r\n# Load an empty list(First launch)\r\ndef env_previews(self, context): \r\n pcoll = preview_collections.get(\"prev\")\r\n if not pcoll:\r\n return []\r\n return pcoll.prev\r\n \r\n# Update the previews list if the folder changes\r\ndef update_dir(self, context):\r\n \r\n scn = bpy.context.scene\r\n enum_items = []\r\n if not 'previews_dir' in scn:\r\n scn['previews_dir'] = ''\r\n if not 'previews_list' in scn:\r\n scn['previews_list'] = [] \r\n scn['previews_list'] = []\r\n \r\n previews_list = [] \r\n previews_folder = scn['previews_dir']\r\n pcoll = preview_collections[\"prev\"] \r\n if os.path.exists(previews_folder):\r\n image_paths = []\r\n for fn in os.listdir(previews_folder):\r\n if fn.lower().endswith(\".hdr\") or fn.lower().endswith(\".exr\"):\r\n image_paths.append(fn)\r\n for i, name in enumerate(image_paths): \r\n filepath = os.path.join(previews_folder, name)\r\n if not pcoll.get(filepath):\r\n thumb = pcoll.load(filepath, filepath, 'IMAGE')\r\n else: thumb = pcoll[filepath] \r\n enum_items.append((name, name, \"\", thumb.icon_id, i))\r\n previews_list.append(name)\r\n scn['previews_list'] = previews_list \r\n pcoll.prev = enum_items\r\n pcoll.previews_dir = previews_folder\r\n if len(previews_list) > 0:\r\n scn.prev = previews_list[0] \r\n return None\r\n\r\n# Update the envirement map\r\ndef update_hdr(self, context):\r\n scn = bpy.context.scene\r\n dynamic = scn.dynamic_load\r\n dynamic_cleanup = scn.dynamic_cleanup\r\n image = scn.prev\r\n images = bpy.data.images\r\n path = scn.previews_dir \r\n \r\n if scn.world:\r\n if 'EasyHDR' in bpy.data.worlds and dynamic:\r\n if scn.world.name == 'EasyHDR':\r\n nodes = scn.world.node_tree.nodes \r\n if 'Environment' in nodes:\r\n env = nodes['Environment']\r\n if image in images:\r\n env.image = images[image]\r\n if dynamic_cleanup:\r\n cleanup_images()\r\n else:\r\n if os.path.exists(path):\r\n if os.access(os.path.join(path, image), os.F_OK):\r\n filepath = os.path.join(path, image) \r\n images.load(filepath) \r\n if image in images:\r\n env.image = images[image]\r\n if dynamic_cleanup:\r\n cleanup_images()\r\n \r\n return None \r\n\r\n# Change display location\r\ndef update_display(self, context):\r\n \r\n panel = World_PT_EasyHDR\r\n display = context.scene.display_location\r\n try:\r\n bpy.utils.unregister_class(World_PT_EasyHDR)\r\n if display == 'Properties': \r\n panel.bl_region_type = 'UI' \r\n else: \r\n panel.bl_region_type = 'TOOLS' \r\n bpy.utils.register_class(World_PT_EasyHDR) \r\n except Exception as error:\r\n print(str(error))\r\n return None \r\n\r\n# Update the preview directory when the favorites change\r\ndef update_favs(self, context):\r\n scn = context.scene \r\n favs = scn.favs\r\n if not favs in ['Empty', '']:\r\n scn.previews_dir = favs\r\n return None\r\n\r\n# World nodes setup\r\ndef create_world_nodes():\r\n \r\n scn = bpy.context.scene\r\n worlds = bpy.data.worlds\r\n # Make sure the render engine is Cycles \r\n scn.render.engine = 'CYCLES'\r\n # Add a new world \"EasyHDR\", or reset the existing one\r\n if not 'EasyHDR' in worlds:\r\n world = bpy.data.worlds.new(\"EasyHDR\") \r\n else:\r\n world = worlds['EasyHDR']\r\n scn.world = world \r\n # Enable Use nodes\r\n world.use_nodes= True\r\n # Delete all the nodes (Start from scratch)\r\n world.node_tree.nodes.clear()\r\n \r\n #Adding new nodes\r\n tex_coord = world.node_tree.nodes.new(type=\"ShaderNodeTexCoord\") \r\n mapping = world.node_tree.nodes.new(type=\"ShaderNodeMapping\") \r\n env = world.node_tree.nodes.new(type=\"ShaderNodeTexEnvironment\") \r\n background = world.node_tree.nodes.new(type=\"ShaderNodeBackground\")\r\n output = world.node_tree.nodes.new(type=\"ShaderNodeOutputWorld\") \r\n \r\n # Change the parameters\r\n env.name = 'Environment'\r\n background.name = 'Background'\r\n mapping.name = 'Mapping'\r\n \r\n # Links\r\n world.node_tree.links.new(tex_coord.outputs['Generated'], mapping.inputs[0])\r\n world.node_tree.links.new(mapping.outputs[0], env.inputs[0])\r\n world.node_tree.links.new(env.outputs[0], background.inputs[0])\r\n world.node_tree.links.new(background.outputs[0], output.inputs[0]) \r\n \r\n # Nodes location \r\n tex_coord.location = (220, 252)\r\n mapping.location = (400, 252)\r\n env.location = (780, 252)\r\n background.location = (960, 252)\r\n output.location = (1120, 252)\r\n \r\n # Load\r\n if 'prev' in scn:\r\n scn.previews_dir = scn.previews_dir # hacky way to force the update\r\n if scn.prev != '' and scn.prev in bpy.data.images:\r\n env.image = bpy.data.images[scn.prev]\r\n \r\n \r\n\r\n# Remove unused images \r\ndef cleanup_images():\r\n images = bpy.data.images\r\n for image in images:\r\n if image.users == 0:\r\n images.remove(image)\r\n \r\n# Check the World's node tree\r\ndef check_world_nodes():\r\n nodes_list = ['Texture Coordinate', 'Mapping', 'Background',\r\n 'World Output', 'Environment']\r\n all_found = True \r\n scn = bpy.context.scene\r\n worlds = bpy.data.worlds\r\n if not scn.world:\r\n return 'Fix' \r\n if not 'EasyHDR' in worlds:\r\n return 'Create'\r\n else:\r\n world = worlds['EasyHDR']\r\n nodes = world.node_tree.nodes\r\n if len(nodes) > 0:\r\n for n in nodes_list:\r\n if not n in nodes:\r\n all_found = False\r\n if not all_found:\r\n return 'Fix'\r\n else:\r\n return 'Fix'\r\n if not scn.world.name == 'EasyHDR':\r\n return 'Fix'\r\n \r\n# Get the list of favorites (enum)\r\ndef get_favs_enum(self, context):\r\n dirs = get_favs()\r\n if len(dirs) > 0:\r\n return [(i, i, '') for i in dirs]\r\n else: return [('Empty', '__Empty__', '')]\r\n\r\n# return the list of favorites\r\ndef get_favs():\r\n dirs = []\r\n fav_file = os.path.join(addon_dir, \"Favorites.fav\")\r\n if os.path.exists(fav_file): \r\n with open(fav_file, 'r') as ff:\r\n lines = ff.read()\r\n fav_dirs = lines.splitlines()\r\n dirs = [i for i in fav_dirs if i.strip() != '']\r\n return dirs \r\n \r\n \r\n \r\n\r\n###########################################################################################\r\n################################### Operators #############################################\r\n###########################################################################################\r\n\r\n# Switch to Cycles\r\nclass SwitchToCycles(Operator):\r\n bl_idname = \"easyhdr.switch_to_cycles\"\r\n bl_label = \"Switch to Cycles\"\r\n bl_description = \"Switch to Cycles.\"\r\n\r\n def execute(self, context):\r\n context.scene.render.engine = 'CYCLES' \r\n return {'FINISHED'} \r\n \r\n# Add to favorites\r\nclass AddToFav(Operator):\r\n bl_idname = \"easyhdr.add_to_fav\"\r\n bl_label = \"Add to fav\"\r\n bl_description = \"Add the current folder to the favorites.\"\r\n\r\n def execute(self, context):\r\n scn = context.scene\r\n new_fav = scn.previews_dir \r\n fav_file = os.path.join(addon_dir, \"Favorites.fav\")\r\n if os.path.exists(new_fav):\r\n if not os.path.exists(fav_file):\r\n with open(fav_file, 'w') as ff:\r\n ff.write('') \r\n dirs = get_favs()\r\n if not new_fav in dirs:\r\n dirs.append(new_fav)\r\n with open(fav_file, 'w') as ff:\r\n for d in dirs:\r\n if d : ff.write(d + '\\n')\r\n else: self.report({'WARNING'}, 'Directory not found !') \r\n \r\n return {'FINISHED'}\r\n \r\n# Remove from favorites\r\nclass RemoveFromFav(Operator):\r\n bl_idname = \"easyhdr.remove_from_fav\"\r\n bl_label = \"Remove\"\r\n bl_description = \"remove the current folder from the favorites.\"\r\n\r\n def execute(self, context):\r\n scn = context.scene\r\n dir = scn.previews_dir \r\n fav_file = os.path.join(addon_dir, \"Favorites.fav\") \r\n dirs = get_favs()\r\n dirs.remove(dir)\r\n with open(fav_file, 'w') as ff:\r\n for d in dirs:\r\n if d : ff.write(d + '\\n') \r\n return {'FINISHED'} \r\n \r\n# Reload previews\r\nclass ReloadPreviews(Operator):\r\n bl_idname = \"easyhdr.reload_previews\"\r\n bl_label = \"Reload previews\"\r\n bl_description = \"Reload previews.\"\r\n\r\n def execute(self, context):\r\n scn = context.scene\r\n if 'previews_dir' in scn:\r\n if scn.previews_dir:\r\n scn.previews_dir = scn.previews_dir\r\n \r\n return {'FINISHED'} \r\n\r\n# Create world nodes \r\nclass CreateWorld(Operator):\r\n bl_idname = \"easyhdr.create_world\"\r\n bl_label = \"Create world nodes\"\r\n bl_description = \"Create world nodes for EasyHDR.\"\r\n\r\n def execute(self, context):\r\n create_world_nodes() \r\n return {'FINISHED'}\r\n \r\n# Load image \r\nclass LoadImage(Operator):\r\n bl_idname = \"easyhdr.load_image\"\r\n bl_label = \"Load image\"\r\n bl_description = \"Load image.\"\r\n\r\n def execute(self, context):\r\n scn = bpy.context.scene\r\n dynamic = scn.dynamic_load\r\n dynamic_cleanup = scn.dynamic_cleanup\r\n image = scn.prev\r\n images = bpy.data.images\r\n path = scn.previews_dir \r\n \r\n if 'EasyHDR' in bpy.data.worlds:\r\n if scn.world.name == 'EasyHDR':\r\n nodes = scn.world.node_tree.nodes \r\n if 'Environment' in nodes:\r\n env = nodes['Environment']\r\n if image in images:\r\n env.image = images[image]\r\n if dynamic_cleanup:\r\n cleanup_images()\r\n else:\r\n if os.path.exists(path):\r\n if os.access(os.path.join(path, image), os.F_OK):\r\n filepath = os.path.join(path, image) \r\n images.load(filepath) \r\n if image in images:\r\n env.image = images[image] \r\n if dynamic_cleanup:\r\n cleanup_images() \r\n \r\n return {'FINISHED'} \r\n \r\n# Remove unused images\r\nclass RemoveUnusedImages(Operator):\r\n bl_idname = \"easyhdr.remove_unused_images\"\r\n bl_label = \"Remove unused images\"\r\n bl_description = \"Remove 0 user images.\"\r\n \r\n def execute(self, context):\r\n cleanup_images()\r\n return {'FINISHED'} \r\n \r\n# Next next image\r\nclass NextImage(Operator):\r\n bl_idname = \"easyhdr.next\"\r\n bl_label = \"Next\"\r\n bl_description = \"Next.\"\r\n\r\n def execute(self, context): \r\n scn = context.scene\r\n list = scn['previews_list']\r\n prev = scn.prev\r\n count = len(list)\r\n index = list.index(prev) + 1\r\n if index > count - 1:\r\n index = 0\r\n image = list[index] \r\n if image != prev:\r\n scn.prev = image \r\n return {'FINISHED'}\r\n \r\n# Preview previous image\r\nclass PreviousImage(Operator):\r\n bl_idname = \"easyhdr.previous\"\r\n bl_label = \"Previous\"\r\n bl_description = \"Previous.\"\r\n\r\n def execute(self, context):\r\n scn = context.scene\r\n list = scn['previews_list']\r\n prev = scn.prev\r\n count = len(list)\r\n index = list.index(prev) - 1\r\n if index < 0:\r\n index = count-1\r\n image = list[index] \r\n if image != prev:\r\n scn.prev = image \r\n return {'FINISHED'} \r\n \r\n \r\n###########################################################################################\r\n##################################### The UI ##############################################\r\n########################################################################################### \r\n \r\n# Easy FX Panel\r\nclass World_PT_EasyHDR(Panel): \r\n bl_label = \"Easy HDRI\"\r\n bl_space_type = \"VIEW_3D\"\r\n bl_region_type = \"TOOLS\"\r\n bl_category = 'Easy HDRI'\r\n #bl_context = \"objectmode\"\r\n \r\n def draw(self, context):\r\n scn = context.scene\r\n favs = get_favs()\r\n dir = scn.previews_dir\r\n layout = self.layout\r\n col = layout.column(align=True) \r\n if scn.render.engine != 'CYCLES':\r\n col.operator('easyhdr.switch_to_cycles', icon = 'ARROW_LEFTRIGHT')\r\n else:\r\n row = col.row(align=True)\r\n if os.path.exists(dir):\r\n if not dir in favs:\r\n row.operator(\"easyhdr.add_to_fav\", text = '', icon = 'SOLO_ON')\r\n else: row.operator(\"easyhdr.remove_from_fav\", text = '', icon = 'X')\r\n row.prop(scn, \"previews_dir\", text = '') \r\n row = layout.row()\r\n row.template_icon_view(scn, \"prev\", show_labels=True)\r\n col = row.column(align=True)\r\n col.operator(\"easyhdr.reload_previews\", text = '', icon = 'FILE_REFRESH')\r\n col.prop(scn, 'favs', text = '', icon = 'SOLO_OFF', icon_only=True)\r\n col.menu(\"easyhdr.settings\", text = '', icon = 'SCRIPTWIN') \r\n col.prop(scn.cycles, 'film_transparent', text = '', icon = 'IMAGEFILE') \r\n col = layout.column() \r\n col = layout.column() \r\n \r\n prev_list = 0\r\n if 'previews_list' in scn:\r\n prev_list = len(scn['previews_list'])\r\n \r\n if len(preview_collections[\"prev\"]) > 0 and prev_list > 0:\r\n box = col.box() \r\n box.scale_y = .6 \r\n col = box.column() \r\n row = col.row() \r\n row.scale_y = 1.7 \r\n row.operator(\"easyhdr.previous\", text = '', icon = 'TRIA_LEFT')\r\n row1 = row.row() \r\n row1.scale_y = 1.7 \r\n row1.enabled = not scn.dynamic_load \r\n row1.operator(\"easyhdr.load_image\", icon = 'LOAD_FACTORY') \r\n row.operator(\"easyhdr.next\", text = '', icon = 'TRIA_RIGHT')\r\n else:\r\n col.label(text = 'The list is empty', icon = 'ERROR') \r\n if check_world_nodes() == 'Create':\r\n col.operator(\"easyhdr.create_world\", icon = 'WORLD_DATA')\r\n elif check_world_nodes() == 'Fix':\r\n col.operator(\"easyhdr.create_world\", text = 'Fix World nodes', icon = 'WORLD_DATA') \r\n else: \r\n col = layout.column()\r\n nodes = scn.world.node_tree.nodes\r\n box = col.box()\r\n col = box.column() \r\n if 'Background' in nodes:\r\n col.prop(nodes['Background'].inputs[1], \"default_value\", text = 'Strength')\r\n col = box.column()\r\n if 'Environment' in nodes:\r\n col.prop(nodes['Environment'], \"projection\", text = '') \r\n if 'Mapping' in nodes:\r\n col = box.column()\r\n col.prop(nodes['Mapping'], \"rotation\")\r\n \r\n# Settings Menu\r\nclass SetingsMenu(Menu):\r\n bl_idname = \"easyhdr.settings\"\r\n bl_label = \"Settings\"\r\n bl_description = \"Settings\"\r\n\r\n def draw(self, context):\r\n scn = context.scene\r\n layout = self.layout\r\n \r\n layout.label('UI settings:')\r\n layout.prop(scn, \"display_location\", text = '')\r\n layout.separator() \r\n layout.label('Cleanup:') \r\n layout.operator(\"easyhdr.remove_unused_images\")\r\n layout.separator()\r\n layout.label('Loading images:')\r\n layout.prop(scn, 'dynamic_load', text = 'Load dynamically')\r\n layout.prop(scn, 'dynamic_cleanup', text = 'Cleanup dynamically')\r\n\r\n\r\n# Register/Unregister\r\ndef register(): \r\n bpy.utils.register_module(__name__) \r\n pcoll = previews.new() \r\n preview_collections[\"prev\"] = pcoll\r\n bpy.types.Scene.prev = EnumProperty(items = env_previews, update = update_hdr)\r\n bpy.types.Scene.favs = EnumProperty(name = 'Favorites', items = get_favs_enum, update = update_favs)\r\n bpy.types.Scene.display_location = EnumProperty(\r\n name = 'Display location',\r\n items = (('Tools','Tools',''),('Properties','Properties','')),\r\n update = update_display,\r\n description = \"Where to place the add-on's panel.\"\r\n ) \r\n bpy.types.Scene.dynamic_load = BoolProperty(default = True, description = 'Load the image dynamically.') \r\n bpy.types.Scene.dynamic_cleanup = BoolProperty(default = False, description = 'Remove 0 user images dynamically.') \r\n bpy.types.Scene.previews_dir = StringProperty(\r\n name=\"Folder Path\",\r\n subtype='DIR_PATH',\r\n default=\"\",\r\n update = update_dir,\r\n description = 'Path to the folder containing the images.' \r\n ) \r\n\r\ndef unregister():\r\n bpy.utils.unregister_module(__name__) \r\n for pcoll in preview_collections.values():\r\n previews.remove(pcoll)\r\n preview_collections.clear()\r\n del bpy.types.Scene.prev\r\n del bpy.types.Scene.favs\r\n del bpy.types.Scene.display_location\r\n del bpy.types.Scene.dynamic_load\r\n del bpy.types.Scene.dynamic_cleanup\r\n del bpy.types.Scene.previews_dir \r\n\r\n\r\nif __name__ == \"__main__\":\r\n register()","sub_path":"EasyHDRI.py","file_name":"EasyHDRI.py","file_ext":"py","file_size_in_byte":19611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"317483905","text":"\"\"\"\nStrings Mix\nhttp://www.codewars.com/kata/strings-mix/python\n\nGiven two strings s1 and s2, we want to visualize how different the two strings are. We will only take into account the\nlowercase letters (a to z). First let us count the frequency of each lowercase letters in s1 and s2.\n\ns1 = \"A aaaa bb c\"\n\ns2 = \"& aaa bbb c d\"\n\ns1 has 4 'a', 2 'b', 1 'c'\n\ns2 has 3 'a', 3 'b', 1 'c', 1 'd'\n\nSo the maximum for 'a' in s1 and s2 is 4 from s1; the maximum for 'b' is 3 from s2. In the following we will not\nconsider letters when the maximum of their occurrences is less than or equal to 1.\n\nWe can resume the differences between s1 and s2 in the following string: \"1:aaaa/2:bbb\" where 1 in 1:aaaa stands for\nstring s1 and aaaa because the maximum for a is 4. In the same manner 2:bbb stands for string s2 and bbb because the\nmaximum for b is 3.\n\nThe task is to produce a string in which each lowercase letters of s1 or s2 appears as many times as its maximum if this\nmaximum is strictly greater than 1; these letters will be prefixed by the number of the string where they appear with\ntheir maximum value and :. If the maximum is in s1 as well as in s2 the prefix is =:.\n\nIn the result, substrings will be in decreasing order of their length and when they have the same length sorted\nalphabetically (more precisely sorted by codepoint); the different groups will be separated by '/'.\n\nHopefully other examples can make this clearer.\n\ns1 = \"my&friend&Paul has heavy hats! &\"\ns2 = \"my friend John has many many friends &\"\nmix(s1, s2) --> \"2:nnnnn/1:aaaa/1:hhh/2:mmm/2:yyy/2:dd/2:ff/2:ii/2:rr/=:ee/=:ss\"\n\ns1 = \"mmmmm m nnnnn y&friend&Paul has heavy hats! &\"\ns2 = \"my frie n d Joh n has ma n y ma n y frie n ds n&\"\nmix(s1, s2) --> \"1:mmmmmm/=:nnnnnn/1:aaaa/1:hhh/2:yyy/2:dd/2:ff/2:ii/2:rr/=:ee/=:ss\"\n\ns1=\"Are the kids at home? aaaaa fffff\"\ns2=\"Yes they are here! aaaaa fffff\"\nmix(s1, s2) --> \"=:aaaaaa/2:eeeee/=:fffff/1:tt/2:rr/=:hh\"\n\"\"\"\nimport string\nfrom collections import Counter\n\n\ndef mix(s1, s2):\n store = []\n result = []\n for stringy in (s1, s2):\n store.append(Counter([x for x in stringy if x.islower()]))\n for count in range(2):\n result.append([k * v for k, v in store[count].items() if v > 1 and v >= store[(count + 1) % 2].get(k, 0)])\n result[-1].sort()\n return \"/\".join(\n sorted(\n [\"1:{}\".format(x) for x in result[0] if x not in result[1]] + [\"2:{}\".format(x) for x in result[1] if x not in result[0]] + [\"=:{}\".format(x) for x in result[0] if x in result[1]],\n key=len,\n reverse=True))\n","sub_path":"strings_mix.py3","file_name":"strings_mix.py3","file_ext":"py3","file_size_in_byte":2570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"123466675","text":"dojeansoo=1\r\nball=0\r\nstrike=0\r\nfrom random import *\r\nrandomgabs1=randrange(1,10)\r\nrandomgabs2=randrange(1,10)\r\nrandomgabs3=randrange(1,10)\r\nwhile randomgabs1==randomgabs2:\r\n\trandomgabs2=randrange(1,10)\r\n\twhile randomgabs2==randomgabs3:\r\n\t\trandomgabs3=randrange(1,10)\r\n\t\twhile randomgabs1==randomgabs3:\r\n\t\t\trandomgabs3=randrange(1,10)\r\nwhile randomgabs2==randomgabs3:\r\n\trandomgabs3=randrange(1,10)\r\n\twhile randomgabs1==randomgabs3:\r\n\t\trandomgabs3=randrange(1,10)\r\n\t\twhile randomgabs1==randomgabs2:\r\n\t\t\trandomgabs2=randrange(1,10)\r\nwhile randomgabs1==randomgabs3:\r\n\trandomgabs3=randrange(1,10)\r\n\twhile randomgabs2==randomgabs3:\r\n\t\trandomgabs3=randrange(1,10)\r\n\t\twhile randomgabs1==randomgabs2:\r\n\t\t\trandomgabs2=randrange(1,10)\r\nwhile strike<3:\r\n\ttry:\r\n\t\timport math\r\n\t\tgabs=int(input('3자리 값을 입력하세요(게임나가기: 0을 3번 입력하세요.): '))\r\n\t\tif gabs==000:\r\n\t\t\tprint('===========================================================================')\r\n\t\t\tsamjin='취소.......'\r\n\t\t\tbreak\r\n\t\tgabs1=gabs%10\r\n\t\tgabs=math.floor(gabs/10)\r\n\t\tgabs2=gabs%10\r\n\t\tgabs=math.floor(gabs/10)\r\n\t\tgabs3=gabs%10\r\n\t\tprint('===========================================================================')\r\n\t\tif gabs1>0:\r\n\t\t\tif randomgabs1==gabs1:\r\n\t\t\t\tstrike+=1\r\n\t\t\telif randomgabs1==gabs3:\r\n\t\t\t\tball+=1\r\n\t\t\telif randomgabs1==gabs2:\r\n\t\t\t\tball+=1\r\n\t\tif gabs2>0:\r\n\t\t\tif randomgabs2==gabs2:\r\n\t\t\t\tstrike+=1\r\n\t\t\telif randomgabs2==gabs3:\r\n\t\t\t\tball+=1\r\n\t\t\telif randomgabs2==gabs1:\r\n\t\t\t\tball+=1\r\n\t\tif gabs3>0:\r\n\t\t\tif randomgabs3==gabs3:\r\n\t\t\t\tstrike+=1\r\n\t\t\telif randomgabs3==gabs2:\r\n\t\t\t\tball+=1\r\n\t\t\telif randomgabs3==gabs1:\r\n\t\t\t\tball+=1\r\n\t\tif strike<3:\r\n\t\t\tprint('%d볼 |'%ball)\r\n\t\t\tprint('%d스트라이크 |'%strike)\r\n\t\t\tprint('===========================================================================')\r\n\t\tif strike==3:\r\n\t\t\tsamjin='삼진아웃! %d번 도전 했습니다.'%dojeansoo\r\n\t\t\tbreak\r\n\t\tdojeansoo+=1\r\n\t\tball=0\r\n\t\tstrike=0\r\n\texcept:\r\n\t\tprint('숫자를 입력하세요!!!!!!!!!')\r\nprint(samjin)","sub_path":"NB.py","file_name":"NB.py","file_ext":"py","file_size_in_byte":2003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"372729907","text":"from django.shortcuts import render\nfrom .models import EnquiryData\nfrom .forms import EnquiryForm,Crops\nfrom django.http.response import HttpResponse\n#import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.tree import DecisionTreeClassifier\n#from sklearn import tree\nfrom sklearn.preprocessing import LabelEncoder\nimport random\nimport numpy as np\n\n# Create your views here.\ndef show(request):\n return render(request,'show.html')\n\ndef enquiry(request):\n if request.method=='POST':\n eform = EnquiryForm(request.POST)\n if eform.is_valid():\n name = request.POST.get('name')\n email = request.POST.get('email')\n city = request.POST.get('city')\n mobile = request.POST.get('mobile')\n query = request.POST.get('query')\n data = EnquiryData(\n name = name,\n email = email,\n city = city,\n mobile = mobile,\n query = query,\n\n )\n data.save()\n eform = EnquiryForm()\n return render(request,'enquiry.html',{'eform':eform})\n else:\n return HttpResponse(\"Invalid User Data\")\n else:\n eform = EnquiryForm()\n return render(request, 'enquiry.html', {'eform': eform})\ndef contact(request):\n return render(request,'contact.html')\n\ndef crop_predict(request):\n if request.method=='POST':\n cform = Crops(request.POST)\n if cform.is_valid():\n location = request.POST.get('location')\n soil_type = request.POST.get('soil_type')\n month = request.POST.get('month')\n data = pd.read_csv(r'C:\\Users\\Atul Kumare\\Desktop\\FakePro\\FakeApp\\crop.csv')\n\n X = data[['Location', 'Avg_Soil_Type', 'Month']]\n Y = data[['Crop_production_1', 'Crop_production_2']]\n\n # Label encoder to cover the categorical values into the numeric\n number = LabelEncoder()\n X['Location'] = number.fit_transform(X['Location'].astype('str'))\n X['Avg_Soil_Type'] = number.fit_transform(X['Avg_Soil_Type'].astype('str'))\n X['Month'] = number.fit_transform(X['Month'].astype('str'))\n Y['Crop_production_1'] = number.fit_transform(Y['Crop_production_1'].astype('str'))\n Y['Crop_production_2'] = number.fit_transform(Y['Crop_production_2'].astype('str'))\n tree = DecisionTreeClassifier()\n tree.fit(X, Y)\n p=random.randint(0,21)\n q=random.randint(0,6)\n r=random.randint(0,11)\n X_new = [[p,q,r]]\n predict1 = tree.predict(X_new)\n # Graph Prediction using the predicted values\n X_year = [2016, 2017, 2018]\n y_cost_Crop1 = [predict1[0][0] + 2, predict1[0][0] + 3, predict1[0][0] + 4]\n y_selling_price_crop1 = [predict1[0][0] + 5, predict1[0][0] + 6, predict1[0][0] + 7]\n # Predict the selling_price_crop1\n plt.bar(X_year, y_selling_price_crop1, color='green')\n plt.xlabel('Year')\n plt.ylabel('Price')\n plt.title('Selling Price of Crop1 in past three years')\n plt.show()\n # Predict the cost_crop1\n plt.bar(X_year, y_cost_Crop1, color='green')\n plt.xlabel('Year')\n plt.ylabel('Cost')\n plt.title('Cost/Expenditure of Crop1 in past three years')\n plt.show()\n\n y_cost_Crop2 = [predict1[0][1] + 8, predict1[0][1] + 9, predict1[0][1] + 10]\n y_selling_price_crop2 = [predict1[0][1] + 11, predict1[0][1] + 12, predict1[0][1] + 13]\n # Predict the selling_price_crop2\n plt.bar(X_year, y_selling_price_crop2, color='green')\n plt.xlabel('Year')\n plt.ylabel('Price')\n plt.title('Selling Price of Crop2 in past three years')\n plt.show()\n # Predict the cost_crop2\n plt.bar(X_year, y_cost_Crop2, color='green')\n plt.xlabel('Year')\n plt.ylabel('Price')\n plt.title('Cost/Expenditure of Crop2 in past three years')\n plt.show()\n\n # Change the predicted values into categorical form\n #change = number.inverse_transform(predict1).split()\n #print(change)\n\n crop1=data['Crop_production_1'].any()\n crop2=data['Crop_production_2'].any()\n crop1 = \"First Crop is : \" + crop1\n crop2 = \"Second Crop is : \" + crop2\n cform = Crops()\n return render(request,'crop.html',{'crop1':crop1,'crop2':crop2,'cform':cform})\n else:\n cform = Crops()\n return render(request,'crop.html',{'cform':cform})","sub_path":"FakePro_2/FakeApp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"430169659","text":"\"\"\"\nCreates a corpus from Wikipedia dump file.\nInspired by:\nhttps://www.kdnuggets.com/2017/11/building-wikipedia-text-corpus-nlp.html\n\"\"\"\n\nimport os\nimport sys\n\nfrom gensim.corpora import WikiCorpus\nfrom gensim.test.utils import datapath\n\nfrom utils import path\n\n\ndef make_corpus(wiki_in_file, wiki_out_file):\n \"\"\"Convert Wikipedia xml dump file to text corpus\"\"\"\n\n path_to_wiki_dump = datapath(wiki_in_file)\n\n with open(wiki_out_file, 'w') as output:\n wiki = WikiCorpus(path_to_wiki_dump) # create word->word_id mapping\n i = 0\n for text in wiki.get_texts():\n output.write(bytes(' '.join(text), 'utf-8').decode('utf-8') + '\\n')\n i += 1\n if i % 10000 == 0:\n print('Processed ' + str(i) + ' articles')\n output.close()\n print('Processing complete!')\n\n\nif __name__ == '__main__':\n\n if len(sys.argv) > 2:\n print('Usage: python exract_wiki_data.py ')\n sys.exit(1)\n\n input_file = \"enwiki-latest-pages-articles1.xml-p000000010p000030302-shortened.bz2\"\n if len(sys.argv) == 2:\n in_file = sys.argv[1]\n\n out_file = os.path.join('..', 'data', 'extracted', 'wiki_en.txt')\n path.create_if_not_exists(out_file)\n make_corpus(input_file, out_file)\n","sub_path":"src/extract_wiki_data.py","file_name":"extract_wiki_data.py","file_ext":"py","file_size_in_byte":1284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"121899809","text":"import csv\nimport re\nimport string\n\nimport pandas as pd\n\n\"\"\"\nDedupe addresses csv file\n\n\"\"\"\n\ndef normalize(business_name):\n\t\"\"\"\n\treturns a normalized string that is all lowercase, with removed punctuation, removed extra whitespace,\n\tand also removed company suffixes, which were one specific difference between some of the dupes\n\t\n\t\"\"\"\n\tname = str(business_name).lower().strip()\n\tto_remove = ['llc', 'ltd', 'svc', 'inc']\n\tfor punc in string.punctuation:\n\t\tname = name.replace(punc, '')\n\tfor word in to_remove:\n\t\tif name.endswith(word):\n\t\t\tname = name.replace(word,'')\n\tname = re.sub(' +',' ', name)\n\treturn name\n\n\ndef dedupe_csv(csv_file, new_filename):\n\t\"\"\"take csv file and remove duplicates, writing new deduped csv filename \n\tas well as two column csv of duplicate business ids\n\t\"\"\"\n\t#business records/names we have seen so far\n\tcount = 0\n\trecords = set()\n\tseen = []\n\tdeduped_count = 0\n\twith open(csv_file,'r') as f, open(new_filename,'w') as write_file, open('dupes.csv', 'w') as dupes_file:\n\t\treader = csv.reader(f)\n\t\twriter = csv.writer(write_file)\n\t\tdupe_writer = csv.writer(dupes_file)\n\t\tfor row in reader:\n\t\t\t(building_id, address) = row\n\t\t\tcount += 1\n\t\t\tif count % 1000 == 0:\n\t\t\t\tprint(\"row...\")\n\t\t\t\tprint(count)\n\t\t\taddress = row[1]\n\t\t\tbuilding_id = row[0]\n\t\t\tif address in records:\n\t\t\t\tprint(\"dupe\")\n\t\t\t\tpass\n\t\t\telse:\n\t\t\t\tdeduped_count += 1\n\t\t\t\trecords.update(address)\n\t\t\t\tprint(records)\n\t\t\t\twriter.writerow(row)\n\tprint(\"list count: \")\n\tprint(count)\n\tprint(\"deduped count: \")\n\tprint(deduped_count)\n\treturn new_filename\n\n\ndef join_csv(csv1, csv2, column_to_join, joined_filename):\t\n\t\"\"\"join two csv files on specified column(column_to_join) and write to a new csv file\"\"\"\n\tfirst_file = pd.read_csv(csv1)\n\tsecond_file = pd.read_csv(csv2)\n\tjoined = first_file.merge(second_file, on=column_to_join)\n\tjoined.to_csv(joined_filename)\n\treturn\n\t\t\n\ndef summary_statistics(csv_file):\n\t\"\"\"\n\tsummary statistics + response rate + average revenue of the following groups:\n\t(statistics are in output from pandas)\n\t1. those who did not respond to interactive messages\n\t2. those who did not respond to text messages\n\t3. those who did respond to interactive messages\n\t4. those who did respond to text messages\n\n\t\"\"\"\n\tframe = pd.read_csv(csv_file)\n\t#correlation matrix\n\tframe.corr()\n\tdata_points_overall = frame.shape[0]\n\tresponded_yes = frame[frame[\"responded\"] == True]\n\ttotal_yes_response = responded_yes.shape[0]\n\toverall_yes_response_rate = responded_yes.shape[0] / data_points_overall\n\t#.07 = 7% response rate overall\n\n\tresponded_no = frame[frame[\"responded\"] == False]\n\tresponded_no.shape[0]\n\t#average revenue for those who did NOT respond to interactive messages\n\tresponded_no_interactive = responded_no[responded_no[\"message\"] == \"Interactive\"]\n\t#summary statistics\n\tresponded_no_interactive['revenue'].describe()\n\ttotal_no_response_interactive = responded_no_interactive.shape[0]\n\n\t#summary of those who did NOT respond to text messages\n\tresponded_no_text = responded_no[responded_no[\"message\"] == \"Text\"]\n\t#summary statistics\n\tresponded_no_text['revenue'].describe()\n\ttotal_no_response_text = responded_no_text.shape[0]\n\n\t#summary of those who DID respond to interactive messages\n\tresponded_yes_interactive = responded_yes[responded_yes[\"message\"] == \"Interactive\"]\n\t#summary statistics\n\tresponded_yes_interactive['revenue'].describe()\n\ttotal_yes_interactive = responded_yes_interactive.shape[0]\n\tresponse_to_interactive = total_yes_interactive / total_yes_response\n\n\t#overall interactive response rate\n\ttotal_interactive = total_no_response_interactive + total_yes_interactive\n\tinteractive_response_rate = total_yes_interactive / total_interactive\n\tprint(\"overall interactive response rate: \")\n\tprint(interactive_response_rate)\n\n\t#summary of those who DID respond to text messages\n\tresponded_yes_text = responded_yes[responded_yes[\"message\"] == \"Text\"]\n\t#summary statistics\n\tresponded_yes_text['revenue'].describe()\n\ttotal_yes_text = responded_yes_text.shape[0]\n\tresponse_to_text = total_yes_text / total_yes_response\n\ttotal_text = total_no_response_text + total_yes_text\n\n\t#overall text response rate\n\ttext_response_rate = total_yes_text / total_text\n\tprint(\"overall text response rate\")\n\tprint(text_response_rate)\n\treturn \n\n\n\n\nif __name__ == '__main__':\n\tdeduped = dedupe_csv('addresses.csv', 'deduped_addresses.csv')\n\t\n\t\n","sub_path":"analysis/management/commands/dedupe.py","file_name":"dedupe.py","file_ext":"py","file_size_in_byte":4328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"255647632","text":"#!/usr/bin/env python\n\nimport sys\nimport json\nimport shutil\nimport pandas as pd\nimport os\nDATA_PARAMS = '/config/data-params.json'\nTEST_PARAMS = '/config/test-params.json'\nTOP_PATH = os.environ['PWD']\nsys.path.append(TOP_PATH + '/src')\nfrom etl import get_data\nimport cleaning\n\ndef load_params(fp):\n with open(fp) as fh:\n param = json.load(fh)\n return param\n\n\ndef main(targets):\n if 'clean' in targets:\n shutil.rmtree('data/raw',ignore_errors=True)\n shutil.rmtree('data/out',ignore_errors=True)\n shutil.rmtree('data/test',ignore_errors=True)\n\n if 'data' in targets:\n cfg = load_params(TOP_PATH + DATA_PARAMS)\n get_data(**cfg)\n\n if 'test' in targets:\n cfg = load_params(TOP_PATH + TEST_PARAMS)\n get_data(**cfg)\n \n\n if 'transform' in targets:\n if not os.path.exists(TOP_PATH + '/data/cleaned'):\n os.makedirs(TOP_PATH + '/data/cleaned')\n for filename in os.listdir(TOP_PATH + '/data/raw'):\n if 'STOPS' in filename:\n if '2018' in filename:\n temp_df = cleaning.clean_2018_2019(TOP_PATH + '/data/raw/' + str(filename))\n elif '2017' in filename:\n temp_df = cleaning.clean_2017(TOP_PATH + '/data/raw/' + str(filename))\n else:\n temp_df = cleaning.clean_2014_2016(TOP_PATH + '/data/raw/' + str(filename))\n elif 'csv' in filename:\n temp_df = cleaning.clean_trends(TOP_PATH + '/data/raw/' + str(filename))\n return\n\n\n \n\n\nif __name__ == '__main__':\n targets = sys.argv[1:]\n main(targets)\n\n\n ","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"442269697","text":"\"\"\"\nSelection sort.\nhttps://en.wikipedia.org/wiki/Selection_sort\n\nWorst case time complexity: O(n^2)\nBest case time complexity: O(n^2)\n\n@author Juhan Bae\n@date 5/22/2018\n\"\"\"\n\n\nfrom Sort import Sort\nimport numpy as np\n\n\nclass SelectionSort(Sort):\n def __init__(self, lst):\n \"\"\" Initialize a class SelectionSort.\n :param lst: List[Object]\n \"\"\"\n Sort.__init__(self, lst)\n\n def sort(self):\n \"\"\" Return a sorted lst.\n :return: List[Object]\n\n >>> lst = SelectionSort([5, 4, 5, 1, 7, 4])\n >>> lst.sort()\n [1, 4, 4, 5, 5, 7]\n \"\"\"\n for i in range(len(self.lst)):\n # A pair of (value, index)\n min_ele = (np.inf, -1)\n for j in range(i, len(self.lst)):\n # Find the minimum among the list.\n if self.lst[j] < min_ele[0]:\n min_ele = (self.lst[j], j)\n self.lst[min_ele[1]], self.lst[i] = self.lst[i], self.lst[min_ele[1]]\n return self.lst\n\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod()","sub_path":"Sorting/SelectionSort.py","file_name":"SelectionSort.py","file_ext":"py","file_size_in_byte":1075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"504890048","text":"\n\n#calss header\nclass _GYROSCOPE():\n\tdef __init__(self,): \n\t\tself.name = \"GYROSCOPE\"\n\t\tself.definitions = [u\"a device containing a wheel that spins freely within a frame, used on aircraft and ships to help keep them horizontal, and as a children's toy\"]\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_gyroscope.py","file_name":"_gyroscope.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"321751289","text":"import asyncio\nimport json\n\nfrom channels.generic.websocket import AsyncJsonWebsocketConsumer\nfrom promise import Promise\n\nfrom ..constants import WS_PROTOCOL\nfrom .subscriptions import subscription_server\n\n\nclass JSONPromiseEncoder(json.JSONEncoder):\n def encode(self, *args, **kwargs):\n self.pending_promises = []\n return super(JSONPromiseEncoder, self).encode(*args, **kwargs)\n\n def default(self, o):\n if isinstance(o, Promise):\n if o.is_pending:\n self.pending_promises.append(o)\n return o.value\n return super(JSONPromiseEncoder, self).default(o)\n\n\nclass GraphQLSubscriptionConsumer(AsyncJsonWebsocketConsumer):\n async def connect(self):\n self.connection_context = None\n if WS_PROTOCOL in self.scope[\"subprotocols\"]:\n self.connection_context = await subscription_server.handle(\n ws=self, request_context=self.scope\n )\n await self.accept(subprotocol=WS_PROTOCOL)\n else:\n await self.close()\n\n async def disconnect(self, code):\n if self.connection_context:\n await subscription_server.on_close(self.connection_context)\n\n async def receive_json(self, content):\n asyncio.ensure_future(\n subscription_server.on_message(self.connection_context, content)\n )\n\n @classmethod\n async def encode_json(cls, content):\n json_promise_encoder = JSONPromiseEncoder()\n e = json_promise_encoder.encode(content)\n while json_promise_encoder.pending_promises:\n # Wait for pending promises to complete, then try encoding again.\n await asyncio.wait(json_promise_encoder.pending_promises)\n e = json_promise_encoder.encode(content)\n return e\n","sub_path":"graphql_ws_django/django/consumers.py","file_name":"consumers.py","file_ext":"py","file_size_in_byte":1786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"515832659","text":"#! /usr/bin/env python\n\n\"\"\"\nОбучение модели на основе градиентного бустинга\n\nОпции\n-----\n--data-filename, -f <ИМЯ_ФАЙЛА>\n Считать обучающие данные из этого файла. Это должен быть CSV файл без\n строки заголовка. Послений столбец считается столбцом целевых значений,\n остальные - матрицей признаков. Этот аргумент обязателен.\n\n--model-filename, -m <ИМЯ_ФАЙЛА>\n Имя файла, в который сохраняем обученную модель. Этот аргумент обязателен.\n\n--disable-extratrees\n Не обучать регрессор на основе случайного леса. Это поведение по умолчанию\n\n--enable-extratrees\n Обучить также регрессор на основе случайного леса.\n\n--disable-sklearn\n Не обучать регрессор sklearn.GradientBoostingRegressor\n\n--disable-xgboost\n Не обучать регрессор на основе XGBoost\n\n--disable-lgbm\n Не обучать регрессор на основе LightGBM\n\n--disable-catboost\n Не обучать регрессор на основе CatBoost\n\n--disable-gridsearch\n Не использовать GridSearch для подбора параметров моделей, использовать\n параметры по умолчанию или заданные вручную\n\n--disable-refit\n Отменить обучение итоговой лучшей модели на полном наборе обучающих данных.\n\n--verbosity <ЗНАЧЕНИЕ>\n Чем больше это значение, тем больше отладочной информации будет выводиться\n на экран.\n\n--n-estimators <ЗНАЧЕНИЕ>\n Задать количество деревьев. При использовании перебора гиперпараметров\n значение может быть числом, либо диапазоном чисел, а без перебора - только\n числом.\n\n--max-depth <ЗНАЧЕНИЕ>\n Задать максимальную глубину деревьев. При использовании перебора\n гиперпараметров значение может быть числом, либо диапазоном чисел,\n а без перебора - только числом.\n\n--remove-columns СПИСОК\n Удалить из исходных данных столбцы с указанными номерами. Номера\n столбцов задаются в формате списка диапазонов или отдельных чисел -\n например, \"1,3,7-9,15-20\" удалить первый столбец, третий, с седьмого\n по девятый и с пятнадцатого по двадцатый включительно.\n\n--keep-columns СПИСОК\n Удалить из исходных данных все столбцы, кроме столбцов с указанными\n номерами. Номера задаются также, как и номера столбцов для опции\n --remove-columns. Последний столбец, являющийся столбцом значений\n целевой переменной, всегда будет сохранен\n\n--named-columns\n Считать первую строку файла с данными строкой заголовка, содержащей\n имена столбцов. Пока этот аргумент не реализован\n\n--target НАЗВАНИЕ_ИЛИ_НОМЕР\n Считать именно этот столбец, а не последний, столбцом значений\n целевой переменной. Если задана опция --named-columns то указывается\n название столбца, иначе номер. Если номер отрицателен, то отсчет\n идет с конца, -1 для последнего столбца, -2 для предпоследнего.\n\"\"\"\n\nimport joblib\n\nfrom argparse import ArgumentParser\n\nfrom sklearn.model_selection import train_test_split\n\nimport pandas as pd\n\nfrom autogb import AutoGBRegressor\n\n\ndef number_in_list(num, ranges):\n \"\"\"\n Проверяет, что число num входит в список чисел, заданный перечислением\n диапазонов\n\n Параметры\n ---------\n num: int\n Число, которое может входить или не входить в список\n\n ranges: str\n Строка со списком чисел, перечисленных через запятую. В строке можно\n использовать диапазоны. Например, строка \"5,8,12,20-25,30,32-38\"\n будет эквивалентна списку [5, 8, 12, 20, 21, 22, 23, 24, 25, 30,\n 32, 33, 34, 35, 36, 37, 38].\n \"\"\"\n chunks = ranges.split(\",\")\n for chunk in chunks:\n if \"-\" in chunk[1:]:\n (start, end) = [int(x) for x in chunk.split(\"-\")]\n if num >= start and num <= end:\n return True\n elif str(num) == chunk.strip():\n return True\n return False\n\n\ndef prepare_data(filename: str,\n *,\n remove_columns: str = None,\n keep_columns: str = None,\n target: str = None):\n \"\"\"\n Считывает данные из файла filename, отделяет последний столбец\n как столбец целевых значений, остальное - как матрицу признаков\n\n Параметры\n ---------\n filename : строка\n Имя файла с данными. Это должен быть файл в CSV формате\n без заголовка\n\n Возвращает\n ----------\n X : numpy.ndarray, размер n_samples * n_features\n Матрица признаков, состоящая из всех считанных данных,\n кроме последнего столбца\n\n y : numpy.ndarray, размер n_samples\n Вектор целевых значений\n\n Замечания\n ---------\n Эта функция частично дублирована в файле reg_train.py\n \"\"\"\n # Считываем данные из файла, без заголовка\n data = pd.read_csv(filename, header=None)\n # И объявляем последний или заданый столбец значениями целевой переменной\n if target is None:\n last_column = len(data.columns) - 1\n else:\n last_column = int(target)\n if last_column < 0:\n last_column = len(data.columns) - 1\n if keep_columns is not None:\n # Если нужно оставить только некоторые столбцы - оставляем только их\n cols = [\n col for col in data.columns if number_in_list(col, keep_columns)\n ]\n if last_column not in cols:\n cols.append(last_column)\n data = data[cols]\n if remove_columns is not None:\n # Если нужно убрать некоторые столбцы - убираем их\n cols = [\n col for col in data.columns if not number_in_list(col, remove_columns)\n ]\n if last_column not in cols:\n cols.append(last_column)\n data = data[cols]\n # Сразу после чтения столбцы будут инде��сированы числами, так\n # что столбец с максимальным номером переименовываем в y,\n # а с остальными номерами N - в строку xN.\n data.rename(\n columns=lambda x: \"y\" if x == last_column else \"x{}\".format(x),\n inplace=True\n )\n # Делим данные на обучающие и тестовые\n X = data.drop('y', axis='columns').astype(float)\n y = data['y'].astype(float).values\n return (X, y)\n\n\nif __name__ == \"__main__\":\n parser = ArgumentParser(\n usage=\"{} --data-filename=<ИМЯ_ФАЙЛА> --model-filename=<ИМЯ_ФАЙЛА> [ДОП_ПАРАМЕТРЫ]\",\n description=\"Обучает модель градиентного бустинга на заданном файле с данными и сохраняет в заданный файл\",\n add_help=True\n )\n parser.add_argument(\n \"--data-filename\", \"-f\",\n help=\"Имя входного файла с данными, ожидается CSV без строки заголовка\",\n required=True,\n type=str,\n metavar=\"ИМЯ_ФАЙЛА\",\n dest=\"data_filename\"\n )\n parser.add_argument(\n \"--model-filename\", \"-m\",\n help=\"Имя файла для сохранения модели Scikit-Learn, с использованием joblib.dump\",\n required=True,\n type=str,\n metavar=\"ИМЯ_ФАЙЛА\",\n dest=\"model_filename\"\n )\n parser.add_argument(\n \"--disable-extratrees\",\n help=\"Не использовать модель на основе случайного леса\",\n action=\"store_const\",\n const=True,\n default=True,\n dest=\"disable_extratrees\"\n )\n parser.add_argument(\n \"--enable-extratrees\",\n help=\"Не использовать модель на основе случайного леса\",\n action=\"store_const\",\n const=False,\n default=True,\n dest=\"disable_extratrees\"\n )\n parser.add_argument(\n \"--disable-sklearn\",\n help=\"Не использовать модель sklearn.GradientBoostingRegressor\",\n action=\"store_const\",\n const=True,\n default=False,\n dest=\"disable_sklearn\"\n )\n parser.add_argument(\n \"--disable-xgboost\",\n help=\"Не использовать модель xgboost.XGBRegressor\",\n action=\"store_const\",\n const=True,\n default=False,\n dest=\"disable_xgboost\"\n )\n parser.add_argument(\n \"--disable-lgbm\",\n help=\"Не использовать модель lightgbm.LGBMRegressor\",\n action=\"store_const\",\n const=True,\n default=False,\n dest=\"disable_lgbm\"\n )\n parser.add_argument(\n \"--disable-catboost\",\n help=\"Не использовать модель catboost.CatBoostRegressor\",\n action=\"store_const\",\n const=True,\n default=False,\n dest=\"disable_catboost\"\n )\n parser.add_argument(\n \"--disable-gridsearch\",\n help=\"Не подбирать гиперпараметры, использовать заданные вручную или по умолчанию\",\n action=\"store_const\",\n const=True,\n default=False,\n dest=\"disable_gridsearch\"\n )\n parser.add_argument(\n \"--disable-refit\",\n help=\"Не обучать итоговую модель на полном наборе данных. Она будет обучена примерно на 64 процентах данных\",\n action=\"store_const\",\n const=True,\n default=False,\n dest=\"disable_refit\"\n )\n parser.add_argument(\n \"--verbosity\",\n help=\"Выводить на экран отладочную информацию в процессе работы\",\n action=\"store\",\n type=int,\n default=0,\n metavar=\"VALUE\",\n dest=\"verbosity\"\n )\n parser.add_argument(\n \"--n-estimators\",\n help=\"Указать число деревьев для построения леса\",\n action=\"store\",\n type=str,\n default=None,\n metavar=\"NUMBER_OR_RANGE\",\n dest=\"n_estimators\"\n )\n parser.add_argument(\n \"--max-depth\",\n help=\"Указать число уровней деревьев\",\n action=\"store\",\n type=str,\n default=None,\n metavar=\"NUMBER_OR_RANGE\",\n dest=\"max_depth\"\n )\n parser.add_argument(\n \"--remove-columns\",\n help=\"Удалить из данных столбцы с указанными номерами\",\n action=\"store\",\n type=str,\n default=None,\n metavar=\"COLUMN_LIST\",\n dest=\"remove_columns\"\n )\n parser.add_argument(\n \"--keep-columns\",\n help=\"Удалить из данных все столбцы кроме указанных\",\n action=\"store\",\n type=str,\n default=None,\n metavar=\"COLUMN_LIST\",\n dest=\"keep_columns\"\n )\n parser.add_argument(\n \"--target\",\n help=\"Считать этот столбец столбцом целевой переменной\",\n action=\"store\",\n type=str,\n default=None,\n metavar=\"COLUMN\",\n dest=\"target\"\n )\n args = parser.parse_args()\n # Считать данные и разделить на обучающие и тестовые\n (X, y) = prepare_data(\n args.data_filename,\n keep_columns=args.keep_columns,\n remove_columns=args.remove_columns,\n target=args.target\n )\n (X_train, X_test, y_train, y_test) = train_test_split(X, y, random_state=0)\n # Создать модель AutoGB с заданными параметрами\n model = AutoGBRegressor(\n use_extratrees=not args.disable_extratrees,\n use_sklearn=not args.disable_sklearn,\n use_xgboost=not args.disable_xgboost,\n use_lgbm=not args.disable_lgbm,\n use_catboost=not args.disable_catboost,\n use_gridsearch=not args.disable_gridsearch,\n refit=not args.disable_refit,\n verbosity=args.verbosity,\n n_estimators=args.n_estimators,\n max_depth=args.max_depth\n )\n # Обучить модель на обучающих данных\n model.fit(X_train, y_train)\n # Вывести на экран качество модели на обучающих данных и те нестовых данных\n print(\"Модель обучена, объект модели:\")\n print(str(model.best_model_))\n print(\"Качество на обучающих данных = {}\".format(model.score(X_train, y_train)))\n print(\"Качество на тестовых данных = {}\".format(model.score(X_test, y_test)))\n print(\"Лучшая модель обучается на полном наборе данных...\")\n # А теперь обучить уже на всех данных и сохранить в файл\n if not args.disable_refit:\n model.best_model_.fit(X, y)\n joblib.dump(model.best_model_, args.model_filename)\n print(\"Модель сохранена в файл {}\".format(args.model_filename))\n","sub_path":"run_autogb.py","file_name":"run_autogb.py","file_ext":"py","file_size_in_byte":15322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"147414058","text":"# Licensed under a 3-clause BSD style license - see LICENSE.rst\n# -*- coding: utf-8 -*-\n\"\"\"\n==================\nprospect.utilities\n==================\n\nUtility functions for prospect.\n\"\"\"\n\nimport os, glob\nfrom pkg_resources import resource_string, resource_listdir\n\nimport numpy as np\nimport astropy.io.fits\nfrom astropy.table import Table, vstack\nimport scipy.ndimage.filters\n\n_desiutil_imported = True\ntry:\n from desiutil.log import get_logger\nexcept ImportError:\n _desiutil_imported = False\n\n_desispec_imported = True\ntry:\n import desispec.spectra\n import desispec.frame\nexcept ImportError:\n _desispec_imported = False\n\n_desitarget_imported = True\ntry:\n from desitarget.targetmask import desi_mask\n from desitarget.cmx.cmx_targetmask import cmx_mask\n from desitarget.sv1.sv1_targetmask import desi_mask as sv1_desi_mask\n from desitarget.sv1.sv1_targetmask import bgs_mask as sv1_bgs_mask\nexcept ImportError:\n _desitarget_imported = False\n\n_redrock_imported = True\ntry:\n import redrock.results\nexcept ImportError:\n _redrock_imported = False\n\n\n# from prospect import mycoaddcam # Does not appear to be used in this module.\nfrom prospect import myspecselect, myspecupdate\n\nvi_flags = [\n # Definition of VI flags\n # Replaces former list viflags = [\"Yes\",\"No\",\"Maybe\",\"LowSNR\",\"Bad\"]\n # shortlabels for \"issue\" flags must be a unique single-letter identifier\n {\"label\" : \"4\", \"type\" : \"class\", \"description\" : \"Confident classification: two or more secure features.\"},\n {\"label\" : \"3\", \"type\" : \"class\", \"description\" : \"Probable classification: at least one secure spectral feature + continuum or many weak spectral features.\"},\n {\"label\" : \"2\", \"type\" : \"class\", \"description\" : \"Possible classification: one strong spectral feature but unsure what it is.\"},\n {\"label\" : \"1\", \"type\" : \"class\", \"description\" : \"Unlikely classification: clear signal but features are unidentified.\"},\n {\"label\" : \"0\", \"type\" : \"class\", \"description\" : \"Nothing there, no signal.\"},\n {\"label\" : \"Bad redshift fit\", \"shortlabel\" : \"R\", \"type\" : \"issue\", \"description\" : \"Mis-estimation of redshift by the pipeline fitter\"},\n {\"label\" : \"Bad spectype fit\", \"shortlabel\" : \"C\", \"type\" : \"issue\", \"description\" : \"Mis-identification of spectral type from the best-fit pipeline solution; e.g., star vs QSO...\"},\n {\"label\" : \"Bad spectrum\", \"shortlabel\" : \"S\", \"type\" : \"issue\", \"description\" : \"Bad spectrum; e.g. strong cosmic/skyline subtraction residuals.\"}\n]\n\nvi_file_fields = [\n # Contents of VI files: [\n # field name (in VI file header),\n # associated variable in cds_targetinfo,\n # dtype in VI file ]\n # Ordered list\n [\"TARGETID\", \"targetid\", \"i8\"],\n [\"EXPID\", \"expid\", \"i4\"],\n [\"NIGHT\", \"night\", \"i4\"],\n [\"TILEID\", \"tileid\", \"i4\"],\n [\"Spec_version\", \"spec_version\", \"i4\"],\n [\"Redrock_version\", \"redrock_version\", \"i4\"], # TODO define\n [\"Template_version\", \"template_version\", \"i4\"], # TODO define\n [\"Redrock_spectype\", \"spectype\", \"S10\"],\n [\"Redrock_z\", \"z\", \"f4\"],\n [\"VI_scanner\", \"VI_scanner\", \"S10\"],\n [\"VI_quality\", \"VI_class_flag\", \"i2\"],\n [\"VI_issue\", \"VI_issue_flag\", \"S6\"],\n [\"VI_z\", \"VI_z\", \"f4\"],\n [\"VI_spectype\", \"VI_spectype\", \"S10\"],\n [\"VI_comment\", \"VI_comment\", \"S100\"]\n]\n\nvi_spectypes =[\n # List of spectral types to fill in VI categories\n # in principle, it should match somehow redrock spectypes...\n \"STAR\",\n \"GALAXY\",\n \"QSO\"\n]\n\nvi_std_comments = [\n # Standardized VI comments\n \"Broad absorption line quasar (BAL)\",\n \"Damped Lyman-alpha system (DLA)\",\n \"Two objects in spectrum\",\n \"Blazar\"\n]\n\n_resource_cache = {'templates': None, 'js': None}\n\n\ndef get_resources(filetype):\n \"\"\"Find all HTML template or JavaScript files in the package.\n\n Caches the results for quick access.\n\n Parameters\n ----------\n filetype : {'templates', 'js'}\n The type of file resource needed.\n\n Returns\n -------\n :class:`dict`\n A dictionary mapping filename to the contents of the file.\n\n Raises\n ------\n ValueError\n If `filetype` is unknown.\n \"\"\"\n global _resource_cache\n if filetype not in _resource_cache:\n raise ValueError(\"Unknown filetype '{0}' for get_resources()!\".format(filetype))\n if _resource_cache[filetype] is None:\n _resource_cache[filetype] = dict()\n for f in resource_listdir('prospect', filetype):\n _resource_cache[filetype][f] = resource_string('prospect', filetype + '/' + f).decode('utf-8')\n return _resource_cache[filetype]\n\n\ndef read_vi(vifile):\n '''Read visual inspection file (ASCII/CSV or FITS according to file extension).\n\n Parameters\n ----------\n vifile : :class:`str`\n Catalog filename.\n\n Returns\n -------\n :class`~astropy.table.Table`\n The full VI catalog.\n\n Raises\n ------\n ValueError\n If the extension is invalid, or if the file contains invalid columns.\n '''\n vi_records = [x[0] for x in vi_file_fields]\n vi_dtypes = [x[2] for x in vi_file_fields]\n _, ext = os.path.splitext(vifile)\n if ext not in ('.fits', '.fit', '.fts', '.csv'):\n raise ValueError(f\"Invalid file extension: {ext}!\")\n if ext == \".csv\":\n vi_info = Table.read(vifile, format='ascii.csv', names=vi_records)\n for i, rec in enumerate(vi_records):\n vi_info[rec] = vi_info[rec].astype(vi_dtypes[i])\n else:\n vi_info = Table.read(vifile)\n if [(x in vi_info.names) for x in vi_records] != [True for x in vi_records]:\n raise ValueError(\"Wrong record names in VI fits file!\")\n\n return vi_info\n\n\ndef match_vi_targets(vifile, targetlist) :\n '''\n Returns list of VIs matching the list of targetids\n For a given target, several VI entries can be available\n '''\n vi_info = read_vi(vifile)\n vicatalog=[ [] for i in range(len(targetlist)) ]\n for itarget,targetnum in enumerate(targetlist) :\n w,=np.where( (vi_info['targetid'] == targetnum) )\n if len(w)>0 : vicatalog[itarget] = vi_info[w]\n return vicatalog\n\n\ndef convert_vi_tofits(vifile_in, overwrite=True) :\n log = get_logger()\n if vifile_in[-4:] != \".csv\" : raise RuntimeError(\"wrong file extension\")\n vi_info = read_vi(vifile_in)\n vifile_out=vifile_in.replace(\".csv\",\".fits\")\n vi_info.write(vifile_out, format='fits', overwrite=overwrite)\n log.info(\"Created fits file : \"+vifile_out+\" (\"+str(len(vi_info))+\" entries).\")\n\n\ndef initialize_master_vi(mastervifile, overwrite=False) :\n '''\n Create \"master\" VI file with no entry\n '''\n log = get_logger()\n vi_records = [x[0] for x in vi_file_fields]\n vi_dtypes = [x[2] for x in vi_file_fields]\n vi_info = Table(names=vi_records, dtype=tuple(vi_dtypes))\n vi_info.write(mastervifile, format='fits', overwrite=overwrite)\n log.info(\"Initialized VI file : \"+mastervifile+\" (0 entry)\")\n\n\ndef merge_vi(mastervifile, newvifile) :\n '''\n Merge a new VI file to the \"master\" VI file\n The master file is overwritten.\n '''\n log = get_logger()\n mastervi = read_vi(mastervifile)\n newvi = read_vi(newvifile)\n mergedvi = vstack([mastervi,newvi], join_type='exact')\n mergedvi.write(mastervifile, format='fits', overwrite=True)\n log.info(\"Updated master VI file : \"+mastervifile+\" (now \"+str(len(mergedvi))+\" entries).\")\n\n\ndef match_zcat_to_spectra(zcat_in, spectra) :\n '''\n zcat_in : astropy Table from redshift fitter\n - creates a new astropy Table whose rows match the targetids of input spectra\n - also returns the corresponding list of indices\n - for each targetid, a unique row in zcat_in must exist.\n TODO : maybe rename this fct ? match_table_to_spectra ?\n => it also works whatever kind of input zcat : just has to be a table with 'TARGETID' key\n => in particular it's useful for \"redrock_cat\" tables\n '''\n\n if zcat_in is None : return None\n\n zcat_out = Table(dtype=zcat_in.dtype)\n index_list = list()\n for i_spec in range(spectra.num_spectra()) :\n ww, = np.where((zcat_in['TARGETID'] == spectra.fibermap['TARGETID'][i_spec]))\n if len(ww)<1 :\n raise RuntimeError(\"No zcat entry for target \"+str(spectra.fibermap['TARGETID'][i_spec]))\n if len(ww)>1 :\n raise RuntimeError(\"Several zcat entries for target \"+str(spectra.fibermap['TARGETID'][i_spec]))\n zcat_out.add_row(zcat_in[ww[0]])\n index_list.append(ww[0])\n return (zcat_out, index_list)\n\n\ndef match_redrock_zfit_to_spectra(redrockfile, spectra, Nfit=None) :\n '''\n Read Redrock file, and return astropy Table of best fits matched to the targetids of input spectra\n - for each target, store arrays chi2[Nfit], coeff[Nfit], z[Nfit], spectype[Nfit], subtype[Nfit]\n - if Nfit is None: take all available fits\n '''\n\n dummy, rr_table = redrock.results.read_zscan(redrockfile)\n rr_targets = rr_table['targetid']\n if Nfit is None :\n ww, = np.where( (rr_targets == rr_targets[0]) )\n Nfit = len(ww)\n matched_redrock_cat = Table(dtype=[('TARGETID', ' zbest_cat ?\n Extract a z catalog from redrock catalog produced in match_redrock_zfit_to_spectra()\n The z catalog has one fit per targetid, corresponding to the (fit_num)th best fit\n '''\n\n rr_cat_num_best_fits = redrock_cat['Z'].shape[1]\n if (fit_num >= rr_cat_num_best_fits) : raise ValueError(\"fit_num too large wrt redrock_cat\")\n zcat_dtype=[('TARGETID', '0 :\n target_dict[tile+\"-\"+night]['exps'] = np.array([fn.replace('.','-').split('-')[-2] for fn in fns])\n # targetid, fibres\n targetid,fiber,petal_list = [],[],[]\n for petal in petals:\n pp = glob.glob(os.path.join(tiledir,tile,night,'zbest-'+petal+'-'+tile+'-'+night+'.fits'))\n if len(pp)>0 :\n fn = pp[0]\n fm = Table.read(fn, 'FIBERMAP')\n tid, keep = np.unique(fm['TARGETID'], return_index=True)\n data = fm[keep]\n #data = astropy.io.fits.open(fn)['fibermap'].data # Not ok with andes\n targetid += data['TARGETID'].tolist()\n fiber += data['FIBER'].tolist()\n petal_list += [petal for i in range(len(data['TARGETID']))]\n target_dict[tile+\"-\"+night]['targetid'] = np.array(targetid, dtype='int64')\n target_dict[tile+\"-\"+night]['fiber'] = np.array(fiber)\n target_dict[tile+\"-\"+night]['petal'] = np.array(petal_list)\n\n return target_dict\n\ndef load_spectra_zcat_from_targets(targets, tiledir, obs_db, with_redrock=False) :\n '''\n Creates (spectra,zcat,[redrock_cat]) = (Spectra object, zcatalog Table, [redrock Table]) from a list of targetids\n - targets must be a list of int64\n - obs_db: \"mini-db\" produced by make_targetdict()\n - with_redrock: if True, also get redrock Table\n '''\n\n targets = np.asarray(targets)\n if targets.dtype != 'int64' :\n raise TypeError('Targetids should be int64.')\n spectra = None\n ztables, rrtables = [], []\n\n for tile_night in obs_db.keys() :\n petals = np.unique(obs_db[tile_night]['petal'])\n for petal in petals :\n targets_subset = []\n for target in targets :\n w, = np.where( (obs_db[tile_night]['targetid']==target) & (obs_db[tile_night]['petal']==petal) )\n if len(w) == 0 : continue\n if len(w) > 1 :\n print(\"Warning ! Several entries in tile/night \"+tile_night+\" available for target \"+str(target))\n targets_subset.append(target)\n # Load spectra for that tile/night/petal only if there's a target from the list\n if len(targets_subset)>0 :\n the_path = tile_night.replace(\"-\",\"/\")\n the_spec = desispec.io.read_spectra(os.path.join(tiledir,the_path,\"coadd-\"+petal+\"-\"+tile_night+\".fits\"))\n the_spec = myspecselect.myspecselect(the_spec, targets=targets_subset, remove_scores=True)\n the_zcat = Table.read(os.path.join(tiledir,the_path,\"zbest-\"+petal+\"-\"+tile_night+\".fits\"),'ZBEST')\n the_zcat, dummy = match_zcat_to_spectra(the_zcat, the_spec)\n ztables.append(the_zcat)\n if with_redrock :\n rrfile = os.path.join(tiledir,the_path,\"redrock-\"+petal+\"-\"+tile_night+\".h5\")\n the_rrcat = match_redrock_zfit_to_spectra(rrfile, the_spec, Nfit=None)\n rrtables.append(the_rrcat)\n if spectra is None : spectra = the_spec\n else : spectra = myspecupdate.myspecupdate(spectra,the_spec)\n\n # Check if all targets were found in spectra\n tids_spectra = spectra.fibermap['TARGETID']\n for target in targets :\n if target not in tids_spectra : print(\"Warning! targetid not found: \"+str(target))\n\n zcat = vstack(ztables)\n if with_redrock :\n rrcat = vstack(rrtables)\n return (spectra, zcat, rrcat)\n else :\n return (spectra,zcat)\n\n\ndef get_y_minmax(pmin, pmax, data, ispec) :\n '''\n Utility, from plotframe\n '''\n dx = np.sort(data[np.isfinite(data)])\n if len(dx)==0 : return (0,0)\n imin = int(np.floor(pmin*len(dx)))\n imax = int(np.floor(pmax*len(dx)))\n if (imax >= len(dx)) : imax = len(dx)-1\n return (dx[imin],dx[imax])\n\n\n\ndef frames2spectra(frames, nspec=None, startspec=None, with_scores=False, with_resolution_data=False):\n '''Convert input list of Frames into Spectra object\n with_score : if true, propagate scores\n with_resolution_data: if true, propagate resolution\n '''\n bands = list()\n wave = dict()\n flux = dict()\n ivar = dict()\n mask = dict()\n res = dict()\n\n for fr in frames:\n fibermap = fr.fibermap\n band = fr.meta['CAMERA'][0]\n bands.append(band)\n wave[band] = fr.wave\n flux[band] = fr.flux\n ivar[band] = fr.ivar\n mask[band] = fr.mask\n res[band] = fr.resolution_data\n if nspec is not None :\n if startspec is None : startspec = 0\n flux[band] = flux[band][startspec:nspec+startspec]\n ivar[band] = ivar[band][startspec:nspec+startspec]\n mask[band] = mask[band][startspec:nspec+startspec]\n res[band] = res[band][startspec:nspec+startspec,:,:]\n fibermap = fr.fibermap[startspec:nspec+startspec]\n\n merged_scores = None\n if with_scores :\n scores_columns = frames[0].scores.columns\n for i in range(1,len(frames)) :\n scores_columns += frames[i].scores.columns\n merged_scores = astropy.io.fits.FITS_rec.from_columns(scores_columns)\n\n if not with_resolution_data : res = None\n\n spectra = desispec.spectra.Spectra(\n bands, wave, flux, ivar, mask, fibermap=fibermap, meta=fr.meta, scores=merged_scores, resolution_data=res\n )\n return spectra\n\n\ndef specviewer_selection(spectra, log=None, mask=None, mask_type=None, gmag_cut=None, rmag_cut=None, chi2cut=None, zbest=None, snr_cut=None, with_dirty_mask_merge=False, remove_scores=False) :\n '''\n Simple sub-selection on spectra based on meta-data.\n Implemented cuts based on : target mask ; photo mag (g, r) ; chi2 from fit ; SNR (in spectra.scores, BRZ)\n - if chi2cut : a catalog zbest must be provided, with entries matching exactly those of spectra\n '''\n\n # SNR selection\n if snr_cut is not None :\n assert ( (len(snr_cut)==2) and (spectra.scores is not None) )\n for band in ['B','R','Z'] :\n w, = np.where( (spectra.scores['MEDIAN_CALIB_SNR_'+band]>snr_cut[0]) & (spectra.scores['MEDIAN_CALIB_SNR_'+band]0) & (spectra.fibermap['MW_TRANSMISSION_G']>0) )\n gmag[w] = -2.5*np.log10(spectra.fibermap['FLUX_G'][w]/spectra.fibermap['MW_TRANSMISSION_G'][w])+22.5\n w, = np.where( (gmag>gmag_cut[0]) & (gmag0) & (spectra.fibermap['MW_TRANSMISSION_R']>0) )\n rmag[w] = -2.5*np.log10(spectra.fibermap['FLUX_R'][w]/spectra.fibermap['MW_TRANSMISSION_R'][w])+22.5\n w, = np.where( (rmag>rmag_cut[0]) & (rmagchi2cut[0]) & (zbest['DELTACHI2'] 1:\n outwave, outflux, outivar, outrdat = _coadd(\n spectra.wave[channel],\n spectra.flux[channel][ii],\n spectra.ivar[channel][ii],\n spectra.resolution_data[channel][ii]\n )\n if mask is not None:\n outmask = spectra.mask[channel][ii[0]]\n for j in range(1, len(ii)):\n outmask |= spectra.mask[channel][ii[j]]\n else:\n outwave, outflux, outivar, outrdat = (\n spectra.wave[channel],\n spectra.flux[channel][ii[0]],\n spectra.ivar[channel][ii[0]],\n spectra.resolution_data[channel][ii[0]]\n )\n if mask is not None:\n outmask = spectra.mask[channel][ii[0]]\n\n flux[channel][i] = outflux\n ivar[channel][i] = outivar\n rdat[channel][i] = outrdat\n if mask is not None:\n mask[channel][i] = outmask\n\n return desispec.spectra.Spectra(spectra.bands, wave, flux, ivar,\n mask=mask, resolution_data=rdat, fibermap=fibermap,\n meta=spectra.meta)\n","sub_path":"py/prospect/utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":26756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"583814156","text":"# -*- coding: utf-8 -*-\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom variables import cols, d\r\nfrom dataloader import train_data\r\nimport nltk\r\nimport _pickle\r\nfrom preorganizer import changedf\r\n\r\nfrom variables import lin, cfd, total, mingram\r\n\r\n\r\ndef mapval(a, i):\r\n u,inv = np.unique(a,return_inverse= True)\r\n tel = tuple(np.array([d[x] for x in u])[inv])\r\n lin[str(i)].add(tel)\r\n \r\ndef trainmode(df = train_data, mode = \"train\"):\r\n npdf = changedf(df)\r\n for i in cols:\r\n #distribution counting\r\n val = pd.DataFrame(np.unique(npdf[str(i)]))\r\n tokd = pd.DataFrame(val[0].map(str).apply(list))\r\n tokd[0].apply(mapval,args = (i,))\r\n\r\n ##Language model implementation\r\n toke = list(val[0].str.cat(sep='\\n'))\r\n mingram[str(i)] = 3\r\n u,inv = np.unique(toke,return_inverse = True)\r\n te = np.array([d[x] for x in u])[inv].reshape(len(toke))\r\n total[str(i)] = len(te)\r\n bigr = nltk.ngrams(te,mingram[str(i)])\r\n condition_pairs = (((w[:-1]), w[-1]) for w in bigr)\r\n cfd[str(i)] = nltk.ConditionalFreqDist(condition_pairs)\r\n print(\"Column \",str(i), \"is completed\")\r\n if (mode == \"feedback\"):\r\n (lind,cfdd,totald,mingramd) = _pickle.load(open(\"save.p\",\"rb\"))\r\n linn = {key:set() for key in cols}\r\n cfdn = dict()\r\n for ij in cols:\r\n linn[str(ij)] = lind[str(ij)] | lin[str(ij)]\r\n cfdn[str(ij)] = {**dict(cfdd[str(ij)]),**dict(cfd[str(ij)])}\r\n# totaln[str(ij)] = {**dict(totald[str(ij)]), **dict(total[str(ij)])}\r\n tobestored = (linn,cfdn,totald, mingramd)\r\n return (linn,cfdn,totald, mingramd)\r\n# _pickle.dump(tobestored, open(\"save.p\",\"wb\"))\r\n# print(cfdn)\r\n elif (mode==\"train\"):\r\n tobestored = (lin,cfd,total,mingram)\r\n _pickle.dump(tobestored,open(\"save.p\", \"wb\"))\r\n print(cfd)\r\n ","sub_path":"AI_System/python_source/trainModel.py","file_name":"trainModel.py","file_ext":"py","file_size_in_byte":1916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"455052550","text":"import torch\nimport pandas as pd\n\nfrom torch.utils.data import Dataset\n\n\ndef read_nsmc_examples(split):\n file_dir = {\n \"train\": \"data/ratings_train.txt\",\n \"test\": \"data/ratings_test.txt\"\n }\n\n if split.lower() not in file_dir:\n raise ValueError(f\"Invalid data type \\\"{split}\\\"\")\n\n df = pd.read_csv(file_dir[split.lower()], sep='\\t', encoding='utf-8')\n df.dropna(inplace=True)\n\n examples = []\n for example in list(zip(df[\"id\"], df[\"document\"], df[\"label\"].values)):\n uid, text, label = example\n examples.append(dict(uid=uid, text=text, label=label))\n\n return examples\n\n\nclass NSMCDataSet(Dataset):\n def __init__(self, data_split, tokenizer, max_seq_length=512, pad_to_max=False):\n\n self.tokenizer = tokenizer\n self.bos_token_id = 3\n self.eos_token_id = 4\n self.pad_token_id = 0\n\n self.max_seq_length = max_seq_length\n self.pad_to_max = pad_to_max\n\n self.examples = read_nsmc_examples(data_split)\n self.features = self._featurize()\n\n def _featurize(self):\n features = []\n for example in self.examples:\n tokens, _ = self.tokenizer.tokenize(example[\"text\"])\n input_ids = self.tokenizer.convert_tokens_to_ids(tokens)\n features.append(dict(input_ids=input_ids, label=example[\"label\"]))\n\n return features\n\n def __getitem__(self, index):\n return self.features[index]\n\n def __len__(self):\n return len(self.features)\n\n def collate_fn(self, batch):\n all_input_ids = []\n all_attention_mask = []\n all_labels = []\n\n lengths = []\n for feature in batch:\n input_ids = feature[\"input_ids\"]\n\n if len(input_ids) > (self.max_seq_length-2):\n input_ids = input_ids[:(self.max_seq_length-2)]\n input_ids = [self.bos_token_id] + input_ids + [self.eos_token_id]\n attention_mask = [1] * len(input_ids)\n\n if self.pad_to_max:\n pad_length = self.max_seq_length - len(input_ids)\n input_ids.extend([self.pad_token_id] * pad_length)\n attention_mask.extend([0] * pad_length)\n else:\n lengths.append(len(input_ids))\n\n all_input_ids.append(input_ids)\n all_attention_mask.append(attention_mask)\n all_labels.append(feature[\"label\"])\n\n if not self.pad_to_max:\n max_seq_length_in_batch = max(lengths)\n\n for i in range(len(batch)):\n pad_length = max_seq_length_in_batch - len(all_input_ids[i])\n all_input_ids[i].extend([self.pad_token_id] * pad_length)\n all_attention_mask[i].extend([0] * pad_length)\n\n return all_input_ids, all_attention_mask, all_labels\n","sub_path":"dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":2800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"580738761","text":"# 5356: 의석이의 세로로 말해요\n\nT = int(input())\nfor test_case in range(1, T+1):\n wlist = [] # input lists\n for _ in range(5):\n wlist.append(input())\n \n # find the maximum length btw lists in wlist\n max_len = 0\n for lists in wlist:\n if len(lists) > max_len:\n max_len = len(lists)\n \n answer = ''\n for i in range(max_len):\n for j in range(5):\n if i < len(wlist[j]):\n answer += wlist[j][i]\n \n print(\"#{} {}\".format(test_case, answer))\n\n\n\n\n\n\"\"\"\n아직 글을 모르는 의석이가 벽에 걸린 칠판에 자석이 붙어있는 글자들을 붙이는 장난감을 가지고 놀고 있다.\n\n이 장난감에 있는 글자들은 영어 대문자 ‘A’부터 ‘Z’, 영어 소문자 ‘a’부터 ‘z’, 숫자 ‘0’부터 ‘9’이다. 의석이는 칠판에 글자들을 수평으로 일렬로 붙여서 단어를 만든다.\n\n다시 그 아래쪽에 글자들을 붙여서 또 다른 단어를 만든다. 이런 식으로 다섯 개의 단어를 만든다. 아래에 의석이가 칠판에 붙여 만든 단어들의 예가 있다.\n \n\nA A B C D D\n\na f z z\n\n0 9 1 2 1\n\na 8 E W g 6\n\nP 5 h 3 k x\n\n \n\n만들어진 다섯 개의 단어들의 글자 개수는 서로 다를 수 있다.\n \n\n심심해진 의석이는 칠판에 만들어진 다섯 개의 단어를 세로로 읽으려 한다.\n\n세로로 읽을 때, 각 단어의 첫 번째 글자들을 위에서 아래로 세로로 읽는다. 다음에 두 번째 글자들을 세로로 읽는다.\n\n이런 식으로 왼쪽에서 오른쪽으로 한 자리씩 이동 하면서 동일한 자리의 글자들을 세로로 읽어 나간다.\n\n위의 그림 1의 다섯 번째 자리를 보면 두 번째 줄의 다섯 번째 자리의 글자는 없다. 이런 경우처럼 세로로 읽을 때 해당 자리의 글자가 없으면, 읽지 않고 그 다음 글자를 계속 읽는다.\n\n그림 1의 다섯 번째 자리를 세로로 읽으면 D1gk로 읽는다.\n\n위에서 의석이가 세로로 읽은 순서대로 글자들을 공백 없이 출력하면 다음과 같다:\n\n \n\nAa0aPAf985Bz1EhCz2W3D1gkD6x\n\n \n\n칠판에 붙여진 단어들이 주어질 때, 의석이가 세로로 읽은 순서대로 글자들을 출력하는 프로그램을 작성하라.\n\"\"\"","sub_path":"D3/5356.py","file_name":"5356.py","file_ext":"py","file_size_in_byte":2312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"146556240","text":"\"\"\"\nRegistration list generator module\n\nCopyright (c) 2018 Qualcomm Technologies, Inc.\n All rights reserved.\n Redistribution and use in source and binary forms, with or without modification, are permitted (subject to the\n limitations in the disclaimer below) provided that the following conditions are met:\n * Redistributions of source code must retain the above copyright notice, this list of conditions and the following\n disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following\n disclaimer in the documentation and/or other materials provided with the distribution.\n * Neither the name of Qualcomm Technologies, Inc. nor the names of its contributors may be used to endorse or promote\n products derived from this software without specific prior written permission.\n NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY\n THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR\n TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n POSSIBILITY OF SUCH DAMAGE.\n\"\"\"\nimport os\nimport sys\nimport csv\nimport datetime\n\nfrom queue import Queue\nimport numpy\n\nfrom flask_script import Command, Option # pylint: disable=deprecated-module\n\nfrom app import app\nfrom app.api.v1.models.approvedimeis import ApprovedImeis\nfrom scripts.common import ScriptLogger\nfrom scripts.listgen.worker import IMEIWorker\n\n\nclass ListGenerator(Command):\n \"\"\"Registration List generator.\n\n \"\"\"\n\n option_list = [\n Option('--list', '-l', dest='param', help='Type of list to generate (full or delta)', default='delta')\n ]\n\n def __init__(self, db):\n \"\"\"Constructor\"\"\"\n super().__init__()\n self.db = db\n self.list_type = ''\n self.logger = ScriptLogger('list_generator').get_logger()\n self.__doc__ = self._command_description()\n self.dir_path = app.config['DRS_LISTS']\n self.current_time_stamp = datetime.datetime.now()\n\n # noinspection PyMethodMayBeStatic\n def _command_description(self):\n \"\"\"Returns command description help.\"\"\"\n return 'Command to Generate Registration List for DIRBS Core.'\n\n @property\n def _csv_file_name(self):\n \"\"\"Property Method to return csv file name.\"\"\"\n return '{0}_registration_list_{1}.csv'.format(self.list_type, self.current_time_stamp)\n\n def _get_details_query(self, request_id):\n \"\"\"Property Method to return appropriate query for imei make, model, brand etc information.\"\"\"\n return \"\"\"SELECT brand, model_name, model_num, device_type, technologies\n FROM search_registration\n WHERE id='{0}'\"\"\".format(request_id)\n\n @property\n def _column_names(self):\n \"\"\"Method to define column names for csv file.\"\"\"\n if self.list_type == 'delta':\n return ['APPROVED_IMEI',\n 'make',\n 'model',\n 'status',\n 'model_number',\n 'brand_name',\n 'device_type',\n 'radio_interface',\n 'change_type']\n return ['APPROVED_IMEI',\n 'make',\n 'model',\n 'status',\n 'model_number',\n 'brand_name',\n 'device_type',\n 'radio_interface']\n\n def generate(self, param):\n \"\"\"Method to generate the list.\"\"\"\n self.logger.info('checking valid directory for list generation')\n if os.path.isdir(self.dir_path):\n imeis = self.calc_imeis_to_export(param)\n if imeis:\n self.logger.info('generating {0} registration list'.format(param))\n with open('{path}/{file_name}'.format(path=self.dir_path, file_name=self._csv_file_name),\n 'w') as reglist:\n writer = csv.DictWriter(reglist, fieldnames=self._column_names)\n writer.writeheader()\n writer.writerows(imeis)\n self.logger.info('{0} list [{1}] generated'.format(param, self._csv_file_name))\n else:\n self.logger.info('no imeis to export, exiting .....')\n sys.exit(0)\n else:\n self.logger.error('Error: please specify directory in config for lists')\n self.logger.info('exiting .......')\n sys.exit(0)\n\n def _get_imei_details(self, imei_norm):\n \"\"\"Property Method to return imei details.\"\"\"\n imei_details = self.db.engine.execute(self._get_details_query(imei_norm.request_id))\n res_dict = {}\n for row in imei_details:\n for column, value in row.items():\n res_dict.update({column: value})\n if self.list_type == 'delta':\n return {\n 'APPROVED_IMEI': imei_norm.imei,\n 'make': res_dict.get('brand'),\n 'model': res_dict.get('model_name'),\n 'status': imei_norm.status,\n 'model_number': res_dict.get('model_num'),\n 'brand_name': res_dict.get('brand'),\n 'device_type': res_dict.get('device_type'),\n 'radio_interface': res_dict.get('technologies', ''),\n 'change_type': imei_norm.delta_status\n }\n return {\n 'APPROVED_IMEI': imei_norm.imei,\n 'make': res_dict.get('brand'),\n 'model': res_dict.get('model_name'),\n 'status': imei_norm.status,\n 'model_number': res_dict.get('model_num'),\n 'brand_name': res_dict.get('brand'),\n 'device_type': res_dict.get('device_type'),\n 'radio_interface': res_dict.get('technologies', '')\n }\n\n def calc_imeis_to_export(self, param):\n \"\"\"Method to calculate imeis that needs to be exported.\"\"\"\n recs_to_export = []\n recs_to_update = []\n\n self.logger.info('calculating imeis for {0} registration list'.format(param))\n imei_records = ApprovedImeis.imei_to_export()\n self.logger.info('{0} imei records to analyze for export'.format(len(imei_records)))\n max_workers = app.config['DRS_CONFIG']['lists']['max_workers']\n self.logger.info('using {0} thread workers for calculation'.format(max_workers))\n self.logger.info('spliting imeis into {0} batches'.format(max_workers))\n imei_records = numpy.array_split(imei_records, max_workers)\n self.logger.info('splited imeis into {0} batches'.format(len(imei_records)))\n\n input_queue = Queue()\n output_queue = Queue()\n\n for worker in range(max_workers): # pylint: disable=unused-variable\n imei_worker = IMEIWorker(in_queue=input_queue, out_queue=output_queue)\n imei_worker.daemon = True\n imei_worker.start()\n\n for imei_record in imei_records:\n input_queue.put((imei_record, param))\n\n input_queue.join()\n for i in range(max_workers): # pylint: disable=unused-variable\n rec_update, rec_export = output_queue.get()\n if not rec_update:\n recs_to_update.extend(rec_update)\n if not rec_export:\n recs_to_export.extend(rec_export)\n ApprovedImeis.bulk_insert_imeis(recs_to_update)\n return recs_to_export\n\n # noinspection PyMethodOverriding\n def run(self, param): # pylint: disable=method-hidden,arguments-differ,\n \"\"\"Overloaded method of the super class.\"\"\"\n if param in ['delta', 'full']:\n self.list_type = param\n self.generate(param)\n return 'List generation successful'\n else:\n return 'Wrong command line argument, available options are: full, delta'\n","sub_path":"scripts/listgen/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":8383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"510860392","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Feb 20 10:21:28 2020\r\n\r\n@author: smt29021\r\n\r\nAim: \r\n - Import all individual actual numbers from 2016:Current Date\r\n - Import predictions based on specific forecast_horizon\r\n - Create YOY Figures and Comparisons\r\n\r\nVariables:\r\n\r\n#datafiles = list of file names\r\n#Start Date = start date of actual series\r\n#Weekly - Binary variable for weekly vs monthly\r\n#categories = category names as list in same order as datafiles\r\n\r\n\r\nData:\r\n\r\nAssumed to be 2017 - 2019 \r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nimport datetime\r\n\r\n\r\n\r\n\r\ndef final_table(datafortemplate, forecasthorizon,start_date,Subcategory, Monthly):\r\n \r\n figures = np.zeros((datafortemplate.shape[0],1))\r\n \r\n matrix = datafortemplate\r\n figures = matrix.iloc[:,0]\r\n figures = pd.DataFrame(figures)\r\n #figures = figures.astype(int)\r\n if Monthly == True:\r\n figures[\"date\"]= pd.date_range(start=start_date, periods=figures.shape[0], freq='M')\r\n figures[\"date\"] = pd.to_datetime(figures[\"date\"])\r\n else:\r\n figures[\"date\"]= pd.date_range(start=start_date, periods=figures.shape[0], freq='W')\r\n figures[\"date\"] = pd.to_datetime(figures[\"date\"])\r\n cols = figures.columns.tolist()\r\n cols = cols[-1:] + cols [:-1]\r\n figures = figures[cols]\r\n #Groupby Year for each series\r\n for i in range((figures.shape[1])-1):\r\n if i == 0:\r\n totals = figures.groupby(figures['date'].dt.year)[i].agg(['sum'])\r\n totals = totals.transpose()\r\n \r\n else:\r\n totals_i = figures.groupby(figures['date'].dt.year)[i].agg(['sum'])\r\n totals_i = totals_i.transpose()\r\n totals = totals.append(totals_i)\r\n \r\n #Create YOY % Columns \r\n #Update row values to be Category names\r\n totals = totals.reset_index()\r\n totals['Category'] = Subcategory\r\n cols = totals.columns\r\n totals[\"2018 MAT YOY %\"] =(totals.iloc[:,3]/totals.iloc[:,2] -1)*100\r\n totals[\"2019 MAT YOY %\"] =(totals.iloc[:,4]/totals.iloc[:,3] -1)*100\r\n totals = totals.rename(columns={2016: \"MAT FY 2016\", 2017: \"MAT FY 2017\", 2018: \"MAT FY 2018\", 2019: 'MAT FY 2019', 2020: \"MAT 2020 FC\", 2021: \"MAT 2021 FC\"})\r\n cols = totals.columns\r\n total_cols = cols[[6,1,2,3,7,4,8,5]]\r\n totals = totals[total_cols]\r\n totals = totals.round(1) \r\n return totals\r\n\r\ndef final_figures(datafiles, forecasthorizon,actual_length,start_date,categories,Monthly):\r\n \r\n figures = np.zeros((actual_length,len(datafiles)))\r\n \r\n #Combine all files into single file\r\n for index, file in enumerate(datafiles):\r\n matrix = pd.read_csv(file)\r\n figures[:,index] = matrix.iloc[:,0]\r\n figures = pd.DataFrame(figures)\r\n if Monthly == True:\r\n figures[\"date\"]= pd.date_range(start=start_date, periods=figures.shape[0], freq='M')\r\n figures[\"date\"] = pd.to_datetime(figures[\"date\"])\r\n else:\r\n figures[\"date\"]= pd.date_range(start=start_date, periods=figures.shape[0], freq='W')\r\n figures[\"date\"] = pd.to_datetime(figures[\"date\"])\r\n cols = figures.columns.tolist()\r\n cols = cols[-1:] + cols [:-1]\r\n figures = figures[cols]\r\n print(figures.shape) \r\n #Groupby Year for each series\r\n for i in range((figures.shape[1])-1):\r\n if i == 0:\r\n totals = figures.groupby(figures['date'].dt.year)[i].agg(['sum'])\r\n totals = totals.transpose()\r\n #print(totals.shape)\r\n \r\n else:\r\n totals_i = figures.groupby(figures['date'].dt.year)[i].agg(['sum'])\r\n totals_i = totals_i.transpose()\r\n totals = totals.append(totals_i)\r\n #print(totals.shape)\r\n \r\n #Create YOY % Columns \r\n #Update row values to be Category names\r\n totals = totals.reset_index()\r\n print(totals.columns)\r\n #categories = {0:\"test\",1:\"test1\",2:\"test2\",3:\"test3\",4:\"test4\", 5:\"test5\"}\r\n totals['Category'] = categories.values()\r\n totals[\"2018 MAT YOY %\"] =(totals.iloc[:,3]/totals.iloc[:,2] -1)*100\r\n totals[\"2019 MAT YOY %\"] =(totals.iloc[:,4]/totals.iloc[:,3] -1)*100\r\n #May need to add above for 2020\r\n #cols = list(totals.columns.values)\r\n #print(cols)\r\n #print(cols)\r\n cols = [\"Category\", 2016,2017,2018, \"2018 MAT YOY %\", 2019, \"2019 MAT YOY %\"]\r\n #cols = cols[5]+ cols[1] + cols[2] +cols[3] + cols[6] + cols[4]+ cols[7]\r\n totals = totals[cols]\r\n return totals\r\n\r\n \r\n #passed_weeks_latest_year = totals_count.iloc[-1].values\r\n #totals [\"2020 MAT FC\"]= totals[\"2020\"] + data_test_predictions.iloc[past_weeks_latest_year: forecasthorizon,:]\r\n","sub_path":"LSTM/final_figures.py","file_name":"final_figures.py","file_ext":"py","file_size_in_byte":4635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"330402820","text":"from zerocon.orders import BaseOrder\nfrom zerocon.exceptions import IOException\nfrom zerocon.seriesdefinition import SeriesDefinition\nimport struct\n\nclass GetDefinition(BaseOrder):\n def __init__(self, name):\n BaseOrder.__init__(self)\n self.name = name\n\n def __str__(self):\n return '\\x00'+struct.pack('>H', len(self.name)) + self.name\n \n def copy(self):\n return GetDefinition(self.name)\n \n def on_data(self, buffer):\n if len(buffer) == 0: return \n if buffer[0] == 1:\n self.result = IOException()\n del buffer[0]\n elif buffer[0] == 2:\n del buffer[0] # not found, keep None\n elif buffer[0] == 0:\n # Found something\n try:\n sd = SeriesDefinition.fromINTP(buffer[1:])\n except:\n return\n else:\n del buffer[:1+sd._lengthInBytes()]\n \n self.result = sd\n self.is_completed = True\n","sub_path":"kod/zeropython/zerocon/orders/getdefinition.py","file_name":"getdefinition.py","file_ext":"py","file_size_in_byte":1014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"488989637","text":"import random\r\ndef display_board(board):\r\n blankBoard=\"\"\"\r\n___________________\r\n| | | |\r\n| 7 | 8 | 9 |\r\n| | | |\r\n|-----------------|\r\n| | | |\r\n| 4 | 5 | 6 |\r\n| | | |\r\n|-----------------|\r\n| | | |\r\n| 1 | 2 | 3 |\r\n| | | |\r\n|-----------------|\r\n\"\"\"\r\n for i in range(1,10):\r\n if board[i] == 'O' or board[i] == 'X':\r\n blankBoard = blankBoard.replace(str(i),board[i])\r\n else:\r\n blankBoard = blankBoard.replace(str(i),' ')\r\n print(blankBoard)\r\n\r\ndef player_input():\r\n while True:\r\n player1 = input(\"choose your marker X or O? \").upper()\r\n if player1 == 'X':\r\n player2 = 'O'\r\n print(f\"you've chose {player1}, the computer will be {player2}\\n\")\r\n return player1,player2\r\n elif player1 == 'O':\r\n player2 = 'X'\r\n print(f\"you've chose {player1}, the computer will be {player2}\\n\")\r\n return player1,player2\r\n\r\ndef place_marker(board , marker, position):\r\n board[position] = marker\r\n return board\r\n\r\ndef is_empty(board,position):\r\n return board[position] == '#'\r\n\r\ndef player_choice(board):\r\n print(\"your turn: \")\r\n choice = input(\"select an empty place between 1 and 9: \")\r\n while not is_empty(board,int(choice)):\r\n choice = input(\"this space isn't free, select a place between 1 and 9: \")\r\n return int(choice)\r\n\r\ndef computer_choice(board):\r\n print(\"computer's turn:\")\r\n choice = random.randint(1,9)\r\n while not is_empty(board,choice):\r\n choice = random.randint(1,9)\r\n return choice\r\ndef fullboard_check(board):\r\n return len([x for x in board if x == '#']) == 1\r\n # for i in range(1,10):\r\n # if board[i] == '#':\r\n # return False\r\n # return True\r\n\r\ndef win_check(board, mark):\r\n if board[1] == board[2] == board[3] == mark:\r\n return True\r\n if board[4] == board[5] == board[6] == mark:\r\n return True\r\n if board[7] == board[8] == board[9] == mark:\r\n return True\r\n if board[1] == board[4] == board[7] == mark:\r\n return True\r\n if board[2] == board[5] == board[8] == mark:\r\n return True\r\n if board[3] == board[6] == board[9] == mark:\r\n return True\r\n if board[1] == board[5] == board[9] == mark:\r\n return True\r\n if board[3] == board[5] == board[7] == mark:\r\n return True\r\n return False\r\n\r\ndef play_again():\r\n while True:\r\n response = input(\"press ENTER if you want to play again,\"\r\n \" otherwise will exit the game\")\r\n if not response:\r\n return True\r\n return False\r\n\r\nif __name__ == \"__main__\":\r\n while True:\r\n print(\"\"\"\r\n____________________________________\r\n| welcome to Tic Tac Toe game | \r\n|___________________________________|\r\n___________________\r\n| | | |\r\n| 7 | 8 | 9 |\r\n| | | |\r\n|-----------------|\r\n| | | |\r\n| 4 | 5 | 6 |\r\n| | | |\r\n|-----------------|\r\n| | | |\r\n| 1 | 2 | 3 |\r\n| | | |\r\n|-----------------|\r\n\"\"\")\r\n board = ['#','#','#','#','#','#','#','#','#','#']\r\n i = 1\r\n player1_marker,computer_marker = player_input()\r\n while not fullboard_check(board):\r\n if i % 2 == 0:\r\n marker = computer_marker\r\n position = computer_choice(board)\r\n\r\n else:\r\n marker = player1_marker\r\n position = player_choice(board)\r\n\r\n place_marker(board,marker,position)\r\n i+=1\r\n display_board(board)\r\n if win_check(board,marker):\r\n print(f\"$$$$ {marker} won the game $$$$\")\r\n break\r\n if not play_again():\r\n break\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"226252335","text":"\"\"\"\r\nEncode 5\r\n\"\"\"\r\n# 5 Conversion de la chaine en une liste d'éléments de longueur six cadrés à droite\r\n\r\n\r\ndef StringToListByLength(myString):\r\n # Initialisation d'une liste vide\r\n myList = []\r\n\r\n # On parcourt la chaine donnée en paramètre tous les 6 caractères et on les ajoute dans la liste vide\r\n for i in range(0, len(myString), 6):\r\n myList.append(myString[i: i+6])\r\n\r\n # On obtient la longueur du dernier élément de la liste\r\n longueurDernierElement = len(myList[len(myList)-1])\r\n\r\n # Si la longueur du dernier élément de la liste ('00' dans notre cas) est inférieure à 6\r\n # On lui rajoute le nombre adéquat de \"0\" manquant afin que la chaine ait une longueur de 6 caractères\r\n if longueurDernierElement < 6:\r\n str1 = myList.pop()\r\n myList.append(str1 + \"0\" * (6 - longueurDernierElement))\r\n\r\n # print(myList)\r\n return myList\r\n\r\n# len() permet d'obtenir la longueur d'une chaine ou d'une liste/tableau\r\n# len('00') => Retourne 2 (la longueur de la chaine '00' vaut 2)\r\n# len(myList) => Ma liste contient 6 éléments\r\n# myList[len(myList)-1] => Permet d'obtenir l'index du dernier élément de ma liste (myList[5] et retourne '00')\r\n# myList.pop() => Récupère le dernier élément de ma liste et le retire de celle-ci (ma liste ne contient plus '00')\r\n","sub_path":"src/Encodage/Function5.py","file_name":"Function5.py","file_ext":"py","file_size_in_byte":1333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"437417501","text":"from argparse import ArgumentParser\n\ndef create_parser():\n parser = ArgumentParser()\n parser.add_argument(\"path\", help=\"path to file\")\n parser.add_argument(\"--export\", action=\"store_true\", help=\"flag for whether this is an export\")\n return parser\n\ndef main():\n from hr import json, users\n \n args = create_parser().parse_args()\n \n if args.export:\n json.export(args.path)\n else:\n users.sync(json.load(args.path))\n\n","sub_path":"src/hr/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"277262153","text":"## tftest1.py - Testing TensorFlow functionality on MNIST\n##\n## by Artem Sokolov\n\nimport tensorflow as tf\nfrom tensorflow.examples.tutorials.mnist import input_data\n\n## Load the data\nmnist = input_data.read_data_sets(\"MNIST_data/\", one_hot=True)\n\n## Declare the input image array for an arbitrary number of images\n## Each image is represented as a 784-dimensional vector\nx = tf.placeholder( tf.float32, [None, 784] )\n\n## Declare the model weights and bias terms\nW = tf.Variable( tf.zeros( [784, 10] ) )\nb = tf.Variable( tf.zeros( [10] ) )\n\n## Declare the model (note the addition operator being row-wise)\ny_pred = tf.nn.softmax( tf.matmul(x, W) + b )\n\n## Declare the space for the true values\ny = tf.placeholder( tf.float32, [None, 10] )\n\n## Declare the loss function\ncross_entropy = tf.reduce_mean( -tf.reduce_sum(y * tf.log(y_pred), reduction_indices=[1]) )\n\n## Select an optimizer\ntrain_step = tf.train.GradientDescentOptimizer(0.5).minimize( cross_entropy )\n\n## Define the performance evaluator\nj_true = tf.argmax( y, 1 )\nj_pred = tf.argmax( y_pred, 1 )\nisCorr = tf.equal( j_true, j_pred )\nacc = tf.reduce_mean( tf.cast( isCorr, tf.float32 ) )\n\n## Create the session and init all variables\nsess = tf.Session()\ninit = tf.initialize_all_variables()\nsess.run( init )\n\n## Define some feed dicts\nfd_tr = {x: mnist.train.images, y: mnist.train.labels}\nfd_te = {x: mnist.test.images, y: mnist.test.labels}\n\n## Training via Stochastic Gradient Descent\nfor i in range(10):\n print( \"Iteration\", i )\n batch_xs, batch_ys = mnist.train.next_batch(100)\n sess.run( train_step, feed_dict={x: batch_xs, y: batch_ys} )\n print( \"Training accuracy:\", sess.run( acc, feed_dict=fd_tr ) )\n\n## Evaluate the model on test data\nres = sess.run( acc, feed_dict=fd_te )\nprint( res )\n\n## Show the bias terms\nprint( sess.run(b) )\n\n","sub_path":"test/tftest1.py","file_name":"tftest1.py","file_ext":"py","file_size_in_byte":1818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"281744570","text":"# 키보드로 정수 수치를 입력 받아 그것이 짝수인지 홀수인지 판별하는 코드를 완성하세요.\n\nimport sys\n\nnumber = input('수를 입력하세요: ')\n\nif number.isdigit():\n if (int(number) % 3) is 0:\n print(\"3의 배수입니다.\")\n else:\n print(\"3의 배수가 아닙니다.\")\nelse:\n print('정수가 아닙니다.')\nsys.exit(0)","sub_path":"python_practice01/prob01.py","file_name":"prob01.py","file_ext":"py","file_size_in_byte":380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"295967580","text":"import requests\nfrom behave import *\nfrom jsonschema import validate\n\nfrom work_tasks.qaat_25_types_checking.schemas.schema_type_checking import correct_schema\n\n\n@given(\"token authorization\")\ndef tokenAuthorization(context):\n url = \"http://discovery-stb3.ertelecom.ru/\"\n api_path = \"api/token/device\"\n token_parameters = \"?client_id=er_ottweb_device×tamp=1500979473&device_id=123\"\n\n request_token = requests.get(url + api_path + token_parameters)\n get_token = request_token.json()\n token = get_token[\"token\"]\n return token\n\n\n@when(\"send request\")\ndef sendRequest(context):\n url = \"http://discovery-stb3.ertelecom.ru/api/v3/pages/library\"\n headers = {\"X-Auth-Token\": tokenAuthorization(context), \"view\": \"stb3\"}\n\n request = requests.get(url, headers=headers)\n response = request.json()\n return response\n\n\n@then(\"validation response schema\")\ndef validationSchema(context):\n actual_json = sendRequest(context)\n validate(actual_json, correct_schema)\n\n\n@then(\"get all showcases types\")\ndef getShowcases(context):\n responseJson = sendRequest(context)\n\n showcase_list = []\n for key_1 in responseJson[\"data\"][\"showcases\"]:\n showcase_list.append(key_1[\"type\"])\n\n return showcase_list\n\n\ndef getChekingTypes(value):\n responseJson = sendRequest(context=sendRequest)\n\n showcases_list = []\n item_list = []\n for i in responseJson[\"data\"][\"showcases\"]:\n showcases_list.append(i[\"type\"])\n\n for j in i[\"items\"]:\n item_list.append(j[\"type\"])\n break\n\n if value == 'showcase':\n return showcases_list\n elif value == \"item\":\n return item_list\n\n\nexpectedShowcas = getChekingTypes('showcase')\nexpectedItem = getChekingTypes('item')\n\n\n@then('validation types showcases and items')\ndef validationTypes(context):\n responseJson = sendRequest(context=sendRequest)\n\n for expected_i in expectedShowcas:\n for actual_i in responseJson[\"data\"][\"showcases\"]:\n\n if expected_i == actual_i[\"type\"]:\n\n for expected_j in expectedItem:\n for actual_j in expectedItem:\n\n if actual_j == expected_j:\n assert expected_j == actual_j\n","sub_path":"qaat_25_types_checking/features/steps/type_checking.py","file_name":"type_checking.py","file_ext":"py","file_size_in_byte":2227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"362619407","text":"\nimport math\nimport copy\n\n\nclass Track():\n\n def __init__(self, _dim=None):\n self.dim = _dim\n self.values = None\n self.ans = None\n self.children = []\n\n def __create_child(self, d_val):\n for i in range(d_val):\n self.children.append(Track())\n\n def create_dimension(self, dim):\n if len(dim) == 0:\n self.ans = math.inf\n else:\n d_val = dim.pop(0)\n self.__create_child(d_val)\n i = 0\n for t in self.children:\n t.values = i\n t.create_dimension(copy.copy(dim))\n i += 1\n\n def get_value(self, div):\n if len(self.children) == 0:\n return self.ans\n else:\n val = div.pop(0)\n for t in self.children:\n if t.values == val:\n return t.get_value(copy.copy(div))\n\n def set_value(self, div, val):\n if len(self.children) == 0:\n self.ans = val\n else:\n tempVal = div.pop(0)\n for t in self.children:\n if t.values == tempVal:\n t.set_value(copy.copy(div), val)\n\n # def get_missing_count(self, dim_index, f_dim):\n # d = self.dim[dim_index]\n # print(d)\n # cnt = 0\n # for i in range(d):\n # print(self.get_value([i, f_dim]))\n # if self.get_value([i, f_dim]) == math.inf:\n # cnt = cnt + 1\n # return cnt\n","sub_path":"track.py","file_name":"track.py","file_ext":"py","file_size_in_byte":1480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"586742305","text":"import gym\n\ngames = [\n'Acrobot-v1',\n'AirRaid-v3',\n'Alien-ram-v3',\n'Amidar-v3',\n'Assault-v3',\n'BattleZone-v3',\n'BeamRider-v3',\n'Boxing-v3',\n'CrazyClimber-v3',\n'DoubleDunk-v3',\n'Enduro-v3',\n'Freeway-v3',\n'Gopher-v0',\n'LunarLander-v2',\n'Pong-v0',\n'Robotank-v3',\n'Walker2d-v1',\n'YarsRevenge',\n'Zaxxon-v3',\n'SpaceInvaders-v0',\n'Breakout-v0',\n'Tennis-v0',\n'Solaris-v0',\n'Skiing-v0',\n'LunarLander-v2']\n\nfor game in range(len(games)):\n env = gym.make(games[game])\n env.reset()\n\n for _ in range(1000):\n env.render()\n _, _, done, _ = env.step(env.action_space.sample())\n\n if done:\n env.close()\n break","sub_path":"Downloads/TensorFlow-ML-Exercises-master/Reinforce/gym_game_list.py","file_name":"gym_game_list.py","file_ext":"py","file_size_in_byte":642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"429520627","text":"N = 43 # 역의 개수\na , b = 1 , 17 # a : 첫번째 역, b : 17번째 역\nn = abs(a-b) # a와 b 사이에 있는 총 역의 개수\n\nprint((1 << (n-1)+(1 << (N-n-1)))-1)\n\n#중간의 역에서 전혀 스탬프를 찍지 않는 경우, 스탬프를 찍는 순서에 영향을 주지 않으므로 중복이 발생할 수 있다 이를 제외 해야함.\n#안쪽으로 도는 경우, 바깥으로 도는 경우를 더한뒤 중복 제거\n#1비트 왼쪽으로 시프트할 때마다 2배, 오른쪽으로 0.5배 a의 b제곱을 계산 경우 pow를 사용하지만 시프트 사용시 빠름.\n#1*a << b ->> a*2^b 이다.!\n# 2^16 + 2^26 - 1 \n#각 역마다 스탬프를 찍을 지 말찌 선택이 각 2번이다 그래서 2^n 하는 것.\n#print의 왼쪽은 내선 오른쪽은 외선으로 돈다 .!","sub_path":"algorithm/Q2.py","file_name":"Q2.py","file_ext":"py","file_size_in_byte":796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"292676767","text":"#! /usr/bin/env python\n\n\"\"\"BIL parser to load elevation info from sites like\nhttp://earthexplorer.usgs.gov/\n\nMostly based of:\nhttp://stevendkay.wordpress.com/2010/05/29/parsing-usgs-bil-digital-elevation-models-in-python/\n\nDocumentation for the format itself:\nhttp://webhelp.esri.com/arcgisdesktop/9.2/index.cfm?TopicName=BIL,_BIP,_and_BSQ_raster_files\n\nDocumentation for the accompanying world files:\nhttp://webhelp.esri.com/arcgisdesktop/9.2/index.cfm?TopicName=World_files_for_raster_datasets\n\n\nusage:\nfrom bil_parser impor BilParser\nbp = BilParser(\"filename.hdr\") # expects to also find filename.bil\nprint bp.header\nprint bp.values.shape \nimshow(bp.values)\n\"\"\"\n\nimport os\nimport struct\nimport numpy as np\n\ndef parse_header(hdr):\n \"\"\"\n Parse a BIL header .hdr file, like:\n\n BYTEORDER I\n LAYOUT BIL\n NROWS 1201\n NCOLS 1201\n ...\n \"\"\"\n contents = open(hdr).read()\n lines = contents.strip().splitlines()\n header = {}\n for li in lines:\n key, _, value = li.partition(\" \")\n header[key] = value.strip()\n\n return header\n\n\ndef parse_bil(path, rows, cols, dtype):\n # where you put the extracted BIL file\n fi = open(path, \"rb\")\n contents = fi.read()\n fi.close()\n\n # unpack binary data into a flat tuple z\n n = int(rows*cols)\n if dtype == \"FLOAT\":\n s = \"<%df\" % (n,)\n else: # spec says to assume unsigned int if no type specified..\n s = \"<%dH\" % (n,) # unsigned int\n z = struct.unpack(s, contents)\n\n values = np.zeros((rows,cols))\n \n for r in range(rows):\n for c in range(cols):\n val = z[(cols*r)+c]\n if (val==65535 or val<0 or val>20000):\n # may not be needed depending on format, and the \"magic number\"\n # value used for 'void' or missing data\n val=0.0\n values[r][c]=float(val)\n return values\n\n\nclass BilParser(object):\n def __init__(self, headerpath):\n self.basepath = os.path.splitext(headerpath)[0]\n self.header = parse_header(self.basepath + \".hdr\")\n self.values = parse_bil(\n self.basepath + \".bil\",\n rows = int(self.header['NROWS']),\n cols = int(self.header['NCOLS']),\n\t\t\t\t\t\tdtype = self.header['PIXELTYPE'])\n\n","sub_path":"bil_parse.py","file_name":"bil_parse.py","file_ext":"py","file_size_in_byte":2256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"159356016","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom .models import People,Card\n# Create your views here.\ndef add(request):\n # p1 = People.objects.create(name='小王',car_num = 4)\n # p2 = People.objects.create(name='老王',car_num = 40)\n #\n # c1 = Card(number='101',source='中国银行',person=p1)\n # c2 = Card(number='102',source='中国农行',person=p1)\n # c3 = Card(number='110',source='中国建行',person=p1)\n # c1.save()\n # c2.save()\n # c3.save()\n # c4 = Card(number='201',source='郑州美容美发',person=p2)\n # c5 = Card(number='202',source='郑州交通一卡通',person=p2)\n # c6 = Card(number='203',source='郑州逍遥镇胡辣汤',person=p2)\n # c7 = Card(number='204',source='郑州惠济四附院',person=p2)\n # c4.save()\n # c5.save()\n # c6.save()\n # c7.save()\n return HttpResponse('添加成功')\ndef select(request):\n c1 = Card.objects.get(number='203')\n print(c1.person.name)\n\n c2 = Card.objects.get(id=3)\n print(c2.person.name)\n\n # 类__字段\n # 类_set\n result = c2.person.card_set.all()\n print(result)\n for res in result:\n print(res.source)\n\n result = People.objects.get(name='老王')\n for card in result.card_set.all():\n print(card.source)\n\n return HttpResponse('查询成功')","sub_path":"Python/9.11/2.onetomany/myPro/myApp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"348796325","text":"#!/usr/bin/env python3\n\nimport sys\nimport numpy as np\nimport pandas as pd\nfrom Bio import SeqIO\nfrom sqlalchemy import create_engine\n\ndb_fp = '/home/mitsuki/mag/db/mag.db'\nengine = create_engine('sqlite:///{}'.format(db_fp))\ncon = engine.connect()\n\ndef query(names):\n assert len(names) < 1000\n names_escaped = [\"\\\"{}\\\"\".format(name) for name in names]\n query = \"\"\"\n SELECT\n sub.cds_id AS cds_id,\n sub.name AS cds_name,\n sub.represent_id AS represent_id,\n hits_refseq.hit_id AS hit_id,\n hits_refseq.identity AS identity,\n hits_refseq.coverage AS coverage,\n hits_refseq.refseq_id AS refseq_id,\n refseq.description AS desc\n FROM (\n SELECT cds_id,represent_id, name\n FROM cdss\n WHERE name IN ({})\n ) AS sub\n LEFT JOIN hits_refseq\n ON sub.represent_id = hits_refseq.represent_id\n LEFT JOIN refseq\n ON hits_refseq.refseq_id = refseq.refseq_id;\n \"\"\".format(','.join(names_escaped))\n\n df = pd.read_sql_query(query, con)\n assert len(set(df[\"cds_id\"]))==len(names)\n return df\n\ndef query_batch(names):\n batch_size = 999\n dfs = []\n for i in range(len(names)//batch_size + 1):\n names_batch = names[i*batch_size: (i+1)*batch_size]\n dfs.append(query(names_batch))\n df = pd.concat(dfs)\n return df\n\ndef main(faa_fp, out_fp):\n\trecords = list(SeqIO.parse(faa_fp, \"fasta\"))\n\tprint(\"found {} records\".format(len(records)))\n\n\tdct_lst = []\n\tfor record in records:\n\t\tdct = dict()\n\t\tdct[\"gene_name\"], dct[\"cds_name\"] = record.description.split()\n\t\tdct_lst.append(dct)\n\tname_df = pd.DataFrame(dct_lst)\n\n\tanno_df = query_batch(name_df[\"cds_name\"])\n\tanno_df[\"score\"] = np.sqrt(anno_df[\"identity\"] * anno_df[\"coverage\"])\n\n\tout_df = pd.merge(name_df, anno_df[~anno_df[\"hit_id\"].isnull()], on=\"cds_name\")\n\tout_df[\"score\"] == out_df[\"identity\"] * out_df[\"coverage\"]\n\tout_df = out_df.sort_values(by=[\"gene_name\", \"score\"], ascending=[True, False]).drop_duplicates([\"gene_name\"])\n\tout_df = out_df[[\"gene_name\", \"cds_name\", \"desc\", \"score\", \"identity\", \"coverage\"]]\n\tout_df.to_csv(out_fp, index=False, sep='\\t')\n\tprint(\"DONE: output {}\".format(out_fp))\n\n\nif __name__==\"__main__\":\n\ttarget = sys.argv[1]\n\tdirec = \"../material/{}\".format(target)\n\tfaa_fp = \"{}/sonic/{}.faa\".format(direc, target)\n\tout_fp = \"{}/pannzer/my.anno\".format(direc)\n\tmain(faa_fp, out_fp)\n\n\n","sub_path":"pannzer/myanno.py","file_name":"myanno.py","file_ext":"py","file_size_in_byte":2375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"304967930","text":"from django.shortcuts import render, redirect\r\nfrom django.urls import reverse\r\nfrom django.template.loader import render_to_string\r\nfrom rest_framework import viewsets\r\nfrom rest_framework.response import Response\r\nfrom rest_framework.permissions import AllowAny, IsAuthenticated\r\nfrom apps.user.models import Wishlist, CustomUser\r\nfrom apps.catalogue.models import Product\r\n\r\n\r\nclass WishlistViewsSet(viewsets.ViewSet):\r\n permission_classes = [AllowAny]\r\n\r\n def data(self, request):\r\n if request.user.is_authenticated:\r\n html = render_to_string('shop/additions/whishlist/wishlist__body.html', {'request' : request})\r\n html = html.replace(' ','').replace('\\n','')\r\n return Response({'html' : html, 'length' : Wishlist.objects.filter(user=request.user).count()})\r\n return Response({'html' : \"\", 'length' : 0})\r\n \r\n\r\n def add(self, request):\r\n ajax = request.data.get('ajax')\r\n user = request.user\r\n if user.is_authenticated:\r\n product_id = request.data.get('product_id')\r\n product = Product.objects.filter(pk=product_id).first()\r\n if product:\r\n try:\r\n Wishlist.objects.get(user=user, product=product)\r\n except:\r\n wish = Wishlist(user=user, product=product)\r\n wish.save()\r\n html = render_to_string('shop/additions/whishlist/wishlist__body.html', {'request' : request})\r\n if ajax:\r\n return Response({'html':html, 'length' : Wishlist.objects.filter(user=user).count()})\r\n return redirect(request.META.get('HTTP_REFERER'))\r\n else:\r\n if ajax:\r\n Response({'error':'Вы не авторизованы в системе'})\r\n return redirect('/')\r\n\r\n\r\n def remove(self, request):\r\n ajax = request.data.get('ajax')\r\n user = request.user\r\n if user.is_authenticated:\r\n product_id = request.data.get('product_id')\r\n product = Wishlist.objects.filter(user=user, product__pk=int(product_id)).delete()\r\n html = render_to_string('shop/additions/whishlist/wishlist__body.html', {'request' : request})\r\n if ajax:\r\n return Response({'html':html, 'length' : Wishlist.objects.filter(user=user).count()})\r\n return redirect(request.META.get('HTTP_REFERER'))\r\n else:\r\n if ajax:\r\n Response({'error':'Вы не авторизованы в системе'})\r\n else:\r\n return redirect('/')\r\n \r\n\r\n","sub_path":"apps/user/views/views__wishlist.py","file_name":"views__wishlist.py","file_ext":"py","file_size_in_byte":2628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"279171435","text":"import itertools\n\nimport numpy as np\nimport pytest\nfrom qibo import gates\nfrom qibo.backends import NumpyBackend\nfrom qibo.models import Circuit\n\nfrom qibolab.native import NativeType\nfrom qibolab.transpilers import Pipeline\n\nfrom .test_transpilers_star_connectivity import transpose_qubits\n\n\ndef generate_random_circuit(nqubits, ngates, seed=None):\n \"\"\"Generate random circuits one-qubit rotations and CZ gates.\"\"\"\n pairs = list(itertools.combinations(range(nqubits), 2))\n if seed is not None: # pragma: no cover\n np.random.seed(seed)\n\n one_qubit_gates = [gates.RX, gates.RY, gates.RZ, gates.X, gates.Y, gates.Z, gates.H]\n two_qubit_gates = [\n gates.CNOT,\n gates.CZ,\n gates.SWAP,\n gates.iSWAP,\n gates.CRX,\n gates.CRY,\n gates.CRZ,\n ]\n n1, n2 = len(one_qubit_gates), len(two_qubit_gates)\n n = n1 + n2 if nqubits > 1 else n1\n circuit = Circuit(nqubits)\n for _ in range(ngates):\n igate = int(np.random.randint(0, n))\n if igate >= n1:\n q = tuple(np.random.randint(0, nqubits, 2))\n while q[0] == q[1]:\n q = tuple(np.random.randint(0, nqubits, 2))\n gate = two_qubit_gates[igate - n1]\n else:\n q = (np.random.randint(0, nqubits),)\n gate = one_qubit_gates[igate]\n if issubclass(gate, gates.ParametrizedGate):\n theta = 2 * np.pi * np.random.random()\n circuit.add(gate(*q, theta=theta))\n else:\n circuit.add(gate(*q))\n return circuit\n\n\n@pytest.mark.parametrize(\n \"two_qubit_natives\",\n [NativeType.CZ, NativeType.iSWAP, NativeType.CZ | NativeType.iSWAP],\n)\n@pytest.mark.parametrize(\"middle_qubit\", [0, 1, 2, 3, 4])\n@pytest.mark.parametrize(\"nqubits\", [1, 2, 3, 4, 5])\n@pytest.mark.parametrize(\"ngates\", [10, 40])\n@pytest.mark.parametrize(\"fuse_one_qubit\", [False, True])\ndef test_transpile(middle_qubit, nqubits, ngates, fuse_one_qubit, two_qubit_natives):\n backend = NumpyBackend()\n # find the number of qubits for hardware circuit\n if nqubits == 1:\n hardware_qubits = 1\n else:\n hardware_qubits = max(nqubits, middle_qubit + 1)\n\n circuit = generate_random_circuit(hardware_qubits, ngates)\n transpiler = Pipeline.default(\n two_qubit_natives=two_qubit_natives,\n middle_qubit=middle_qubit,\n fuse_one_qubit=fuse_one_qubit,\n )\n transpiled_circuit, hardware_qubits = transpiler(circuit)\n assert transpiler.is_satisfied(transpiled_circuit)\n\n final_state = backend.execute_circuit(transpiled_circuit).state()\n target_state = backend.execute_circuit(circuit).state()\n target_state = transpose_qubits(target_state, hardware_qubits)\n fidelity = np.abs(np.conj(target_state).dot(final_state))\n np.testing.assert_allclose(fidelity, 1.0)\n\n\ndef test_can_execute_false():\n transpiler = Pipeline.default(two_qubit_natives=NativeType.CZ | NativeType.iSWAP)\n circuit1 = Circuit(1)\n circuit1.add(gates.H(0))\n assert not transpiler.is_satisfied(circuit1)\n circuit2 = Circuit(2)\n circuit2.add(gates.CNOT(0, 1))\n assert not transpiler.is_satisfied(circuit2)\n circuit3 = Circuit(3)\n circuit3.add(gates.TOFFOLI(0, 1, 2))\n assert not transpiler.is_satisfied(circuit3)\n","sub_path":"tests/test_transpilers_pipeline.py","file_name":"test_transpilers_pipeline.py","file_ext":"py","file_size_in_byte":3271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"300584635","text":"#!/usr/bin/env python3\n\n# assignABdepth_singlecell_singlechr calculates an compartmental field effects\n# on each bead as well as calculating an insulation score for each bead.\n#\n# For example, the total A compartment field effects at bead i will be a sum over\n# all A compartment beads j != i of a normally distributed field around bead j\n# evaluated at the point i. This is then normalised by the total field effects\n# (A, B and null) at bead i. For full details see write up.\n#\n# As inputs, the script takes a cell summary h5py file as created by ABComparison.py,\n# a sigma_multiplier controlling the range of field effects and a max_abs_AB_ratio\n# bounding the possible insulation scores. In the initial report, I took sigma_multiplier\n# to be 2.\n#\n# The script outputs an h5py file, {}_fields_sigma{}.h5py. The file has ome parent group\n# ['chromosomes']. Each chromosome group contains 3 datasets:\n# - 'fields': a (num_models,num_beads,4) array. Each bead and model has 4 values.\n# These are the A field strength, B field strength, null field strength\n# and the insulation score (log(A_strenght/B_strength) - see the initial\n# for details).\n# - 'genomic_position': genomic positions of each bead\n# - 'AB_data': Probability of a bead being in A or B based on how much that\n# bead overlaps with compartment boundaries.\n#\n\n\nimport h5py as h\nimport numpy as np\nimport math\nimport scipy.stats as stats\n\n\n\ndef cscore_cross_correlation(list_first_chr, list_second_chr):\n\n output = np.zeros((8,len(list_first_chr[0,:]), len(list_second_chr[0,:])))\n for i in range(8):\n rolled = np.roll(list_second_chr, -i, axis = 0)\n output[i,:,:] = np.dot(np.transpose(list_first_chr), rolled)\n\n\n return output\n\n\n#System for executing the script from the command line\nif __name__ == \"__main__\":\n import sys\n if len(sys.argv) != 4:\n print(\"provide .hdf5 file path for analysis\")\n sys.exit()\n\n aggregate_summary_path, sigma, timepoint = sys.argv[1:]\n\n #check that user has given a valid file for analysis\n if '.hdf5' not in aggregate_summary_path:\n raise ValueError(\"Input file must be of .hdf5 format. Usage: assignABdepth_singlecell \")\n\n with h.File(aggregate_summary_path, 'r') as agg_summary, h.File(\"expressionscore_cross_corrs_simga{}_{}hrs.hdf5\".format(sigma, timepoint), \"w\") as corrfile:\n chromosomes = agg_summary['cells']['1']\n num_models = len(chromosomes['1']['coords'][:,0,0])\n\n for chr in chromosomes:\n\n num_beads = len(agg_summary['genomic_positions'][chr])\n corrfile.create_group(chr)\n list_first_chr = np.zeros((8,num_models,num_beads))\n for i in range(8):\n cscores_first_chr = agg_summary['cells']['{}'.format(i+1)][chr]['expression_fields']\n list_first_chr[i,:,:min(len(agg_summary['cells']['{}'.format(i+1)][chr]['expression_fields'][0,:]),num_beads)] = cscores_first_chr[:,:min(len(agg_summary['cells']['{}'.format(i+1)][chr]['cscore-fields'][0,:]),num_beads)]\n list_first_chr = np.mean(np.array(list_first_chr), axis = 1)\n list_first_chr = list_first_chr - np.mean(list_first_chr, axis = 0, keepdims = True)\n for secondary_chr in chromosomes:\n num_secondary = len(agg_summary['genomic_positions'][secondary_chr])\n list_second_chr = np.zeros((8,num_models,num_secondary))\n for i in range(8):\n cscores_second_chr = agg_summary['cells']['{}'.format(i+1)][secondary_chr]['expression_fields']\n list_second_chr[i,:,:min(len(agg_summary['cells']['{}'.format(i+1)][secondary_chr]['expression_fields'][0,:]),num_secondary)] = cscores_second_chr[:,:min(len(agg_summary['cells']['{}'.format(i+1)][secondary_chr]['cscore-fields'][0,:]),num_secondary)]\n list_second_chr = np.mean(np.array(list_second_chr), axis = 1)\n list_second_chr = list_second_chr - np.mean(list_second_chr, axis = 0, keepdims = True)\n p1 = np.dot(list_first_chr.T, list_second_chr)\n p2 = np.sum(list_first_chr**2, axis = 0)\n p3 = np.sum(list_second_chr**2, axis = 0)\n sq = np.sqrt(np.dot(p2[:,None],p3[None,:]))\n\n corr_chrom1_chrom2 = np.divide(p1, sq)\n\n print(\"Working in chromosome: {} \\n Comparing to chromosome: {}\".format(chr, secondary_chr))\n corrfile[chr].create_dataset(secondary_chr, data = corr_chrom1_chrom2)\n","sub_path":"cross_correlations/expression_score_cross_corr.py","file_name":"expression_score_cross_corr.py","file_ext":"py","file_size_in_byte":4645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"433404239","text":"# Copyright 2017 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Helper/utility functions that a tf-transform implementation would find handy.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nimport itertools\n\n\nimport numpy as np\nimport six\nfrom six.moves import range # pylint: disable=redefined-builtin\nfrom six.moves import zip # pylint: disable=redefined-builtin\nimport tensorflow as tf\nfrom tensorflow_transform import api\nfrom tensorflow_transform.saved import saved_transform_io\nfrom tensorflow_transform.tf_metadata import dataset_schema\nfrom tensorflow.contrib.session_bundle import bundle_shim\n\n_EMPTY_ARRAY = np.array([])\n_EMPTY_ARRAY.setflags(write=False)\n\n\ndef infer_feature_schema(columns):\n \"\"\"Given a dict of columns, creates a `Schema`.\n\n Infers a schema, in the format of a tf.Transform `Schema`, for the given\n dictionary of columns.\n\n Args:\n columns: A dict mapping column names to `Column`s. The tensors represented\n by these columns should have a 0'th dimension interpreted as the batch\n dimension. In order to pass a tensor representing a single instance, it\n must be wrapped in a batch of size 1.\n\n Returns:\n A `Schema` object.\n \"\"\"\n # If the column already has a schema attached, use that. Otherwise infer the\n # schema from the underlying tensor.\n return dataset_schema.Schema({\n name: (column.schema if column.schema\n else dataset_schema.infer_column_schema_from_tensor(column.tensor))\n for name, column in six.iteritems(columns)\n })\n\n\ndef make_feed_dict(input_tensors, schema, instances):\n \"\"\"Creates a feed dict for passing data to the graph.\n\n Converts a list of instances in the in-memory representation to a batch\n suitable for passing to `tf.Session.run`.\n\n Args:\n input_tensors: A map from column names to `Tensor`s or `SparseTensor`s.\n schema: A `Schema` object.\n instances: A list of instances, each of which is a map from column name to a\n python primitive, list, or ndarray.\n\n Returns:\n A map from `Tensor`s or `SparseTensor`s to batches in the format required by\n `tf.Session.run`.\n\n Raises:\n ValueError: If `schema` is invalid.\n \"\"\"\n def make_batch_indices(instance_indices):\n \"\"\"Converts a list of instance indices to the corresponding batch indices.\n\n Given a list of iterables representing the indices of N sparse tensors,\n creates a single list of indices representing the result of concatenating\n the sparse tensors along the 0'th dimension into a batch of size N.\n\n Args:\n instance_indices: A list of N iterables, each containing the sparse tensor\n indices for an instance.\n\n Returns:\n A list of indices with a batch dimension prepended.\n \"\"\"\n batch_indices = list(itertools.chain.from_iterable([\n [(row_number, index) for index in indices]\n for row_number, indices in enumerate(instance_indices)\n ]))\n # Indices must have shape (?, 2). Therefore if we encounter an empty\n # batch, we return an empty ndarray with shape (0, 2).\n return batch_indices if batch_indices else np.empty([0, 2], dtype=np.int64)\n\n def make_sparse_batch(instance_indices, instance_values, max_index):\n \"\"\"Converts a list of sparse instances into a sparse batch.\n\n Takes lists representing the indices and values of N sparse instances and\n concatenates them along the 0'th dimension into a sparse batch of size N.\n\n Args:\n instance_indices: A list of N iterables, each containing the sparse tensor\n indices for an instance.\n instance_values: A list of N iterables, each containing the sparse tensor\n values for an instance.\n max_index: An int representing the maximum index in `instance_indices`.\n\n Returns:\n A `SparseTensorValue` representing a batch of N sparse instances.\n \"\"\"\n batch_indices = make_batch_indices(instance_indices)\n batch_values = list(itertools.chain.from_iterable(instance_values))\n batch_shape = (len(instance_indices), max_index)\n return tf.SparseTensorValue(batch_indices, batch_values, batch_shape)\n\n result = {}\n for key, input_tensor in six.iteritems(input_tensors):\n representation = schema.column_schemas[key].representation\n if isinstance(representation, dataset_schema.FixedColumnRepresentation):\n feed_value = [instance[key] for instance in instances]\n\n elif isinstance(representation, dataset_schema.ListColumnRepresentation):\n values = [instance[key] for instance in instances]\n indices = [range(len(instance[key])) for instance in instances]\n max_index = max([len(instance[key]) for instance in instances])\n feed_value = make_sparse_batch(indices, values, max_index)\n\n elif isinstance(representation, dataset_schema.SparseColumnRepresentation):\n max_index = schema.column_schemas[key].axes[0].size\n indices, values = [], []\n for instance in instances:\n instance_indices, instance_values = instance[key]\n check_valid_sparse_tensor(\n instance_indices, instance_values, max_index, key)\n indices.append(instance_indices)\n values.append(instance_values)\n feed_value = make_sparse_batch(indices, values, max_index)\n\n else:\n raise ValueError('Invalid column %r.' % schema.column_schemas[key])\n result[input_tensor] = feed_value\n\n return result\n\n\ndef make_output_dict(schema, fetches):\n \"\"\"Maps the values fetched by `tf.Session.run` to the internal batch format.\n\n Args:\n schema: A `Schema` object.\n fetches: A dict representing a batch of data, as returned by `Session.run`.\n\n Returns:\n A dict from keys to a list or 2-tuple of lists.\n\n Raises:\n ValueError: If `schema` is invalid.\n \"\"\"\n def decompose_sparse_batch(sparse_value):\n \"\"\"Decomposes a sparse batch into a list of sparse instances.\n\n Args:\n sparse_value: A `SparseTensorValue` representing a batch of N sparse\n instances. The indices of the SparseTensorValue are expected to be\n sorted by row order.\n\n Returns:\n A tuple (instance_indices, instance_values) where the elements are lists\n of N lists representing the indices and values, respectively, of the\n instances in the batch.\n\n Raises:\n ValueError: If `sparse_value` contains out-of-order indices.\n \"\"\"\n batch_indices, batch_values, batch_shape = sparse_value\n # Preallocate lists of length batch_size, initialized to empty ndarrays,\n # representing the indices and values of instances. We can reuse\n # _EMPTY_ARRAY here because it is immutable.\n instance_indices = [_EMPTY_ARRAY] * batch_shape[0]\n instance_values = [_EMPTY_ARRAY] * batch_shape[0]\n instance_rank = len(batch_shape[1:])\n\n # Iterate over the rows in the batch. At each row, consume all the elements\n # that belong to that row.\n current_offset = 0\n for current_row in range(batch_shape[0]):\n start_offset = current_offset\n\n # Scan forward until we reach an element that does not belong to the\n # current row.\n while current_offset < len(batch_indices):\n row = batch_indices[current_offset][0]\n if row == current_row:\n # This element belongs to the current row.\n current_offset += 1\n elif row > current_row:\n # We've reached the end of the current row.\n break\n else:\n raise ValueError('Encountered out-of-order sparse index: %r.' %\n batch_indices[current_offset])\n\n if current_offset == start_offset:\n # If the current row is empty, leave the default value, _EMPTY_ARRAY.\n pass\n else:\n instance_indices[current_row] = batch_indices[\n start_offset:current_offset, 1:]\n if instance_rank == 1:\n # In this case indices will have length 1, so for convenience we\n # reshape from [-1, 1] to [-1].\n instance_indices[current_row] = (\n instance_indices[current_row].reshape([-1]))\n instance_values[current_row] = batch_values[start_offset:current_offset]\n\n return instance_indices, instance_values\n\n # Make a dict where the values are lists with one element per instance.\n result = {}\n for key, value in six.iteritems(fetches):\n representation = schema.column_schemas[key].representation\n if isinstance(representation, dataset_schema.FixedColumnRepresentation):\n result[key] = [value[i] for i in range(value.shape[0])]\n\n elif isinstance(representation, dataset_schema.ListColumnRepresentation):\n if not isinstance(value, tf.SparseTensorValue):\n raise ValueError('Expected a SparseTensorValue, but got %r' % value)\n instance_indices, instance_values = decompose_sparse_batch(value)\n for indices in instance_indices:\n if len(indices.shape) > 1 or np.any(indices != np.arange(len(indices))):\n raise ValueError('Encountered a SparseTensorValue that cannot be '\n 'decoded by ListColumnRepresentation.')\n result[key] = instance_values\n\n elif isinstance(representation, dataset_schema.SparseColumnRepresentation):\n if not isinstance(value, tf.SparseTensorValue):\n raise ValueError('Expected a SparseTensorValue, but got %r' % value)\n result[key] = decompose_sparse_batch(value)\n\n else:\n raise ValueError('Unhandled column representation: %r.' % representation)\n\n return result\n\n\ndef to_instance_dicts(batch_dict):\n \"\"\"Converts from the internal batch format to a list of instances.\n\n Args:\n batch_dict: A dict in the in-memory batch format, as returned by\n `make_output_dict`.\n\n Returns:\n A list of dicts in the in-memory instance format.\n \"\"\"\n def get_instance_values(batch_dict):\n # SparseFeatures are represented as a 2-tuple of list of lists, so\n # in that case we convert to a list of 2-tuples of lists.\n columns = (column if not isinstance(column, tuple) else zip(*column)\n for column in six.itervalues(batch_dict))\n return itertools.izip(*columns)\n\n return [dict(zip(six.iterkeys(batch_dict), instance_values))\n for instance_values in get_instance_values(batch_dict)]\n\n\ndef check_valid_sparse_tensor(indices, values, size, name):\n # Check that all indices are in range.\n if len(indices): # pylint: disable=g-explicit-length-test\n i_min, i_max = min(indices), max(indices)\n if i_min < 0 or i_max >= size:\n i_bad = i_min if i_min < 0 else i_max\n raise ValueError('Sparse column %r has index %d out of range [0, %d)'\n % (name, i_bad, size))\n\n if len(indices) != len(values):\n raise ValueError(\n 'Sparse column %r has indices and values of different lengths: '\n 'values: %r, indices: %r' % (name, values, indices))\n\n\ndef _make_input_columns(schema):\n \"\"\"Create input columns based on a `Schema`.\"\"\"\n placeholders = schema.as_batched_placeholders()\n return {\n # pylint: disable=protected-access\n key: api._InputColumn(placeholders[key], column_schema)\n for key, column_schema in six.iteritems(schema.column_schemas)\n }\n\n\n# Arguments to the constructor of tf.Constant.\nConstantTensorValue = collections.namedtuple(\n 'ConstantTensorValue', ['value', 'dtype', 'shape'])\n\n\ndef replace_tensors_with_constant_values(\n saved_model_dir, bound_saved_model_dir, input_value_mapping):\n \"\"\"Takes a SavedModel and replaces some inputs with constant values.\n\n Replaces some inputs from the SavedModel with constant tensors constructed\n based on `tensor_value_mapping`.\n\n Args:\n saved_model_dir: The directory of a SavedModel.\n bound_saved_model_dir: The directory to which to write the SavedModel with\n some inputs bound to constants.\n input_value_mapping: A map from inputs to `ConstantTensorValue`s.\n \"\"\"\n with tf.Graph().as_default():\n # Create constant tensors representing bound inputs.\n bound_input_tensors = {\n key: tf.constant(value.value, value.dtype)\n for key, value in six.iteritems(input_value_mapping)\n }\n with tf.Session() as session:\n input_tensors, output_tensors = (\n saved_transform_io.partially_apply_saved_transform(\n saved_model_dir, bound_input_tensors))\n saved_transform_io.write_saved_transform_from_session(\n session, input_tensors, output_tensors, bound_saved_model_dir)\n\n\ndef _copy_placeholder(placeholder):\n \"\"\"Copies a placeholder to a new graph.\"\"\"\n if isinstance(placeholder, tf.SparseTensor):\n # NOTE: We don't use sparse_placeholder because we want to ensure that the\n # placeholder we produce is identical to the original tensor.\n return tf.SparseTensor(\n indices=_copy_placeholder(placeholder.indices),\n values=_copy_placeholder(placeholder.values),\n dense_shape=_copy_placeholder(placeholder.dense_shape))\n else:\n if placeholder.op.type != 'Placeholder':\n raise ValueError(\n 'Attempted to copy a tensor that was not a placeholder: %s'\n % placeholder.op.type)\n return tf.placeholder(placeholder.dtype, shape=placeholder.get_shape())\n\n\ndef make_transform_fn_def(schema, inputs, outputs, saved_model_dir):\n \"\"\"Loads the graph defined by a partial preprocesssing function.\n\n Creates a SavedModel on disk representing the transform function. The given\n input and output columns implicitly define a transformation DAG; this is the\n function that is written. The resulting SavedModel requires additional inputs\n providing analyzer results. The mapping from these input names to the\n `_AnalyzerOutput`s will be returned.\n\n Args:\n schema: A `Schema` object.\n inputs: A dict from strings to `Column`s.\n outputs: A dict from strings to `Column`s.\n saved_model_dir: The directory where the SavedModel should be stored.\n\n Returns:\n A dict from input names in saved model to statistics (`_AnalyzerOutput`s).\n\n Raises:\n ValueError: If `schema` and `inputs` do not have the same keys, or if output\n columns cannot be derived from input columns.\n \"\"\"\n # Construct the graph, keeping track of tensors for input columns, output\n # columns, and statistic placeholders. Note that while each column already\n # has a tensor, these are only for validation. We ignore these and construct\n # a new graph here, because it's easier to construct the subgraph we are\n # interested in, than to extract it from the graph we already have.\n input_tensors = {}\n column_names_to_statistics = {}\n if (sorted(six.iterkeys(schema.as_feature_spec())) !=\n sorted(six.iterkeys(inputs))):\n raise ValueError('Schema and input columns had different keys (%s vs %s).'\n % (sorted(six.iterkeys(schema.as_feature_spec())),\n sorted(six.iterkeys(inputs))))\n\n def get_new_input_column_name():\n analyzer_idx = 0\n while True:\n name = 'analyzer_placeholder_input_column_%d' % analyzer_idx\n analyzer_idx += 1\n if name not in input_tensors:\n return name\n\n cached_column_to_tensor = {}\n def column_to_tensor(column):\n \"\"\"Returns the tensor that represents the given column.\"\"\"\n if column in cached_column_to_tensor:\n return cached_column_to_tensor[column]\n\n # pylint: disable=protected-access\n if isinstance(column, api._AnalyzerOutput):\n # For analyzer outputs, copy over the placeholder tensor and add the\n # placeholder to the dict that keeps track of the map between tensors and\n # analyzer output placeholders.\n tensor = _copy_placeholder(column.tensor)\n name = get_new_input_column_name()\n input_tensors[name] = tensor\n column_names_to_statistics[name] = column\n elif isinstance(column,\n (api._TransformedColumn, api._TransformedStatistic)):\n # For transformed columns or statistics, apply the transformation.\n tensor = column.fn(*[column_to_tensor(input_column)\n for input_column in column.inputs])\n elif isinstance(column, api._InputColumn):\n raise ValueError('Reached input column that wasn\\'t in input dict')\n # pylint: enable=protected-access\n\n cached_column_to_tensor[column] = tensor\n return tensor\n\n graph = tf.Graph()\n with graph.as_default():\n # Input columns form the roots of the graph, and so we need the create them\n # again from scratch in this new graph.\n new_input_columns = _make_input_columns(schema)\n\n # Compute placeholder for input columns.\n input_tensors.update({\n key: column.placeholder\n for key, column in six.iteritems(new_input_columns)\n })\n\n # Initialize cache of column tensors with the input columns.\n cached_column_to_tensor.update({\n inputs[key]: new_input_columns[key].tensor\n for key in six.iterkeys(inputs)\n })\n\n # Compute tensors representing output columns. As a side effect this will\n # populate column_names_to_statistics with all placeholders for\n # `_AnalyzerOutputs` that are parents of outputs, and also augment\n # input_tensors\n output_tensors = {key: column_to_tensor(column)\n for key, column in six.iteritems(outputs)}\n\n with tf.Session() as session:\n saved_transform_io.write_saved_transform_from_session(\n session, input_tensors, output_tensors, saved_model_dir)\n return column_names_to_statistics\n\n\ndef load_transform_fn_def(saved_model_dir):\n \"\"\"Loads a TransformFnDef into a graph.\n\n Similar to apply_transform_fn_def except it loads input placeholders and\n returns a column to tensor mapping for inputs.\n\n Args:\n saved_model_dir: The location of the SavedModel.\n\n Returns:\n A pair of dicts, for inputs and outputs, whose keys are column names and\n whose values are `Tensor`s or `SparseTensor`s representing these columns.\n \"\"\"\n with tf.Session():\n return saved_transform_io.partially_apply_saved_transform(\n saved_model_dir, {})\n\n\ndef run_preprocessing_fn(preprocessing_fn, schema):\n \"\"\"Runs the user-defined preprocessing function, returning a DAG of columns.\n\n Args:\n preprocessing_fn: A function that takes a dict of `Column`s as input and\n returns a dict of `Column`s as output.\n schema: A dict mapping column names to `tf.FixedLenFeature`,\n `tf.VarLenFeature` or `tf.SparseFeature` objects.\n\n Returns:\n A tuple of input columns and output columns.\n\n Raises:\n ValueError: If `schema` contains unsupported feature types.\n \"\"\"\n # Run the preprocessing function, which will construct a TF graph for the\n # purpose of validation. The graphs used for computation will be built from\n # the DAG of columns in make_transform_fn_def.\n graph = tf.Graph()\n with graph.as_default():\n inputs = _make_input_columns(schema)\n\n # Construct the deferred preprocessing graph by calling preprocessing_fn on\n # the inputs.\n outputs = preprocessing_fn(inputs)\n\n return inputs, outputs\n\n\ndef make_tensor_func_from_saved_model(model_dir,\n tags,\n signature_name=None,\n input_keys_in_signature=None,\n output_keys_in_signature=None):\n \"\"\"Create a tensor-in-tensor-out function as a transform used in tft.map.\n\n When tft.map is called with this function as first parameter, the second\n parameter (input columns) should match the `input_keys_in_signature`\n in their orders.\n\n Args:\n model_dir: A path containing a saved model.\n tags: The tags specifying which metagraph to load from the saved model.\n signature_name: Specify signature of the loaded model. The default value\n None can be used if there is only one signature in the MetaGraphDef.\n input_keys_in_signature: A list of strings which should match the inputs\n in the signature of the saved model. The purpose of this parameter is to\n specify the order of the input columns passed to tft.map when called\n with the returned tensor_fn. The default value None can be used if there\n is only one input.\n output_keys_in_signature: A list of strings which should be a subset of\n the outputs in the signature of the saved model. The returned tensor_fn\n will return the corresponding tensors, in the same order. The default\n value None can be used if there is only one output from signature.\n\n Returns:\n A tensor-in-tensor-out function which can be used in tft.map.\n\n Raises:\n ValueError: If\n `signature_name` is None but the saved model contains multiple signature, or\n `input_keys_in_signature` do not match the signature inputs, or\n `output_keys_in_signature` is not a subset of the signature outputs, or\n the metagraph from saved model contains TABLE_INITIALIZERS operations.\n \"\"\"\n\n # Load model, get graph, inputs and outputs.\n loaded_graph = tf.Graph()\n with loaded_graph.as_default():\n session, meta_graph = (\n bundle_shim.load_session_bundle_or_saved_model_bundle_from_path(\n model_dir, tags=tags))\n if signature_name:\n signature = meta_graph.signature_def[signature_name]\n elif len(meta_graph.signature_def) > 1:\n raise ValueError(\n 'The saved model contains multiple signatures \"%s\". Specify a '\n 'signature_name.' % ','.join(meta_graph.signature_def.keys()))\n else:\n signature = meta_graph.signature_def.values()[0]\n\n inputs = {\n key: tensor_info_proto.name\n for (key, tensor_info_proto) in signature.inputs.items()\n }\n outputs = {\n key: tensor_info_proto.name\n for (key, tensor_info_proto) in signature.outputs.items()\n }\n\n # Get input tensor names.\n if input_keys_in_signature is not None:\n if set(input_keys_in_signature) != set(inputs.keys()):\n raise ValueError(\n 'keys in input logical names do not match inputs of saved model. ' +\n 'Model signature has \"%s\" but input logical names has \"%s\".' %\n (','.join(inputs.keys()), ','.join(input_keys_in_signature)))\n input_tensor_names = [\n inputs[key] for key in input_keys_in_signature\n ]\n else:\n if len(inputs) > 1:\n raise ValueError(\n 'The signature from saved model contains multiple inputs \"%s\". '\n 'Input logical names are required.' % ','.join(inputs.keys()))\n else:\n input_tensor_names = [inputs.values()[0]]\n\n # Get output tensor names.\n if output_keys_in_signature:\n if not set(output_keys_in_signature) <= set(outputs.keys()):\n raise ValueError(\n 'output names are not a subset of outputs of saved model. ' +\n 'output names has \"%s\" but model signature has \"%s\".' %\n (','.join(output_keys_in_signature), ','.join(outputs.keys())))\n\n output_tensor_names = [\n outputs[key] for key in output_keys_in_signature\n ]\n else:\n if len(outputs) > 1:\n raise ValueError(\n 'The signature from saved model contains multiple outputs \"%s\". '\n 'Output names are required.' % ','.join(outputs.keys()))\n output_tensor_names = [outputs.values()[0]]\n\n if tf.get_collection(tf.GraphKeys.TABLE_INITIALIZERS):\n raise ValueError(\n 'Models with table init ops in metagraph are not supported.')\n\n # Convert_variables_to_constants() requires op name.\n output_op_names = [loaded_graph.get_tensor_by_name(x).op.name\n for x in output_tensor_names]\n constant_graph_def = tf.graph_util.convert_variables_to_constants(\n session, loaded_graph.as_graph_def(), output_op_names)\n\n def tensor_fn(*si):\n input_name_to_tensor_map = dict(zip(input_tensor_names, si))\n output_tensors = tf.import_graph_def(\n constant_graph_def,\n input_map=input_name_to_tensor_map,\n return_elements=output_tensor_names)\n return output_tensors[0]\n\n return tensor_fn\n\n\ndef make_tensor_func_from_checkpoint(input_tensor_func,\n checkpoint,\n include=None,\n exclude=None):\n \"\"\"Create a tensor function from a checkpoint as a transform used in tft.map.\n\n When tft.map is called with this function as first parameter, the second\n parameter (input columns) should be the same as the parameters for\n `input_tensor_func` function.\n\n Args:\n input_tensor_func: A tensor-in-tensor-out function that may contain\n variables.\n checkpoint: The checkpoint path to load variables from.\n include: An optional list/tuple of scope strings for filtering which\n variables from the VARIABLES collection to include. If None, all\n variables will be included.\n exclude: An optional list/tuple of scope strings for filtering which\n variables from the VARIABLES collection to exclude. If None, no variables\n will be excluded.\n\n Returns:\n A tensor-in-tensor-out function which can be used in tft.map.\n\n Raises:\n ValueError if the input tensor-in-tensor-out function adds to\n TABLE_INITIALIZERS collections.\n \"\"\"\n\n def tensor_fn(*si):\n \"\"\"The returned tensor-in-tensor-out function.\"\"\"\n\n loaded_graph = tf.Graph()\n with loaded_graph.as_default():\n input_tensors = [\n tf.placeholder(dtype=x.dtype, shape=x.shape, name=x.op.name)\n for x in si]\n output_tensor = input_tensor_func(*input_tensors)\n\n if tf.get_collection(tf.GraphKeys.TABLE_INITIALIZERS):\n raise ValueError('Models with table init ops are not supported.')\n\n vars_to_restore = tf.contrib.slim.get_variables_to_restore(\n include=include, exclude=exclude)\n saver = tf.train.Saver(vars_to_restore)\n with tf.Session() as sess:\n saver.restore(sess, checkpoint)\n output_graph_def = tf.graph_util.convert_variables_to_constants(\n sess, loaded_graph.as_graph_def(), [output_tensor.op.name])\n\n input_map = {x.name: x for x in si}\n output_tensors = tf.import_graph_def(output_graph_def, input_map=input_map,\n return_elements=[output_tensor.name])\n return output_tensors[0]\n\n return tensor_fn\n","sub_path":"tensorflow_transform/impl_helper.py","file_name":"impl_helper.py","file_ext":"py","file_size_in_byte":26587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"258335052","text":"class TriangularNumber():\n previous_natural_number = 0\n triangular_number = 0\n\n def add_next_natural_number(self):\n self.previous_natural_number += 1\n self.triangular_number += self.previous_natural_number\n\n def return_number(self):\n return self.triangular_number\n\n def number_of_factors(self):\n count = 0\n for i in range(1, self.triangular_number + 1):\n if(self.triangular_number % i == 0):\n count += 1\n return count\n\n def count(self):\n return self.previous_natural_number\n\nfile = open('12.txt', 'w') \nfile.close() \ntriangle = TriangularNumber()\ni = 0\nwhile(i <500000):\n count = triangle.count()\n if(count % 100 == 0):\n with open('12.txt', 'a') as file:\n file.write(str(count))\n file.write('\\n')\n i += 1\n triangle.add_next_natural_number()\n if(triangle.number_of_factors() >= 500):\n with open('12.txt', 'a') as file:\n file.write(\"==========RESULT==========\")\n file.write(str(triangle.return_number()))\n#print(triangle.return_number())\n#print(triangle.number_of_factors())","sub_path":"Unfinished/12-high-divis-triangular-number.py","file_name":"12-high-divis-triangular-number.py","file_ext":"py","file_size_in_byte":1142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"420916594","text":"import matplotlib.pyplot as plt\r\n\r\n# Valores de entrada\r\ninput_values = [1,2,3,4,5]\r\nsquares = [1, 4, 9, 16, 25]\r\n\r\n# Fijar estilo de la plantilla\r\nplt.style.use('seaborn')\r\n\r\n# Crea dos figuras, la principal fig y ax\r\nfig, ax = plt.subplots()\r\n\r\n# Muestra la grafica con los valores de entrada\r\nax.plot(input_values, squares, linewidth=3)\r\n\r\n# Fijar el titulo y las etiquetas de los ejes\r\nax.set_title(\"Numeros cuadrados\", fontsize=24)\r\nax.set_xlabel(\"Valor\", fontsize=14)\r\nax.set_ylabel(\"Valor del cuadrado\", fontsize=14)\r\n\r\n# Fijar el tamaño de grosor de las etiquetas\r\nax.tick_params(axis='both', labelsize=14)\r\n\r\n# Abre matplotlib viewer\r\nplt.show()\r\n\r\n","sub_path":"mpl_squares.py","file_name":"mpl_squares.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"72092943","text":"def get_vars(self, loader, play=None, host=None, task=None, include_hostvars=True, include_delegate_to=True, use_cache=True):\n '\\n Returns the variables, with optional \"context\" given via the parameters\\n for the play, host, and task (which could possibly result in different\\n sets of variables being returned due to the additional context).\\n\\n The order of precedence is:\\n - play->roles->get_default_vars (if there is a play context)\\n - group_vars_files[host] (if there is a host context)\\n - host_vars_files[host] (if there is a host context)\\n - host->get_vars (if there is a host context)\\n - fact_cache[host] (if there is a host context)\\n - play vars (if there is a play context)\\n - play vars_files (if there\\'s no host context, ignore\\n file names that cannot be templated)\\n - task->get_vars (if there is a task context)\\n - vars_cache[host] (if there is a host context)\\n - extra vars\\n '\n display.debug('in VariableManager get_vars()')\n cache_entry = self._get_cache_entry(play=play, host=host, task=task)\n if ((cache_entry in VARIABLE_CACHE) and use_cache):\n display.debug('vars are cached, returning them now')\n return VARIABLE_CACHE[cache_entry]\n all_vars = dict()\n magic_variables = self._get_magic_variables(loader=loader, play=play, host=host, task=task, include_hostvars=include_hostvars, include_delegate_to=include_delegate_to)\n if play:\n for role in play.get_roles():\n all_vars = combine_vars(all_vars, role.get_default_vars())\n if (task and (task._role is not None) and (play or (task.action == 'include_role'))):\n all_vars = combine_vars(all_vars, task._role.get_default_vars(dep_chain=task.get_dep_chain()))\n if host:\n all_vars = combine_vars(all_vars, host.get_group_vars())\n if ('all' in self._group_vars_files):\n data = preprocess_vars(self._group_vars_files['all'])\n for item in data:\n all_vars = combine_vars(all_vars, item)\n for group in sorted(host.get_groups(), key=(lambda g: (g.depth, g.priority, g.name))):\n if ((group.name in self._group_vars_files) and (group.name != 'all')):\n for data in self._group_vars_files[group.name]:\n data = preprocess_vars(data)\n for item in data:\n all_vars = combine_vars(all_vars, item)\n all_vars = combine_vars(all_vars, host.get_vars())\n host_name = host.get_name()\n if (host_name in self._host_vars_files):\n for data in self._host_vars_files[host_name]:\n data = preprocess_vars(data)\n for item in data:\n all_vars = combine_vars(all_vars, item)\n try:\n host_facts = wrap_var(self._fact_cache.get(host.name, dict()))\n if (not C.NAMESPACE_FACTS):\n all_vars = combine_vars(all_vars, host_facts)\n all_vars = combine_vars(all_vars, {\n 'ansible_facts': host_facts,\n })\n if ('ansible_local' in all_vars['ansible_facts']):\n all_vars.update({\n 'ansible_local': all_vars['ansible_facts']['ansible_local'],\n })\n else:\n all_vars.update({\n 'ansible_local': {\n \n },\n })\n if ('ansible_local' in all_vars['ansible_facts']):\n del all_vars['ansible_facts']['ansible_local']\n except KeyError:\n pass\n if play:\n all_vars = combine_vars(all_vars, play.get_vars())\n for vars_file_item in play.get_vars_files():\n temp_vars = combine_vars(all_vars, self._extra_vars)\n temp_vars = combine_vars(temp_vars, magic_variables)\n templar = Templar(loader=loader, variables=temp_vars)\n vars_file_list = vars_file_item\n if (not isinstance(vars_file_list, list)):\n vars_file_list = [vars_file_list]\n try:\n for vars_file in vars_file_list:\n vars_file = templar.template(vars_file)\n try:\n data = preprocess_vars(loader.load_from_file(vars_file))\n if (data is not None):\n for item in data:\n all_vars = combine_vars(all_vars, item)\n break\n except AnsibleFileNotFound:\n continue\n except AnsibleParserError:\n raise\n else:\n if include_delegate_to:\n raise AnsibleFileNotFound(('vars file %s was not found' % vars_file_item))\n except (UndefinedError, AnsibleUndefinedVariable):\n if ((host is not None) and self._fact_cache.get(host.name, dict()).get('module_setup') and (task is not None)):\n raise AnsibleUndefinedVariable((\"an undefined variable was found when attempting to template the vars_files item '%s'\" % vars_file_item), obj=vars_file_item)\n else:\n display.vvv((\"skipping vars_file '%s' due to an undefined variable\" % vars_file_item))\n continue\n if (not C.DEFAULT_PRIVATE_ROLE_VARS):\n for role in play.get_roles():\n all_vars = combine_vars(all_vars, role.get_vars(include_params=False))\n if task:\n if task._role:\n all_vars = combine_vars(all_vars, task._role.get_vars(task.get_dep_chain(), include_params=False))\n all_vars = combine_vars(all_vars, task.get_vars())\n if host:\n all_vars = combine_vars(all_vars, self._vars_cache.get(host.get_name(), dict()))\n all_vars = combine_vars(all_vars, self._nonpersistent_fact_cache.get(host.name, dict()))\n if task:\n if task._role:\n all_vars = combine_vars(all_vars, task._role.get_role_params(task.get_dep_chain()))\n all_vars = combine_vars(all_vars, task.get_include_params())\n all_vars = combine_vars(all_vars, self._extra_vars)\n all_vars = combine_vars(all_vars, magic_variables)\n if task:\n if ('environment' not in all_vars):\n all_vars['environment'] = task.environment\n else:\n display.warning(\"The variable 'environment' appears to be used already, which is also used internally for environment variables set on the task/block/play. You should use a different variable name to avoid conflicts with this internal variable\")\n if (task and (task.delegate_to is not None) and include_delegate_to):\n all_vars['ansible_delegated_vars'] = self._get_delegated_vars(loader, play, task, all_vars)\n if (task or play):\n all_vars['vars'] = all_vars.copy()\n display.debug('done with get_vars()')\n return all_vars","sub_path":"Data Set/bug-fixing-5/97cb2016d86523ad6efbee2c2975ca287075a2a4--fix.py","file_name":"97cb2016d86523ad6efbee2c2975ca287075a2a4--fix.py","file_ext":"py","file_size_in_byte":6968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"443937733","text":"import cv2\nimport numpy as np\n\nimg = cv2.imread('thinned.png', 0)\n\ncorners = cv2.goodFeaturesToTrack(img, 20, 0.01, 3)\ncorners = np.int0(corners)\n\nimg = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)\n\nfor i in corners:\n x, y = i.ravel()\n cv2.circle(img, (x, y), 5, (255, 0, 0), 1)\n\ncv2.imwrite('shi-tomasi.png', img)\n\ncv2.imshow('Shi-Tomasi', img)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n","sub_path":"fingerprint_Shi_Tomasi.py","file_name":"fingerprint_Shi_Tomasi.py","file_ext":"py","file_size_in_byte":384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"472011778","text":"import discord\nfrom discord.ext import commands\nimport userdata as ud\n\nimport asyncio\n\n\nclass Owner(commands.Cog):\n \n def __init__(self, bot):\n self.bot = bot\n\n\n @commands.command()\n @commands.is_owner()\n async def iamyourcommander(self,ctx):\n async with ctx.typing():\n await asyncio.sleep(.1)\n return await ctx.send('Yes. You are')\n \n @commands.group(name=\"db\",invoke_without_command=True)\n @commands.is_owner()\n async def db(self, ctx):\n async with ctx.typing():\n await asyncio.sleep(.1)\n return await ctx.send('```asciidoc\\n= Database Help =\\nA list of commands\\n=====\\n- give ```')\n \n @db.command(name=\"give\")\n @commands.is_owner()\n async def db_update(self, ctx, user:discord.User, choice:str, *, arg1):\n async with ctx.typing():\n await asyncio.sleep(.1)\n pp = await ud.Pp.fetch(user.id)\n if choice == 'size':\n pp.size += int(arg1)\n elif choice == 'multiplier':\n pp.default_multiplier += int(arg1)\n elif choice == 'name':\n pp.name = str(arg1)\n else:\n return await ctx.message.add_reaction('❌')\n await pp.update()\n return await ctx.message.add_reaction('👌')\n\n @db.group(name=\"shop\",invoke_without_command=True)\n @commands.is_owner()\n async def shop(self,ctx):\n async with ctx.typing():\n await asyncio.sleep(.1)\n return await ctx.send('```asciidoc\\n= Shop Database Help =\\nA list of commands\\n=====\\n- add \\n- set ```')\n \n @shop.command(name=\"add\")\n @commands.is_owner()\n async def db_shop_add(self, ctx, *, item_name:str):\n async with ctx.typing():\n def check(m):\n return m.author == ctx.author\n item = item.lower()\n await asyncio.sleep(.1)\n await ctx.send('What\\'s the item type?')\n try:\n x = await self.bot.wait_for('message', timeout=120.0, check=check)\n item_type = str(x.content.upper())\n await ctx.send('What\\'s the item description?')\n x = await self.bot.wait_for('message', timeout=120.0, check=check)\n item_desc = str(x.content)\n await ctx.send('What\\'s the default price?')\n x = await self.bot.wait_for('message', timeout=120.0, check=check)\n default_price = int(x.content)\n await ctx.send('Is the item multiplier dependant?')\n x = await self.bot.wait_for('message', timeout=120.0, check=check)\n multiplierDependant = x == 'yes'\n await ud.Shop.add_item(item_name,item_type,item_desc,default_price,multiplierDependant)\n await ctx.send('Process completed.')\n except asyncio.TimeoutError:\n await ctx.send('Slowpoke.')\n\n @shop.command(name=\"set\")\n @commands.is_owner()\n async def db_shop_set(self, ctx, column,arg,*,item_name):\n async with ctx.typing():\n await asyncio.sleep(.1)\n await ud.runsql('execute',f\"UPDATE userdata.shopItems set {column} = {arg} WHERE item_name = '{item_name}'\")\n \n @shop.command(name=\"delete\")\n @commands.is_owner()\n async def db_shop_delete(self, ctx, *, item_name:str):\n async with ctx.typing():\n await asyncio.sleep(.1)\n await ud.runsql('execute',f\"DELETE FROM userdata.shopItems WHERE item_name = '{item_name}'\")\n\n\n\n\ndef setup(bot):\n bot.add_cog(Owner(bot))\n","sub_path":"cogs/owner.py","file_name":"owner.py","file_ext":"py","file_size_in_byte":3529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"569167405","text":"import xlrd\nimport unittest\nimport requests\nimport HTMLTestRunner\nclass Test(unittest.TestCase):\n def test_duqu(self,filename='1.xlsx'):\n data=xlrd.open_workbook(filename)\n table=data.sheet_by_index(0)\n parmeter=table.col_values(3)\n print(parmeter)\n #jsoninfo=eval(parmeter[3])\n c=str(parmeter)\n print(c)\n i=0\n j=0\n for i in range(0,800):\n if i%16==0:\n print(i)\n j+=1\n print(j)\n url='https://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel='+c[i:i+11]\n print(url)\n r=requests.get(url)\n print(r.text)\n\n # def test_requests(self):\n # auth=self.duqu()\n # #r=requests.request(\"%s\"% auth[0],params=auth[1])\n # r=requests.get(\"%s\"% auth[5])\n # print(r.text)\nif __name__==\"__main__\":\n unittest.main()","sub_path":"jkou/testb.py","file_name":"testb.py","file_ext":"py","file_size_in_byte":918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"620481140","text":"import pandas as _pd\nfrom parserix import parse as _parse\nfrom cptools2 import utils\n\ndef create_loaddata(img_list):\n \"\"\"\n create a dataframe suitable for cellprofilers LoadData module\n \"\"\"\n df_long = create_long_loaddata(img_list)\n return cast_dataframe(df_long)\n\n\ndef create_long_loaddata(img_list):\n \"\"\"\n create a dataframe of image paths with metadata columns\n \"\"\"\n just_filenames = [_parse.img_filename(i) for i in img_list]\n df_img = _pd.DataFrame({\n \"URL\" : just_filenames,\n \"path\" : [_parse.path(i) for i in img_list],\n \"Metadata_platename\" : [_parse.plate_name(i) for i in img_list],\n \"Metadata_well\" : [_parse.img_well(i) for i in just_filenames],\n \"Metadata_site\" : [_parse.img_site(i) for i in just_filenames],\n \"Metadata_channel\" : [_parse.img_channel(i) for i in just_filenames],\n \"Metadata_platenum\" : [_parse.plate_num(i) for i in img_list]\n })\n return df_img\n\n\ndef cast_dataframe(dataframe, check_nan=True):\n \"\"\"reshape a create_loaddata dataframe from long to wide format\"\"\"\n n_channels = len(set(dataframe.Metadata_channel))\n wide_df = dataframe.pivot_table(\n index=[\"Metadata_site\", \"Metadata_well\", \"Metadata_platenum\",\n \"Metadata_platename\", \"path\"],\n columns=\"Metadata_channel\",\n values=\"URL\",\n aggfunc=\"first\").reset_index()\n # rename FileName columns from 1, 2... to FileName_W1, FileName_W2 ...\n columns = dict()\n for i in range(1, n_channels+1):\n columns[i] = \"FileName_W\" + str(i)\n wide_df.rename(columns=columns, inplace=True)\n # duplicate PathName for each channel\n for i in range(1, n_channels+1):\n wide_df[\"PathName_W\" + str(i)] = wide_df.path\n wide_df.drop([\"path\"], axis=1, inplace=True)\n if check_nan is True:\n if utils.any_nan_values(dataframe):\n raise Warning(\"dataframe contains missing values\")\n return wide_df\n\n","sub_path":"cptools2/loaddata.py","file_name":"loaddata.py","file_ext":"py","file_size_in_byte":1946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"444911127","text":"# Import * from googleDriveAPI\nfrom sys import argv\nfrom googleDriveAPI.drive_list import driveCaller\nimport googleDriveAPI\n\n# Check __name__ == \"__main__.py ==> run main()\"\n\nif __name__ == \"__main__\":\n \n ans = True\n while ans:\n try:\n # exampel folder id \"0B69RRb17QL4pflctSUpZYmlScVlMNmFKVnFuS1RLT1BHR1BGZkR2eW5YYmhiQlZMSmo2Nm8\"\n # Specify the folder \n # Get user input\n print ('\\nEnter folder id: \\n')\n folder_id = input()\n res = driveCaller(folder_id)\n print ('\\nYour output =>\\n')\n print (res)\n print ('\\n ... sending output dto file\\n\\n')\n\n # write contents to file \n f = open('filecontents.txt','w')\n f.write(str(res))\n f.close()\n\n #check if user wants to run again\n print ('Would you like to run again?')\n run_again = input()\n if run_again != 'yes':\n ans = False\n\n except:\n ans = False\n print ('error has occured')\n\n\n\n \n ","sub_path":"Folder_Lister.py","file_name":"Folder_Lister.py","file_ext":"py","file_size_in_byte":1085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"553491218","text":"from __future__ import print_function\nimport os\nimport functools\n\nfrom avocado.utils import output\nfrom six.moves.urllib.request import urlopen\n\n\ndef url_download_interactive(url, output_file, title='', chunk_size=102400):\n \"\"\"\n Download file from a given url.\n \"\"\"\n with open(output_file, 'wb') as out:\n inc = urlopen(url)\n try:\n filesize = int(inc.headers['Content-Length'])\n except KeyError:\n raise ValueError('Could not find file size in HTTP headers')\n pb = output.ProgressBar(maximum=filesize, title=title)\n pb.draw()\n records = iter(functools.partial(inc.read, chunk_size), b'')\n for record in records:\n pb.append_amount(len(record))\n out.write(record)\n print()\n\n\nif __name__ == '__main__':\n url = ('http://download.eng.bos.redhat.com/brewroot/packages/'\n 'qemu-kvm-rhev/2.10.0/15.el7/x86_64/'\n 'qemu-img-rhev-2.10.0-15.el7.x86_64.rpm')\n url_download_interactive(url,\n '/home/test/qemu-img-rhev-2.10.\\\n 0-15.el7.x86_64.rpm')\n","sub_path":"download.py","file_name":"download.py","file_ext":"py","file_size_in_byte":1122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"310160777","text":"from numpy import array\n\nclass PhysicalConstants:\n \"\"\"\n Define physical constants (defaults to SI units)\n \n Physical Constants List\n -----------------------\n gravitationalAcceleration : acceleration due to gravity (defaults to numpy.array([0,-9.8]) (m/s))\n boltzmannConstant : boltzmann's constant (defaults to 1.38e-23 (J/K))\n vacuumPermittivity : vacuum permittivity (defaults to 8.85e-12 (F/m))\n \"\"\"\n def __init__(self,gravitationalAcceleration=[0,-9.8],boltzmannConstant=1.38e-23,vacuumPermittivity=8.85e-12):\n self.gravitationalAcceleration = array(gravitationalAcceleration)\n self.boltzmannConstant = boltzmannConstant\n self.vacuumPermittivity = vacuumPermittivity","sub_path":"build/lib/ptspy/physical/physicalConstants.py","file_name":"physicalConstants.py","file_ext":"py","file_size_in_byte":721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"362143424","text":"import os\nimport re\nfrom PyQt5 import QtWidgets, QtGui, QtCore\n\n\nclass WordGame(QtWidgets.QWidget):\n \"\"\" GUI Class Buttons, Labels, Graphics, Images. If Images not visible - PYTHONPATH incorrect! \"\"\"\n def __init__(self, parent=None):\n QtWidgets.QWidget.__init__(self, parent)\n self.center()\n self.setStyleSheet(\"background: qlineargradient(x1:1, x2:0, stop:0 #672491, stop:1 #777777);\")\n self.wordbtn1 = QtWidgets.QPushButton(\"Browse\", self)\n self.wordbtn1.setStyleSheet(\"background-color: #777777; color: #FFFD77;\")\n self.wordbtn1.setFont(QtGui.QFont(\"Tahoma\", 12, 95))\n self.wordle1 = QtWidgets.QLineEdit(self)\n self.wordle1.setStyleSheet(\"background-color: #777777; color: #141414;\")\n self.wordle1.setFont(QtGui.QFont(\"Tahoma\", 12, 95))\n self.wordle2 = QtWidgets.QLineEdit(self)\n self.wordle2.setStyleSheet(\"padding: 14px; background-color: #777777; color: #141414;\")\n self.wordle2.setFont(QtGui.QFont(\"Tahoma\", 21, 95))\n self.wordle2.setReadOnly(True)\n self.wordle2.setEchoMode(2)\n self.wordbtn2 = QtWidgets.QPushButton(\"PLAY\", self)\n self.wordbtn2.setStyleSheet(\"background-color: #627419; color: #FFFD77;\")\n self.wordbtn2.setFont(QtGui.QFont(\"Tahoma\", 12, 95))\n self.wordle3 = QtWidgets.QLineEdit(self)\n self.wordle3.setStyleSheet(\"background-color: #777777; color: #141414;\")\n self.wordle3.setFont(QtGui.QFont(\"Tahoma\", 12, 95))\n self.wordle3.setPlaceholderText(\"Input letter of You word...\")\n self.wordbtn3 = QtWidgets.QPushButton(\"New\", self)\n self.wordbtn3.setStyleSheet(\"background-color: #627419; color: #FFFD77;\")\n self.wordbtn3.setFont(QtGui.QFont(\"Tahoma\", 12, 95))\n self.wordbtn4 = QtWidgets.QPushButton(\"Statistics\", self)\n self.wordbtn4.setStyleSheet(\"background-color: #627491; color: #FFFD77;\")\n self.wordbtn4.setFont(QtGui.QFont(\"Tahoma\", 10, 95))\n self.wordbtn5 = QtWidgets.QPushButton(\"File\", self)\n self.wordbtn5.setStyleSheet(\"background-color: #627491; color: #FFFD77;\")\n self.wordbtn5.setFont(QtGui.QFont(\"Tahoma\", 10, 95))\n self.wordbtn6 = QtWidgets.QPushButton(\"Close\", self)\n self.wordbtn6.setStyleSheet(\"background-color: #672419; color: #FFFD77;\")\n self.wordbtn6.setFont(QtGui.QFont(\"Tahoma\", 12, 95)) \n self.wordte = QtWidgets.QTextEdit(self)\n self.wordte.setStyleSheet(\"background-color: #777777; color: #141414;\")\n self.wordte.setFont(QtGui.QFont(\"Tahoma\", 12, 95))\n self.wordte.setReadOnly(True)\n self.grid = QtWidgets.QGridLayout()\n self.grid.addWidget(self.wordbtn1, 0, 0, 1, 1)\n self.grid.addWidget(self.wordle1, 0, 1, 1, 3)\n self.grid.addWidget(self.wordle2, 1, 0, 1, 4)\n self.grid.addWidget(self.wordbtn2, 2, 0, 1, 1)\n self.grid.addWidget(self.wordle3, 2, 1, 1, 3)\n self.grid.addWidget(self.wordbtn3, 3, 0, 1, 1)\n self.grid.addWidget(self.wordbtn4, 3, 1, 1, 1)\n self.grid.addWidget(self.wordbtn5, 3, 2, 1, 1)\n self.grid.addWidget(self.wordbtn6, 3, 3, 1, 1)\n self.grid.addWidget(self.wordte, 4, 0, 1, 4)\n self.setLayout(self.grid)\n self.wgtime1 = QtCore.QTimer()\n self.wgtime1.start(100)\n self.wgtime2 = QtCore.QTimer()\n self.wgtime2.start(150) \n self.wordbtn1.clicked.connect(self.word_btn1)\n self.wordbtn2.clicked.connect(self.word_btn2)\n self.wordbtn3.clicked.connect(self.word_btn3)\n self.wordbtn4.clicked.connect(self.word_btn4)\n self.wordbtn5.clicked.connect(self.word_btn5)\n self.wordbtn6.clicked.connect(self.word_btn6)\n self.wgtime1.timeout.connect(self.on_wgtime1)\n self.wgtime2.timeout.connect(self.on_wgtime2)\n self.wgame = 0\n self.wscore = 0\n self.wbeep = 0\n self.wlost = 0\n self.wordfind = r\"([\\`а-яА-ЯёЁA-Za-z0-9]+)\\s\"\n\n \"\"\" OPEN FILES \"\"\"\n def word_btn1(self):\n self.wbeep = 0\n self.wordte.clear()\n self.wordte.setStyleSheet(\"background-color: #777777; color: #141414;\")\n self.wordte.setFont(QtGui.QFont(\"Tahoma\", 12, 95)) \n self.wordfile1 = QtWidgets.QFileDialog.getOpenFileName(self, caption=\"Images\", directory=QtCore.QDir.homePath())\n if self.wordfile1 is not None:\n path1 = os.path.dirname(self.wordfile1[0])\n sys.path.append(str(path1))\n self.wordle1.setText(str(self.wordfile1[0]))\n self.fileread1 = open(self.wordfile1[0], 'r')\n self.fileread12 = self.fileread1.read()\n with open(self.wordfile1[0], 'r') as fileread13:\n self.counter51 = fileread13.readlines()\n self.filestring1 = self.fileread12.replace('\\r', ' ').replace('\\n', ' ').replace('\\t', ' ').replace('\\v', ' ').replace('\\f', ' ').replace('\\a', ' ').replace('\\b', ' ') \n\n \"\"\" START PLAY \"\"\"\n def word_btn2(self):\n self.wmatch = 0\n self.wgame += 1\n self.wordte.clear()\n self.wordte.setStyleSheet(\"background-color: #777777; color: #141414;\")\n self.wordte.setFont(QtGui.QFont(\"Tahoma\", 12, 95)) \n self.word21 = self.wordle3.text()\n self.word22 = self.word21.replace('\\r', ' ').replace('\\n', ' ').replace('\\t', ' ').replace('\\v', ' ').replace('\\f', ' ').replace('\\a', ' ').replace('\\b', ' ')\n self.word23 = re.findall(r\"%s\" % (self.word22), self.filestring1, re.S)\n self.word24 = re.findall(self.wordfind, self.filestring1, re.S)\n for w21 in self.word24[0:]:\n if w21 == self.word22:\n self.wmatch += 1 \n if len(self.word23) > 0:\n self.wordle2.setStyleSheet(\"padding: 14px; background-color: #627419; color: #141414;\") \n self.wordle2.setEchoMode(2)\n self.wordle2.setText(self.word22)\n self.wbeep = 0\n if self.word22 in self.word24:\n self.wordle2.setEchoMode(0)\n self.wordle2.setText(self.word22)\n self.wordle2.setStyleSheet(\"padding: 14px; background-color: #627419; color: #01FFD9;\")\n self.wordte.setText(\"YOU\")\n self.wordte.setAlignment(QtCore.Qt.AlignCenter)\n self.wordte.append(\"WINNER !!!\")\n self.wordte.setAlignment(QtCore.Qt.AlignCenter)\n self.wordte.setStyleSheet(\"background-color: #627419; color: #01FFD9;\")\n self.wordte.setFont(QtGui.QFont(\"Tahoma\", 34, 95))\n self.wbeep = 1\n self.wscore += 1\n if len(self.word22) == 2:\n self.wscore += 100\n if len(self.word22) == 3:\n self.wscore += 1000\n if len(self.word22) == 4:\n self.wscore += 10000\n if len(self.word22) == 5:\n self.wscore += 100000\n if len(self.word22) == 6:\n self.wscore += 1000000\n if len(self.word22) == 7:\n self.wscore += 10000000\n \"\"\" SCORES \"\"\"\n self.wordte.moveCursor(1)\n if self.wscore > 1000:\n if self.wscore < 10000:\n self.wordte.insertPlainText(\"PRIVATE\\n\")\n self.wordte.setAlignment(QtCore.Qt.AlignCenter)\n if self.wscore > 10000:\n if self.wscore < 100000:\n self.wordte.insertPlainText(\"CORPORAL\\n\")\n self.wordte.setAlignment(QtCore.Qt.AlignCenter)\n if self.wscore > 100000:\n if self.wscore < 1000000:\n self.wordte.insertPlainText(\"SERGEANT\\n\")\n self.wordte.setAlignment(QtCore.Qt.AlignCenter)\n if self.wscore > 1000000:\n if self.wscore < 10000000:\n self.wordte.insertPlainText(\"LEUTENANT\\n\")\n self.wordte.setAlignment(QtCore.Qt.AlignCenter)\n if self.wscore > 10000000:\n if self.wscore < 100000000:\n self.wordte.insertPlainText(\"CAPTAIN\\n\")\n self.wordte.setAlignment(QtCore.Qt.AlignCenter)\n if self.wscore > 100000000:\n if self.wscore < 1000000000:\n self.wordte.insertPlainText(\"MAJOR\\n\")\n self.wordte.setAlignment(QtCore.Qt.AlignCenter)\n if self.wscore > 1000000000:\n if self.wscore < 10000000000:\n self.wordte.insertPlainText(\"COLONEL\\n\")\n self.wordte.setAlignment(QtCore.Qt.AlignCenter)\n if self.wscore > 10000000000:\n self.wordte.insertPlainText(\"GENERAL\\n\")\n self.wordte.setAlignment(QtCore.Qt.AlignCenter)\n if len(self.word23) == 0:\n self.wordle2.setEchoMode(0)\n fault1 = \"x\" * len(self.word22)\n self.wordle2.setText(fault1)\n self.wbeep = 0\n self.wordle2.setStyleSheet(\"padding: 14px; background-color: #627419; color: #672419;\") \n if self.word22 not in self.word24:\n self.wlost -= 10\n self.wordte.setText(\"YOU\")\n self.wordte.setAlignment(QtCore.Qt.AlignCenter)\n self.wordte.append(\"LOST !!!\")\n self.wordte.setAlignment(QtCore.Qt.AlignCenter)\n self.wordte.setStyleSheet(\"background-color: #672419; color: #141414;\")\n self.wordte.setFont(QtGui.QFont(\"Tahoma\", 34, 95))\n\n \"\"\" NEW GAME \"\"\"\n def word_btn3(self):\n self.wgame = 0\n self.wmatch = 0\n self.wscore = 0\n self.wbeep = 0\n self.wlost = 0\n self.wordle2.clear()\n self.wordle2.setStyleSheet(\"padding: 14px; background-color: #777777; color: #141414;\")\n self.wordle3.clear()\n self.wordte.clear()\n self.wordte.setStyleSheet(\"background-color: #777777; color: #141414;\")\n self.wordte.setFont(QtGui.QFont(\"Tahoma\", 12, 95))\n\n \"\"\" STATISTICS \"\"\"\n def word_btn4(self):\n self.wbeep = 0\n self.wordte.setStyleSheet(\"background-color: #777777; color: #141414;\")\n self.wordte.setFont(QtGui.QFont(\"Tahoma\", 12, 95)) \n try :\n if self.wscore < 1000:\n f40 = \"Rank : Pink Girl\" + '\\n' \n if self.wscore > 1000:\n f40 = \"Rank : Private\" + '\\n'\n if self.wscore > 10000:\n f40 = \"Rank : Corporal\" + '\\n'\n if self.wscore > 100000:\n f40 = \"Rank : Sergeant\" + '\\n'\n if self.wscore > 1000000:\n f40 = \"Rank : Leutenant\" + '\\n'\n if self.wscore > 10000000:\n f40 = \"Rank : Captain\" + '\\n'\n if self.wscore > 100000000:\n f40 = \"Rank : Major\" + '\\n'\n if self.wscore > 1000000000:\n f40 = \"Rank : Colonel\" + '\\n'\n if self.wscore > 10000000000:\n f40 = \"Rank : General\" + '\\n'\n f41 = \"Games : \" + str(self.wgame) + \"\\n\"\n f42 = \"Matches : \" + str(self.wmatch) + \"\\n\"\n f43 = \"Success score : \" + str(self.wscore) + \"\\n\"\n f44 = \"Lost score : \" + str(abs(self.wlost)) + \"\\n\"\n f45 = \"Total Score : \" + str(self.wscore + self.wlost) + \"\\n\"\n f46 = f40 + f41 + f42 + f43 + f44 + f45\n self.wordte.setText(str(f46))\n except:\n self.wordte.setText(\"Choose File !\")\n self.wordte.setStyleSheet(\"background-color: #777777; color: #672419;\")\n self.wordte.setFont(QtGui.QFont(\"Tahoma\", 19, 95))\n self.wordte.setAlignment(QtCore.Qt.AlignCenter)\n\n \"\"\" READ FILES \"\"\" \n def word_btn5(self):\n self.wbeep = 0\n self.wordte.setStyleSheet(\"background-color: #777777; color: #141414;\")\n self.wordte.setFont(QtGui.QFont(\"Tahoma\", 12, 95)) \n try :\n word51 = re.findall(self.wordfind, self.filestring1, re.S)\n f51 = os.path.basename(self.wordfile1[0])\n f52 = \"File name : \" + str(f51) + \"\\n\"\n f53 = \"File size : \" + str(os.path.getsize(self.wordfile1[0])) + \" bytes\" + \"\\n\"\n f54 = \"Characters in file : \" + str(len(self.fileread12)) + \"\\n\"\n f55 = \"Lines in file : \" + str(len(self.counter51)) + \"\\n\"\n f56 = \"Words in file : \" + str(len(word51)) + \"\\n\"\n f57 = f52 + f53 + f54 + f55 + f56\n self.wordte.setText(str(f57))\n except:\n self.wordte.setText(\"Choose File !\")\n self.wordte.setStyleSheet(\"background-color: #777777; color: #672419;\")\n self.wordte.setFont(QtGui.QFont(\"Tahoma\", 19, 95))\n self.wordte.setAlignment(QtCore.Qt.AlignCenter)\n\n def word_btn6(self):\n self.wbeep = 0\n self.close()\n\n def on_wgtime1(self):\n if self.wbeep == 1:\n self.wordte.setStyleSheet(\"background-color: #627419; color: #01FFD9;\")\n\n def on_wgtime2(self):\n if self.wbeep == 1:\n self.wordte.setStyleSheet(\"color: #FFFFFF;\")\n\n def center(self):\n resolution = QtWidgets.QDesktopWidget().screenGeometry()\n self.move((resolution.width() / 2) - (self.frameSize().width() / 2), (resolution.height() / 2) - (self.frameSize().height() / 2))\n\n \nif __name__ == \"__main__\":\n import sys\n app = QtWidgets.QApplication(sys.argv)\n window = WordGame()\n window.show()\n sys.exit(app.exec_())\n","sub_path":"wordgame.py","file_name":"wordgame.py","file_ext":"py","file_size_in_byte":13694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"413098617","text":"\"\"\"Understand recursion\"\"\"\nfrom typing import List, Any\n\n\ndef flatten(arr: List[Any]) -> List[int]:\n \"\"\"I love flat() in JS))\"\"\"\n result = []\n\n def flat(given_arr):\n for i in given_arr:\n if isinstance(i, int):\n result.append(i)\n else:\n flat(i)\n flat(arr)\n\n return result\n","sub_path":"flatten.py","file_name":"flatten.py","file_ext":"py","file_size_in_byte":345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"629758072","text":"# this script will use rsync to sync files and folders\n\nimport os\nimport sys\nimport subprocess\nimport time\n\nfrom watchdog.observers import Observer\nfrom watchdog.events import FileSystemEventHandler\nfrom config import src, dest\n\n\nall_files = []\n\n# Updating files in destination initially\ncmd = \"rsync -a --update \"+src+\" \"+dest\np = subprocess.Popen(cmd, shell=True)\nprint(\"Destination synced with source\")\n\nclass MyHandler(FileSystemEventHandler):\n\n\tdef on_modified(self,event):\n\t\tflag = True\n\t\tglobal all_files\n\t\tcurrent_files = []\n\n\t\tfor root, dirs, files in os.walk(src):\n\n\t\t\tfor filename in files:\n\t\t\t\tif \"Untitled Document\" in filename or filename.startswith(\".\"):\n\t\t\t\t\tflag = False\n\t\t\t\t\tcontinue\n\n\t\t\t\tlocal_path = os.path.join(root, filename)\n\t\t\t\tcurrent_files.append(local_path)\n\n\t\t\t\tif local_path not in all_files:\n\t\t\t\t\tall_files.append(local_path)\n\n\n\t\t# Assuming the process always runs on BOTH the machines,\n\t\t# this will work as expected\n\t\tif flag:\n\t\t\t# updates files in destination only if source has recent modified timestamp\n\t\t\tcmd = \"rsync -a --update \"+src+\" \"+dest\n\t\t\tprocess = subprocess.Popen(cmd, shell=True)\n\t\t\t# out, err = process.communicate()\n\t\t\t# print(out)\n\n\t\t\t# deletes files which are not in source\n\t\t\tcmd = \"rsync -a --delete \"+src+\" \"+dest\n\t\t\tprocess2 = subprocess.Popen(cmd, shell=True)\n\n\t\t\tprint(\"Synchronized\")\n\n\n\nif __name__ == \"__main__\": \n event_handler = MyHandler()\n observer = Observer()\n observer.schedule(event_handler, path=src, recursive=True)\n observer.start()\n print('Watchdog is now watching \"'+format(src)+'\" for changes')\n try:\n while True:\n time.sleep(1)\n except KeyboardInterrupt:\n observer.stop()\n observer.join()","sub_path":"sync.py","file_name":"sync.py","file_ext":"py","file_size_in_byte":1716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"38538263","text":"from scipy.spatial import distance\n\nimport Parameter as para\nfrom MobileCharger_Method import get_location, charging\nimport csv\nimport numpy as np\n\nclass MobileCharger:\n def __init__(self, index, writer_t=None, writer_d=None, information_log_t = None, information_log_d=None, energy=None, e_move=None, start=para.depot, end=para.depot, velocity=None,\n e_self_charge=None, capacity=None):\n self.is_stand = False # is true if mc stand and charge\n self.is_self_charge = False # is true if mc is charged\n self.is_active = False # is false if none of node request and mc is standing at depot\n\n self.start = start # from location\n self.end = end # to location\n self.current = start # location now\n self.end_time = -1 # the time when mc finish charging\n\n self.energy = energy # energy now\n self.capacity = capacity # capacity of mc\n self.e_move = e_move # energy for moving\n self.e_self_charge = e_self_charge # energy receive per second\n self.velocity = velocity # velocity of mc\n\n self.list_request = [] # the list of request node\n self.index = index\n self.writer_t = writer_t\n self.writer_d = writer_d\n self.temp1 = 0\n self.energy1 = 0\n self.dead1 = 0\n self.avg_en1 = 0\n self.temp2 = 0\n\n self.avg_en2 = 0\n self.first = 0\n self.second = 0\n self.information_log_t = information_log_t\n self.information_log_d = information_log_d\n print(self.writer_t)\n print(self.writer_d)\n def update_location(self, func=get_location):\n self.current = func(self)\n self.energy -= self.e_move\n\n def charge(self, network=None, node=None, charging_func=charging):\n charging_func(self, network, node)\n\n def self_charge(self):\n self.energy = min(self.energy + self.e_self_charge, self.capacity)\n\n def check_state(self):\n if distance.euclidean(self.current, self.end) < 1:\n self.is_stand = True\n self.current = self.end\n else:\n self.is_stand = False\n if distance.euclidean(para.depot, self.end) < 10 ** -3:\n self.is_self_charge = True\n else:\n self.is_self_charge = False\n\n def get_next_location(self, network, time_stem, optimizer=None):\n next_location, charging_time, first, second = optimizer.update(network, mc_current_location=self.current)\n self.start = self.current\n self.end = next_location\n moving_time = distance.euclidean(self.start, self.end) / self.velocity\n self.end_time = time_stem + moving_time + charging_time\n self.end_time = int(self.end_time) + 1\n return first, second\n\n def run(self, network, time_stem, optimizer=None):\n # print(self.energy, self.start, self.end, self.current)\n\n\n if (not self.is_active and self.list_request) or abs(\n time_stem - self.end_time) < 1:\n self.is_active = True\n self.list_request = [request for request in self.list_request if\n network.node[request[\"id\"]].energy < network.node[request[\"id\"]].energy_thresh]\n if not self.list_request:\n self.is_active = False\n\n self.first, self.second = self.get_next_location(network=network, time_stem=time_stem, optimizer=optimizer)\n self.energy1 = [network.node[i].energy for i in range(len(network.node))]\n self.dead1 = [i for i in range(len(network.node)) if network.node[i].is_active is False]\n self.temp1 = time_stem\n self.avg_en1 = [network.node[i].avg_energy for i in range(len(network.node))]\n min_index = np.argmin([network.node[i].energy / (network.node[i].avg_energy+1e-8) for i in range(len(network.node)) if network.node[i].is_active is True])\n #print(\"[INFO] avg_en1: {}, temp1: {}, min_energy: {}, min_avg_energy: {}\".format( self.avg_en1, self.temp1, network.node[min_index].energy,\n #network.node[min_index].avg_energy))\n check = self.end_time\n\n else:\n if self.is_active:\n\n if not self.is_stand:\n #print(\"moving\")\n self.update_location()\n elif not self.is_self_charge:\n #print(\"charging\")\n\n\n self.charge(network)\n #print(\"[INFO] Printing charging end time\", self.end_time)\n #print(\"[INFO] Printing current time\", time_stem)\n if (time_stem == (self.end_time - 2)) :\n self.temp2 = self.end_time\n self.avg_en2 = [network.node[i].avg_energy for i in range(len(network.node))]\n min_index = np.argmin([network.node[i].energy for i in range(len(network.node)) if\n network.node[i].is_active is True])\n print(\"[INFO] avg_en2: {}, temp2: {}, min_energy: {}, min_avg_energy: {}\".format(self.avg_en2, self.temp2, network.node[min_index].energy, network.node[min_index].avg_energy))\n\n avg = [(self.avg_en2[i] + self.avg_en1[i])/2 for i in range(len(self.avg_en1))]\n self.temp1 += min([(self.energy1[i] / (avg[i]+1e-8)) for i in range(len(network.node)) if i not in self.dead1])\n self.temp2 += + min([(network.node[i].energy / (avg[i]+1e-8)) for i in range(len(network.node)) if network.node[i].is_active is True])\n delta = self.temp2 - self.temp1\n print(\"[INFO] Print time log: {}, {}\".format(self.temp2, self.temp1))\n\n self.writer_t.writerow({\"delta\": delta})\n self.information_log_t.flush()\n print(\"[INFO] Print log Elements: {}, {}\".format(self.first, self.second))\n self.writer_d.writerow(({\"E_ele\": self.first, \"M_ele\": self.second}))\n self.information_log_d.flush()\n else:\n #print(\"self charging\")\n self.self_charge()\n if self.energy < para.E_mc_thresh and not self.is_self_charge and self.end != para.depot:\n self.start = self.current\n self.end = para.depot\n self.is_stand = False\n charging_time = self.capacity / self.e_self_charge\n moving_time = distance.euclidean(self.start, self.end) / self.velocity\n self.end_time = time_stem + moving_time + charging_time\n self.check_state()\n","sub_path":"MobileCharger.py","file_name":"MobileCharger.py","file_ext":"py","file_size_in_byte":6715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"134440815","text":"from scr.Ploting.PlotingRayTracing import PlotingRayTracing\nfrom scr.Ploting.PlotPoarization import Plotpolarization\nimport scr.mainParamPakage as mp\nimport scr.RayTracing.Rays as rmain\n\n# import numpy as np\n# I n i t\n\ntLine = mp.Parametrs(mp.mainPath + mp.xlsDir + mp.systemSettingsDir + mp.sysParamFilename + mp.fExtend, \"LineParam\")\nsysParam = mp.Parametrs(mp.mainPath + mp.xlsDir + mp.systemSettingsDir + mp.sysParamFilename + mp.fExtend, \"SysParam\")\nRin = mp.Parametrs(mp.mainPath + mp.xlsDir + mp.rInDir + mp.raysInFname + mp.fExtend, 'circul20')\n\nmirrorSheetName = 'Mirror' + str(int(sysParam.DataSheet.Rin[0]))\nraysSheetName = 'Ray_' + str(int(sysParam.DataSheet.Rin[0] - 1)) + '_' + str(int(sysParam.DataSheet.Rin[0]))\n# print('Rin.DataSheet = IN mainRun')\n# print(Rin.DataSheet)\n\nmirrorObj = mp.Parametrs(mp.mainPath + mp.xlsDir + mp.systemSettingsDir + mp.sysParamFilename + mp.fExtend, 'Mirror1')\nrInObj = rmain.Rays(mirrorObj.DataSheet, Rin.DataSheet, getRefRay=0) # Create object of Rays\n\nraysInDFn = rInObj.RaysDFnormal\n# save to Excel\nrOutFname = 'Ray'+'_' + \\\n str(int(sysParam.DataSheet.Rin[0]-1)) + '_' + \\\n str(int(sysParam.DataSheet.Rin[0]))\n\nmirrorList = sysParam.getMirrorList(sysParam.DataSheet)\nraysInDFn.to_excel(mp.mainPath + mp.xlsDir + mp.rOutDir + rOutFname + mp.fExtend)\n\n# ============== Get List of Section for calculation ========================#\n\ndef mirrorLoop(mirrorList):\n countMirror = int(sysParam.DataSheet.Rin[0])\n for mirrorIndex in mirrorList:\n print('====================================================== ++++++++++++++++++++++++++++++++++++++++++++++++++++++ Mirror Loop ', mirrorIndex)\n Mirror = mp.Parametrs(mp.mainPath + mp.xlsDir + mp.systemSettingsDir + mp.sysParamFilename + mp.fExtend, mirrorIndex) ## mirror List - The name of Sheets in Exel file\n raysFName = ['Ray_' + (str(countMirror - 1)) + '_' + str(countMirror),\n 'Ray_' + str(countMirror) + '_' + str(countMirror + 1),\n 'normalRay_' + str(countMirror) + '_' + str(countMirror)]\n RaysObj = mp.Parametrs(mp.mainPath + mp.xlsDir + mp.rOutDir + raysFName[0] + mp.fExtend, 'Sheet1' )\n # print(RaysObj.DataSheet)\n pathList = [mp.mainPath + mp.xlsDir + mp.rOutDir , raysFName, mp.fExtend]\n refRayObj = rmain.Rays(Mirror.DataSheet, RaysObj.DataSheet, getRefRay=1)\n refRayObj.NormalRayDF.to_excel(mp.mainPath + mp.xlsDir + mp.rOutDir + raysFName[2] + mp.fExtend, 'Sheet1')\n refRayObj.ReflectedRayDF.to_excel(mp.mainPath + mp.xlsDir + mp.rOutDir + raysFName[1] + mp.fExtend, 'Sheet1')\n countMirror += 1\n print('============== ++++++++++++++++++++++++++++++++++++++++++++++++++++++ END Mirror Loop', mirrorIndex)\n\ndef plotLoop(mirrorList):\n\n countMirror = int(sysParam.DataSheet.Rin[0])\n\n print('****************************************************************** PlotLoop',countMirror)\n dataRays = []\n data2D= []\n for mirrorIndex in mirrorList:\n print('mirrorIndex = ', mirrorIndex)\n Mirror = mp.Parametrs(mp.mainPath + mp.xlsDir + mp.systemSettingsDir + mp.sysParamFilename + mp.fExtend, mirrorIndex) ## mirror List - The name of Sheets in Exel file\n raysFName = ['Ray_' + (str(countMirror - 1)) + '_' + str(countMirror),\n 'Ray_' + str(countMirror) + '_' + str(countMirror + 1),\n 'normalRay_' + str(countMirror) + '_' + str(countMirror)]\n\n pathInRay = mp.mainPath + mp.xlsDir + mp.rOutDir + raysFName[0] + mp.fExtend\n pathReflctedRay = mp.mainPath + mp.xlsDir + mp.rOutDir + raysFName[1] + mp.fExtend\n pathNormalRay = mp.mainPath + mp.xlsDir + mp.rOutDir + raysFName[2] + mp.fExtend\n\n # print('pathInRay = ', pathInRay)\n # print('pathReflctedRay = ', pathReflctedRay)\n # print('pathNormalRay = ', pathNormalRay)\n\n RaysInObject = mp.Parametrs(pathInRay, 'Sheet1')\n RayReflectedObject = mp.Parametrs(pathReflctedRay, 'Sheet1')\n RaysNormalObject = mp.Parametrs(pathNormalRay, 'Sheet1')\n plotFileName = mp.mainPath + 'result/htmlFiles/test.html'\n plotFileName2D = mp.mainPath + 'result/htmlFiles/test2D' + '_' + mirrorIndex + '.html'\n\n plotObject = PlotingRayTracing(Mirror.DataSheet, RaysInObject.DataSheet, RayReflectedObject.DataSheet, RaysNormalObject.DataSheet, mirrorIndex, plotFileName)\n plotObject2D = Plotpolarization(Mirror.DataSheet, RaysInObject.DataSheet, RayReflectedObject.DataSheet,\n RaysNormalObject.DataSheet, mirrorIndex, plotFileName2D)\n\n surfR = plotObject.setMirrorSurf()\n dataRays.append(plotObject.rayInDict)\n dataRays.append(plotObject.rayReflectedDict)\n dataRays.append(plotObject.rayReflectedDictMarkers)\n dataRays.append(plotObject.rayInDictMarkers)\n dataRays.append(plotObject.pInData)\n # dataRays.append(surfR)\n\n data2D.append(plotObject.rayInDict)\n data2D.append(plotObject.pInData)\n if mirrorIndex == 'Mirror4':\n data2D.append(plotObject.rayReflectedDict)\n plotObject2D.plotIs(data2D, plotObject.layout, plotObject2D.plotFileName)\n\n data2D = []\n\n countMirror += 1\n print('=========================================================================== End Plot Loop')\n dataRays.append(plotObject.Tline1)\n dataRays.append(plotObject.Tline2)\n layout = plotObject.layout\n plotObject.plotIs(dataRays, layout)\n\ndef plotLoopPolar(mirrorList):\n countMirror = int(sysParam.DataSheet.Rin[0])\n # print('****************************************************************** Mirror Loop',countMirror)\n dataRays = []\n data1 = []\n dataInOut = []\n for mirrorIndex in mirrorList:\n Mirror = mp.Parametrs(mp.mainPath + mp.xlsDir + mp.systemSettingsDir + mp.sysParamFilename + mp.fExtend,\n mirrorIndex) ## mirror List - The name of Sheets in Exel file\n MdfSx = Mirror.DataSheet.Source[0]\n MdfSy = Mirror.DataSheet.Source[1]\n MdfSz = Mirror.DataSheet.Source[2]\n\n MdfDx = Mirror.DataSheet.Detector[0]\n MdfDy = Mirror.DataSheet.Detector[1]\n MdfDz = Mirror.DataSheet.Detector[2]\n\n raysFName = ['Ray_' + (str(countMirror - 1)) + '_' + str(countMirror),\n 'Ray_' + str(countMirror) + '_' + str(countMirror + 1),\n 'normalRay_' + str(countMirror) + '_' + str(countMirror)]\n\n pathInRay = mp.mainPath + mp.xlsDir + mp.rOutDir + raysFName[0] + mp.fExtend\n pathReflctedRay = mp.mainPath + mp.xlsDir + mp.rOutDir + raysFName[1] + mp.fExtend\n pathNormalRay = mp.mainPath + mp.xlsDir + mp.rOutDir + raysFName[2] + mp.fExtend\n\n RaysInObject = mp.Parametrs(pathInRay, 'Sheet1')\n RayReflectedObject = mp.Parametrs(pathReflctedRay, 'Sheet1')\n RaysNormalObject = mp.Parametrs(pathNormalRay, 'Sheet1')\n\n plotFileName = mp.mainPath +'result/htmlFiles/Rin_vs_Rout' + str(mirrorIndex) + '.html'\n plotFileName1 = mp.mainPath +'result/htmlFiles/DataIN_' + str( mirrorIndex) + '.html'\n plotFileName2 = mp.mainPath + 'result/htmlFiles/DataInOut_' + str( mirrorIndex) + '.html'\n\n plotObject = Plotpolarization(Mirror.DataSheet, RaysInObject.DataSheet, RayReflectedObject.DataSheet,\n RaysNormalObject.DataSheet, mirrorIndex, plotFileName)\n dataRays.append(plotObject.setRays4Plot_All)\n\n DataIn1, DataOut1, DataInOut1, PinData1, POutData1, rayMInDict = plotObject.setRays4plotSection(0,20, Mirror.DataSheet, 'blue') #from 0 t0 19\n\n data1.append(DataIn1)\n data1.append(DataOut1)\n data1.append(PinData1)\n data1.append(POutData1)\n data1.append(rayMInDict)\n\n dataInOut.append(DataInOut1)\n dataInOut.append(PinData1)\n dataInOut.append(POutData1)\n\n # DataIn2, DataOut2, DataInOut2, PinData2, POutData2 = plotObject.setRays4plotSection(20, 40, 'green' )\n #\n # data1.append(DataIn2)\n # data1.append(DataOut2)\n # data1.append(PinData2)\n # data1.append(POutData2)\n #\n # dataInOut.append(DataInOut2)\n # dataInOut.append(PinData2)\n # dataInOut.append(POutData2)\n #\n # DataIn3, DataOut3, DataInOut3, PinData3, POutData3 = plotObject.setRays4plotSection(40, 60,'red')\n #\n # data1.append(DataIn3)\n # data1.append(DataOut3)\n # data1.append(PinData3)\n # data1.append(POutData3)\n #\n # dataInOut.append(DataInOut3)\n # dataInOut.append(PinData3)\n # dataInOut.append(POutData3)\n\n # print('DataIn1 = ')\n # print(DataIn1)\n # print('DataIn2 = ')\n # print(DataIn2)\n # print('DataIn3 = ')\n # print(DataIn3)\n\n countMirror += 1\n #dataRays.append(plotObject.rayReflectedDict)\n\n layout = plotObject.layout\n # plotObject.plotIs(dataRays, layout, plotFileName)\n plotObject.plotIs(data1, layout, plotFileName1)\n plotObject.plotIs(dataInOut, layout, plotFileName2)\n dataRays = []\n print('=========================================================================== End Plot Loop')\n\nmirrorLoop(mirrorList)\n\n# mainDir = '/home/konstantin/rt/RayTracer/'\n# RinDirName = '/home/konstantin/rt/RayTracer/files/XLS/Rout/'\n# R1 = mp.Parametrs(RinDirName + 'Ray_0_1.xls', 'Sheet1')\n# R2 = mp.Parametrs(RinDirName + 'Ray_1_2.xls', 'Sheet1')\n# R3 = mp.Parametrs(RinDirName + 'Ray_2_3.xls', 'Sheet1')\n# R4 = mp.Parametrs(RinDirName + 'Ray_3_4.xls', 'Sheet1')\n# R5 = mp.Parametrs(RinDirName + 'Ray_4_5.xls', 'Sheet1')\n#-\n# mirrorIndex = 'Aperture-morror2'\n# plotFileName2 = mainDir + 'result/htmlFiles/Rin_vs_Rout_Section_In_Out_0_1' + '.html'\n# plotFileName3 = mainDir + 'result/htmlFiles/Rin_vs_Rout_Section_In_Out_0_2' + '.html'\n# plotFileName4 = mainDir + 'result/htmlFiles/Rin_vs_Rout_Section_In_Out_AA' + '.html'\n#\n# Mirror = mp.Parametrs(mp.mainPath + mp.xlsDir + mp.systemSettingsDir + mp.sysParamFilename + mp.fExtend, 'Mirror1') ## mirror List - The name of Sheets in Exel file\n# plotObject = Plotpolarization(Mirror.DataSheet, R1.DataSheet, R2.DataSheet, R3.DataSheet, mirrorIndex , plotFileName2)\n#\n# # rayInDict_markers1, rayOutDict_markers1 = plotObject.setRays4plotR1R2R3Section_markers(R1.DataSheet, R3.DataSheet, 0, 20, 'blue')\n# # rayInDict_markers2, rayOutDict_markers2 = plotObject.setRays4plotR1R2R3Section_markers(R1.DataSheet, R3.DataSheet, 21, 41, 'red')\n# # rayInDict_markers3, rayOutDict_markers3 = plotObject.setRays4plotR1R2R3Section_markers(R1.DataSheet, R3.DataSheet, 42, 62, 'green')\n#\n# # rayInDict_markers3, rayOutDict_markers3 = plotObject.setRays4plot_R1_R2_Section_markers(R1.DataSheet, R2.DataSheet, 0, 20, 'green')\n# # rayInDict_line3 = plotObject.setRays4plot_R1_R2_Section_Lines(R1.DataSheet, R2.DataSheet, 0, 20, 'blue')\n# # PrayInDict3, PrayOutDict3 = plotObject.setPolRays4Plot_R1_R2_Section_0_1(R1.DataSheet, R2.DataSheet, 0, 20,)\n# # PrayInOutDict3 = plotObject.setPolRays4Plot_R1_R2_Section_direction_0_1(R1.DataSheet, R2.DataSheet, 0, 20,)\n#\n# #rayInDict_line1 = plotObject.setRays4plotR1R2R3Section_Lines(R1.DataSheet, R2.DataSheet, 0, 20, 'blue')\n# #rayInDict_line2 = plotObject.setRays4plotR1R2R3Section_Lines(R1.DataSheet, R2.DataSheet, 21, 41, 'red')\n#\n# # rayInDict_line03 = plotObject.setRays4plot_R1_R3_Section_Lines(R1.DataSheet, R3.DataSheet, 0, 20, 'blue')\n# # rayInDict_markers03, rayOutDict_markers03 = plotObject.setRays4plot_R1_R3_Section_markers(R1.DataSheet, R3.DataSheet, 0, 20, 'green')\n# # PrayInDict03, PrayOutDict03 = plotObject.setPolRays4Plot_R1_R3_Section_0_2(R1.DataSheet, R3.DataSheet, 0, 20,)\n# # PrayInOutDict03 = plotObject.setPolRays4Plot_R1_R3_Section_direction_0_2(R1.DataSheet, R3.DataSheet, 0, 20,)\n#\n# #r1m1, r2m1, r3m1 = plotObject.setRays4plot_R1_R2_R3_Section_markers(R1.DataSheet, R2.DataSheet, R3.DataSheet, 0, 20, 'green')\n# r1m1, r2m1, r3m1, r4m1, r5m1 = plotObject.setRays4plot_R1_R2_R3_R4_R5_Section_markers(R1.DataSheet, R2.DataSheet, R3.DataSheet, R4.DataSheet,R5.DataSheet, 0, 20, 'green')\n# rl1 = plotObject.setRays4plot_R1_R2_R3_R4_R5_Section_Lines(R1.DataSheet, R2.DataSheet, R3.DataSheet, R4.DataSheet,R5.DataSheet, 0, 20, 'blue')\n#\n# # rl1 = plotObject.setRays4plot_R1_R2_Section_Lines(R1.DataSheet, R2.DataSheet, 0, 20, 0, 400,'blue')\n# # rl2 = plotObject.setRays4plot_R1_R2_Section_Lines(R2.DataSheet, R3.DataSheet, 0, 20, 400, 800,'blue')\n# # rl3 = plotObject.setRays4plot_R1_R2_Section_Lines(R3.DataSheet, R4.DataSheet, 0, 20, 800, 1250,'blue')\n# # rl4 = plotObject.setRays4plot_R1_R2_Section_Lines(R4.DataSheet, R5.DataSheet, 0, 20, L1, L2,'blue')\n# p01, p11, p21, pAA = plotObject.setPolRays4Plot_R1_R2_R3_Section_0_3(R1.DataSheet, R2.DataSheet, R3.DataSheet, 0, 20,)\n# pDirection1 = plotObject.setPolRays4Plot_R1_R2_R3_Section_direction_0_3(R1.DataSheet, R2.DataSheet, R3.DataSheet, 0, 20,)\n#\n# layout = plotObject.layout\n#\n# data4Plot=[]\n# data4Plot1=[]\n# data4Plot2=[]\n# data1 = []\n#\n# # data4Plot.append(rayInDict_markers1)\n# # data4Plot.append(rayOutDict_markers1)\n# # data4Plot.append(rayInDict_line1)\n# #\n# # data4Plot.append(rayInDict_markers2)\n# # data4Plot.append(rayOutDict_markers2)\n# # data4Plot.append(rayInDict_line2)\n# #\n# # data4Plot.append(rayInDict_markers3)\n# # data4Plot.append(rayOutDict_markers3)\n# # data4Plot.append(rayInDict_line3)\n# # data4Plot.append(PrayInDict3)\n# # data4Plot.append(PrayOutDict3)\n# # data4Plot.append(PrayInOutDict3)\n# #\n# # data4Plot1.append(rayInDict_markers03)\n# # data4Plot1.append(rayOutDict_markers03)\n# # data4Plot1.append(rayInDict_line03)\n# # data4Plot1.append(PrayInDict03)\n# # data4Plot1.append(PrayOutDict03)\n# # data4Plot1.append(PrayInOutDict03)\n#\n# data4Plot1.append(r1m1)\n# data4Plot1.append(r2m1)\n# data4Plot1.append(r3m1)\n# data4Plot1.append(r4m1)\n# data4Plot1.append(r5m1)\n# data4Plot2.append(rl1)\n# # data4Plot2.append(rl2)\n# # data4Plot2.append(rl3)\n# # data4Plot2.append(rl4)\n#\n# #data4Plot1.append(p01)\n# #data4Plot1.append(p11)\n# #data4Plot1.append(p21)\n# #data4Plot1.append(pDirection1)\n# data1.append(pAA)\n#\n# plotObject.plotIs(data4Plot, layout, plotFileName2)\n# plotObject.plotIs(data4Plot1, layout, plotFileName3)\n# plotObject.plotIs(data4Plot2, layout, plotFileName4)\n# #plotObject.plotIs(pAA, layout, plotFileName4)\nplotLoop(mirrorList)\n#plotLoopPolar(mirrorList)","sub_path":"scr/mainRun.py","file_name":"mainRun.py","file_ext":"py","file_size_in_byte":14543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"315122954","text":"import turtle\r\nimport random\r\n\r\nwindow = turtle.Screen();\r\n\r\nsquare = turtle.Turtle();\r\nsquare.speed(0);\r\nsquare.hideturtle();\r\n\r\nsquare.up();\r\nsquare.goto(-200, 200);\r\nsquare.down();\r\n\r\nfor i in range(4):\r\n square.forward(50);\r\n square.right(90);\r\n\r\nsquare.up();\r\nsquare.goto(-205, 205);\r\nsquare.write(\"Change Color\");\r\n\r\n##first square end\r\n\r\nsquare.up();\r\nsquare.goto(150, 200);\r\nsquare.down();\r\n\r\nfor i in range(4):\r\n square.forward(50);\r\n square.right(90);\r\n\r\nsquare.up();\r\nsquare.goto(145, 205);\r\nsquare.write(\"Move Mouse\");\r\n\r\n##second square end\r\n\r\npencil = turtle.Turtle();\r\npencil.shape(\"circle\");\r\npencil.speed(9);\r\n\r\n##print(\"x, y\");\r\n\r\ndef drawingControls(x, y):\r\n if (-200 <= x <= -150) and (150 <= y <= 200):\r\n red = random.random();\r\n green = random.random();\r\n blue = random.random();\r\n pencil.color(red, green, blue);\r\n #change color\r\n \r\n if (150 <= x <= 200) and (150 <= y <= 200):\r\n x = random.randrange(750);\r\n y = random.randrange(600);\r\n x = x - 375;\r\n y = y - 300;\r\n ##print(x, y)\r\n pencil.goto(x, y);\r\n #move turtle\r\n\r\nwindow.onclick(drawingControls);\r\n\r\npencil.onrelease(pencil.goto);\r\n\r\n\r\n\r\n\r\n","sub_path":"Labs/CSCI 127 Lab II.py","file_name":"CSCI 127 Lab II.py","file_ext":"py","file_size_in_byte":1229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"304802208","text":"#!/usr/bin/env python\r\nfrom flask import Flask, flash, redirect, render_template, request, url_for, Response\r\nfrom flask import jsonify\r\nimport pymysql\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib.figure import Figure\r\nfrom matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas\r\nimport random\r\nimport io\r\nimport base64\r\n\r\n\r\napp = Flask(__name__)\r\n\r\n### TO EDIT ###\r\nsql_host = '35.244.90.38' \r\nsql_connection_name='healthy-dolphin-316510:australia-southeast1:googlecloudsql'\r\nsql_port = 3306\r\nsql_database = 'emotions'\r\nsql_user = 'root'\r\nsql_password = 'griffith_cloud_learning'\r\n### END TO EDIT ###\r\n\r\n### SHARED SQL FUNCTIONS ###\r\ndef sqlConnect():\r\n global db\r\n global cursor\r\n ##local\r\n ##db = pymysql.connect(host=sql_host, port=sql_port, database=sql_database, user=sql_user, password=sql_password) \r\n ##production\r\n db = pymysql.connect(unix_socket='/cloudsql/' +sql_connection_name, database=sql_database, user=sql_user, password=sql_password) \r\n cursor = db.cursor()\r\n return db\r\ndef sqlClose():\r\n db.close()\r\n return\r\n### END SHARED SQL FUNCTIONS ###\r\n\r\n\r\ndef create_figure():\r\n sqlConnect()\r\n sql = \"SELECT sentiment , COUNT(*) as total_comment FROM emotions GROUP BY sentiment \"\r\n cursor.execute(sql)\r\n results = list(cursor.fetchall())\r\n sqlClose()\r\n results.sort(key=lambda x: x[1], reverse=True)\r\n\r\n fig = Figure()\r\n axis = fig.add_subplot(1, 1, 1)\r\n bar_width = 0.35\r\n opacity = 0.4\r\n values =[]\r\n sentiments = []\r\n for item in results[:5]:\r\n values.append(item[1])\r\n sentiments.append(item[0])\r\n axis.bar(sentiments, values, bar_width, alpha=opacity, color='b')\r\n return fig\r\n\r\n@app.route('/plot.png')\r\ndef plot_png():\r\n fig = create_figure()\r\n output = io.BytesIO()\r\n FigureCanvas(fig).print_png(output)\r\n return Response(output.getvalue(), mimetype='image/png')\r\n\r\n@app.route('/data.json')\r\ndef getData():\r\n sqlConnect()\r\n sql = \"SELECT * FROM emotions\"\r\n cursor.execute(sql)\r\n results = list(cursor.fetchall())\r\n sqlClose()\r\n return jsonify(results)\r\n\r\n@app.route('/')\r\ndef index():\r\n return render_template('index.html')\r\n \r\nif __name__=='__main__':\r\n app.run(debug=True)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"372803400","text":"# -*- coding: utf-8 -*-\nimport os, sys, re, json\nimport datetime\nfrom pymongo import MongoClient\nimport pymongo\n\nreload(sys)\nsys.setdefaultencoding(\"utf-8\")\nsys.path.append(os.path.join(os.path.split(os.path.realpath(__file__))[0], '../../../util'))\nsys.path.append(os.path.join(os.path.split(os.path.realpath(__file__))[0], '../../support'))\nimport loghelper, config, util\nimport db\nimport desc_helper\n\n#logger\nloghelper.init_logger(\"find_member\", stream=True)\nlogger = loghelper.get_logger(\"find_member\")\n\nscores = {\"description\":1, \"work\":1, \"education\":1, \"photo\":1, \"email\":0.5}\n\nDUPS = 0\ndef check_dup(rels, pattern):\n dups =[]\n for rel in rels:\n if rel[\"position\"] is None or rel[\"position\"].strip() == \"\":\n continue\n if re.search(pattern, rel[\"position\"], re.I):\n dups.append(rel)\n\n if len(dups) <= 1:\n return\n else:\n logger.info(\"Find dups\")\n for dup in dups:\n logger.info(json.dumps(dup, ensure_ascii=False, cls=util.CJsonEncoder))\n remove_dup(dups)\n\ndef remove_dup(rels):\n global DUPS\n id_remain = None\n max = 0\n companyId = None\n conn = db.connect_torndb()\n for rel in rels:\n if companyId is None:\n companyId = rel[\"companyId\"]\n if id_remain is None:\n id_remain = rel[\"id\"]\n member = conn.get(\"select * from member where id=%s\", rel[\"memberId\"])\n logger.info(\"Check id: %s, position: %s, name: %s\", rel[\"id\"], rel[\"position\"], member[\"name\"])\n logger.info(json.dumps(member, ensure_ascii=False, cls=util.CJsonEncoder))\n score = 0\n for column in scores:\n if member[column] is not None and member[column].strip() != \"\":\n score += scores[column]\n if score > max:\n max = score\n id_remain = rel[\"id\"]\n\n logger.info(\"Remain id : %s\", id_remain)\n conn.update(\"update company_member_rel set active='N' where companyId=%s and id!=%s\", companyId, id_remain)\n conn.close()\n DUPS += 1\n\ndef check_e(cid, rels):\n conn = db.connect_torndb()\n names = []\n newnames = []\n md = {}\n for rel in rels:\n member = conn.get(\"select * from member where id=%s\", rel[\"memberId\"])\n if (member[\"name\"] is None or member[\"name\"].strip() == \"\" or desc_helper.count_chinese(member[\"name\"]) ==0) \\\n and member[\"verify\"] is None:\n # logger.info(\"Check english name: %s, position: %s, name: %s, company: %s\",\n # member[\"id\"], rel[\"position\"], member[\"name\"], cid)\n names.append(member['name'])\n\n if md.has_key(rel[\"position\"]) is True:\n md[rel[\"position\"]].append(member[\"name\"])\n else:\n md[rel[\"position\"]] = [member[\"name\"]]\n\n for p in md:\n if len(md[p])>1:\n for name in md[p]:\n if name in names:\n newnames.append(name)\n\n\n conn.close()\n # return names\n return names, newnames\n\nif __name__ == \"__main__\":\n start = 0\n num = 0\n num1 = 0\n cid = 0\n fp2 = open(\"mm.txt\", \"w\")\n\n while True:\n conn = db.connect_torndb()\n companies = list(conn.query(\"select * from company where (active is null or active='Y') and id>%s \"\n \"order by id limit 10000\",cid))\n if len(companies) == 0:\n break\n\n for company in companies:\n cid = company[\"id\"]\n member_rels = conn.query(\"select * from company_member_rel where (active is null or active='Y') \"\n \"and companyId=%s and (type=5010 or type=5020)\", cid)\n if len(member_rels) > 1:\n noe, node = check_e(cid, member_rels)\n if len(noe) < len(member_rels) and len(noe)>0:\n num1 += 1\n priority = 1\n if len(node)>0:\n num += 1\n priority = 2\n # logger.info(ns)\n logger.info(\"Check english name %s|%s: names: %s, company: %s\",\n len(node), len(member_rels), \":\".join(node), cid)\n c = conn.get(\"select * from company where id=%s\", cid)\n link = 'http://www.xiniudata.com/validator/#/company/%s/overview' % c[\"code\"]\n line = \"%s+++%s+++%s+++%s\\n\" % (c[\"code\"], c[\"name\"], link, priority)\n fp2.write(line)\n\n conn.close()\n\n\n start += 1000\n fp2.close()\n logger.info(\"Total companies: %s|%s\", num,num1)","sub_path":"data/spider2/aggregator/member/find_e_member.py","file_name":"find_e_member.py","file_ext":"py","file_size_in_byte":4593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"6204915","text":"import psycopg2\nfrom psycopg2 import Error\n\ntry:\n # Hago la conexión a la base de datos:\n conexion = psycopg2.connect(user = 'postgres',\n password = 'Lana2409',\n host = 'localhost',\n port = '5432',\n database = 'db_ezagastizabal')\n\n cursor = conexion.cursor()\n query = \"UPDATE alumnos SET correo_alumno = 'edwin.zagastizabal@gmail.com' WHERE id_alumno = 3;\"\n cursor.execute(query)\n conexion.commit()\n \n query = \"SELECT * FROM alumnos;\"\n cursor.execute(query)\n record = cursor.fetchall()\n print(record)\n\nexcept Error as error:\n print(f\"Hubo un error: {str(error)}\")\nfinally:\n if (conexion):\n cursor.close()\n conexion.close()\n","sub_path":"Edwin/bddPostgres.py","file_name":"bddPostgres.py","file_ext":"py","file_size_in_byte":785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"56498734","text":"#!/usr/bin/python\n# -*- coding: UTF-8 -*-\nimport MySQLdb\nfrom warnings import filterwarnings\nfilterwarnings('ignore', category = MySQLdb.Warning)\n\nSVNAME = \"localhost\"\nSVUSER = \"root\"\nSVPAWD = \"1234321xy\"\nDBNAME = \"TESTDB\"\nclass XueQiuSql():\n '''专用于雪球的数据库方法类'''\n login = ()\n def __init__(self):\n '''检查,如果没有XUEQIU数据库,则建立一个'''\n try:\n db = MySQLdb.connect(SVNAME,SVUSER,SVPAWD,DBNAME,charset=\"utf8\")\n cursor = db.cursor()\n # 创建数据表SQL语句\n sql = \"\"\"CREATE TABLE IF NOT EXISTS TESTDB.XUEQIU (\n FIRST_NAME VARCHAR(40) NOT NULL,\n ADDR CHAR(20) PRIMARY KEY NOT NULL,\n GAIN INT\n )\"\"\"\n cursor.execute(sql)\n sql = \"\"\"CREATE TABLE IF NOT EXISTS TESTDB.READSP (\n SP INT NOT NULL,\n CHANGEDATE DATE NOT NULL\n )\"\"\"\n cursor.execute(sql)\n #text = cursor.fetchall()\n except MySQLdb.MySQLError as e:\n print(e);\n #print(text)\n db.close()\n\n def addPlayer(self,players):\n '''把收集到的用户名和网址存储'''\n db = MySQLdb.connect(SVNAME, SVUSER, SVPAWD, DBNAME, charset=\"utf8\")\n cursor = db.cursor()\n for each in players:\n try:\n sql = \"INSERT IGNORE INTO XUEQIU(FIRST_NAME,ADDR)\\\n VALUES (%s, %s)\"\n # 执行sql语句\n n = cursor.execute(sql,(each[0],each[1]))\n # 提交到数据库执行\n db.commit()\n except :\n # Rollback in case there is any error\n print(\"有错误,rollback\")\n db.rollback()\n # 关闭数据库连接\n db.close()\n\n def showTable(self):\n '''显示数据库中所有信息'''\n db = MySQLdb.connect(SVNAME, SVUSER, SVPAWD, DBNAME, charset=\"utf8\")\n cursor = db.cursor()\n # SQL 查询语句\n sql = \"SELECT * FROM XUEQIU \"\n try:\n # 执行SQL语句\n cursor.execute(sql)\n # 获取所有记录列表\n results = cursor.fetchall()\n for row in results:\n fname = row[0]\n addr = row[1]\n # 打印结果\n print(\"fname=%s,addr=%s\" % \\\n (fname, addr))\n except:\n print(\"Error: unable to fecth data\")\n db.close()\n\n def clearDB(self):\n '''清除雪球表的数据'''\n db = MySQLdb.connect(SVNAME, SVUSER, SVPAWD, DBNAME, charset=\"utf8\")\n cursor = db.cursor()\n sql =\"DELETE FROM XUEQIU \"\n n = cursor.execute(sql)\n print(n)\n db.commit()\n db.close()\n\n def initSP(self,):\n '''初始化READSP数据库,将SP设为1'''\n db = MySQLdb.connect(SVNAME, SVUSER, SVPAWD, DBNAME, charset=\"utf8\")\n cursor = db.cursor()\n sql = \"DELETE FROM READSP\"\n n = cursor.execute(sql)\n sql = \"INSERT INTO READSP(SP,CHANGEDATE) VALUES(0,CURRENT_DATE)\"\n n = cursor.execute(sql)\n db.commit()\n db.close()\n\n def getSP(self):\n '''得到sp的数值'''\n db = MySQLdb.connect(SVNAME, SVUSER, SVPAWD, DBNAME, charset=\"utf8\")\n cursor = db.cursor()\n sql = \"SELECT SP FROM READSP\"\n n = cursor.execute(sql)\n sp = cursor.fetchone()\n if sp!=None:\n sp = sp[0]\n else:\n n = cursor.execute(\"INSERT INTO XUEQIU(SP,CHANGEDATE) VALUES(0,CURRENT_DATE)\")\n sp = 0\n db.close()\n return sp\n\n def getTotalOfRoles(self):\n '''得到sp的数值'''\n db = MySQLdb.connect(SVNAME, SVUSER, SVPAWD, DBNAME, charset=\"utf8\")\n cursor = db.cursor()\n sql = \"SELECT COUNT(*) FROM XUEQIU\"\n try:\n n = cursor.execute(sql)\n tatol = cursor.fetchone()\n ta = tatol[0]\n db.close()\n return ta\n except:\n db.rollback()\n db.close()\n\n def gConnectDB(self):\n '''建立一个外部可以操作的数据连接'''\n self.db = MySQLdb.connect(SVNAME, SVUSER, SVPAWD, DBNAME, charset=\"utf8\")\n self.cursor = self.db.cursor()\n\n def gConnectDB2(self):\n '''建立一个外部可以操作的数据连接'''\n self.db2 = MySQLdb.connect(SVNAME, SVUSER, SVPAWD, DBNAME, charset=\"utf8\")\n self.cursor2 = self.db2.cursor()\n\n\n def gExcuteCmd(self, sql, repeatParam=None, commit = 0):\n '''执行命令'''\n try:\n if not repeatParam:\n n = self.cursor.execute(sql)\n else:\n n = self.cursor.executemany(sql, repeatParam)\n if commit:\n self.db.commit()\n except Exception as e:\n self.db.rollback()\n print(\"数据库执行有错误\")\n print(e)\n\n def gExcuteCmd2(self, sql, repeatParam=None, commit = 0):\n '''执行命令'''\n try:\n if not repeatParam:\n n = self.cursor2.execute(sql)\n else:\n n = self.cursor2.executemany(sql, repeatParam)\n if commit:\n self.db2.commit()\n except Exception as e:\n self.db2.rollback()\n print(\"数据库执行有错误\")\n print(e)\n\n\n def gScroll(self,num):\n '''移动指针'''\n self.cursor.scroll(num,mode='absolute')\n\n def gScroll2(self,num):\n '''移动指针'''\n self.cursor2.scroll(num,mode='absolute')\n\n def gFetch(self,num=0):\n if num==0:\n results = self.cursor.fetchall()\n elif num==1:\n results = self.cursor.fetchone()\n elif num>1:\n results = self.cursor.fetchmany(num)\n else :\n print(\"参数设置错误\")\n results = None\n return results\n\n def gFetch2(self,num=0):\n if num==0:\n results = self.cursor2.fetchall()\n elif num==1:\n results = self.cursor2.fetchone()\n elif num>1:\n results = self.cursor2.fetchmany(num)\n else :\n print(\"参数设置错误\")\n results = None\n return results\n\n def gCloseDB(self):\n self.db.close()\n\n def gCloseDB(self):\n self.db2.close()\n\n\n\nc = XueQiuSql()\n\n\n\n\n","sub_path":"MySql.py","file_name":"MySql.py","file_ext":"py","file_size_in_byte":6503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"318114265","text":"from kivy.lang import Builder\nfrom kivymd.card import MDCard, MDSeparator\nfrom kivymd.button import MDFlatButton\nfrom kivy.uix.behaviors import ButtonBehavior\nfrom kivy.app import App\nfrom server_api import get_product_info\n\nBuilder.load_file('custom_widgets.kv')\n\n\nclass ReviewView(ButtonBehavior, MDCard):\n def __init__(self, **kwargs):\n super().__init__()\n self._product_id = kwargs.get('id', None)\n self.size_hint_x = None\n self.width = 128\n self.size_hint_y = 1\n self.ids.picture.source = kwargs.get('source', None)\n # self.ids.picture.reload()\n self.ids.name.text = kwargs.get('name', None)\n self.reviews_count = kwargs.get('review_count', 0)\n self.rate = kwargs.get('rate', 0)\n self.ids.review_count.text = '{} reviews'.format(self.reviews_count) if self.reviews_count != 1 else '1 review'\n\n def on_release(self):\n app = App.get_running_app()\n app.selected_product_id = self._product_id\n app.selected_product_name = self.ids.name.text\n app.selected_product_source = self.ids.picture.source\n app.selected_product_revs = self.reviews_count\n app.selected_product_rate = self.rate\n app.prev_screen = 'Categories'\n app.screen_root_manager.current = 'Reviews of'\n\n\nclass ProductInfo(ButtonBehavior, MDCard):\n def __init__(self, **kwargs):\n super().__init__()\n self._product_id = kwargs.get('id', None)\n self.size_hint_y = None\n self.height = 128\n self.ids.picture.source = kwargs.get('source', None)\n self.ids.name.text = kwargs.get('name', None)\n self.reviews_count = kwargs.get('review_count', 0)\n self.ids.review_count.text = '{} reviews'.format(self.reviews_count) if self.reviews_count != 1 else '1 review'\n self.ids.rate.value = kwargs.get('rate', 0)\n\n def on_release(self):\n app = App.get_running_app()\n app.selected_product_id = self._product_id\n app.selected_product_name = self.ids.name.text\n app.selected_product_source = self.ids.picture.source\n app.selected_product_revs = self.reviews_count\n app.selected_product_rate = self.ids.rate.value\n app.prev_screen = 'Reviews'\n app.screen_root_manager.current = 'Reviews of'\n\n\nclass ProductReview(ButtonBehavior, MDCard):\n def __init__(self, **kwargs):\n super().__init__()\n\n self.spacing = 20\n self.padding = 12\n self.size_hint_y = None\n self.height = max(self.minimum_height, 64)\n self.orientation = 'vertical'\n self._review_id = kwargs.get('review_id', None)\n self.ids.rate_bar.value = kwargs.get('rate', 0)\n self.ids.timestamp.text = kwargs.get('timestamp', '')\n self.ids.review_title.text = kwargs.get('title', '')\n self.ids.review_content.text = kwargs.get('content', '')\n","sub_path":"custom_widgets.py","file_name":"custom_widgets.py","file_ext":"py","file_size_in_byte":2878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"406030008","text":"# encoding: utf-8\nimport pytest\nfrom rdflib import Graph, Namespace, logger\n\nfrom FuXi.DLP.DLNormalization import NormalFormReduction\nfrom FuXi.Rete.RuleStore import SetupRuleStore\nfrom FuXi.Rete.Util import generateTokenSet, renderNetwork\n\nEX = Namespace(\"http://example.org/\")\nEX_TERMS = Namespace(\"http://example.org/terms/\")\n\nexpected_triples = [\n (EX.john, EX_TERMS.has_sibling, EX.jack),\n (EX.john, EX_TERMS.brother, EX.jack),\n (EX.jack, EX_TERMS.has_brother, EX.john),\n]\n\nABOX = \"\"\"\\\n@prefix exterms: .\n@prefix : .\n\n:john exterms:has_brother :jack .\n:jack exterms:brother :john .\n\"\"\"\n\nTBOX = \"\"\"\\\n@prefix exterms: .\n@prefix rdf: .\n@prefix rdfs: .\n@prefix owl: .\n\nexterms:Agent\n a rdfs:Class .\n\nexterms:Person\n a rdfs:Class ;\n rdfs:subClassOf exterms:Agent .\n\nexterms:has_sibling\n a rdf:Property .\n\nexterms:has_brother\n a rdf:Property ;\n rdfs:subPropertyOf exterms:has_sibling ;\n rdfs:domain exterms:Person ;\n rdfs:range exterms:Person .\n\nexterms:brother\n a rdf:Property ;\n owl:equivalentProperty exterms:has_brother ;\n rdfs:domain exterms:Person ;\n rdfs:range exterms:Person .\n\n\"\"\"\n\n\n@pytest.mark.xfail(reason=\"Keyerror from FuXi.Util.generateBGLNode #327\")\ndef test_network_render():\n rule_store, rule_graph, network = SetupRuleStore(makeNetwork=True)\n tboxgraph = Graph().parse(data=TBOX, format=\"n3\")\n aboxgraph = Graph().parse(data=ABOX, format=\"n3\")\n NormalFormReduction(tboxgraph)\n network.setupDescriptionLogicProgramming(tboxgraph)\n network.feedFactsToAdd(generateTokenSet(tboxgraph))\n network.feedFactsToAdd(generateTokenSet(aboxgraph))\n network.inferredFacts.bind(\"ex\", EX)\n network.inferredFacts.bind(\"exterms\", EX_TERMS)\n\n nsmap = {\"ex\": EX, \"exterms\": EX_TERMS}\n\n renderNetwork(network, nsmap)\n","sub_path":"test/test_rete/test_network_render.py","file_name":"test_network_render.py","file_ext":"py","file_size_in_byte":1992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"645639313","text":"# Pytorch 0.4.0 VGG16实现cifar10分类.\n# @Time: 2018/6/23\n# @Author: wxq\n\nimport torch\nimport torch.nn as nn\nimport math\nimport torchvision.transforms as transforms\nimport torchvision as tv\nfrom torch.utils.data import DataLoader\nimport numpy as np\nimport adder\n#model_path = './model_pth/vgg16_bn-6c64b313.pth' # 预训练模型的数据储存文件\n# 当时LR=0.01遇到问题,loss逐渐下降,但是accuracy并没有提高,而是一直在10%左右,修改LR=0.00005后,该情况明显有所好转,准确率最终提高到了\n# 当LR=0.0005时,发现准确率会慢慢提高,但是提高的速度很慢,这时需要增加BATCH_SIZE,可以加快训练的速度,但是要注意,BATCH_SIZE增大会影响最终训练的准确率,太大了还可能也会出现不收敛的问题\n# 另外,注意每次进入下一个EPOCH都会让准确率有较大的提高,所以EPOCH数也非常重要,需要让网络对原有数据进行反复学习,强化记忆\n#\n# 目前,调试的最好的参数是BATCH_SIZE = 500 LR = 0.0005 EPOCH = 10 最终准确率为:69.8% 用时:\n# BATCH_SIZE = 500 # 将训练集划分为多个小批量训练,每个小批量的数据量为BATCH_SIZE\n# LR = 0.0005 # learning rate\n# EPOCH = 10 # 训练集反复训练的次数,每完整训练一次训练集,称为一个EPOCH\n# CLASSES = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')\n\ndef conv3x3(in_channels, out_channels, padding=1):\n \"\"\"3x3 convolution with padding\"\"\"\n return adder.adder2d(in_channels, out_channels, kernel_size=3, stride=1,\n padding=1, bias=False)\n\nclass VGG(nn.Module):\n def __init__(self, features, num_classes=10): # 构造函数 num_class根据最后分类的种类数量而定,cifar为10所以这里是10\n super(VGG, self).__init__() # pytorch继承nn.Module模块的标准格式,需要继承nn.Module的__init__初始化函数\n self.features = features # 图像特征提取网络结构(仅包含卷积层和池化层,不包含分类器)\n self.classifier = nn.Sequential( # 图像特征分类器网络结构\n # FC4096 全连接层\n nn.Linear(512, 4096),\n nn.ReLU(inplace=True),\n nn.Dropout(),\n\n # FC4096 全连接层\n nn.Linear(4096, 4096),\n nn.ReLU(inplace=True),\n nn.Dropout(),\n\n # FC1000 全连接层\n nn.Linear(4096, num_classes))\n # 初始化各层的权值参数\n self._initialize_weights()\n\n def forward(self, x):\n x = self.features(x)\n x = x.view(x.size(0), -1)\n x = self.classifier(x)\n return x\n\n def _initialize_weights(self):\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n m.weight.data.normal_(0, math.sqrt(2. / n))\n if m.bias is not None:\n m.bias.data.zero_()\n elif isinstance(m, nn.BatchNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n elif isinstance(m, nn.Linear):\n m.weight.data.normal_(0, 0.01)\n m.bias.data.zero_()\n\n\ncfg = [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512, 'M'] # vgg16的网络结构参数,数字代表该层的卷积核个数,'M'代表该层为最大池化层\n\n\ndef make_layers(cfg, batch_norm=False):\n \"\"\"利用cfg,生成vgg网络每层结构的函数\"\"\"\n layers = []\n in_channels = 3\n for v in cfg:\n if v == 'M': # 最大池化层\n layers += [nn.MaxPool2d(kernel_size=2, stride=2)]\n else:\n # 根据cfg设定卷积层的卷积核的数量v,根据论文,vgg网络中的卷积核尺寸均使用3x3xn,n是输入数据的通道数\n conv2d = conv3x3(in_channels, v, padding=1) # 卷积层,in_channels是输入数据的通道数,初始RGB图像的通道数为3\n if batch_norm: # 对batch是否进行标准化\n layers += [conv2d, nn.BatchNorm2d(v), nn.ReLU(inplace=True)]\n else:\n layers += [conv2d, nn.ReLU(inplace=True)] # 每次卷积完成后,需要使用激活函数ReLU激活一下,保持特征的非线性属性\n in_channels = v # 下一层的输入数据的通道数,就是上一层卷积核的个数\n return nn.Sequential(*layers) # 返回一个包含了网络结构的时序容器,加*是为了只传递layers列表中的内容,而不是传递列表本身\n\n\ndef vgg16(**kwargs):\n model = VGG(make_layers(cfg, batch_norm=True), **kwargs) # batch_norm一定要等于True,如果不对batch进行标准化,那么训练结果的准确率一直无法提升\n # model.load_state_dict(torch.load(model_path)) # 如果需要使用预训练模型,则加入该代码\n return model\n\n\n\n\n\n","sub_path":"vgg16.py","file_name":"vgg16.py","file_ext":"py","file_size_in_byte":4963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"545914775","text":"# Columnar Transposition Ciper Decryption inspired by chapter 8 of Cracking Codes with Python \n# https://www.nostarch.com/crackingcodes/ (BSD Licensed)\n\nimport math, pyperclip\n\ndef decrypt_message(key, ciphertext):\n\n num_columns = int(math.ceil(len(ciphertext) / float(key)))\n\n num_rows = key\n\n extra_boxes = (num_columns * num_rows) - len(ciphertext)\n\n plaintext = [''] * num_columns\n\n column = 0\n row =0\n\n for symbol in ciphertext:\n plaintext[column] += symbol\n column += 1 # Point to the next column.\n\n if (column == num_columns) or (column == num_columns - 1 and row >= num_rows - extra_boxes):\n column = 0\n row += 1\n \n return ''.join(plaintext)\n\ndef main(): \n ciphertext = input('What is the text you would like to decrypt? ')\n key = int(input('What is the key you would like to use? '))\n\n decrypt_message(key, ciphertext)\n\n\nif __name__ == '__main__': \n decrypt_message(key, ciphertext)\n","sub_path":"python/cracking_codes_with_python/g_decrypt_columnar_transposition_cipher.py","file_name":"g_decrypt_columnar_transposition_cipher.py","file_ext":"py","file_size_in_byte":934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"635635369","text":"'''\n\nRun extra electron ID algorithms.\n\nOriginal author: M. Bachtis\n\n'''\n\nimport FWCore.ParameterSet.Config as cms\nimport sys\n\nrecoElectronID = cms.Sequence()\n\ntry:\n from EGamma.EGammaAnalysisTools.electronIdMVAProducer_cfi import \\\n mvaTrigV0, mvaNonTrigV0\n\n recoElectronID += mvaTrigV0\n recoElectronID += mvaNonTrigV0\nexcept ImportError:\n # Don't crash if not installed\n sys.stderr.write(__file__ +\n \": EG MVA ID dependency not installed, will not be run!\\n\")\n# For PAT\nelectronIDSources = cms.PSet(\n\tcicLoose = cms.InputTag(\"eidLoose\"),\n\tcicTight = cms.InputTag(\"eidTight\"),\n mvaTrigV0 = cms.InputTag(\"mvaTrigV0\"),\n mvaNonTrigV0 = cms.InputTag(\"mvaNonTrigV0\"),\n)\n","sub_path":"PatTools/python/electrons/electronID_cff.py","file_name":"electronID_cff.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"412771164","text":"from typing import List, Dict\nfrom datetime import datetime\n\nfrom republic.model.republic_pagexml_model import parse_derived_coords\n\n\ndef check_textline_textequiv_assertions(text_equiv: dict) -> None:\n text_equiv_children = ['Unicode', 'PlainText']\n for child in text_equiv:\n if child not in text_equiv_children:\n raise KeyError(f\"Unknown child element in PageXML TextEquiv: {child}\")\n if child == 'PlainText':\n assert(text_equiv['PlainText'] is None)\n if child == 'Unicode':\n assert(isinstance(text_equiv['Unicode'], str))\n\n\ndef check_baseline_assertions(base_line: dict) -> None:\n base_line_children = ['@points']\n for child in base_line:\n if child not in base_line_children:\n raise KeyError(f\"Unknown child element in PageXML Baseline: {child}\")\n if child == '@points':\n assert(isinstance(base_line['@points'], str))\n\n\ndef check_textline_coords_assertions(text_line_coords: dict) -> None:\n coords_children = ['@points', 'Point']\n for child in text_line_coords:\n if child not in coords_children:\n raise KeyError(f\"Unknown child element in PageXML TextLine Coords: {child}\")\n if child == '@points':\n assert(isinstance(text_line_coords['@points'], str))\n if child == 'Point':\n assert(text_line_coords['Point'] is None)\n\n\ndef check_textline_assertions(textline: dict) -> None:\n textline_children = ['@xheight', 'idString', 'Coords', 'Baseline', 'TextEquiv', 'TextStyle']\n for child in textline:\n if child not in textline_children:\n print(textline)\n raise KeyError(f\"Unknown child element in PageXML TextLine: {child}\")\n if child == 'idString':\n assert(textline['idString'] is None)\n if child == 'TextStyle':\n assert(textline['TextStyle'] is None)\n\n\ndef check_textregion_assertions(textregion: dict) -> None:\n textregion_children = ['@orientation', 'Coords', 'TextEquiv', 'TextLine', 'TextRegion']\n assert('@orientation' in textregion)\n assert('Coords' in textregion)\n assert('TextEquiv' in textregion)\n assert (textregion['Coords'] is None)\n assert (textregion['TextEquiv'] is None)\n for child in textregion:\n if child not in textregion_children:\n raise KeyError(f\"Unknown child element in PageXML TextRegion: {child}\")\n if child == '@orientation':\n assert(textregion['@orientation'] == '0.0')\n\n\ndef check_page_metadata_assertions(metadata: dict) -> None:\n fields = ['Creator', 'Created', 'LastChange', 'TranskribusMetadata', 'Comments']\n for field in fields:\n if field in ['Creator', 'TranskribusMetadata', 'Comments']:\n assert(metadata[field] is None)\n if field in ['Created', 'LastChange']:\n assert(metadata[field].isdigit() is True)\n\n\ndef check_page_assertions(page_json: dict) -> None:\n \"\"\"These assertions are to check if the PageXML format changes based on additional output of OCR/HTR analysis.\"\"\"\n assert(page_json['PcGts']['schemaLocation'] is None)\n if page_json['PcGts']['Metadata']:\n check_page_metadata_assertions(page_json['PcGts']['Metadata'])\n if 'pcGtsId' in page_json['PcGts']:\n assert(page_json['PcGts']['pcGtsId'] is None)\n assert(page_json['PcGts']['Page']['@imageWidth'].isdigit() is True)\n assert(page_json['PcGts']['Page']['@imageHeight'].isdigit() is True)\n assert(page_json['PcGts']['Page']['ReadingOrder'] is None)\n assert(page_json['PcGts']['Page']['PrintSpace'] is None)\n pcgts_children = ['schemaLocation', 'Metadata', 'pcGtsId', 'Page']\n for child in page_json['PcGts']:\n if child not in pcgts_children:\n raise KeyError(f\"Unknown child element in PageXML PcGts: {child}\")\n page_children = ['ReadingOrder', 'TextRegion', 'PrintSpace', '@imageWidth', '@imageHeight']\n for child in page_json['PcGts']['Page']:\n if child not in page_children:\n raise KeyError(f\"Unknown child element in PageXML Page: {child}\")\n\n\ndef parse_textline_metadata(textline: dict) -> dict:\n line = {'coords': parse_coords(textline['Coords']), 'xheight': int(textline['@xheight'])}\n return line\n\n\ndef parse_coords(coords: dict) -> Dict[str, int]:\n check_textline_coords_assertions(coords)\n parts = coords['@points'].split(\" \")\n left, top = [int(coord) for coord in parts[0].split(\",\")]\n right, bottom = [int(coord) for coord in parts[2].split(\",\")]\n test_right, test_top = [int(coord) for coord in parts[1].split(\",\")]\n test_left, test_bottom = [int(coord) for coord in parts[3].split(\",\")]\n assert(left == test_left)\n assert(right == test_right)\n assert(top == test_top)\n assert(bottom == test_bottom)\n return {\n 'left': left,\n 'right': right,\n 'top': top,\n 'bottom': bottom,\n 'height': bottom - top,\n 'width': right - left\n }\n\n\ndef parse_textline(textline: dict) -> dict:\n check_textline_assertions(textline)\n line = parse_textline_metadata(textline)\n line['text'] = textline['TextEquiv']['Unicode']\n return line\n\n\ndef parse_textline_list(textline_list: list) -> List[dict]:\n return [parse_textline(textline) for textline in textline_list]\n\n\ndef parse_textregion(textregion: dict) -> dict:\n check_textregion_assertions(textregion)\n parsed_region = {\n 'orientation': float(textregion['@orientation'])\n }\n for child in textregion:\n if child == 'TextLine':\n if isinstance(textregion['TextLine'], list):\n parsed_region['lines'] = parse_textline_list(textregion['TextLine'])\n else:\n parsed_region['lines'] = [parse_textline(textregion['TextLine'])]\n parsed_region['coords'] = parse_derived_coords(parsed_region['lines'])\n if child == 'TextRegion':\n if isinstance(textregion['TextRegion'], list):\n parsed_region['textregions'] = parse_textregion_list(textregion['TextRegion'])\n else:\n parsed_region['textregions'] = [parse_textregion(textregion['TextRegion'])]\n parsed_region['coords'] = parse_derived_coords(parsed_region['textregions'])\n return parsed_region\n\n\ndef parse_textregion_list(textregion_list: list) -> List[dict]:\n return [parse_textregion(textregion) for textregion in textregion_list]\n\n\ndef parse_page_metadata(metadata_json: dict) -> dict:\n metadata = {}\n for field in metadata_json:\n if not metadata_json[field]:\n continue\n if field in ['Created', 'LastChange']:\n metadata[field] = datetime.fromtimestamp(int(metadata_json[field]) / 1000)\n elif metadata_json[field].isdigit():\n metadata[field] = int(metadata_json[field])\n elif metadata_json[field]:\n metadata[field] = metadata_json[field]\n return metadata\n\n\ndef parse_page_image_size(page_json: dict) -> dict:\n coords = {\n 'left': 0,\n 'right': 0,\n 'top': 0,\n 'bottom': 0,\n 'width': 0,\n 'height': 0\n }\n if page_json['@imageWidth'] is not '0':\n coords['width'] = int(page_json['@imageWidth'])\n coords['right'] = coords['width']\n if page_json['@imageHeight'] is not '0':\n coords['height'] = int(page_json['@imageHeight'])\n coords['bottom'] = coords['height']\n return coords\n\n\ndef parse_pagexml(scan_json: dict) -> dict:\n check_page_assertions(scan_json)\n scan_doc = {'metadata': {}}\n if 'Metadata' in scan_json['PcGts'] and scan_json['PcGts']['Metadata']:\n scan_doc['metadata'] = parse_page_metadata(scan_json['PcGts']['Metadata'])\n scan_json = scan_json['PcGts']['Page']\n if scan_json['@imageWidth'] is not '0' and scan_json['@imageHeight'] is not '0':\n scan_doc['coords'] = parse_page_image_size(scan_json)\n if 'TextRegion' in scan_json:\n if isinstance(scan_json['TextRegion'], list):\n scan_doc['textregions'] = parse_textregion_list(scan_json['TextRegion'])\n else:\n scan_doc['textregions'] = [parse_textregion(scan_json['TextRegion'])]\n return scan_doc\n\n\n","sub_path":"republic/parser/pagexml/generic_pagexml_parser.py","file_name":"generic_pagexml_parser.py","file_ext":"py","file_size_in_byte":8139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"350134854","text":"import opytimizer.utils.logging as l\n\nlogger = l.get_logger(__name__)\n\n\nclass Function:\n \"\"\"A Function class to hold objective functions\n that will be further evaluated.\n\n It will serve as the basis class for holding in-code related\n objective functions.\n\n \"\"\"\n\n def __init__(self, pointer=callable):\n \"\"\"Initialization method.\n\n Args:\n function (callable): This should be a pointer to a function\n that will return the fitness value.\n\n \"\"\"\n\n logger.info('Creating class: Function.')\n\n # Also, we need a pointer to point to our actual function\n self._pointer = callable\n\n # Indicates whether the function is built or not\n self._built = False\n\n # Now, we need to build this class up\n self._build(pointer)\n\n logger.info('Class created.')\n\n @property\n def pointer(self):\n \"\"\"callable: A pointer to point to our actual function.\n\n \"\"\"\n\n return self._pointer\n\n @pointer.setter\n def pointer(self, pointer):\n self._pointer = pointer\n\n @property\n def built(self):\n \"\"\"bool: A boolean to indicate whether the function is built.\n\n \"\"\"\n\n return self._built\n\n @built.setter\n def built(self, built):\n self._built = built\n\n def _build(self, pointer):\n \"\"\"This method will serve as the object building process.\n \n One can define several commands here that does not necessarily\n needs to be on its initialization.\n\n Args:\n function (callable): This should be a pointer to a function\n that will return the fitness value.\n\n Raises:\n RuntimeError\n\n \"\"\"\n\n logger.debug('Running private method: build().')\n\n # We apply to class pointer's the desired function\n if pointer:\n self.pointer = pointer\n else:\n e = f\"Property 'pointer' cannot be {pointer}.\"\n logger.error(e)\n raise RuntimeError(e)\n\n # Set built variable to 'True'\n self.built = True\n\n # Logging attributes\n logger.debug(\n f'Pointer: {self.pointer} | Built: {self.built}')\n","sub_path":"opytimizer/core/function.py","file_name":"function.py","file_ext":"py","file_size_in_byte":2211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"555832895","text":"# Copyright (c) 2015, Alphamonak Solutions Ltd. \n# License: GNU General Public License v3. See license.txt\n\nfrom __future__ import unicode_literals\nimport redapp\n\ndef execute():\t\t\t\t\t\n\tfor po in redapp.db.sql(\"\"\"select name from `tabProduction Order` where docstatus < 2\"\"\", as_dict=1):\n\t\tprod_order = redapp.get_doc(\"Production Order\", po.name)\n\t\tif prod_order.operations:\n\t\t\tprod_order.flags.ignore_validate_update_after_submit = True\n\t\t\tprod_order.calculate_time()\n\t\t\tprod_order.save()","sub_path":"redapple/patches/v5_0/reclculate_planned_operating_cost_in_production_order.py","file_name":"reclculate_planned_operating_cost_in_production_order.py","file_ext":"py","file_size_in_byte":487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"49409309","text":"# -*- coding: utf-8 -*-\n\n\nfrom jsonschema import ValidationError, validate\n\nfrom cognito import Cognito\nfrom gluon import HTTP\n\n\n@auth.allows_jwt()\n@auth.requires_login()\n@request.restful()\ndef add_user_to_group():\n schema = {\n \"type\": \"object\",\n \"properties\": {\n \"Username\": {\"type\": \"string\"},\n \"GroupName\": {\"type\": \"string\"},\n },\n \"required\": [\"Username\", \"GroupName\"],\n }\n\n def PATCH(*reqargs, **reqvars):\n try:\n validate(instance=reqvars, schema=schema)\n except ValidationError:\n raise HTTP(400, \"InvalidParameterException\")\n\n username = reqvars[\"Username\"]\n group_name = reqvars[\"GroupName\"]\n\n return response.json(Cognito().add_user_to_group(username, group_name))\n\n return locals()\n\n\n@auth.allows_jwt()\n@auth.requires_login()\n@request.restful()\ndef create_group():\n schema = {\n \"type\": \"object\",\n \"properties\": {\n \"GroupName\": {\"type\": \"string\"},\n \"Description\": {\"type\": \"string\"},\n },\n \"required\": [\"GroupName\", \"Description\"],\n }\n\n def POST(*reqargs, **reqvars):\n try:\n validate(instance=reqvars, schema=schema)\n except ValidationError:\n raise HTTP(400, \"InvalidParameterException\")\n\n group_name = reqvars[\"GroupName\"]\n description = reqvars[\"Description\"]\n\n return response.json(Cognito().create_group(group_name, description))\n\n return locals()\n\n\n@auth.allows_jwt()\n@auth.requires_login()\n@request.restful()\ndef delete_group():\n schema = {\n \"type\": \"object\",\n \"properties\": {\"GroupName\": {\"type\": \"string\"},},\n \"required\": [\"GroupName\"],\n }\n\n def DELETE(*reqargs, **reqvars):\n try:\n validate(instance=reqvars, schema=schema)\n except ValidationError:\n raise HTTP(400, \"InvalidParameterException\")\n\n group_name = reqvars[\"GroupName\"]\n\n return response.json(Cognito().delete_group(group_name))\n\n return locals()\n\n\n@auth.allows_jwt()\n@auth.requires_login()\n@request.restful()\ndef sign_up():\n schema = {\n \"type\": \"object\",\n \"properties\": {\n \"Username\": {\"type\": \"string\"},\n \"Password\": {\"type\": \"string\"},\n \"UserAttributes\": {\"type\": \"object\"},\n },\n \"required\": [\"Username\", \"Password\"],\n }\n\n def POST(*reqargs, **reqvars):\n try:\n validate(instance=reqvars, schema=schema)\n except ValidationError:\n raise HTTP(400, \"InvalidParameterException\")\n\n username = reqvars[\"Username\"]\n password = reqvars[\"Password\"]\n user_attributes = reqvars.get(\"UserAttributes\")\n\n return response.json(Cognito().sign_up(username, password, user_attributes))\n\n return locals()\n","sub_path":"controllers/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":2822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"58445537","text":"import numpy as np\n\nnumber_of_leaves = 9\nepsilon = 0.15\ndelta = 0.15\nuniform_samples = 500\niterations = 50\n\n\ndef beta(s):\n return np.log(number_of_leaves / delta) + np.log(np.log(s) + 1)\n\n\nclass Node:\n def __init__(self, name, left_child, middle_child, right_child, parent, is_root=False, is_max_node=False):\n self.left_child = left_child\n self.middle_child = middle_child\n self.right_child = right_child\n self.parent = parent\n self.is_root = is_root\n self.is_max_node = is_max_node\n self.name = name\n\n def update_left_child(self, left_child):\n self.left_child = left_child\n\n def update_middle_child(self, middle_child):\n self.middle_child = middle_child\n\n def update_right_child(self, right_child):\n self.right_child = right_child\n\n def value(self):\n values = []\n values.append(self.left_child.empirical_mean())\n values.append(self.middle_child.empirical_mean())\n values.append(self.right_child.empirical_mean())\n values.sort()\n return min(values)\n\n def representative_node(self):\n left_value = self.left_child.value()\n middle_value = self.middle_child.value()\n right_value = self.right_child.value()\n\n if left_value >= middle_value and left_value >= right_value:\n return self.left_child\n elif middle_value >= left_value and middle_value >= right_value:\n return self.middle_child\n else:\n return self.right_child\n\n def representative_leaf(self):\n # For our case the node is the min node - so let's have a fixed rule\n left_lower, _ = self.left_child.confidence_interval()\n middle_lower, _ = self.middle_child.confidence_interval()\n right_lower, _ = self.right_child.confidence_interval()\n if left_lower <= middle_lower and left_lower <= middle_lower:\n return self.left_child\n elif middle_lower <= left_lower and middle_lower <= right_lower:\n return self.middle_child\n else:\n return self.right_child\n\n def confidence_interval(self):\n lowers = []\n uppers = []\n\n left_lower, left_upper = self.left_child.confidence_interval()\n lowers.append(left_lower)\n uppers.append(left_upper)\n\n middle_lower, middle_upper = self.middle_child.confidence_interval()\n lowers.append(middle_lower)\n uppers.append(middle_upper)\n\n right_lower, right_upper = self.right_child.confidence_interval()\n lowers.append(right_lower)\n uppers.append(right_upper)\n\n lowers.sort()\n uppers.sort()\n return [min(lowers), min(uppers)]\n\n def find_best_arm_and_competitor_by_value(self):\n b_c = {}\n left_lower, left_upper = self.left_child.confidence_interval()\n b_c[self.left_child] = self.left_child.value() + np.sqrt(\n 2 * (left_upper - left_lower) / self.left_child.representative_leaf().number_sampled)\n middle_lower, middle_upper = self.middle_child.confidence_interval()\n b_c[self.middle_child] = self.middle_child.value() + np.sqrt(\n 2 * (middle_upper - middle_lower) / self.middle_child.representative_leaf().number_sampled)\n right_lower, right_upper = self.right_child.confidence_interval()\n b_c[self.right_child] = self.right_child.value() + np.sqrt(\n 2 * (right_upper - right_lower) / self.right_child.representative_leaf().number_sampled)\n\n best_arm, competitor = [k for k, v in sorted(b_c.items(), key=lambda item: item[1], reverse=True)][:2]\n return best_arm, competitor\n\n def find_best_arm_and_competitor(self):\n left_lower, left_upper = self.left_child.confidence_interval()\n middle_lower, middle_upper = self.middle_child.confidence_interval()\n right_lower, right_upper = self.right_child.confidence_interval()\n\n B_left_middle = middle_upper - left_lower\n B_left_right = right_upper = left_lower\n B_left = None\n if B_left_middle > B_left_right:\n B_left = B_left_middle\n else:\n B_left = B_left_right\n\n B_middle_left = left_upper - middle_lower\n B_middle_right = right_upper - middle_lower\n B_middle = None\n if B_middle_left > B_middle_right:\n B_middle = B_middle_left\n else:\n B_middle = B_middle_right\n\n B_right_left = left_upper - right_lower\n B_right_middle = middle_upper - right_lower\n B_right = None\n if B_right_left > B_right_middle:\n B_right = B_right_left\n else:\n B_right = B_right_middle\n\n b_t = None\n c_t_list = []\n if B_left < B_middle and B_left < B_right:\n b_t = self.left_child\n c_t_list.append(self.middle_child)\n c_t_list.append(self.right_child)\n elif B_middle < B_left and B_middle < B_right:\n b_t = self.middle_child\n c_t_list.append(self.left_child)\n c_t_list.append(self.right_child)\n else:\n b_t = self.right_child\n c_t_list.append(self.left_child)\n c_t_list.append(self.middle_child)\n\n c_t = None\n _, ub_first = c_t_list[0].confidence_interval()\n _, ub_second = c_t_list[1].confidence_interval()\n\n if ub_first > ub_second:\n c_t = c_t_list[0]\n else:\n c_t = c_t_list[1]\n\n return b_t, c_t\n\n\nclass LeafNode:\n def __init__(self, name, parent, true_mean_val):\n self.parent = parent\n self.true_mean_val = true_mean_val\n self.values = []\n self.number_sampled = 0\n self.name = name\n\n def sample(self):\n random_value = np.random.normal(self.true_mean_val, 0.2)\n self.values.append(random_value)\n self.number_sampled += 1\n return random_value\n\n def empirical_mean(self):\n return np.mean(self.values)\n\n def lower_bound(self):\n confidence_gap = np.sqrt(beta(self.number_sampled) / self.number_sampled)\n emp_mean = self.empirical_mean()\n return emp_mean - confidence_gap\n\n def upper_bound(self):\n confidence_gap = np.sqrt(beta(self.number_sampled) / self.number_sampled)\n emp_mean = self.empirical_mean()\n return emp_mean + confidence_gap\n\n def confidence_interval(self):\n lower_bound = self.lower_bound()\n upper_bound = self.upper_bound()\n return [lower_bound, upper_bound]\n\n def true_mean(self):\n return self.true_mean_val\n\n def sample_complexity(self):\n return self.number_sampled\n\n def reset(self):\n self.number_sampled = 0\n self.values = []\n\n\nleaves = []\n\nroot = Node('root', None, None, None, None, is_root=True, is_max_node=True)\n\nleaf_1 = LeafNode('leaf_1', root, 0.45)\nleaves.append(leaf_1)\nleaf_2 = LeafNode('leaf_2', root, 0.50)\nleaves.append(leaf_2)\nleaf_3 = LeafNode('leaf_3', root, 0.55)\nleaves.append(leaf_3)\nnode_left = Node('node_left', leaf_1, leaf_2, leaf_3, root, is_root=False, is_max_node=False)\nroot.update_left_child(node_left)\n\nleaf_4 = LeafNode('leaf_4', root, 0.35)\nleaves.append(leaf_4)\nleaf_5 = LeafNode('leaf_5', root, 0.40)\nleaves.append(leaf_5)\nleaf_6 = LeafNode('leaf_6', root, 0.60)\nleaves.append(leaf_6)\nnode_middle = Node('node_middle', leaf_4, leaf_5, leaf_6, root, is_root=False, is_max_node=False)\nroot.update_middle_child(node_middle)\n\nleaf_7 = LeafNode('leaf_7', root, 0.30)\nleaves.append(leaf_7)\nleaf_8 = LeafNode('leaf_8', root, 0.47)\nleaves.append(leaf_8)\nleaf_9 = LeafNode('leaf_9', root, 0.52)\nleaves.append(leaf_9)\nnode_right = Node('node_right', leaf_7, leaf_8, leaf_9, root, is_root=False, is_max_node=False)\nroot.update_right_child(node_right)\n\n\ndef total_sample_complexity():\n samples = 0\n for leaf in leaves:\n samples += leaf.sample_complexity()\n\n return samples\n\n\ndef get_best_arm():\n node_left_vlaue = node_left.value()\n node_middle_value = node_middle.value()\n node_right_value = node_right.value()\n\n if node_left_vlaue >= node_middle_value and node_left_vlaue >= node_right_value:\n return 'node_left'\n elif node_middle_value >= node_left_vlaue and node_middle_value >= node_right_value:\n return 'node_middle'\n else:\n return 'node_right'\n\n\ndef root_value():\n values = []\n values.append(root.left_child.value())\n values.append(root.middle_child.value())\n values.append(root.right_child.value())\n # root is a max node\n values.sort()\n return max(values)\n\n\ndef reset():\n leaf_1.reset()\n leaf_2.reset()\n leaf_3.reset()\n leaf_4.reset()\n leaf_5.reset()\n leaf_6.reset()\n leaf_7.reset()\n leaf_8.reset()\n leaf_9.reset()\n\n\n# MCTS-BAI\nprint('Running MCTS-BAI ... ')\nsample_complexity_list = []\nbest_arm_list = []\nroot_values_list = []\n\nfor i in range(iterations):\n reset()\n leaf_1.sample()\n leaf_2.sample()\n leaf_3.sample()\n leaf_4.sample()\n leaf_5.sample()\n leaf_6.sample()\n leaf_7.sample()\n leaf_8.sample()\n leaf_9.sample()\n\n while True:\n b_t, c_t = root.find_best_arm_and_competitor()\n b_lower, b_upper = b_t.confidence_interval()\n b_diff = b_upper - b_lower\n c_lower, c_upper = c_t.confidence_interval()\n c_diff = c_upper - c_lower\n\n if c_upper - b_lower <= epsilon:\n break\n\n next_move = None\n if b_diff > c_diff:\n next_move = b_t\n else:\n next_move = c_t\n\n representative_leaf = next_move.representative_leaf()\n representative_leaf.sample()\n\n samples = total_sample_complexity()\n best_arm = get_best_arm()\n sample_complexity_list.append(samples)\n best_arm_list.append(best_arm)\n root_values_list.append(root_value())\naverate_complexity = 0\nfor sample in sample_complexity_list:\n averate_complexity += sample\naverate_complexity = averate_complexity / iterations\n\naverage_root_value = 0\nfor root_val in root_values_list:\n average_root_value += root_val\naverage_root_value = average_root_value / iterations\n\npercentage_correct = None\naverage_best_arm = None\ncount_left = 0\ncount_middle = 0\ncount_right = 0\n\nfor b_arm in best_arm_list:\n if b_arm == 'node_left':\n count_left += 1\n elif b_arm == 'node_middle':\n count_middle += 1\n else:\n count_right += 1\n\nif count_left > count_middle and count_left > count_right:\n average_best_arm = 'node_left'\n percentage_correct = (count_left / iterations) * 100\nelif count_middle > count_left and count_middle > count_right:\n average_best_arm = 'node_middle'\n percentage_correct = (count_middle / iterations) * 100\nelse:\n average_best_arm = 'node_right'\n percentage_correct = (count_right / iterations) * 100\n\nprint('MCTS-BAI')\nprint(f'Average Best Arm: {average_best_arm}')\nprint(f'Average Complexity: {averate_complexity}')\nprint(f'Average Root Value: {round(average_root_value, 2)}')\nprint(f'Percentage Correct: {percentage_correct} %')\n\n# MCTS-BAI - Dharma\nprint('\\n')\nprint('Running MCTS-BAI-Dharma ... ')\nsample_complexity_list = []\nbest_arm_list = []\nroot_values_list = []\nfor i in range(iterations):\n reset()\n\n leaf_1.sample()\n leaf_2.sample()\n leaf_3.sample()\n leaf_4.sample()\n leaf_5.sample()\n leaf_6.sample()\n leaf_7.sample()\n leaf_8.sample()\n leaf_9.sample()\n\n while True:\n b_t, c_t = root.find_best_arm_and_competitor_by_value()\n b_lower, b_upper = b_t.confidence_interval()\n b_diff = b_upper - b_lower\n c_lower, c_upper = c_t.confidence_interval()\n c_diff = c_upper - c_lower\n\n if c_upper - b_lower <= epsilon:\n break\n\n next_move = None\n if b_diff > c_diff:\n next_move = b_t\n else:\n next_move = c_t\n\n representative_leaf = next_move.representative_leaf()\n representative_leaf.sample()\n\n samples = total_sample_complexity()\n best_arm = get_best_arm()\n sample_complexity_list.append(samples)\n best_arm_list.append(best_arm)\n root_values_list.append(root_value())\n\naverate_complexity = 0\nfor sample in sample_complexity_list:\n averate_complexity += sample\naverate_complexity = averate_complexity / iterations\n\naverage_root_value = 0\nfor root_val in root_values_list:\n average_root_value += root_val\naverage_root_value = average_root_value / iterations\n\npercentage_correct = None\naverage_best_arm = None\ncount_left = 0\ncount_middle = 0\ncount_right = 0\n\nfor b_arm in best_arm_list:\n if b_arm == 'node_left':\n count_left += 1\n elif b_arm == 'node_middle':\n count_middle += 1\n else:\n count_right += 1\n\nif count_left > count_middle and count_left > count_right:\n average_best_arm = 'node_left'\n percentage_correct = (count_left / iterations) * 100\nelif count_middle > count_left and count_middle > count_right:\n average_best_arm = 'node_middle'\n percentage_correct = (count_middle / iterations) * 100\nelse:\n average_best_arm = 'node_right'\n percentage_correct = (count_right / iterations) * 100\n\nprint('MCTS-BAI-Dharma')\nprint(f'Average Best Arm: {average_best_arm}')\nprint(f'Average Complexity: {averate_complexity}')\nprint(f'Average Root Value: {round(average_root_value, 2)}')\nprint(f'Percentage Correct: {percentage_correct} %')\n\n# Uniform-Sampling\nreset()\nfor i in range(uniform_samples):\n leaf_1.sample()\n leaf_2.sample()\n leaf_3.sample()\n leaf_4.sample()\n leaf_5.sample()\n leaf_6.sample()\n leaf_7.sample()\n leaf_8.sample()\n leaf_9.sample()\n\nsamples = total_sample_complexity()\nbest_arm = get_best_arm()\n\nprint('\\n')\nprint('Uniform Sampling')\nprint(f'Best Arm: {best_arm}')\nprint(f'Samples: {samples}')\nprint(f'Value at root: {round(root_value(), 2)}')\n","sub_path":"mcts_bai.py","file_name":"mcts_bai.py","file_ext":"py","file_size_in_byte":13756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"130285839","text":"import csv\n# r is to read the file\n# cal_csv is the name of the var storing the csv\nclass Workout:\n def workcal (self):\n workout = open('Workouts.csv','r')\n reader = csv.reader(workout)\n header = next(reader)\n\n day1 = []\n day2 = []\n day3 = []\n day4 = []\n day5 = []\n day6 = []\n day7 = []\n for line in reader:\n if line[0] == \"10/04/2020\":\n day1.append(int(line[2])*int(line[3]))\n elif line[0] == \"11/04/2020\":\n day2.append(int(line[2])*int(line[3]))\n elif line[0] == \"12/04/2020\":\n day3.append(int(line[2])*int(line[3]))\n elif line[0] == \"13/04/2020\":\n day4.append(int(line[2])*int(line[3]))\n elif line[0] == \"14/04/2020\":\n day5.append(int(line[2])*int(line[3]))\n elif line[0] == \"15/04/2020\":\n day6.append(int(line[2])*int(line[3]))\n elif line[0] == \"16/04/2020\":\n day7.append(int(line[2])*int(line[3]))\n\n days = []\n days.append(sum(day1))\n days.append(sum(day2))\n days.append(sum(day3))\n days.append(sum(day4))\n days.append(sum(day5))\n days.append(sum(day6))\n days.append(sum(day7))\n return days\n","sub_path":"workoutcsv.py","file_name":"workoutcsv.py","file_ext":"py","file_size_in_byte":1321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"1432452","text":"#coding=utf-8\r\n#读取label中每个像素点的B, G, R值\r\nimport os\r\nimport cv2\r\nimport numpy as np\r\n\r\n\r\ndef read_RGB(data_path):\r\n dirs = os.listdir(data_path)\r\n num = 0\r\n for d in dirs:\r\n num += 1\r\n img_path = os.path.join(data_path, d)\r\n img = np.array(cv2.imread(img_path))\r\n sp = img.shape\r\n height, width = sp[0], sp[1]\r\n for i in range(height):\r\n tmp = []\r\n for j in range(width):\r\n if img[i, j ,0] != 0 or img[i, j, 1] != 0 or img[i, j, 2] != 0:\r\n tmp.append([i, j])\r\n if tmp != []:\r\n with open(\"%s pixel_coordinate.txt\"%d, 'a') as f:\r\n f.write(str(tmp))\r\n f.write(\"\\n\")\r\n print(\"Finished read No.%s pixel coordinate\"%num)\r\n return num\r\n\r\nif __name__ == '__main__':\r\n data_path = \"/xxx/xxx/xxx/\" #添加自己的路径\r\n read_RGB(data_path)","sub_path":"make_label.py","file_name":"make_label.py","file_ext":"py","file_size_in_byte":970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"507266047","text":"import unittest\nfrom Wpp.WppCore import WppCore\nfrom Python.PyCore import PyCore\nfrom out.OutContextMemoryStream import OutContextMemoryStream\n\nclass TestPyIf(unittest.TestCase):\n\n\tdef testSimple(self):\n\t\tsource = \"\"\"\nfunc public positive: int\n\tparam value: int\n\tif value < 0\n\t\tvalue = 0\n\tvalue\n\t\t\"\"\"\n\t\texpected = \"\"\"\ndef positive(value):\n\tif value < 0:\n\t\tvalue = 0\n\treturn value\n\t\t\"\"\"\n\t\tsrcModule = WppCore.createMemModule(source, 'simpleIf.fake')\n\t\tdstModule = srcModule.cloneRoot(PyCore())\n\t\toutContext = OutContextMemoryStream()\n\t\tdstModule.export(outContext)\n\t\tself.assertEqual(str(outContext), expected.strip())\n\n\n\tdef testElse(self):\n\t\tsource = \"\"\"\nfunc public getState: String\n\tparam value: int\n\tvar result: String\n\tif value < 0\n\t\tresult = \"Negative\"\n\telse\n\t\tresult = \"Positive\"\n\tresult\n\t\t\"\"\"\n\t\texpected = \"\"\"\ndef getState(value):\n\tresult = ''\n\tif value < 0:\n\t\tresult = 'Negative'\n\telse:\n\t\tresult = 'Positive'\n\treturn result\n\t\t\"\"\"\n\t\tsrcModule = WppCore.createMemModule(source, 'elseIf.fake')\n\t\tdstModule = srcModule.cloneRoot(PyCore())\n\t\toutContext = OutContextMemoryStream()\n\t\tdstModule.export(outContext)\n\t\tself.assertEqual(str(outContext), expected.strip())\n\n\n\tdef testCases(self):\n\t\tsource = \"\"\"\nfunc public getNumName: String\n\tparam value: int\n\tvar result: String\n\tif value == 0\n\t\tresult = \"Zero\"\n\telif value == 1\n\t\tresult = \"One\"\n\telif value == 2\n\t\tresult = \"Two\"\n\telse\n\t\tresult = \"Else\"\n\tresult\n\t\t\"\"\"\n\t\texpected = \"\"\"\ndef getNumName(value):\n\tresult = ''\n\tif value == 0:\n\t\tresult = 'Zero'\n\telif value == 1:\n\t\tresult = 'One'\n\telif value == 2:\n\t\tresult = 'Two'\n\telse:\n\t\tresult = 'Else'\n\treturn result\n\t\t\"\"\"\n\t\tsrcModule = WppCore.createMemModule(source, 'elseIf.fake')\n\t\tdstModule = srcModule.cloneRoot(PyCore())\n\t\toutContext = OutContextMemoryStream()\n\t\tdstModule.export(outContext)\n\t\tself.assertEqual(str(outContext), expected.strip())\n","sub_path":"src/Python/tests/testPyIf.py","file_name":"testPyIf.py","file_ext":"py","file_size_in_byte":1850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"49111118","text":"from nltk.tree import Tree\nimport nltk as nl\nfrom nltk.draw.tree import draw_trees\nfrom nltk import tree, treetransforms\nfrom copy import deepcopy\nimport sys\n\n\ndef chomsky_normal_form(tree, factor=\"right\", horzMarkov=None, vertMarkov=0, childChar=\"|\", parentChar=\"^\"):\n if horzMarkov is None: horzMarkov = 999\n nodeList = [(tree, ['0'])]\n while nodeList != []:\n node, parent = nodeList.pop()\n if isinstance(node,Tree):\n node.set_label(\"0\")\n if vertMarkov != 0 and node != tree and isinstance(node[0],Tree):\n node.set_label(\"0\")\n if len(node)==1:\n if (len(node.leaves()))==1:\n word = node.leaves()[0]\n node[0] = word\n elif len(node[0]) != 1:\n node.append(node[0][1])\n node[0] = node[0][0]\n elif len(node[0][0])!=1:\n node.append(node[0][0][1])\n node[0]=node[0][0][0]\n for child in node:\n nodeList.append((child, \"0\"))\n if len(node) > 2:\n childNodes = ['0' for child in node]\n nodeCopy = node.copy()\n for i in range(1,len(nodeCopy) - 1):\n if factor == \"right\":\n newNode = Tree(\"0\", [])\n node[0:] = [nodeCopy.pop(0), newNode]\n else:\n newNode = Tree(\"0\", [])\n node[0:] = [newNode, nodeCopy.pop()]\n node = newNode\n node[0:] = [child for child in nodeCopy]\n\nwith open(sys.argv[1],'rt') as fin:\n raw_data = fin.read().split('\\n\\n')\n del raw_data[len(raw_data)-1]\n TT = [Tree.fromstring(t) for t in raw_data]\n\nwith open('testingBinaryTree','wt') as fout:\n for i,x in enumerate(TT):\n chomsky_normal_form(x)\n a=x.pformat().split()\n b=' '.join(a)\n fout.write(b+'\\n')\n\n","sub_path":"hw2/transform.py","file_name":"transform.py","file_ext":"py","file_size_in_byte":1972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"335241979","text":"import urllib.request\nimport csv\n\nbase_url = 'http://192.168.253.38:3000'\nurl = base_url + '/channels/1/feed.csv'\nfile_name = 'feed_thingspeak.csv'\n\nr = urllib.request.urlretrieve(url, file_name)\n\nprint(\"Saved as \"+file_name+\"\\n\")\n\nprint(\"__Show Entry__\")\nwith open(file_name, newline='') as csvfile:\n Reader = csv.reader(csvfile, delimiter=',', quotechar='|')\n for row in Reader:\n print (', '.join(row))\n","sub_path":"fetch_csv_thingspeak.py","file_name":"fetch_csv_thingspeak.py","file_ext":"py","file_size_in_byte":418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"343218751","text":"import time\nfrom resTool.opst import *\nfrom resTool.utils import *\n\nclass ResNet(object):\n def __init__(self, sess, args):\n self.model_name = 'ResNet'\n self.sess = sess\n self.dataset_name = args.dataset\n\n if self.dataset_name == 'cifar10' :\n self.train_x, self.train_y, self.test_x, self.test_y = load_cifar10()\n self.img_size = 32\n self.c_dim = 3\n self.label_dim = 10\n\n if self.dataset_name == 'cifar100' :\n self.train_x, self.train_y, self.test_x, self.test_y = load_cifar100()\n self.img_size = 32\n self.c_dim = 3\n self.label_dim = 100\n\n if self.dataset_name == 'mnist' :\n self.train_x, self.train_y, self.test_x, self.test_y = load_mnist()\n self.img_size = 28\n self.c_dim = 1\n self.label_dim = 10\n\n if self.dataset_name == 'fashion-mnist' :\n self.train_x, self.train_y, self.test_x, self.test_y = load_fashion()\n self.img_size = 28\n self.c_dim = 1\n self.label_dim = 10\n\n if self.dataset_name == 'tiny' :\n self.train_x, self.train_y, self.test_x, self.test_y = load_tiny()\n self.img_size = 64\n self.c_dim = 3\n self.label_dim = 200\n\n\n self.checkpoint_dir = args.checkpoint_dir\n self.log_dir = args.log_dir\n\n self.res_n = args.res_n\n\n self.epoch = args.epoch\n self.batch_size = args.batch_size\n self.iteration = len(self.train_x) // self.batch_size\n\n self.init_lr = args.lr\n\n\n ##################################################################################\n # Generator\n ##################################################################################\n\n def network(self, x, is_training=True, reuse=False):\n with tf.variable_scope(\"Resnet\", reuse=reuse):\n\n if self.res_n < 50 :\n residual_block = resblock\n else :\n residual_block = bottle_resblock\n\n residual_list = get_residual_layer(self.res_n)\n\n ch = 32 # paper is 64\n x = conv(x, channels=ch, kernel=3, stride=1, scope='conv')\n\n for i in range(residual_list[0]) :\n x = residual_block(x, channels=ch, is_training=is_training, downsample=False, scope='resblock0_' + str(i))\n\n ########################################################################################################\n\n x = residual_block(x, channels=ch*2, is_training=is_training, downsample=True, scope='resblock1_0')\n\n for i in range(1, residual_list[1]) :\n x = residual_block(x, channels=ch*2, is_training=is_training, downsample=False, scope='resblock1_' + str(i))\n\n ########################################################################################################\n\n x = residual_block(x, channels=ch*4, is_training=is_training, downsample=True, scope='resblock2_0')\n\n for i in range(1, residual_list[2]) :\n x = residual_block(x, channels=ch*4, is_training=is_training, downsample=False, scope='resblock2_' + str(i))\n\n ########################################################################################################\n\n x = residual_block(x, channels=ch*8, is_training=is_training, downsample=True, scope='resblock_3_0')\n\n for i in range(1, residual_list[3]) :\n x = residual_block(x, channels=ch*8, is_training=is_training, downsample=False, scope='resblock_3_' + str(i))\n\n ########################################################################################################\n\n\n x = batch_norm(x, is_training, scope='batch_norm')\n x = relu(x)\n\n x = global_avg_pooling(x)\n x = fully_conneted(x, units=self.label_dim, scope='logit')\n\n return x\n\n ##################################################################################\n # Model\n ##################################################################################\n\n def build_model(self):\n \"\"\" Graph Input \"\"\"\n self.train_inptus = tf.placeholder(tf.float32, [self.batch_size, self.img_size, self.img_size, self.c_dim], name='train_inputs')\n self.train_labels = tf.placeholder(tf.float32, [self.batch_size, self.label_dim], name='train_labels')\n\n self.test_inptus = tf.placeholder(tf.float32, [len(self.test_x), self.img_size, self.img_size, self.c_dim], name='test_inputs')\n self.test_labels = tf.placeholder(tf.float32, [len(self.test_y), self.label_dim], name='test_labels')\n\n self.lr = tf.placeholder(tf.float32, name='learning_rate')\n\n \"\"\" Model \"\"\"\n self.train_logits = self.network(self.train_inptus)\n self.test_logits = self.network(self.test_inptus, is_training=False, reuse=True)\n\n self.train_loss, self.train_accuracy = classification_loss(logit=self.train_logits, label=self.train_labels)\n self.test_loss, self.test_accuracy = classification_loss(logit=self.test_logits, label=self.test_labels)\n \n reg_loss = tf.losses.get_regularization_loss()\n self.train_loss += reg_loss\n self.test_loss += reg_loss\n\n\n \"\"\" Training \"\"\"\n self.optim = tf.train.MomentumOptimizer(self.lr, momentum=0.9).minimize(self.train_loss)\n\n \"\"\"\" Summary \"\"\"\n self.summary_train_loss = tf.summary.scalar(\"train_loss\", self.train_loss)\n self.summary_train_accuracy = tf.summary.scalar(\"train_accuracy\", self.train_accuracy)\n\n self.summary_test_loss = tf.summary.scalar(\"test_loss\", self.test_loss)\n self.summary_test_accuracy = tf.summary.scalar(\"test_accuracy\", self.test_accuracy)\n\n self.train_summary = tf.summary.merge([self.summary_train_loss, self.summary_train_accuracy])\n self.test_summary = tf.summary.merge([self.summary_test_loss, self.summary_test_accuracy])\n\n ##################################################################################\n # Train\n ##################################################################################\n\n def train(self):\n # initialize all variables\n tf.global_variables_initializer().run()\n\n # saver to save model\n self.saver = tf.train.Saver()\n\n # summary writer\n self.writer = tf.summary.FileWriter(self.log_dir + '/' + self.model_dir, self.sess.graph)\n\n # restore check-point if it exits\n could_load, checkpoint_counter = self.load(self.checkpoint_dir)\n if could_load:\n epoch_lr = self.init_lr\n start_epoch = (int)(checkpoint_counter / self.iteration)\n start_batch_id = checkpoint_counter - start_epoch * self.iteration\n counter = checkpoint_counter\n\n if start_epoch >= int(self.epoch * 0.75) :\n epoch_lr = epoch_lr * 0.01\n elif start_epoch >= int(self.epoch * 0.5) and start_epoch < int(self.epoch * 0.75) :\n epoch_lr = epoch_lr * 0.1\n print(\" [*] Load SUCCESS\")\n else:\n epoch_lr = self.init_lr\n start_epoch = 0\n start_batch_id = 0\n counter = 1\n print(\" [!] Load failed...\")\n\n # loop for epoch\n start_time = time.time()\n for epoch in range(start_epoch, self.epoch):\n if epoch == int(self.epoch * 0.5) or epoch == int(self.epoch * 0.75) :\n epoch_lr = epoch_lr * 0.1\n\n # get batch data\n for idx in range(start_batch_id, self.iteration):\n batch_x = self.train_x[idx*self.batch_size:(idx+1)*self.batch_size]\n batch_y = self.train_y[idx*self.batch_size:(idx+1)*self.batch_size]\n\n batch_x = data_augmentation(batch_x, self.img_size, self.dataset_name)\n\n train_feed_dict = {\n self.train_inptus : batch_x,\n self.train_labels : batch_y,\n self.lr : epoch_lr\n }\n\n test_feed_dict = {\n self.test_inptus : self.test_x,\n self.test_labels : self.test_y\n }\n\n\n # update network\n _, summary_str, train_loss, train_accuracy = self.sess.run(\n [self.optim, self.train_summary, self.train_loss, self.train_accuracy], feed_dict=train_feed_dict)\n self.writer.add_summary(summary_str, counter)\n\n # test\n summary_str, test_loss, test_accuracy = self.sess.run(\n [self.test_summary, self.test_loss, self.test_accuracy], feed_dict=test_feed_dict)\n self.writer.add_summary(summary_str, counter)\n\n # display training status\n counter += 1\n print(\"Epoch: [%2d] [%5d/%5d] time: %4.4f, train_accuracy: %.2f, test_accuracy: %.2f, learning_rate : %.4f\" \\\n % (epoch, idx, self.iteration, time.time() - start_time, train_accuracy, test_accuracy, epoch_lr))\n\n # After an epoch, start_batch_id is set to zero\n # non-zero value is only for the first epoch after loading pre-trained model\n start_batch_id = 0\n\n # save model\n self.save(self.checkpoint_dir, counter)\n\n # save model for final step\n self.save(self.checkpoint_dir, counter)\n\n @property\n def model_dir(self):\n return \"{}{}_{}_{}_{}\".format(self.model_name, self.res_n, self.dataset_name, self.batch_size, self.init_lr)\n\n def save(self, checkpoint_dir, step):\n checkpoint_dir = os.path.join(checkpoint_dir, self.model_dir)\n\n if not os.path.exists(checkpoint_dir):\n os.makedirs(checkpoint_dir)\n\n self.saver.save(self.sess, os.path.join(checkpoint_dir, self.model_name+'.model'), global_step=step)\n\n def load(self, checkpoint_dir):\n print(\" [*] Reading checkpoints...\")\n checkpoint_dir = os.path.join(checkpoint_dir, self.model_dir)\n\n ckpt = tf.train.get_checkpoint_state(checkpoint_dir)\n if ckpt and ckpt.model_checkpoint_path:\n ckpt_name = os.path.basename(ckpt.model_checkpoint_path)\n self.saver.restore(self.sess, os.path.join(checkpoint_dir, ckpt_name))\n counter = int(ckpt_name.split('-')[-1])\n print(\" [*] Success to read {}\".format(ckpt_name))\n return True, counter\n else:\n print(\" [*] Failed to find a checkpoint\")\n return False, 0\n\n def test(self):\n tf.global_variables_initializer().run()\n\n self.saver = tf.train.Saver()\n could_load, checkpoint_counter = self.load(self.checkpoint_dir)\n\n if could_load:\n print(\" [*] Load SUCCESS\")\n else:\n print(\" [!] Load failed...\")\n\n test_feed_dict = {\n self.test_inptus: self.test_x,\n self.test_labels: self.test_y\n }\n\n\n test_accuracy = self.sess.run(self.test_accuracy, feed_dict=test_feed_dict)\n print(\"test_accuracy: {}\".format(test_accuracy))\n\ndef ConvLayer(inp,h,w,inc,outc,training,padding='SAME',strides=[1,1,1,1],name='Conv2d'):\n with tf.name_scope(name):\n weight = tf.Variable(tf.truncated_normal([h,w,inc,outc],mean=0,stddev=1e-3),name='weight')\n bias = tf.Variable(tf.truncated_normal([outc],mean=0,stddev=1e-8),name='bias')\n out = tf.nn.conv2d(inp,weight,padding=padding,name='conv',strides=strides) + bias\n out = tf.layers.batch_normalization(out,training=training)\n out = tf.nn.relu(out)\n return out\n\ndef getRes18(inp, num_class, is_training=True, reuse=False):\n with tf.variable_scope(\"Resnet\", reuse=reuse):\n residual_block = resblock\n residual_list = get_residual_layer(18)\n\n ch = 32\n tmp = conv(inp, channels=ch, kernel=3, stride=1, scope='conv')\n\n L224 = tmp\n\n\n for i in range(residual_list[0]) :\n tmp = residual_block(tmp, channels=ch, is_training=is_training, downsample=False, scope='resblock0_' + str(i))\n\n ########################################################################################################\n\n L112 = residual_block(tmp, channels=ch*2, is_training=is_training, downsample=True, scope='resblock1_0')\n tmp = L112\n for i in range(1, residual_list[1]) :\n tmp = residual_block(tmp, channels=ch*2, is_training=is_training, downsample=False, scope='resblock1_' + str(i))\n\n ########################################################################################################\n\n L56 = residual_block(tmp, channels=ch*4, is_training=is_training, downsample=True, scope='resblock2_0')\n tmp = L56\n for i in range(1, residual_list[2]) :\n tmp = residual_block(tmp, channels=ch*4, is_training=is_training, downsample=False, scope='resblock2_' + str(i))\n\n\n\n '''改进二 最后一段接短点 \n ########################################################################################################\n\n L28 = residual_block(tmp, channels=ch*8, is_training=is_training, downsample=True, scope='resblock_3_0')\n x1 = batch_norm(L28, is_training, scope='batch_normx1')\n x2 = tf.nn.leaky_relu(x1)\n x2 = conv(x2, channels=ch*16,kernel=3,scope='resblock_3_' + str(i))\n\n ########################################################################################################\n\n x3 = batch_norm(x2, is_training, scope='batch_normx3')\n x3 = tf.nn.leaky_relu(x3)\n x3 = global_avg_pooling(x3)\n logitMid = dropout(x3, is_training)\n logitFinal = fully_conneted(logitMid, units=num_class, scope='logitFinal')\n '''\n\n ''' 改进一:中间直接解出来'''\n L28 = residual_block(tmp, channels=ch * 8, is_training=is_training, downsample=True, scope='resblock_3_0')\n\n c1 = conv(L56,ch * 4,scope='appendc1')\n c1 = batch_norm(c1,is_training,scope='appendc1')\n c1 = relu(c1)\n c1 = tf.nn.max_pool(c1,[1,2,2,1],[1,2,2,1],'SAME')\n c2 = conv(c1, ch * 8,scope='appendc2')\n c2 = batch_norm(c2, is_training,scope='appendc2')\n c2 = relu(c2)\n x3 = global_avg_pooling(c2)\n logitMid = dropout(x3, is_training)\n logitFinal = fully_conneted(logitMid, units=num_class, scope='logitFinal')\n\n\n ''' 原始设置 -- 目前最佳 周五\n ########################################################################################################\n\n L28 = residual_block(tmp, channels=ch*8, is_training=is_training, downsample=True, scope='resblock_3_0')\n tmp = L28\n tmp = resblockSpecial1(tmp, channels=ch*16, is_training=is_training, downsample=True, scope='resblock_3_' + str(i))\n\n ######################################################################################################## \n\n x1 = batch_norm(tmp, is_training, scope='batch_norm')\n x2 = tf.nn.leaky_relu(x1)\n x3 = global_avg_pooling(x2)\n logitMid = dropout(x3, is_training)\n logitFinal = fully_conneted(logitMid, units=num_class, scope='logitFinal')\n '''\n\n '''改进三:\n L28 = residual_block(tmp, channels=ch*8, is_training=is_training, downsample=True, scope='resblock_3_0')\n c1 = ConvLayer(L28,3,3,256,512,is_training,strides=[1,2,2,1])\n c1 = tf.nn.max_pool(c1,[1,2,2,1],strides=[1,2,2,1],padding='SAME')\n c2 = ConvLayer(c1,7,7,512,1024,is_training,strides=[1,2,2,1],padding='VALID')\n logitMid = dropout(c2, is_training)\n logitFinal = fully_conneted(logitMid, units=num_class, scope='logitFinal')\n ##\n '''\n\n\n endPoints = dict()\n endPoints['L224'] = L224\n endPoints['L112'] = L112\n endPoints['L56'] = L56\n endPoints['L28'] = L28\n endPoints['logitFinal'] = logitFinal\n\n return endPoints\n\n\ndef getRes18Dig(inp, num_class, choice,is_training=True, reuse=False):\n with tf.variable_scope(\"Resnet\", reuse=reuse):\n residual_block = resblock\n residual_list = get_residual_layer(18)\n\n ch = 32\n tmp = conv(inp, channels=ch, kernel=3, stride=1, scope='conv')\n\n L224 = tmp\n\n\n for i in range(residual_list[0]) :\n tmp = residual_block(tmp, channels=ch, is_training=is_training, downsample=False, scope='resblock0_' + str(i))\n\n ########################################################################################################\n\n L112 = residual_block(tmp, channels=ch*2, is_training=is_training, downsample=True, scope='resblock1_0')\n tmp = L112\n for i in range(1, residual_list[1]) :\n tmp = residual_block(tmp, channels=ch*2, is_training=is_training, downsample=False, scope='resblock1_' + str(i))\n\n ########################################################################################################\n\n L56 = residual_block(tmp, channels=ch*4, is_training=is_training, downsample=True, scope='resblock2_0')\n tmp = L56\n for i in range(1, residual_list[2]) :\n tmp = residual_block(tmp, channels=ch*4, is_training=is_training, downsample=False, scope='resblock2_' + str(i))\n\n\n if choice == 1:\n '''改进二 最后一段接短点 '''\n ########################################################################################################\n\n L28 = residual_block(tmp, channels=ch*8, is_training=is_training, downsample=True, scope='resblock_3_0')\n x1 = batch_norm(L28, is_training, scope='batch_normx1')\n x2 = tf.nn.leaky_relu(x1)\n x2 = conv(x2, channels=ch*16,kernel=3,scope='resblock_3_' + str(i))\n\n ########################################################################################################\n\n x3 = batch_norm(x2, is_training, scope='batch_normx3')\n x3 = tf.nn.leaky_relu(x3)\n x3 = global_avg_pooling(x3)\n logitMid = dropout(x3, is_training)\n logitFinal = fully_conneted(logitMid, units=num_class, scope='logitFinal')\n\n elif choice == 2:\n ''' 改进一:中间直接解出来'''\n L28 = residual_block(tmp, channels=ch * 8, is_training=is_training, downsample=True, scope='resblock_3_0')\n\n c1 = conv(L56, ch * 4, scope='appendc1')\n c1 = batch_norm(c1, is_training, scope='appendc1')\n c1 = relu(c1)\n c1 = tf.nn.max_pool(c1, [1, 2, 2, 1], [1, 2, 2, 1], 'SAME')\n c2 = conv(c1, ch * 8, scope='appendc2')\n c2 = batch_norm(c2, is_training, scope='appendc2')\n c2 = relu(c2)\n x3 = global_avg_pooling(c2)\n logitMid = dropout(x3, is_training)\n logitFinal = fully_conneted(logitMid, units=num_class, scope='logitFinal')\n elif choice == 3:\n ''' 原始设置 -- 目前最佳 周五'''\n ########################################################################################################\n\n L28 = residual_block(tmp, channels=ch*8, is_training=is_training, downsample=True, scope='resblock_3_0')\n tmp = L28\n tmp = resblockSpecial1(tmp, channels=ch*16, is_training=is_training, downsample=True, scope='resblock_3_' + str(i))\n\n ########################################################################################################\n\n x1 = batch_norm(tmp, is_training, scope='batch_norm')\n x2 = tf.nn.leaky_relu(x1)\n x3 = global_avg_pooling(x2)\n logitMid = dropout(x3, is_training)\n logitFinal = fully_conneted(logitMid, units=num_class, scope='logitFinal')\n\n elif choice == 4:\n '''改进三:'''\n L28 = residual_block(tmp, channels=ch*8, is_training=is_training, downsample=True, scope='resblock_3_0')\n c1 = ConvLayer(L28,3,3,256,512,is_training,strides=[1,2,2,1])\n c1 = tf.nn.max_pool(c1,[1,2,2,1],strides=[1,2,2,1],padding='SAME')\n c2 = ConvLayer(c1,7,7,512,1024,is_training,strides=[1,2,2,1],padding='VALID')\n logitMid = dropout(c2, is_training)\n logitFinal = fully_conneted(logitMid, units=num_class, scope='logitFinal')\n ##\n endPoints = dict()\n endPoints['L224'] = L224\n endPoints['L112'] = L112\n endPoints['L56'] = L56\n endPoints['L28'] = L28\n endPoints['logitFinal'] = logitFinal\n\n return endPoints\n\n\ndef getRes18Cls(inp, num_class, is_training=True):\n residual_block = resblock\n residual_list = get_residual_layer(18)\n ch = 32\n x = conv(inp, channels=ch, kernel=3, stride=1, scope='conv')\n\n for i in range(residual_list[0]):\n x = residual_block(x, channels=32, is_training=is_training, downsample=False, scope='resblock0_' + str(i))\n\n ########################################################################################################\n\n x = residual_block(x, channels= 64, is_training=is_training, downsample=True, scope='resblock1_0')\n\n for i in range(1, residual_list[1]):\n x = residual_block(x, channels=64, is_training=is_training, downsample=False, scope='resblock1_' + str(i))\n\n ########################################################################################################\n\n x = residual_block(x, channels=128, is_training=is_training, downsample=True, scope='resblock2_0')\n\n for i in range(1, residual_list[2]):\n x = residual_block(x, channels=128, is_training=is_training, downsample=False, scope='resblock2_' + str(i))\n\n ########################################################################################################\n\n x = residual_block(x, channels=256, is_training=is_training, downsample=True, scope='resblock_3_0')\n\n ########################################################################################################\n\n x = batch_norm(x, is_training, scope='batch_norm1')\n x = relu(x)\n x = conv(x,channels=512,kernel=3)\n x = batch_norm(x, is_training, scope='batch_norm2')\n x = relu(x)\n x = global_avg_pooling(x)\n x = dropout(x,is_training)\n x = fully_conneted(x, units=num_class, scope='logit')\n\n return x","sub_path":"resTool/ResNetGen.py","file_name":"ResNetGen.py","file_ext":"py","file_size_in_byte":22343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"303504270","text":"import argparse\r\nimport sys\r\nimport os\r\nfrom jinja2 import Environment, FileSystemLoader\r\nparser = argparse.ArgumentParser(\r\n description='Parser to install programs on dockers')\r\nparser.add_argument('--roles', dest=\"roles\", default=None,\r\n type=str, help=\"tasks for remote dockers\", required=False)\r\nargs = parser.parse_args()\r\nroles = args.roles\r\n\r\ndef main(roles):\r\n listOfTasks = roles.split(\",\")\r\n for i in listOfTasks:\r\n print(i)\r\n tempFile = 'playbook.yml.j2'\r\n file_loader = FileSystemLoader(\".\")\r\n env = Environment(loader=file_loader)\r\n test = True\r\n template = env.get_template(tempFile)\r\n output = template.render(roles=listOfTasks)\r\n with open(\"playbook.yml\", \"w\") as f:\r\n f.write(output)\r\nmain(roles)","sub_path":"dynamic-playbook2.py","file_name":"dynamic-playbook2.py","file_ext":"py","file_size_in_byte":777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"92749826","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Apr 23 09:25:54 2020\n\n@author: gregoryvanbeek\n\"\"\"\n\nimport os,sys\nimport numpy as np\n#import matplotlib.pyplot as plt\nimport pandas as pd\nimport seaborn as sb\n\nfile_dirname = os.path.dirname(os.path.abspath('__file__'))\nsys.path.insert(1,os.path.join(file_dirname))\nfrom chromosome_and_gene_positions import chromosome_position, chromosomename_roman_to_arabic\nfrom chromosome_names_in_files import chromosome_name_bedfile\n\n#%%\ndef chromosome_insertion_periodicity(chromosome=None,bed_file=None,gff_file=None,printing=False):\n '''Determines statistical values for the transposon insertion per chromosome.\n When the printing variable is set to True, it prints these values and creates a plot for showing the distribution of the distance between insertions in terms of basepairs.\n The functions returns the distance between insertions in terms of basepairs for the chromosome given as a roman numeral.\n When no chromosome is given, the return variable contains all chromosome with a list of distances between insertions in the form of a dictionary.\n '''\n\n#%% USED FILES\n if gff_file is None:\n import os\n file_dirname = os.path.dirname(os.path.abspath('__file__'))\n if os.path.isfile(os.path.join(file_dirname,'Data_Files','Saccharomyces_cerevisiae.R64-1-1.99.gff3')):\n gff_file = os.path.join(file_dirname,'Data_Files','Saccharomyces_cerevisiae.R64-1-1.99.gff3')\n else:\n gff_file = os.path.join(file_dirname,'..','Data_Files','Saccharomyces_cerevisiae.R64-1-1.99.gff3')\n#%% GET CHROMOSOME START AND END POSTIONS\n chr_length_dict, chr_start_pos_dict, chr_end_pos_dict = chromosome_position(gff_file)\n\n#%% GET ROMAN ARABIC NUMERALS\n roman_to_arabic_dict = chromosomename_roman_to_arabic()[1]\n chromosome_romannames_list = []\n for roman in roman_to_arabic_dict:\n chromosome_romannames_list.append(roman)\n\n#%% OPEN BED FILE\n with open(bed_file) as f:\n lines = f.readlines()\n\n#%% GET NAMES FOR THE CHROMOSOMES IN THE BED FILE\n# chrom_names_dict = {}\n# chrom_start_index_dict = {}\n# chrom_end_index_dict = {}\n# chrom_name = ''\n# chr_counter = 0\n# line_counter = 0\n# stop_loop = False\n# while stop_loop is False:\n# line = lines[line_counter]\n# chrom_name_current = line.split(' ')[0].replace('chr','')\n# if not chrom_name_current.startswith('track'): #SKIP HEADER\n# if not chrom_name_current.startswith('M'): #SKIP MITOCHRONDRIAL CHROMOSOMES\n# if chrom_name_current != chrom_name:\n# chrom_names_dict[chromosome_romannames_list[chr_counter]] = chrom_name_current\n# chrom_name = chrom_name_current\n## print('Chromosome ',chromosome_romannames_list[chr_counter], 'is ',chrom_name_current)\n# \n# chrom_start_index_dict[chromosome_romannames_list[chr_counter]] = line_counter #GET START INDEX IN THE BED FILE OF THE CURENT CHROMOSOME\n# if chr_counter != 0:\n# chrom_end_index_dict[chromosome_romannames_list[chr_counter-1]] = line_counter-1 #GET THE END INDEX IN THE BED OF THE PREVIOUS CHROMOSOME (SKIP FOR THE FIRST CHROMOSOME)\n#\n# chr_counter += 1\n#\n# elif chrom_name_current.startswith('M'):\n# chrom_end_index_dict[chromosome_romannames_list[-1]] = line_counter-1 #GET THE END INDEX IN THE BED FILE FOR THE FINAL CHROMOSOME\n# stop_loop = True\n# \n# line_counter += 1\n\n chrom_names_dict,chrom_start_index_dict, chrom_end_index_dict= chromosome_name_bedfile(lines)\n\n\n#%% DETERMINE STATISTICS FOR INDIVIDUAL CHROMOSOMES AND PUT THE RESULTS IN A DICT\n if chromosome != None:\n chromosome = chromosome.upper()\n chrom_loop = {}\n chrom_loop[chromosome] = chrom_names_dict.get(chromosome)\n else:\n chrom_loop = chrom_names_dict\n\n bp_between_tn_insertions_dict = {}\n reads_per_tn_dict = {}\n for chrom in chrom_loop:\n tn_insertion_position_list = []\n reads_per_tn_list = []\n for line in lines[chrom_start_index_dict.get(chrom):chrom_end_index_dict.get(chrom)+1]:\n line = line.strip('\\n').split()\n tn_insertion_position_list.append(int(line[1]))\n reads_per_tn_list.append((int(line[4])-100)/20)\n bp_between_tn_insertions = [abs(y-x) for x, y in zip(tn_insertion_position_list[:-1], tn_insertion_position_list[1:])]\n bp_between_tn_insertions.insert(0,tn_insertion_position_list[0]) #ADD START OF GENE (bp=0)\n bp_between_tn_insertions.append(chr_length_dict.get(chrom) - tn_insertion_position_list[-1]) #ADD END OF GENE (bp=INDEX LAST TN - GENE LENGTH)\n bp_between_tn_insertions_dict[chrom] = bp_between_tn_insertions\n reads_per_tn_dict[chrom] = reads_per_tn_list\n\n tn_insertion_meanfrequency = np.nanmean(bp_between_tn_insertions)\n tn_insertion_stdfrequency = np.nanstd(bp_between_tn_insertions)\n tn_insertion_medianfrequency = np.nanmedian(bp_between_tn_insertions)\n if printing != False:\n print('')\n print('For chromosome ',chrom,' with length ',chr_length_dict.get(chrom) ,':')\n print('Number of transposon insertions is ', len(reads_per_tn_list))\n print('Coverage is %.2f percent' % (len(tn_insertion_position_list)/chr_length_dict.get(chrom)*100))\n print('Mean transposon insertion periodicity is once every %.2f bp' % tn_insertion_meanfrequency)\n print('Standard deviation in transposon insertion periodicity is %.2f' % tn_insertion_stdfrequency)\n print('Median transposon insertion periodicity is once every %.2f bp' % tn_insertion_medianfrequency)\n print('Largest area devoid of transposons is %.2f' % max(bp_between_tn_insertions))\n print('Mean number of reads per transposon is %.2f' % np.nanmean(reads_per_tn_list))\n print('Median number of reads per transposon is %.2f' % np.nanmedian(reads_per_tn_list))\n print('')\n\n#%% APPLY AUTOCORRELATION FOR CHECKING THE PERIODICITY\n\n #MAKE LIST OF ALL INSERTION LOCATIONS AND HOW MANY INSERTIONS EACH LOCATION HAS\n# for chrom in chrom_loop:\n# number_of_insertions = [0]*chr_length_dict.get(chrom)\n# for ins in tn_insertion_position_list:\n# number_of_insertions[ins] += 1\n# \n# norm = number_of_insertions - np.mean(number_of_insertions)\n# n = norm.size\n# corr = np.correlate(norm, norm, mode='same')\n# autocorr = corr[n//2 + 1:] / (np.var(number_of_insertions) * np.arange(n-1, n//2, -1))\n# lag = np.abs(autocorr).argmax() + 1\n# print(lag)\n# r = autocorr[lag-1]\n# print(r)\n \n#%% DETERMINE STATISTICS FOR THE ENTIRE GENOME\n if chromosome == None:\n bp_between_tn_insertions_genome = []\n number_tn_insertions_list = []\n reads_per_tn_genome = []\n for chrom in chrom_loop:\n #the next line includes the distance between the start of each chromosome and the first insertion and the distance between the last insertion and the end of the chromosome.\n #This might not be accurate. Please check!\n for bp_between in bp_between_tn_insertions_dict.get(chrom):\n bp_between_tn_insertions_genome.append(bp_between)\n number_tn_insertions_list.append(len(bp_between_tn_insertions_dict.get(chrom)))\n# number_tn_insertions_list.append(sum(x > 0 for x in alltransposoncounts_dict.get(chrom)))\n\n for reads_tn in reads_per_tn_dict.get(chrom):\n reads_per_tn_genome.append(reads_tn)\n\n if printing != False:\n print('')\n print('For the entire genome:')\n print('Coverage is %.2f percent' % (sum(number_tn_insertions_list)/sum(chr_length_dict.values())*100))\n print('Mean transposon insertion periodicity for the entire genome is %.2f' % np.nanmean(bp_between_tn_insertions_genome))\n print('Median transposon insertion periodicity for the entire genome is %.2f' % np.nanmedian(bp_between_tn_insertions_genome))\n print('Mean number of reads per transposon for the entire genome is %.2f' % np.nanmean(reads_per_tn_genome))\n print('Median number of reads per transposon for the entire genome is %.2f' % np.nanmedian(reads_per_tn_genome))\n#%% DETERMINE THE DISTRIBUTION OF THE NUMBER OF BP BETWEEN SUBSEQUENT TRANSPOSON INSERTIONS\n\n if printing != False:\n if chromosome != None:\n bp_between_tn_insertions_norm_list = [x/chr_length_dict.get(chromosome) for x in bp_between_tn_insertions_dict.get(chromosome)]\n# df = pd.DataFrame(data=bp_between_tn_insertions_dict.get(chromosome))\n df = pd.DataFrame(data=bp_between_tn_insertions_norm_list)\n df.columns = [chromosome]\n df_melt = df.melt(var_name='chromosomes',value_name='bp between insertions')\n elif chromosome == None:\n bp_between_tn_insertions_norm_list = [x/chr_length_dict.get('I') for x in bp_between_tn_insertions_dict.get('I')]\n df = pd.DataFrame(data=bp_between_tn_insertions_norm_list)\n for chrom in chrom_loop:\n if chrom != 'I':\n bp_between_tn_insertions_norm_list = [x/chr_length_dict.get(chrom) for x in bp_between_tn_insertions_dict.get(chrom)]\n df_temp = pd.DataFrame(data=bp_between_tn_insertions_norm_list)\n df = pd.concat([df,df_temp], axis=1)\n df.columns = chromosome_romannames_list\n df_melt = df.melt(var_name='chromosomes',value_name='bp between insertions')\n \n v = sb.violinplot(x='chromosomes',y='bp between insertions',data=df_melt,inner='quartile',gridsize=3000, cut=0)\n v.set_yscale('log')\n\n#%%\n return(bp_between_tn_insertions_dict)\n\n#%%\nif __name__ == '__main__':\n chromosome_insertion_periodicity(chromosome='xvi',bed_file=r\"C:\\Users\\gregoryvanbeek\\Documents\\GitHub\\LaanLab-SATAY-DataAnalysis\\satay_analysis_testdata\\Output_Processing\\Cerevisiae_WT2_Michel2017_trimmed1.bam.bed\",printing=True)","sub_path":"python_modules/statistics_perchromosome.py","file_name":"statistics_perchromosome.py","file_ext":"py","file_size_in_byte":10174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"457022106","text":"\"\"\"\nProblem:\n\nA self-dividing number is a number that is divisible by every digit it contains.\nFor example, 128 is a self-dividing number because 128 % 1 == 0, 128 % 2 == 0, and 128 % 8 == 0.\nAlso, a self-dividing number is not allowed to contain the digit zero.\nGiven a lower and upper number bound, output a list of every possible self dividing number, \nincluding the bounds if possible.\n\"\"\"\n\nclass Solution:\n def selfDividingNumbers(self, left, right):\n \"\"\"\n :type left: int\n :type right: int\n :rtype: List[int]\n \"\"\"\n selfDividing = []\n for i in range(left, right+1):\n string = str(i)\n for j in range(len(string)):\n if int(string[j]) == 0:\n break\n if i % int(string[j]) != 0:\n break\n else:\n selfDividing.append(i)\n return selfDividing\n","sub_path":"leetcode/easy/Self Dividing Numbers/self-dividing-numbers.py","file_name":"self-dividing-numbers.py","file_ext":"py","file_size_in_byte":913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"170669119","text":"# Largest prime factor\n\n# The prime factors of 13195 are 5, 7, 13 and 29.\n# What is the largest prime factor of the number 600851475143 ?\n\nfrom functools import reduce\n\ndef primeFactor(number):\n\n\tfactors = [number]\n\tprimes = []\n\n\t# Taken from http://stackoverflow.com/questions/6800193/what-is-the-most-efficient-way-of-finding-all-the-factors-of-a-number-in-python\n\tfactors = reduce(list.__add__, ([factor, number//factor] for factor in range(1, int(number**0.5)+1) if number % factor == 0))\n\n\tfactors.remove(1)\n\t\n\tfor i in factors:\n\t\tisPrime = True\n\t\tfor j in range(2,i):\n\t\t\tif i % j == 0:\n\t\t\t\tisPrime = False\n\t\t\t\tbreak\n\t\tif isPrime:\n\t\t\tprimes.append(i)\n\n\n\treturn sorted(primes)\n\n\nprint(primeFactor(600851475143))","sub_path":"Problems/003/003 Largest prime factor.py","file_name":"003 Largest prime factor.py","file_ext":"py","file_size_in_byte":715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"604306851","text":"import json, random, time, sys\nimport transactionMaker as tm\nimport minerUtil as ut\ndebugging = False\nrandom.seed()\n\ndef calculateDifficulty(defaultDifficulty):\n\twith open('json/minerBlockchain.json', 'r+') as blockchainFile:\n\t\tblockchain = blockchainFile.read()\n\t\t#return default if its the first one\n\t\tif blockchain == '' or blockchain == '\\n':\n\t\t\treturn defaultDifficulty\n\t\tblockchain = json.loads(blockchain)\n\n\t\t#find time bewteen last two blocks\n\t\ttimeDiff = blockchain[-1]['header']['timeStamp'] - blockchain[-2]['header']['timeStamp']\n\n\t\t#if average is more than 2 minutes return previous block difficulty - 2\n\t\tif timeDiff > 120:\n\t\t\treturn blockchain[-1]['header']['difficultyTarget'] - 2\n\t\t#if average is less than 2 minutes return previous block difficulty + 2\n\t\treturn blockchain[-1]['header']['difficultyTarget'] + 2\n\n#creates money out of nowhere for the miner and adds transaction fees\n#return json string of coinbase transaction\ndef createCoinbaseTransaction(transactions):\n\tgeneration = 50\n\tfee = 0\n\tfor transaction in transactions:\n\t\ttransaction = json.loads(transaction)\n\t\ttransaction = json.loads(transaction['transaction'])\n\t\tfee += transaction['value'] - transaction['payment'] - transaction['change']\n\n\tcoinbaseTransaction = {'sender' : None ,'receiver' : ut.getMinerKey(), 'value' : fee+generation, 'payment' : fee+generation, 'change' : 0, 'time' : time.ctime()}\n\tcoinbaseTransactionDump = json.dumps(coinbaseTransaction)\n\tcoinbaseTransactionFull = {'transaction' : coinbaseTransactionDump, 'signature' : None}\n\n\treturn json.dumps(coinbaseTransactionFull)\n\ndef generateBlockBody(transactions):\n\tdict = {}\n\tfor transaction in transactions:\n\t\t#if sender is none, then its the coinbase transaction to dont worry about it\n\t\touterTransaction = json.loads(transaction)\n\t\tinnerTransaction = json.loads(outerTransaction['transaction'])\n\t\tif innerTransaction['sender'] == None:\n\t\t\tdigest = ut.hashInput(transaction)\n\t\t\tdict[digest] = transaction\n\t\t#if its not the coinbase transcation make sure the signature matches the transaction\n\t\telif tm.checkSign(transaction):\n\t\t\tdigest = ut.hashInput(transaction)\n\t\t\tdict[digest] = transaction\n\t\telse:\n\t\t\t#send nack\n\t\t\tpass\n\n\treturn dict\n\n#creates a header for the block without a nonce\ndef generateBlockHeader(difficulty, transactions):\n\tblockHeader = {'prevBlockHash':ut.getLastBlockHash(), 'timeStamp':time.time(), 'difficultyTarget':difficulty, 'nonce':None, 'merkleRoot':ut.merkleRoot(transactions)}\n\treturn blockHeader\n\ndef generateNonce(header):\n\tloop = True\n\tbest = 0\n\ttimer = time.time()\n\n\twhile loop:\n\t\t#generate random nonce\n\t\tnonce = random.randint(0,9999999999999)\n\n\t\t#add nonce to header\n\t\theader['nonce'] = nonce\n\t\tdifficulty = header['difficultyTarget']\n\n\t\tdigest = ut.hashInput(json.dumps(header))\n\n\t\t#create string to hold bits as int rather than byte type\n\t\tbits = ''\n\n\t\t#takes bits one at a time and convert to 8-bit binary string\n\t\tfor i in digest:\n\t\t\t#add binary string representation of byte into bits string\n\t\t\tbits += bin(int(i,16))[2:].zfill(8)\n\n\t\tfor i in range(0,difficulty + 1):\n\t\t\t#check if value of bit is 0\n\t\t\tif int(bits[i]) == 0:\n\t\t\t\t#This whole section is just to help visualise progress\n\t\t\t\t# write current highest bit reached, to help visualise progress. Not necessary\n\t\t\t\tif int(i) > best:\n\t\t\t\t\tbest = int(i)\n\t\t\t\tsys.stdout.write('Best: %d \\r' % best)\n\t\t\t\tsys.stdout.flush()\n\n\t\t\t\t#if you have a run of 0s long enough then break out of the loop\n\t\t\t\tif int(i) == difficulty:\n\t\t\t\t\tloop = False\n\t\t\t#if this bit isnt zero move one to next nonce\n\t\t\telse:\n\t\t\t\tbreak\n\t#add time taken\n\tif debugging:\n\t\tprint(\"\\n\\nTime taken: \", time.time() - timer)\n\t#header['processingTime'] = processingTime\n\treturn header\n\n#add block to blockchain\ndef addToBlockchain(header, body):\n\theader = json.dumps(header)\n\tblock = {'header':header, 'body':body}\n\n\twith open('json/minerBlockchain.json', 'r+') as blockchainFile:\n\t\tblockchain = blockchainFile.read()\n\t\t# if the chain is empty put the block in an array first\n\t\tif blockchain == '' or blockchain == '\\n':\n\t\t\tblock = [block]\n\t\t\tblockchainFile.write(json.dumps(block))\n\t\t\treturn True\n\n\t\t#if there is already blocks there append it to the chain array\n\t\tblockchain = json.loads(blockchain)\n\t\tblockchain.append(block)\n\t\tblockchainFile.seek(0)\n\t\tblockchainFile.write(json.dumps(blockchain))\n\n\t\treturn json.dumps(blockchain)\n","sub_path":"minerFunctions.py","file_name":"minerFunctions.py","file_ext":"py","file_size_in_byte":4345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"478433074","text":"#!/usr/bin/env python\n\n'''\nCreated on June 6, 2015\ngoHyperG.py\n- The purpose of this script is to calculate GO enrichment using hypergeometric test\n\n- INPUT:\n - genelist a file with a list of genes (required)\n - a goterm association file (it doesn't have to be go-terms\n - a file with description of the go-terms.\n\n- OUTPUT:\n - a tab delimited file / table summarizing the terms and their p-values\n\n@author: mkatari\n'''\n__author__ = 'manpreetkatari'\n\nfrom optparse import OptionParser\nfrom scipy.stats import hypergeom\nfrom statsmodels.sandbox.stats.multicomp import fdrcorrection0\nimport sys\n\n##################################################\n# Do all the parsing of command line options here\n##################################################\n\ndef parseArguments():\n parser = OptionParser()\n parser.add_option(\"-g\", \"--genelist\", dest=\"genelistfile\", default=\"cassava_genelist.txt\",\n help=\"specify path to file with list of genes\")\n parser.add_option(\"-a\", \"--associationfile\", dest=\"associationfile\", default=\"cassavaV61.go\",\n help=\"association file\")\n parser.add_option(\"-d\", \"--description\", dest=\"descriptionfile\", default=\"/export/apps/mkatari-ilri/go.names.txt\",\n help=\"file containing the description of the terms that are in association file\")\n (options, args) = parser.parse_args()\n return options, parser\n\n##################################################\n# load association files\n##################################################\n\ndef loadAssociation(associationfile):\n fh = open(associationfile, 'r')\n allterms = {}\n allgenes = {}\n\n for i in fh.readlines():\n linesplit = i.split()\n if len(linesplit) < 2:\n continue\n\n gene = linesplit[0]\n # print(gene)\n term = linesplit[1]\n # print(term)\n eachterm = term.split(\",\")\n\n for e in eachterm:\n if gene in allgenes.keys():\n if e in allgenes[gene]:\n pass\n else:\n allgenes[gene].append(e)\n else:\n allgenes[gene]=[]\n allgenes[gene].append(e)\n\n if e in allterms.keys():\n if gene in allterms[e]:\n pass\n else:\n allterms[e].append(gene)\n else:\n allterms[e]=[]\n allterms[e].append(gene)\n\n return allgenes,allterms\n\n##################################################\n# load gene list\n##################################################\n\ndef loadGeneList(genelistfile):\n fh = open(genelistfile, 'r')\n genelist = []\n\n for i in fh.readlines():\n linesplit = i.split()\n gene = linesplit[0]\n # print(gene)\n\n if gene in genelist:\n pass\n else:\n genelist.append(gene)\n\n return genelist\n\n##################################################\n# load association name\n##################################################\n\ndef loadassocname(descriptionfile):\n fh = open(descriptionfile, 'r')\n goterm = {}\n\n for i in fh.readlines():\n linesplit = i.split()\n goterm[linesplit.pop(0)] = \" \".join(linesplit)\n\n return goterm\n\n\n##################################################\n# do hyperg test\n##################################################\n\ndef doHyperG(genelist, allgenes, allterms, assocname):\n\n geneswithterms = allgenes.keys()\n termswithgenes = allterms.keys()\n\n M=len(geneswithterms)\n N=len(list(set(geneswithterms).intersection(set(genelist))))\n\n pvalues=[]\n termsingenelist=[]\n termsinbackground=[]\n termname=[]\n\n for t in termswithgenes:\n n = len(allterms[t])\n x = len(list(set(allterms[t]).intersection(set(genelist))))\n if x == 0:\n continue\n\n pvalue = 1.0 - hypergeom.cdf(x,M,n,N)\n pvalues.append(pvalue)\n\n termsingenelist.append(x)\n termsinbackground.append(n)\n termname.append(t)\n\n adjpvalue = list(fdrcorrection0(pvalues)[1])\n\n print(\"\\t\".join([\"Term annotation\", \"pvalue\", \"fdr adj pvalue\",\"Background\",\"Expected\",\"GeneList\",\"Observed\",\"Genes\"]))\n for u in range(0,len(adjpvalue)):\n print(\"\\t\".join([assocname[termname[u]],\n str(pvalues[u]),\n str(adjpvalue[u]),\n str(M),\n str(termsinbackground[u]),\n str(N),\n str(termsingenelist[u]),\n \",\".join(list(set(allterms[termname[u]]).intersection(set(genelist))))]\n )\n )\n\n\n\n##################################################\n##### MAIN #######################################\n##################################################\n\nif __name__ == '__main__':\n allarguments,parser = parseArguments()\n\n # exit if no args provided\n if allarguments.genelistfile is None and allarguments.associationfile is None:\n parser.print_help()\n sys.exit(1)\n\n\n allgenes, allterms = loadAssociation(str(allarguments.associationfile))\n genelist = loadGeneList(str(allarguments.genelistfile))\n assocname = loadassocname(str(allarguments.descriptionfile))\n doHyperG(genelist, allgenes, allterms, assocname)\n\n","sub_path":"goHyperG.py","file_name":"goHyperG.py","file_ext":"py","file_size_in_byte":5328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"373060242","text":"import pyowm\n\nowm = pyowm.OWM('2ebadb0ce2b75afd9f221d5942cd6f98') # API key\n\ndef get_forecast():\n fcst = owm.three_hours_forecast('Tainan')\n\n if fcst.will_have_rain():\n for f in fcst.when_rain():\n print('{} {}\\n'.format(f.get_reference_time('iso'), f.get_status()))\n\nif __name__ == '__main__':\n print('Collecting weather data...')\n get_forecast()","sub_path":"weather.py","file_name":"weather.py","file_ext":"py","file_size_in_byte":377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"351318441","text":"import argparse\n\nimport pandas as pd\n\nfrom data.dataset import two_seconds_dataset\nfrom model.prophet import two_prophet\n\nparse = argparse.ArgumentParser(\"Training!\")\nparse.add_argument(\"--path\", type=str, default=\"../../input/\")\nparse.add_argument(\"--epoch\", type=int, default=30)\nparse.add_argument(\"--file\", type=str, default=\"future.csv\")\nargs = parse.parse_args()\n\ndf, train, valid = two_seconds_dataset(args.path)\n\nif __name__ == \"__main__\":\n prophet_params = pd.read_pickle(\"../../parameters/best_two_params.pkl\")\n forecast = two_prophet(prophet_params, df)\n forecast.to_csv(\"../../submission/\" + args.file, index=False)\n","sub_path":"src/Final-NeuralFBProphet/prophet_two.py","file_name":"prophet_two.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"47873281","text":"#!/usr/bin/env python\n# simulate the tracker without camera involved \nimport numpy as np\nfrom numpy import sin, cos \nimport cv2\nimport time\nimport numpy as np\nfrom math import pi\nfrom geometry_msgs.msg import Vector3\nfrom std_msgs.msg import Float32\nimport rospy\nimport pyrealsense2 as rs\n\nmax_value = 255\nmax_value_H = 360//2\nlow_H = 0\nlow_S = 0\nlow_V = 0\nhigh_H = max_value_H\nhigh_S = max_value\nhigh_V = max_value\nwindow_capture_name = 'Video Capture'\nwindow_detection_name = 'Object Detection'\nlow_H_name = 'Low H'\nlow_S_name = 'Low S'\nlow_V_name = 'Low V'\nhigh_H_name = 'High H'\nhigh_S_name = 'High S'\nhigh_V_name = 'High V'\n\nWidth = 640\nHeight = 480\n\ndef rotate(ROT, x):\n rotx = np.array(ROT[0])\n roty = np.array(ROT[1])\n rotz = np.array(ROT[2])\n \n transx = np.array(ROT[3])\n transy = np.array(ROT[4])\n transz = np.array(ROT[5])\n \n rotx = np.array([[1,0,0],[0, cos(rotx),-sin(rotx)],[0,sin(rotx),cos(rotx)]])\n rotx = np.array(rotx)\n roty = np.array([[cos(roty),0,sin(roty)],[0,1,0],[-sin(roty),0,cos(roty)]])\n roty = np.array(roty)\n rotz = np.array([[cos(rotz),-sin(rotz),0],[sin(rotz),cos(rotz),0],[0,0,1]])\n rotz = np.array(rotz)\n \n rot = np.dot(rotx,roty)\n rot = np.dot(rot,rotz);\n \n rot = np.hstack((rot,np.array([[transx],[transy],[transz]])))\n rot = np.vstack((rot,np.array([0,0,0,1])))\n \n return np.dot(rot,x)\n\ndef on_low_H_thresh_trackbar(val):\n global low_H\n global high_H\n low_H = val\n low_H = min(high_H-1, low_H)\n cv2.setTrackbarPos(low_H_name, window_detection_name, low_H)\ndef on_high_H_thresh_trackbar(val):\n global low_H\n global high_H\n high_H = val\n high_H = max(high_H, low_H+1)\n cv2.setTrackbarPos(high_H_name, window_detection_name, high_H)\ndef on_low_S_thresh_trackbar(val):\n global low_S\n global high_S\n low_S = val\n low_S = min(high_S-1, low_S)\n cv2.setTrackbarPos(low_S_name, window_detection_name, low_S)\ndef on_high_S_thresh_trackbar(val):\n global low_S\n global high_S\n high_S = val\n high_S = max(high_S, low_S+1)\n cv2.setTrackbarPos(high_S_name, window_detection_name, high_S)\ndef on_low_V_thresh_trackbar(val):\n global low_V\n global high_V\n low_V = val\n low_V = min(high_V-1, low_V)\n cv2.setTrackbarPos(low_V_name, window_detection_name, low_V)\ndef on_high_V_thresh_trackbar(val):\n global low_V\n global high_V\n high_V = val\n high_V = max(high_V, low_V+1)\n cv2.setTrackbarPos(high_V_name, window_detection_name, high_V)\n\n# cv2.namedWindow(window_capture_name)\ncv2.namedWindow(window_detection_name)\ncv2.createTrackbar(low_H_name, window_detection_name , low_H, max_value_H, on_low_H_thresh_trackbar)\ncv2.createTrackbar(high_H_name, window_detection_name , high_H, max_value_H, on_high_H_thresh_trackbar)\ncv2.createTrackbar(low_S_name, window_detection_name , low_S, max_value, on_low_S_thresh_trackbar)\ncv2.createTrackbar(high_S_name, window_detection_name , high_S, max_value, on_high_S_thresh_trackbar)\ncv2.createTrackbar(low_V_name, window_detection_name , low_V, max_value, on_low_V_thresh_trackbar)\ncv2.createTrackbar(high_V_name, window_detection_name , high_V, max_value, on_high_V_thresh_trackbar)\n\nclass Tracker:\n \"\"\"\n A basic color tracker, it will look for colors in a range and\n create an x and y offset valuefrom the midpoint\n \"\"\"\n\n def __init__(self, height, width, color_lower, color_upper):\n self.color_lower = color_lower\n self.color_upper = color_upper\n self.midx = int(width / 2)\n self.midy = int(height / 2)\n self.xoffset = 0\n self.yoffset = 0\n # self.depth = 0\n\n def draw_arrows(self, frame):\n \"\"\"Show the direction vector output in the cv2 window\"\"\"\n return frame\n\n def track(self, frame):\n \"\"\"Simple HSV color space tracking\"\"\"\n # resize the frame, blur it, and convert it to the HSV\n # color space\n blurred = cv2.GaussianBlur(frame, (11, 11), 0)\n hsv = cv2.cvtColor(blurred, cv2.COLOR_BGR2HSV)\n\n # construct a mask for the color then perform\n # a series of dilations and erosions to remove any small\n # blobs left in the mask\n # mask = cv2.inRange(hsv, self.color_lower, self.color_upper)\n # (low_H, low_S, low_V), (high_H, high_S, high_V) (0, 0, 0), (7, 255, 255)\n mask = cv2.inRange(hsv, (low_H, low_S, low_V), (high_H, high_S, high_V))\n mask = cv2.erode(mask, None, iterations=2)\n mask = cv2.dilate(mask, None, iterations=2)\n cv2.imshow('mask', mask)\n # find contours in the mask and initialize the current\n # (x, y) center of the ball\n img, cnts, trash= cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL,\n cv2.CHAIN_APPROX_SIMPLE)\n # print(cnts)\n # cnts = cnts[0] # this is a set of points\n center = None\n # only proceed if at least one contour was found\n if len(cnts) > 0:\n # find the largest contour in the mask, then use\n # it to compute the minimum enclosing circle and\n # centroid\n\n c = max(cnts, key=cv2.contourArea)\n # c = max(cnts, cv2.contourArea(cnts))\n ((x, y), radius) = cv2.minEnclosingCircle(c)\n # print( x, y, radius) # \"x = %d, y = %d, r = %d\" % \n M = cv2.moments(c) \n # print(\"XXXXXX\", c)\n\n center = (int(M[\"m10\"] / M[\"m00\"]), int(M[\"m01\"] / M[\"m00\"]))\n \n # if not (M[\"m00\"]==0):\n # center = (int(M[\"m10\"] / M[\"m00\"]), int(M[\"m01\"] / M[\"m00\"]))\n # else:\n # center = (0,0)\n \n # only proceed if the radius meets a minimum size\n if radius > 1:\n # draw the circle and centroid on the frame,\n # then update the list of tracked points\n cv2.circle(frame, (int(x), int(y)), int(radius),\n (0, 255, 255), 2)\n cv2.circle(frame, center, 5, (0, 0, 255), -1)\n\n self.xoffset = int(center[0])\n\n self.yoffset = int(center[1])\n \n else:\n self.xoffset = 0\n self.yoffset = 0\n # self.depth = 0\n else:\n self.xoffset = 0\n self.yoffset = 0\n # self.depth = 0\n return self.xoffset, self.yoffset # , self.depth \n\n\ndef main():\n \n red_lower = (0, 104, 118)\n red_upper = (23, 255, 255)\n\n x_off = [0]\n y_off = [0]\n\n level = 10\n search_num = level**2\n\n for i in range(-10,11):\n for j in range(-10,11):\n x_off.append(i)\n y_off.append(j)\n\n # Configure depth and color streams\n pipeline = rs.pipeline()\n config = rs.config()\n config.enable_stream(rs.stream.depth, Width, Height, rs.format.z16, 30)\n config.enable_stream(rs.stream.color, Width, Height, rs.format.bgr8, 30)\n\n # Start streaming\n profile = pipeline.start(config)\n\n # Intrinsic Matrix\n depth_profile = rs.video_stream_profile(profile.get_stream(rs.stream.depth))\n depth_intrinsics = depth_profile.get_intrinsics()\n\n # Getting the depth sensor's depth scale (see rs-align example for explanation)\n depth_sensor = profile.get_device().first_depth_sensor()\n depth_scale = depth_sensor.get_depth_scale()\n # print(\"Depth Scale is: \" , depth_scale)\n\n # align depth stream to GRB stream\n align_to = rs.stream.color\n align = rs.align(align_to)\n\n # create ball tracker for dilter the color\n redtracker = Tracker(Width, Height, red_lower, red_upper)\n\n # create camera node\n rospy.init_node('position_pub',anonymous = True)\n\n depth_pub = rospy.Publisher(\"depth\",Float32, queue_size = 1)\n depth_state_pub = rospy.Publisher(\"depth_error\",Float32, queue_size = 1)\n rate_pub = rospy.Publisher(\"loop_rate\",Float32, queue_size = 1)\n\n camera_pub = rospy.Publisher('camera_view', Vector3, queue_size = 10)\n##### robot_pub = rospy.Publisher('robot_view',Vector3,queue_size = 10)\n\n # loop rate\n loop_rate = 30\n dt = 1/loop_rate\n rate = rospy.Rate(loop_rate)\n\n while not rospy.is_shutdown():\n\n # Wait for a coherent pair of frames: depth and color\n frames = pipeline.wait_for_frames()\n\n # Align the depth frame to color frame\n aligned_frames = align.process(frames)\n\n # Get aligned frames\n aligned_depth_frame = aligned_frames.get_depth_frame() # aligned_depth_frame is a 640x480 depth image\n color_frame = aligned_frames.get_color_frame()\n\n # Validate that both frames are valid\n if not aligned_depth_frame or not color_frame:\n continue\n\n # depth_frame_ = frames.get_depth_frame()\n color_frame = frames.get_color_frame()\n # if not depth_frame_ or not color_frame:\n # continue\n\n # Convert images to numpy arrays\n depth_image = np.asanyarray(aligned_depth_frame.get_data())\n color_image = np.asanyarray(color_frame.get_data())\n\n depth_intrinsics = rs.video_stream_profile(\n aligned_frames.profile).get_intrinsics()\n\n # X-480 Y-640\n X, Y= redtracker.track(color_image)\n color_image = redtracker.draw_arrows(color_image)\n\n #X = 720\n #Y = 550\n \n\n Depth = rs.depth_frame.get_distance(aligned_depth_frame, X, Y)\n\n X_ = X\n Y_ = Y\n\n TT = 0\n jj = 0\n while (Depth==0):\n\n X = X_ + x_off[jj]\n Y = Y_ + y_off[jj]\n\n Depth = rs.depth_frame.get_distance(aligned_depth_frame, X, Y)\n\n if (Depth!=0):\n depth_pub.publish(Depth)\n\n jj = jj+1\n\n if (Depth!=0) or (jj==search_num):\n if (jj==search_num) and (Depth==0):\n depth_state_pub.publish(0)\n break\n #\n # Depth = depth_image[X,Y]\n # print('X = %.10f, Y = %.10f, Z = %.10f' % (X, Y, Depth))\n\n # print(Depth)\n # Y = 240\n # X = 320\n X, Y, Z= rs.rs2_deproject_pixel_to_point(depth_intrinsics, [X, Y], Depth)\n if Depth!=0:\n camera_pub.publish(Vector3(X,Y,Z))\n rate_pub.publish(0)\n## X, Y, Z, trash = rotate(np.array([pi/2, 0,0,1,2,3]),np.array([X,Y,Z,1]))\n\n## robot_pub.publish(Vector3(X,Y,Z))\n # print('real_depth: ',(Y, X, Depth))\n # Apply colormap on depth image (image must be converted to 8-bit per pixel first)\n depth_colormap = cv2.applyColorMap(cv2.convertScaleAbs(depth_image, alpha=0.03), cv2.COLORMAP_JET)\n\n # Depth = depth_image[X, Y]\n\n # Stack both images horizontally\n images = np.hstack((color_image, depth_colormap))\n\n # images = color_image\n # Show images\n font = cv2.FONT_HERSHEY_SIMPLEX\n cv2.putText(images,'Y: %.4f, X: %.4f Depth: %.4f' % (Y, X, Z),(10,450), font, 0.8,(0,255,0),2,cv2.LINE_AA)\n cv2.namedWindow('RealSense', cv2.WINDOW_AUTOSIZE)\n cv2.imshow('RealSense', images)\n\n key = cv2.waitKey(30)\n if key == ord('q') or key == 27:\n cv2.destroyAllWindows()\n break\n rate.sleep()\n # cv2.waitKey(1)\n\n # Stop streaming\n pipeline.stop()\n \n\nif __name__ == '__main__':\n main()\n","sub_path":"src/kendama/scripts/real_camera_pub.py","file_name":"real_camera_pub.py","file_ext":"py","file_size_in_byte":11297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"543769568","text":"from queue import Queue\nfrom collections import defaultdict\nn=int(input())\n\na=defaultdict(list)\nv=[0]*(n+1)\nl=[0]*(n+1)\n\nfor i in range(n-1):\n\tx,y=map(int,input().split())\n\ta[x].append(y)\n\ta[y].append(x)\n\nlevel=int(input())\n\nq=Queue(maxsize=100)\nq.put(1)\nv[1]=1\nl[1]=1\n\nwhile(not q.empty()):\n\tp=q.get()\n\tfor i in a[p]:\n\t\tif(v[i]==0):\n\t\t\tl[i]=l[p]+1\n\t\t\tq.put(i)\n\t\t\tv[i]=1\n\t\t\t\nprint(l.count(level))\n","sub_path":"level.py","file_name":"level.py","file_ext":"py","file_size_in_byte":397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"362165319","text":"from acados_template import AcadosModel\nfrom casadi import SX, vertcat, sin, cos, norm_2\n\nimport numpy as np\n\ndef export_disturbed_chain_mass_model(n_mass, m, D, L):\n\n model_name = 'chain_mass_ds_' + str(n_mass)\n x0 = np.array([0, 0, 0]) # fix mass (at wall)\n\n M = n_mass - 2 # number of intermediate massesu\n\n nx = (2*M + 1)*3 # differential states\n nu = 3 # control inputs\n\n xpos = SX.sym('xpos', (M+1)*3, 1) # position of fix mass eliminated\n xvel = SX.sym('xvel', M*3, 1)\n u = SX.sym('u', nu, 1)\n xdot = SX.sym('xdot', nx, 1)\n w = SX.sym('w', M*3, 1)\n\n f = SX.zeros(3*M, 1) # force on intermediate masses\n\n for i in range(M):\n f[3*i+2] = - 9.81\n\n for i in range(M+1):\n if i == 0:\n dist = xpos[i*3:(i+1)*3] - x0\n else:\n dist = xpos[i*3:(i+1)*3] - xpos[(i-1)*3:i*3]\n\n scale = D/m*(1-L/ norm_2(dist))\n F = scale*dist\n \n # mass on the right\n if i < M:\n f[i*3:(i+1)*3] -= F\n \n # mass on the left\n if i > 0:\n f[(i-1)*3:i*3] += F\n\n x = vertcat(xpos, xvel)\n\n # dynamics\n f_expl = vertcat(xvel, u, f+w)\n f_impl = xdot - f_expl\n\n model = AcadosModel()\n\n model.f_impl_expr = f_impl\n model.f_expl_expr = f_expl\n model.x = x\n model.xdot = xdot\n model.u = u\n model.p = w\n model.name = model_name\n\n return model\n\n","sub_path":"export_disturbed_chain_mass_model.py","file_name":"export_disturbed_chain_mass_model.py","file_ext":"py","file_size_in_byte":1405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"293351449","text":"from django.contrib.auth.models import AnonymousUser\nfrom rest_framework.test import APITestCase, APIClient\n\nfrom accounts.models import User, UserProfile\nfrom club.models import Club, ClubRating\nfrom club.user_rating.models import UserRating\nfrom club.user_rating.serializers import UserRatingSerializer\n\n\nclass MockRequest:\n def __init__(self, user):\n self.user = user\n\n\ndef user_rating_generator(user_profile, club):\n def r():\n from random import randint\n return randint(1, 10)\n return UserRating(user=user_profile, club=club, overall=r(), operation=r(), facility=r(), newcomer=r(), compulsory=r(),\n meetfreq=r(), age=r(), friendliness=r(), alcohol=r(), comments=f'test{r()}')\n\n\nclass ClubTestCase(APITestCase):\n def setUp(self):\n self.client = APIClient()\n self.user = User.objects.create_user(\n email='testemail@gmail.com',\n username='testuser',\n password='testpwd123',\n )\n self.user.is_active = True\n self.user.save()\n self.user_profile = UserProfile.objects.create(\n user=self.user\n )\n self.club = Club.objects.create(\n admin=self.user_profile,\n activity_type=2,\n category=3,\n subcategory=18\n )\n ClubRating.objects.create(club=self.club)\n UserRating.objects.bulk_create([\n user_rating_generator(self.user_profile, self.club),\n user_rating_generator(self.user_profile, self.club),\n user_rating_generator(self.user_profile, self.club),\n user_rating_generator(self.user_profile, self.club),\n ])\n self.user_ratings = UserRating.objects.all()\n\n def test_user_rating_list(self):\n resp = self.client.get('/api/rating/')\n serializer = UserRatingSerializer(\n self.user_ratings,\n many=True,\n context={'request': MockRequest(AnonymousUser)}\n )\n self.assertEqual(resp.status_code, 200)\n self.assertEqual(resp.data['results'], serializer.data)\n\n def test_user_rating_create(self):\n user = User.objects.create_user(\n email='testemail2@gmail.com',\n username='testuser2',\n password='testpwd123',\n )\n user.is_active = True\n user.save()\n UserProfile.objects.create(\n user=user\n )\n self.client.force_login(user)\n data = {\n 'club': self.club.pk, 'overall': 4, 'operation': 3, 'facility': 3, 'newcomer': 3, 'compulsory': 3,\n 'meetfreq': 3, 'age': 3, 'friendliness': 3, 'alcohol': 3, 'comments': '...'\n }\n resp = self.client.post('/api/rating/', data=data)\n self.assertEqual(resp.status_code, 201)\n\n resp = self.client.post('/api/rating/', data=data)\n self.assertEqual(resp.status_code, 400, \"중복 평가 금지\")\n\n self.client.logout()\n resp = self.client.post('/api/rating/', data=data)\n self.assertEqual(resp.status_code, 403)\n\n def test_user_rating_retrieve(self):\n url = f'/api/rating/{self.user_ratings[0].pk}/'\n resp = self.client.get(url)\n serializer = UserRatingSerializer(\n UserRating.objects.get(pk=self.user_ratings[0].pk),\n context={'request': MockRequest(AnonymousUser)}\n )\n self.assertEqual(resp.status_code, 200)\n self.assertEqual(resp.data, serializer.data)\n\n def test_user_rating_update(self):\n self.client.login(\n username='testemail@gmail.com',\n password='testpwd123'\n )\n data = {\n 'club': self.club.pk, 'overall': 1, 'operation': 1, 'facility': 1, 'newcomer': 1, 'compulsory': 3,\n 'meetfreq': 3, 'age': 1, 'friendliness': 3, 'alcohol': 3, 'comments': ''\n }\n url = f'/api/rating/{self.user_ratings[0].pk}/'\n resp = self.client.put(url, data=data)\n self.assertEqual(resp.status_code, 200)\n\n resp = self.client.patch(url, data={'overall': 3})\n self.assertEqual(resp.status_code, 200)\n self.assertEqual(UserRating.objects.get(pk=self.user_ratings[0].pk).overall, 3)\n\n self.client.logout()\n resp = self.client.post(url, data=data)\n self.assertEqual(resp.status_code, 403)\n\n def test_user_rating_delete(self):\n self.client.login(\n username='testemail@gmail.com',\n password='testpwd123'\n )\n url = f'/api/rating/{self.user_ratings[0].pk}/'\n resp = self.client.delete(url)\n self.assertEqual(resp.status_code, 204)\n\n self.client.logout()\n resp = self.client.delete(url)\n self.assertEqual(resp.status_code, 403)\n","sub_path":"backend/snuclub/club/user_rating/test_api.py","file_name":"test_api.py","file_ext":"py","file_size_in_byte":4726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"298084146","text":"#!/usr/bin/python3\nimport socket, sys, os, argparse, subprocess, struct, string, random, time, gzip\nfrom _thread import start_new_thread\nfrom Crypto.Cipher import AES\nparser = argparse.ArgumentParser(description='q*bert says goodbye')\nparser.add_argument('-p', dest='port', help='Hosting port', required=True, type=int)\nparser.add_argument('-s', dest='host', help='Hosting IP')\nargs = parser.parse_args()\naeskey = 'This is a key123'\naesiv = 'This is an IV456'\n\nif args.host is None:\n args.host = '0.0.0.0'\n\ndef update_aeskeys():\n global aeskey\n global aesiv\n tmpkey = ''.join(random.SystemRandom().choice(string.ascii_letters + string.digits) for _ in range(32))\n tmpiv = ''.join(random.SystemRandom().choice(string.ascii_letters + string.digits) for _ in range(16))\n tmp = do_encrypt(bytes('aeskey '+ tmpkey + ' '+ tmpiv, 'utf-8'))\n aeskey = tmpkey\n aesiv = tmpiv\n return tmp\n\ndef do_encrypt(message):\n if isinstance(message, bytes):\n pass\n else:\n message = bytes(message, 'utf-8')\n message = gzip.compress(message)\n length = 16 - (len(message) % 16)\n message += bytes([length])*length\n obj = AES.new(aeskey, AES.MODE_CBC, aesiv)\n cipher = obj.encrypt(message)\n return cipher\n\ndef do_decrypt(ciphertext):\n obj2 = AES.new(aeskey, AES.MODE_CBC, aesiv)\n message = obj2.decrypt(ciphertext)\n return gzip.decompress(message[:-message[-1]])\n\ndef get_data(conn, buff):\n bs = conn.recv(8)\n try:\n (length,) = struct.unpack('>Q', bs)\n except struct.error as err:\n print(\"{0}\".format(err))\n return 0\n data = b''\n while len(data) < length:\n to_read = length - len(data)\n data += conn.recv(buff if to_read > buff else to_read)\n return data\n\ndef sendit(conn, message):\n length = struct.pack('>Q', len(message))\n conn.sendall(length)\n conn.sendall(message)\n\ndef client(conn, addr, buff):\n reply = ''\n sendit(conn, do_encrypt('Arsenal Backdoor'))\n while True:\n data = get_data(conn, buff)\n if data == 0:\n break\n else:\n print(str(do_decrypt(data).strip(), 'utf-8'))\n while True:\n try:\n reply=input('Enter command for %s: ' %addr[0])\n except ValueError:\n print(\"Bad input\")\n if reply == 'help':\n print('update_key\\nget_file /path/to/file filename\\nsend_file filename /path/to/file')\n elif reply == \"update_key\":\n sendit(conn, update_aeskeys())\n break\n elif 'get_file' in reply:\n sendit(conn, do_encrypt(reply))\n data1 = get_data(conn, buff)\n with open(reply.split(' ')[2], 'wb+') as f:\n f.write(do_decrypt(data1))\n break\n elif 'send_file' in reply:\n sendit(conn, do_encrypt(reply))\n with open(reply.split(' ')[1], 'rb') as f:\n tmp = f.read()\n sendit(conn, do_encrypt(tmp))\n break\n else:\n sendit(conn, do_encrypt('cmd ' + reply))\n break\n if not data:\n break\n conn.close()\n print(\"\\nClosed connection from %s:%s\" %(addr[0],addr[1]))\n if 'sleep' in reply:\n sleepy = int(reply.split(' ')[1])\n for i in range(sleepy, 0, -1):\n sys.stdout.write(\"\\r{0} sleeping for {1} \".format(addr[0], i))\n time.sleep(1)\ndef main():\n s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n buff = 4096\n s.bind((args.host, args.port))\n s.listen(5)\n while True:\n conn, addr = s.accept()\n os.system('clear')\n print(\"\\nConnection received from %s:%s\" %(addr[0], addr[1]))\n try:\n start_new_thread(client, (conn, addr, buff))\n except socket.error:\n sys.stderr.write(\"[Error] %s\\n\" %socket.error.msg[1])\n except KeyboardInterrupt:\n print('[-] Server shutting down...')\n break\n\nif __name__ == '__main__':\n main()\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":4130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"531232147","text":"\"\"\"\nIf the mouse hasn't moved, nudges the mouse every once in a while an imperceptible amount.\nDoes not work well when mouse is not on main monitor.\n\"\"\"\n\n__author__ = 'slefebre'\n\nfrom time import sleep\nimport pyautogui\n\nif __name__ == '__main__':\n SLEEP_TIME = 60 # Time between mouse location checks\n ADJUSTMENT = 10 # Distance to move mouse during inactivity\n pyautogui.FAILSAFE = True\n\n x, y = pyautogui.position()\n\n while True:\n sleep(SLEEP_TIME)\n if (x, y) == pyautogui.position():\n pyautogui.moveRel(ADJUSTMENT, 0)\n ADJUSTMENT *= -1 # Alternate to 'bounce' mouse back and forth rather than drift across screen over time\n x, y = pyautogui.position()\n","sub_path":"automation/mouse_nudge.py","file_name":"mouse_nudge.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"295635864","text":"from typeguard import typechecked\nfrom ai4good.models.model import Model, ModelResult\nfrom ai4good.params.param_store import ParamStore\nfrom ai4good.models.abm.initialise_parameters import Parameters\n# from ai4good.webapp.cm_model_report_utils import *\nimport logging\nfrom . import abm\nimport numpy as np\nimport pandas as pd\nimport math\n\n\n@typechecked\nclass ABM(Model):\n\n ID = 'agent-based-model'\n\n def __init__(self, ps: ParamStore):\n Model.__init__(self, ps)\n\n def id(self) -> str:\n return self.ID\n\n def result_id(self, p: Parameters) -> str:\n return p.sha1_hash()\n\n def run(self, p: Parameters) -> ModelResult:\n \n for i in range(p.number_of_steps):\n \n p.track_states[i, :] = np.bincount(p.population[:, 1].astype(int), minlength=14)\n\n if abm.epidemic_finish(np.concatenate((p.track_states[i, 1:6], p.track_states[i, 7:p.number_of_states])), i):\n break\n p.mild_rec = np.random.uniform(0, 1, p.total_population) > math.exp(0.2 * math.log(0.1)) # Liu et al 2020 The Lancet.\n p.sev_rec = np.random.uniform(0, 1, p.total_population) > math.exp(math.log(63 / 153) / 12) # Cai et al.\n p.pick_sick = np.random.uniform(0, 1, p.total_population) # Get random numbers to determine health states.\n \n if (p.ACTIVATE_INTERVENTION and (i > 0)):\n p.iat1 = i\n p.ACTIVATE_INTERVENTION = False\n p.smaller_movement_radius = 0.001\n p.transmission_reduction = 0.25\n p.foodpoints_location, p.foodpoints_numbers, p.foodpoints_sharing = abm.position_foodline(p.households_location, p.foodline_blocks[0], p.foodline_blocks[1])\n p.local_interaction_space = abm.interaction_neighbours_fast(p.households_location, p.smaller_movement_radius, p.larger_movement_radius, p.overlapping_rages_radius, p.ethnical_corellations)\n p.viol_rate = 0.05 \n p.population[:, 8] = np.where(np.random.rand(p.total_population) < p.viol_rate, 1, 0)\n\n p.population[np.where(p.population[:, 1] > 0), 3] += 1\n\n p.population, p.total_number_of_hospitalized = abm.disease_state_update(\n p.population,\n p.mild_rec,\n p.sev_rec,\n p.pick_sick,\n p.total_number_of_hospitalized)\n \n p.population, p.total_number_of_hospitalized = abm.disease_state_update(\n p.population,\n p.mild_rec,\n p.sev_rec,\n p.pick_sick,\n p.total_number_of_hospitalized,quarantined=True)\n \n p.population = abm.assign_new_infections(p.population,\n p.toilets_sharing,\n p.foodpoints_sharing,\n p.num_toilet_visit,\n p.num_toilet_contact,\n p.num_food_visit,\n p.num_food_contact,\n p.pct_food_visit,\n p.transmission_reduction,\n p.local_interaction_space,\n p.probability_infecting_person_in_household_per_day,\n p.probability_infecting_person_in_foodline_per_day,\n p.probability_infecting_person_in_toilet_per_day,\n p.probability_infecting_person_in_moving_per_day)\n\n p.population = abm.move_hhl_quarantine(p.population, p.probability_spotting_symptoms_per_day)\n\n p.quarantine_back = np.logical_and(p.population[:, 1] == 13, p.population[:, 3] >= p.clearday)\n p.population[p.quarantine_back, 1] = 6\n\n # placeholders for the report\n standard_sol = [{'t': range(p.number_of_steps)}]\n perc = [0] * p.number_of_steps\n percentiles = [perc, perc, perc, perc, perc]\n config_dict = []\n [config_dict.append(dict(\n beta = 0,\n latentRate = 0,\n removalRate = 0,\n hospRate = 0,\n deathRateICU = 0,\n deathRateNoIcu = 0\n )) for _ in range(p.number_of_steps)]\n\n report_raw = [[0]]\n prevalence_age = pd.DataFrame([[0]])\n prevalence_all = pd.DataFrame([[0]])\n cumulative_all = pd.DataFrame([[0]])\n cumulative_age = pd.DataFrame([[0]])\n\n states = ['exposed_tl', 'presymptomatic_tl', 'symptomatic_tl', 'mild_tl', 'severe_tl', 'recovered_tl',\n 'qua_susceptible_tl', 'qua_exposed_tl', 'qua_presymptomatic_tl', 'qua_symptomatic_tl', 'qua_mild_tl',\n 'qua_severe_tl', 'qua_recovered_tl']\n # disease_state_tracker_plot = go.Figure()\n\n mr = ModelResult(self.result_id(p), {\n 'standard_sol': standard_sol,\n 'percentiles': percentiles,\n 'config_dict': config_dict,\n 'params': p,\n 'report': report_raw,\n 'track_states_df': p.track_states,\n 'multiple_categories_to_plot': states,\n 'prevalence_all': prevalence_all,\n 'cumulative_all': cumulative_all,\n 'cumulative_age': cumulative_age\n })\n\n return mr\n\n\n\n","sub_path":"ai4good/models/abm/abm_model.py","file_name":"abm_model.py","file_ext":"py","file_size_in_byte":5751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"479582953","text":"from locust import HttpLocust, TaskSet, task\nimport json\n \nclass UserBehavior(TaskSet):\n\n @task(1) \n def create_post(self):\n \n API_ENDPOINT = 'http://afsconnect1.njit.edu:5681'\n query = \"batman\" \n headers = headers={'Accept' : 'application/json','Content-Type': 'application/json'}\n aString = json.dumps({'query': query ,'searchType':'multipleItemSearch'} )\n self.client.post( url = API_ENDPOINT, \n data = aString, \n headers={'Accept' : 'application/json','Content-Type': 'application/json'} )\n \nclass WebsiteUser(HttpLocust):\n task_set = UserBehavior\n\n ","sub_path":"LoadTesting/nodeServerLocustPOST.py","file_name":"nodeServerLocustPOST.py","file_ext":"py","file_size_in_byte":662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"181300778","text":"# Copyright (c) 2016 Anki, 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 in the file LICENSE.txt or 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\"\"\"\nAutogenerated python message buffer code.\nSource: clad/audio/audioCallbackMessage.clad\nFull command line: ../tools/message-buffers/emitters/Python_emitter.py -C ./src/ -I ../robot/clad/src/ ../coretech/vision/clad/src/ ../coretech/common/clad/src/ -o ../generated/cladPython// clad/audio/audioCallbackMessage.clad\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import print_function\n\ndef _modify_path():\n import inspect, os, sys\n search_paths = [\n '../..',\n '../../../../tools/message-buffers/support/python',\n ]\n currentpath = os.path.abspath(os.path.dirname(inspect.getfile(inspect.currentframe())))\n for search_path in search_paths:\n search_path = os.path.normpath(os.path.abspath(os.path.realpath(os.path.join(currentpath, search_path))))\n if search_path not in sys.path:\n sys.path.insert(0, search_path)\n_modify_path()\n\nimport msgbuffers\n\nAnki = msgbuffers.Namespace()\nAnki.AudioEngine = msgbuffers.Namespace()\nAnki.AudioEngine.Multiplexer = msgbuffers.Namespace()\nAnki.AudioMetaData = msgbuffers.Namespace()\nAnki.AudioMetaData.GameEvent = msgbuffers.Namespace()\n\nfrom clad.audio.audioEventTypes import Anki as _Anki\nAnki.update(_Anki.deep_clone())\n\nclass AudioCallbackDuration(object):\n \"Generated message-passing structure.\"\n\n __slots__ = (\n '_duration', # float_32\n '_estimatedDuration', # float_32\n '_audioNodeId', # uint_32\n '_isStreaming', # bool\n )\n\n @property\n def duration(self):\n \"float_32 duration struct property.\"\n return self._duration\n\n @duration.setter\n def duration(self, value):\n self._duration = msgbuffers.validate_float(\n 'AudioCallbackDuration.duration', value, 'f')\n\n @property\n def estimatedDuration(self):\n \"float_32 estimatedDuration struct property.\"\n return self._estimatedDuration\n\n @estimatedDuration.setter\n def estimatedDuration(self, value):\n self._estimatedDuration = msgbuffers.validate_float(\n 'AudioCallbackDuration.estimatedDuration', value, 'f')\n\n @property\n def audioNodeId(self):\n \"uint_32 audioNodeId struct property.\"\n return self._audioNodeId\n\n @audioNodeId.setter\n def audioNodeId(self, value):\n self._audioNodeId = msgbuffers.validate_integer(\n 'AudioCallbackDuration.audioNodeId', value, 0, 4294967295)\n\n @property\n def isStreaming(self):\n \"bool isStreaming struct property.\"\n return self._isStreaming\n\n @isStreaming.setter\n def isStreaming(self, value):\n self._isStreaming = msgbuffers.validate_bool(\n 'AudioCallbackDuration.isStreaming', value)\n\n def __init__(self, duration=0.0, estimatedDuration=0.0, audioNodeId=0, isStreaming=False):\n self.duration = duration\n self.estimatedDuration = estimatedDuration\n self.audioNodeId = audioNodeId\n self.isStreaming = isStreaming\n\n @classmethod\n def unpack(cls, buffer):\n \"Reads a new AudioCallbackDuration from the given buffer.\"\n reader = msgbuffers.BinaryReader(buffer)\n value = cls.unpack_from(reader)\n if reader.tell() != len(reader):\n raise msgbuffers.ReadError(\n ('AudioCallbackDuration.unpack received a buffer of length {length}, ' +\n 'but only {position} bytes were read.').format(\n length=len(reader), position=reader.tell()))\n return value\n\n @classmethod\n def unpack_from(cls, reader):\n \"Reads a new AudioCallbackDuration from the given BinaryReader.\"\n _duration = reader.read('f')\n _estimatedDuration = reader.read('f')\n _audioNodeId = reader.read('I')\n _isStreaming = bool(reader.read('b'))\n return cls(_duration, _estimatedDuration, _audioNodeId, _isStreaming)\n\n def pack(self):\n \"Writes the current AudioCallbackDuration, returning bytes.\"\n writer = msgbuffers.BinaryWriter()\n self.pack_to(writer)\n return writer.dumps()\n\n def pack_to(self, writer):\n \"Writes the current AudioCallbackDuration to the given BinaryWriter.\"\n writer.write(self._duration, 'f')\n writer.write(self._estimatedDuration, 'f')\n writer.write(self._audioNodeId, 'I')\n writer.write(int(self._isStreaming), 'b')\n\n def __eq__(self, other):\n if type(self) is type(other):\n return (self._duration == other._duration and\n self._estimatedDuration == other._estimatedDuration and\n self._audioNodeId == other._audioNodeId and\n self._isStreaming == other._isStreaming)\n else:\n return NotImplemented\n\n def __ne__(self, other):\n if type(self) is type(other):\n return not self.__eq__(other)\n else:\n return NotImplemented\n\n def __len__(self):\n return (msgbuffers.size(self._duration, 'f') +\n msgbuffers.size(self._estimatedDuration, 'f') +\n msgbuffers.size(self._audioNodeId, 'I') +\n msgbuffers.size(self._isStreaming, 'b'))\n\n def __str__(self):\n return '{type}(duration={duration}, estimatedDuration={estimatedDuration}, audioNodeId={audioNodeId}, isStreaming={isStreaming})'.format(\n type=type(self).__name__,\n duration=self._duration,\n estimatedDuration=self._estimatedDuration,\n audioNodeId=self._audioNodeId,\n isStreaming=self._isStreaming)\n\n def __repr__(self):\n return '{type}(duration={duration}, estimatedDuration={estimatedDuration}, audioNodeId={audioNodeId}, isStreaming={isStreaming})'.format(\n type=type(self).__name__,\n duration=repr(self._duration),\n estimatedDuration=repr(self._estimatedDuration),\n audioNodeId=repr(self._audioNodeId),\n isStreaming=repr(self._isStreaming))\n\nAnki.AudioEngine.Multiplexer.AudioCallbackDuration = AudioCallbackDuration\ndel AudioCallbackDuration\n\n\nclass AudioCallbackMarker(object):\n \"Generated message-passing structure.\"\n\n __slots__ = (\n '_identifier', # uint_32\n '_position', # uint_32\n '_labelTitle', # string[uint_8]\n )\n\n @property\n def identifier(self):\n \"uint_32 identifier struct property.\"\n return self._identifier\n\n @identifier.setter\n def identifier(self, value):\n self._identifier = msgbuffers.validate_integer(\n 'AudioCallbackMarker.identifier', value, 0, 4294967295)\n\n @property\n def position(self):\n \"uint_32 position struct property.\"\n return self._position\n\n @position.setter\n def position(self, value):\n self._position = msgbuffers.validate_integer(\n 'AudioCallbackMarker.position', value, 0, 4294967295)\n\n @property\n def labelTitle(self):\n \"string[uint_8] labelTitle struct property.\"\n return self._labelTitle\n\n @labelTitle.setter\n def labelTitle(self, value):\n self._labelTitle = msgbuffers.validate_string(\n 'AudioCallbackMarker.labelTitle', value, 255)\n\n def __init__(self, identifier=0, position=0, labelTitle=''):\n self.identifier = identifier\n self.position = position\n self.labelTitle = labelTitle\n\n @classmethod\n def unpack(cls, buffer):\n \"Reads a new AudioCallbackMarker from the given buffer.\"\n reader = msgbuffers.BinaryReader(buffer)\n value = cls.unpack_from(reader)\n if reader.tell() != len(reader):\n raise msgbuffers.ReadError(\n ('AudioCallbackMarker.unpack received a buffer of length {length}, ' +\n 'but only {position} bytes were read.').format(\n length=len(reader), position=reader.tell()))\n return value\n\n @classmethod\n def unpack_from(cls, reader):\n \"Reads a new AudioCallbackMarker from the given BinaryReader.\"\n _identifier = reader.read('I')\n _position = reader.read('I')\n _labelTitle = reader.read_string('B')\n return cls(_identifier, _position, _labelTitle)\n\n def pack(self):\n \"Writes the current AudioCallbackMarker, returning bytes.\"\n writer = msgbuffers.BinaryWriter()\n self.pack_to(writer)\n return writer.dumps()\n\n def pack_to(self, writer):\n \"Writes the current AudioCallbackMarker to the given BinaryWriter.\"\n writer.write(self._identifier, 'I')\n writer.write(self._position, 'I')\n writer.write_string(self._labelTitle, 'B')\n\n def __eq__(self, other):\n if type(self) is type(other):\n return (self._identifier == other._identifier and\n self._position == other._position and\n self._labelTitle == other._labelTitle)\n else:\n return NotImplemented\n\n def __ne__(self, other):\n if type(self) is type(other):\n return not self.__eq__(other)\n else:\n return NotImplemented\n\n def __len__(self):\n return (msgbuffers.size(self._identifier, 'I') +\n msgbuffers.size(self._position, 'I') +\n msgbuffers.size_string(self._labelTitle, 'B'))\n\n def __str__(self):\n return '{type}(identifier={identifier}, position={position}, labelTitle={labelTitle})'.format(\n type=type(self).__name__,\n identifier=self._identifier,\n position=self._position,\n labelTitle=msgbuffers.shorten_string(self._labelTitle))\n\n def __repr__(self):\n return '{type}(identifier={identifier}, position={position}, labelTitle={labelTitle})'.format(\n type=type(self).__name__,\n identifier=repr(self._identifier),\n position=repr(self._position),\n labelTitle=repr(self._labelTitle))\n\nAnki.AudioEngine.Multiplexer.AudioCallbackMarker = AudioCallbackMarker\ndel AudioCallbackMarker\n\n\nclass AudioCallbackComplete(object):\n \"Generated message-passing structure.\"\n\n __slots__ = (\n '_eventType', # Anki.AudioMetaData.GameEvent.GenericEvent\n )\n\n @property\n def eventType(self):\n \"Anki.AudioMetaData.GameEvent.GenericEvent eventType struct property.\"\n return self._eventType\n\n @eventType.setter\n def eventType(self, value):\n self._eventType = msgbuffers.validate_integer(\n 'AudioCallbackComplete.eventType', value, 0, 4294967295)\n\n def __init__(self, eventType=Anki.AudioMetaData.GameEvent.GenericEvent.Invalid):\n self.eventType = eventType\n\n @classmethod\n def unpack(cls, buffer):\n \"Reads a new AudioCallbackComplete from the given buffer.\"\n reader = msgbuffers.BinaryReader(buffer)\n value = cls.unpack_from(reader)\n if reader.tell() != len(reader):\n raise msgbuffers.ReadError(\n ('AudioCallbackComplete.unpack received a buffer of length {length}, ' +\n 'but only {position} bytes were read.').format(\n length=len(reader), position=reader.tell()))\n return value\n\n @classmethod\n def unpack_from(cls, reader):\n \"Reads a new AudioCallbackComplete from the given BinaryReader.\"\n _eventType = reader.read('I')\n return cls(_eventType)\n\n def pack(self):\n \"Writes the current AudioCallbackComplete, returning bytes.\"\n writer = msgbuffers.BinaryWriter()\n self.pack_to(writer)\n return writer.dumps()\n\n def pack_to(self, writer):\n \"Writes the current AudioCallbackComplete to the given BinaryWriter.\"\n writer.write(self._eventType, 'I')\n\n def __eq__(self, other):\n if type(self) is type(other):\n return self._eventType == other._eventType\n else:\n return NotImplemented\n\n def __ne__(self, other):\n if type(self) is type(other):\n return not self.__eq__(other)\n else:\n return NotImplemented\n\n def __len__(self):\n return (msgbuffers.size(self._eventType, 'I'))\n\n def __str__(self):\n return '{type}(eventType={eventType})'.format(\n type=type(self).__name__,\n eventType=self._eventType)\n\n def __repr__(self):\n return '{type}(eventType={eventType})'.format(\n type=type(self).__name__,\n eventType=repr(self._eventType))\n\nAnki.AudioEngine.Multiplexer.AudioCallbackComplete = AudioCallbackComplete\ndel AudioCallbackComplete\n\n\nclass CallbackErrorType(object):\n \"Automatically-generated uint_8 enumeration.\"\n Invalid = 0\n EventFailed = 1\n Starvation = 2\n\nAnki.AudioEngine.Multiplexer.CallbackErrorType = CallbackErrorType\ndel CallbackErrorType\n\n\nclass AudioCallbackError(object):\n \"Generated message-passing structure.\"\n\n __slots__ = (\n '_callbackError', # Anki.AudioEngine.Multiplexer.CallbackErrorType\n )\n\n @property\n def callbackError(self):\n \"Anki.AudioEngine.Multiplexer.CallbackErrorType callbackError struct property.\"\n return self._callbackError\n\n @callbackError.setter\n def callbackError(self, value):\n self._callbackError = msgbuffers.validate_integer(\n 'AudioCallbackError.callbackError', value, 0, 255)\n\n def __init__(self, callbackError=Anki.AudioEngine.Multiplexer.CallbackErrorType.Invalid):\n self.callbackError = callbackError\n\n @classmethod\n def unpack(cls, buffer):\n \"Reads a new AudioCallbackError from the given buffer.\"\n reader = msgbuffers.BinaryReader(buffer)\n value = cls.unpack_from(reader)\n if reader.tell() != len(reader):\n raise msgbuffers.ReadError(\n ('AudioCallbackError.unpack received a buffer of length {length}, ' +\n 'but only {position} bytes were read.').format(\n length=len(reader), position=reader.tell()))\n return value\n\n @classmethod\n def unpack_from(cls, reader):\n \"Reads a new AudioCallbackError from the given BinaryReader.\"\n _callbackError = reader.read('B')\n return cls(_callbackError)\n\n def pack(self):\n \"Writes the current AudioCallbackError, returning bytes.\"\n writer = msgbuffers.BinaryWriter()\n self.pack_to(writer)\n return writer.dumps()\n\n def pack_to(self, writer):\n \"Writes the current AudioCallbackError to the given BinaryWriter.\"\n writer.write(self._callbackError, 'B')\n\n def __eq__(self, other):\n if type(self) is type(other):\n return self._callbackError == other._callbackError\n else:\n return NotImplemented\n\n def __ne__(self, other):\n if type(self) is type(other):\n return not self.__eq__(other)\n else:\n return NotImplemented\n\n def __len__(self):\n return (msgbuffers.size(self._callbackError, 'B'))\n\n def __str__(self):\n return '{type}(callbackError={callbackError})'.format(\n type=type(self).__name__,\n callbackError=self._callbackError)\n\n def __repr__(self):\n return '{type}(callbackError={callbackError})'.format(\n type=type(self).__name__,\n callbackError=repr(self._callbackError))\n\nAnki.AudioEngine.Multiplexer.AudioCallbackError = AudioCallbackError\ndel AudioCallbackError\n\n\nclass AudioCallbackInfo(object):\n \"Generated message-passing union.\"\n\n __slots__ = ('_tag', '_data')\n\n class Tag(object):\n \"The type indicator for this union.\"\n callbackDuration = 0 # Anki.AudioEngine.Multiplexer.AudioCallbackDuration\n callbackMarker = 1 # Anki.AudioEngine.Multiplexer.AudioCallbackMarker\n callbackComplete = 2 # Anki.AudioEngine.Multiplexer.AudioCallbackComplete\n callbackError = 3 # Anki.AudioEngine.Multiplexer.AudioCallbackError\n\n @property\n def tag(self):\n \"The current tag for this union.\"\n return self._tag\n\n @property\n def tag_name(self):\n \"The name of the current tag for this union.\"\n if self._tag in self._tags_by_value:\n return self._tags_by_value[self._tag]\n else:\n return None\n\n @property\n def data(self):\n \"The data held by this union. None if no data is set.\"\n return self._data\n\n @property\n def callbackDuration(self):\n \"Anki.AudioEngine.Multiplexer.AudioCallbackDuration callbackDuration union property.\"\n msgbuffers.safety_check_tag('callbackDuration', self._tag, self.Tag.callbackDuration, self._tags_by_value)\n return self._data\n\n @callbackDuration.setter\n def callbackDuration(self, value):\n self._data = msgbuffers.validate_object(\n 'AudioCallbackInfo.callbackDuration', value, Anki.AudioEngine.Multiplexer.AudioCallbackDuration)\n self._tag = self.Tag.callbackDuration\n\n @property\n def callbackMarker(self):\n \"Anki.AudioEngine.Multiplexer.AudioCallbackMarker callbackMarker union property.\"\n msgbuffers.safety_check_tag('callbackMarker', self._tag, self.Tag.callbackMarker, self._tags_by_value)\n return self._data\n\n @callbackMarker.setter\n def callbackMarker(self, value):\n self._data = msgbuffers.validate_object(\n 'AudioCallbackInfo.callbackMarker', value, Anki.AudioEngine.Multiplexer.AudioCallbackMarker)\n self._tag = self.Tag.callbackMarker\n\n @property\n def callbackComplete(self):\n \"Anki.AudioEngine.Multiplexer.AudioCallbackComplete callbackComplete union property.\"\n msgbuffers.safety_check_tag('callbackComplete', self._tag, self.Tag.callbackComplete, self._tags_by_value)\n return self._data\n\n @callbackComplete.setter\n def callbackComplete(self, value):\n self._data = msgbuffers.validate_object(\n 'AudioCallbackInfo.callbackComplete', value, Anki.AudioEngine.Multiplexer.AudioCallbackComplete)\n self._tag = self.Tag.callbackComplete\n\n @property\n def callbackError(self):\n \"Anki.AudioEngine.Multiplexer.AudioCallbackError callbackError union property.\"\n msgbuffers.safety_check_tag('callbackError', self._tag, self.Tag.callbackError, self._tags_by_value)\n return self._data\n\n @callbackError.setter\n def callbackError(self, value):\n self._data = msgbuffers.validate_object(\n 'AudioCallbackInfo.callbackError', value, Anki.AudioEngine.Multiplexer.AudioCallbackError)\n self._tag = self.Tag.callbackError\n\n def __init__(self, **kwargs):\n if not kwargs:\n self._tag = None\n self._data = None\n\n elif len(kwargs) == 1:\n key, value = next(iter(kwargs.items()))\n if key not in self._tags_by_name:\n raise TypeError(\"'{argument}' is an invalid keyword argument for this method.\".format(argument=key))\n # calls the correct property\n setattr(self, key, value)\n\n else:\n raise TypeError('This method only accepts up to one keyword argument.')\n\n @classmethod\n def unpack(cls, buffer):\n \"Reads a new AudioCallbackInfo from the given buffer.\"\n reader = msgbuffers.BinaryReader(buffer)\n value = cls.unpack_from(reader)\n if reader.tell() != len(reader):\n raise msgbuffers.ReadError(\n ('AudioCallbackInfo.unpack received a buffer of length {length}, ' +\n 'but only {position} bytes were read.').format(\n length=len(reader), position=reader.tell()))\n return value\n\n @classmethod\n def unpack_from(cls, reader):\n \"Reads a new AudioCallbackInfo from the given BinaryReader.\"\n tag = reader.read('B')\n if tag in cls._tags_by_value:\n value = cls()\n setattr(value, cls._tags_by_value[tag], cls._tag_unpack_methods[tag](reader))\n return value\n else:\n raise ValueError('AudioCallbackInfo attempted to unpack unknown tag {tag}.'.format(tag=tag))\n\n def pack(self):\n \"Writes the current AudioCallbackInfo, returning bytes.\"\n writer = msgbuffers.BinaryWriter()\n self.pack_to(writer)\n return writer.dumps()\n\n def pack_to(self, writer):\n \"Writes the current SampleUnion to the given BinaryWriter.\"\n if self._tag in self._tags_by_value:\n writer.write(self._tag, 'B')\n self._tag_pack_methods[self._tag](writer, self._data)\n else:\n raise ValueError('Cannot pack an empty AudioCallbackInfo.')\n\n def clear(self):\n self._tag = None\n self._data = None\n\n @classmethod\n def typeByTag(cls, tag):\n return cls._type_by_tag_value[tag]()\n\n def __eq__(self, other):\n if type(self) is type(other):\n return self._tag == other._tag and self._data == other._data\n else:\n return NotImplemented\n\n def __ne__(self, other):\n if type(self) is type(other):\n return not self.__eq__(other)\n else:\n return NotImplemented\n\n def __len__(self):\n if 0 <= self._tag < 4:\n return self._tag_size_methods[self._tag](self._data)\n else:\n return 1\n\n def __str__(self):\n if 0 <= self._tag < 4:\n return '{type}({name}={value})'.format(\n type=type(self).__name__,\n name=self.tag_name,\n value=self._data)\n else:\n return '{type}()'.format(\n type=type(self).__name__)\n\n def __repr__(self):\n if 0 <= self._tag < 4:\n return '{type}({name}={value})'.format(\n type=type(self).__name__,\n name=self.tag_name,\n value=repr(self._data))\n else:\n return '{type}()'.format(\n type=type(self).__name__)\n\n _tags_by_name = dict(\n callbackDuration=0,\n callbackMarker=1,\n callbackComplete=2,\n callbackError=3,\n )\n\n _tags_by_value = dict()\n _tags_by_value[0] = 'callbackDuration'\n _tags_by_value[1] = 'callbackMarker'\n _tags_by_value[2] = 'callbackComplete'\n _tags_by_value[3] = 'callbackError'\n \n\n _tag_unpack_methods = dict()\n _tag_unpack_methods[0] = lambda reader: reader.read_object(Anki.AudioEngine.Multiplexer.AudioCallbackDuration.unpack_from)\n _tag_unpack_methods[1] = lambda reader: reader.read_object(Anki.AudioEngine.Multiplexer.AudioCallbackMarker.unpack_from)\n _tag_unpack_methods[2] = lambda reader: reader.read_object(Anki.AudioEngine.Multiplexer.AudioCallbackComplete.unpack_from)\n _tag_unpack_methods[3] = lambda reader: reader.read_object(Anki.AudioEngine.Multiplexer.AudioCallbackError.unpack_from)\n \n\n _tag_pack_methods = dict()\n _tag_pack_methods[0] = lambda writer, value: writer.write_object(value)\n _tag_pack_methods[1] = lambda writer, value: writer.write_object(value)\n _tag_pack_methods[2] = lambda writer, value: writer.write_object(value)\n _tag_pack_methods[3] = lambda writer, value: writer.write_object(value)\n \n\n _tag_size_methods = dict()\n _tag_size_methods[0] = lambda value: msgbuffers.size_object(value)\n _tag_size_methods[1] = lambda value: msgbuffers.size_object(value)\n _tag_size_methods[2] = lambda value: msgbuffers.size_object(value)\n _tag_size_methods[3] = lambda value: msgbuffers.size_object(value)\n \n\n _type_by_tag_value = dict()\n _type_by_tag_value[0] = lambda : Anki.AudioEngine.Multiplexer.AudioCallbackDuration\n _type_by_tag_value[1] = lambda : Anki.AudioEngine.Multiplexer.AudioCallbackMarker\n _type_by_tag_value[2] = lambda : Anki.AudioEngine.Multiplexer.AudioCallbackComplete\n _type_by_tag_value[3] = lambda : Anki.AudioEngine.Multiplexer.AudioCallbackError\n \n\nAnki.AudioEngine.Multiplexer.AudioCallbackInfo = AudioCallbackInfo\ndel AudioCallbackInfo\n\n\nclass AudioCallback(object):\n \"Generated message-passing message.\"\n\n __slots__ = (\n '_callbackId', # uint_16\n '_callbackInfo', # Anki.AudioEngine.Multiplexer.AudioCallbackInfo\n )\n\n @property\n def callbackId(self):\n \"uint_16 callbackId struct property.\"\n return self._callbackId\n\n @callbackId.setter\n def callbackId(self, value):\n self._callbackId = msgbuffers.validate_integer(\n 'AudioCallback.callbackId', value, 0, 65535)\n\n @property\n def callbackInfo(self):\n \"Anki.AudioEngine.Multiplexer.AudioCallbackInfo callbackInfo struct property.\"\n return self._callbackInfo\n\n @callbackInfo.setter\n def callbackInfo(self, value):\n self._callbackInfo = msgbuffers.validate_object(\n 'AudioCallback.callbackInfo', value, Anki.AudioEngine.Multiplexer.AudioCallbackInfo)\n\n def __init__(self, callbackId=0, callbackInfo=Anki.AudioEngine.Multiplexer.AudioCallbackInfo()):\n self.callbackId = callbackId\n self.callbackInfo = callbackInfo\n\n @classmethod\n def unpack(cls, buffer):\n \"Reads a new AudioCallback from the given buffer.\"\n reader = msgbuffers.BinaryReader(buffer)\n value = cls.unpack_from(reader)\n if reader.tell() != len(reader):\n raise msgbuffers.ReadError(\n ('AudioCallback.unpack received a buffer of length {length}, ' +\n 'but only {position} bytes were read.').format(\n length=len(reader), position=reader.tell()))\n return value\n\n @classmethod\n def unpack_from(cls, reader):\n \"Reads a new AudioCallback from the given BinaryReader.\"\n _callbackId = reader.read('H')\n _callbackInfo = reader.read_object(Anki.AudioEngine.Multiplexer.AudioCallbackInfo.unpack_from)\n return cls(_callbackId, _callbackInfo)\n\n def pack(self):\n \"Writes the current AudioCallback, returning bytes.\"\n writer = msgbuffers.BinaryWriter()\n self.pack_to(writer)\n return writer.dumps()\n\n def pack_to(self, writer):\n \"Writes the current AudioCallback to the given BinaryWriter.\"\n writer.write(self._callbackId, 'H')\n writer.write_object(self._callbackInfo)\n\n def __eq__(self, other):\n if type(self) is type(other):\n return (self._callbackId == other._callbackId and\n self._callbackInfo == other._callbackInfo)\n else:\n return NotImplemented\n\n def __ne__(self, other):\n if type(self) is type(other):\n return not self.__eq__(other)\n else:\n return NotImplemented\n\n def __len__(self):\n return (msgbuffers.size(self._callbackId, 'H') +\n msgbuffers.size_object(self._callbackInfo))\n\n def __str__(self):\n return '{type}(callbackId={callbackId}, callbackInfo={callbackInfo})'.format(\n type=type(self).__name__,\n callbackId=self._callbackId,\n callbackInfo=self._callbackInfo)\n\n def __repr__(self):\n return '{type}(callbackId={callbackId}, callbackInfo={callbackInfo})'.format(\n type=type(self).__name__,\n callbackId=repr(self._callbackId),\n callbackInfo=repr(self._callbackInfo))\n\nAnki.AudioEngine.Multiplexer.AudioCallback = AudioCallback\ndel AudioCallback\n\n\n","sub_path":"rest_env/Lib/site-packages/cozmoclad/clad/audio/audioCallbackMessage.py","file_name":"audioCallbackMessage.py","file_ext":"py","file_size_in_byte":25340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"145245362","text":"from copy import deepcopy\nfrom robot.helper import Player\n\ninfinity = float('infinity')\n\n\ndef decision(game, depth):\n root_state = deepcopy(game)\n return negamax(root_state, depth, -infinity, infinity)[0]\n\n\ndef evaluate(player, winner):\n if winner == player:\n return 100\n elif winner == Player.EMPTY:\n return 0\n else:\n return -100\n\n\ndef negamax(game, depth, alpha, beta):\n\n best = [None, -infinity]\n\n winner = game.is_end()\n\n if depth == 0 or winner:\n score = evaluate(game.player, winner)\n return [None, score]\n\n state = game\n\n for move in game.possible_moves():\n game = deepcopy(state)\n\n game.play_move(move)\n\n value = negamax(game, depth - 1, -beta, -alpha)\n value[0] = move\n value[1] *= -1\n\n if value[1] > best[1]:\n best = value\n\n alpha = max(alpha, value[1])\n if alpha >= beta:\n break\n\n return best\n","sub_path":"robot/negamax.py","file_name":"negamax.py","file_ext":"py","file_size_in_byte":950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"75995922","text":"# learn from Crossin's wechat\n# practice for python\n# coding=UTF-8\nimport pygame\nimport random\n\npygame.init()\n\nSIZE = (450, 869)\nscreen = pygame.display.set_mode(SIZE)\npygame.display.set_caption(\"雪花飘飘\")\norigin = pygame.image.load('xiaohei.jpg')\nbg = pygame.transform.scale(origin, (450, 869))\n\nsnow_list = []\n\n\nclass Snowflake:\n def __init__(self):\n self.x = random.randrange(0, SIZE[0])\n self.y = random.randrange(0, SIZE[1])\n self.sx = random.randint(-1, 1) # x speed\n self.sy = random.randint(3, 6) # y speed\n self.r = random.randint(0, 3)\n\n def fly(self):\n self.x += self.sx\n self.y += self.sy\n\n\nfor i in range(270):\n snow = Snowflake()\n snow_list.append(snow)\n\n# set the frame rate\nclock = pygame.time.Clock()\ndone = False\nwhile True:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n exit()\n\n screen.blit(bg, (0, 0))\n for snow in snow_list:\n pygame.draw.circle(screen, (255, 255, 255), (snow.x, snow.y), snow.r)\n\n snow.fly()\n\n if snow.y > SIZE[1]:\n snow.x = random.randrange(0, SIZE[0])\n snow.y = random.randrange(-50, -10)\n\n # update the contents of the entire display\n pygame.display.flip()\n clock.tick(40)\n","sub_path":"snow/snow.py","file_name":"snow.py","file_ext":"py","file_size_in_byte":1307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"511224211","text":"import pandas as pd\r\nimport sys\r\n\r\nargs = sys.argv\r\n\r\nfilename = args[1]\r\noutfile = args[2]\r\nvartools=['MuTect2, ', 'VarScan2, ', 'VarDict, ', 'LoFreq, ', 'Strelka']\r\n\r\ndf = pd.read_csv(filename)\r\nx = df['Otherinfo1']\r\ndiscarded_column=df.columns.get_loc('Otherinfo2')\r\ndata = dict()\r\nsomatic_cols=['Chr','Start','End','Ref','Alt','Variant_Callers','FILTER','SOMATIC_FLAG','VariantCaller_Count','REF_COUNT','ALT_COUNT','VAF','Func.refGene','Gene.refGene','ExonicFunc.refGene','AAChange.refGene','Gene_full_name.refGene','Function_description.refGene','Disease_description.refGene','cosmic84','PopFreqMax','1000G_ALL','ExAC_ALL','CG46','ESP6500siv2_ALL','InterVar_automated']\r\ndata.setdefault('FILTER', [])\r\ndata.setdefault('SOMATIC_FLAG', [])\r\ndata.setdefault('VariantCaller_Count', [])\r\ndata.setdefault('Variant_Callers', [])\r\ndata.setdefault('VAF', [])\r\ndata.setdefault('REF_COUNT', [])\r\ndata.setdefault('ALT_COUNT', [])\r\nfor row in x:\r\n rowitems=row.split('\\t')\r\n data['FILTER'].append(rowitems[9])\r\n info=rowitems[10].split(';')\r\n formatval=rowitems[-1].split(':')\r\n readcounts=formatval[2]\r\n if len(info)!=5 and info[0]!='SOMATIC':\r\n data['SOMATIC_FLAG'].append('NON SOMATIC')\r\n name_toolskey=0\r\n else:\r\n data['SOMATIC_FLAG'].append(info[0])\r\n name_toolskey=1\r\n num_toolskey=name_toolskey+1 \r\n tools_binary=info[name_toolskey].split('=')[1].split(',')\r\n tools_name=''\r\n for key in range(len(tools_binary)):\r\n if tools_binary[key]=='1':\r\n tools_name+=vartools[key]\r\n data['Variant_Callers'].append(tools_name) \r\n data['VariantCaller_Count'].append(info[num_toolskey].split('=')[1])\r\n vaf=\"{:.2%}\".format(float(info[-1].split('=')[1]))\r\n data['VAF'].append(vaf)\r\n data['REF_COUNT'].append(readcounts.split(',')[1])\r\n data['ALT_COUNT'].append(readcounts.split(',')[-1])\r\n \r\ndf1=df.iloc[:,:5]\r\ndf2=pd.DataFrame(data, columns=data.keys())\r\ndf3=df.iloc[:,5:discarded_column]\r\n\r\nhorizontal_stack = pd.concat([df1, df2, df3], axis=1)\r\nhorizontal_stack.to_csv(outfile, index=False)\r\n","sub_path":"scripts/somaticseqoutput-format.py","file_name":"somaticseqoutput-format.py","file_ext":"py","file_size_in_byte":2097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"393586698","text":"v1 = input(\"Please Enter Name of The Dairy: \")\r\ndate = input(\"Please Enter Date: \")\r\n\r\nd1 = open(v1 + \".txt\",\"w\")\r\n\r\nv2 = input(\"Write What You Did Today: \")\r\n\r\nd1 = open(v1 + \".txt\",\"a\")\r\n\r\nd1.write(date)\r\nd1.write(\"\\n\"+\" \" + v2)\r\n\r\npreference = int(input(\"If you read what you write, press 1. If you don't want it, press 2: \"))\r\n\r\nd1 = open(v1 + \".txt\",\"r\")\r\n\r\nif preference == 1:\r\n print(d1.read())\r\nelif preference == 2:\r\n print(\"You Diary is Saved\")\r\nelse:\r\n print(\"Please Choose One of Them\")\r\n\r\nd1.close()","sub_path":"diary.py","file_name":"diary.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"214216058","text":"def sample_sort(a):\n '''\n 简单排序\n 从第一个元素开始,遍历整个列表将最小的放到前面\n '''\n l = len(a)\n for i in range(0,l-1):\n for j in range(i,l):\n if a[j] < a[i]:\n a[j],a[i] = a[i],a[j]\n print('第'+str(i+1)+'次排序后:',a)\n print(a)\n \n\ndef bubble_sort(a):\n '''\n 冒泡排序\n 从第一个元素开始,比较相邻的两个元素将较大的放到后面\n '''\n l = len(a)\n for i in range(l-1):\n for j in range(1,l-i):\n if a[j-1] > a[j]:\n a[j-1],a[j] = a[j],a[j-1]\n print('第'+str(i+1)+'次排序后:',a)\n print(a)\n \ndef insert_sort(a):\n '''\n 插入排序\n [4,3,2]\n '''\n l = len(a)\n for i in range(1,l):\n key = a[i]\n j = i-1\n while j >= 0 and key < a[j]:\n a[j+1] = a[j]\n j -= 1\n a[j+1] = key\n print(a) \n\nif __name__ == '__main__':\n a = [8,7,6,5,4,3,2,1]\n insert_sort(a)\n ","sub_path":"sort/sort.py","file_name":"sort.py","file_ext":"py","file_size_in_byte":1027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"127541805","text":"\"\"\"\n Sort Colors\n\nProblem:\n\n Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, \n with the colors in the order red, white and blue.\n\n Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.\n\n Note: You are not suppose to use the library's sort function for this problem.\n\nExample:\n\n Input: [2,0,2,1,1,0]\n Output: [0,0,1,1,2,2]\n\nFollow up:\n\n A rather straight forward solution is a two-pass algorithm using counting sort.\n First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's.\n Could you come up with a one-pass algorithm using only constant space?\n\n\"\"\"\nfrom typing import List\n\nclass Solution:\n def sortColors(self, nums: List[int]) -> None:\n \"\"\"\n Do not return anything, modify nums in-place instead.\n \"\"\"\n # we will use the bubble sorting algorith,\n swapped = True\n while swapped :\n swapped = False\n for index in range(len(nums)-1):\n if nums[index] > nums[index+1]:\n nums[index], nums[index+1] = nums[index+1], nums[index]\n swapped = True\n\nif __name__ == \"__main__\":\n sol = Solution()\n l_colors = [2,0,2,1,1,0]\n sol.sortColors(l_colors)\n print(l_colors)","sub_path":"Challenge_June_30_days_leetcoding_challenge/day11.py","file_name":"day11.py","file_ext":"py","file_size_in_byte":1435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"414958643","text":"from django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n path('', views.landing, name='landing'),\n path('signup', views.signup, name='signup'),\n path('newPatient', views.patient, name='patient'),\n path('newDoctor', views.doctor, name='doctor'),\n path('doctorpage', views.doctorpage, name='doctpage'),\n path('patientpage', views.patientpage, name='patientpage'),\n path('index', views.index, name='index')\n]","sub_path":"mysite/register/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"313437966","text":"from flask import Flask, request, session, g, redirect, url_for, abort, render_template, flash\napp = Flask(__name__)\napp.config.update(\n SECRET_KEY = 'AMN',\n DEBUG = True\n)\n\n@app.route('/')\ndef hello(name=None):\n user = { 'name' : 'hello'}\n return render_template('index.html',n=user)\n\nif __name__ == \"__main__\":\n\tapp.run()\t\n\n","sub_path":"render.py","file_name":"render.py","file_ext":"py","file_size_in_byte":338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"571546074","text":"# coding: utf-8\n\nimport six\n\nfrom huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization\n\n\nclass ListAgentStatusRequestBody:\n\n \"\"\"\n Attributes:\n openapi_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n sensitive_list = []\n\n openapi_types = {\n 'instance_ids': 'list[str]',\n 'uniagent_status': 'str',\n 'extension_name': 'str',\n 'extension_status': 'str'\n }\n\n attribute_map = {\n 'instance_ids': 'instance_ids',\n 'uniagent_status': 'uniagent_status',\n 'extension_name': 'extension_name',\n 'extension_status': 'extension_status'\n }\n\n def __init__(self, instance_ids=None, uniagent_status=None, extension_name=None, extension_status=None):\n \"\"\"ListAgentStatusRequestBody\n\n The model defined in huaweicloud sdk\n\n :param instance_ids: 机器实例id列表\n :type instance_ids: list[str]\n :param uniagent_status: uniagent运行状态,不传查所有状态,none无,running运行中,silent静默中,unknown故障\n :type uniagent_status: str\n :param extension_name: 插件名称,不传查所有插件,目前仅支持telescope\n :type extension_name: str\n :param extension_status: 插件状态,不传查所有状态, none未安装,running运行中,stopped已停止,fault故障(进程异常),unknown故障(连接异常)\n :type extension_status: str\n \"\"\"\n \n \n\n self._instance_ids = None\n self._uniagent_status = None\n self._extension_name = None\n self._extension_status = None\n self.discriminator = None\n\n self.instance_ids = instance_ids\n if uniagent_status is not None:\n self.uniagent_status = uniagent_status\n if extension_name is not None:\n self.extension_name = extension_name\n if extension_status is not None:\n self.extension_status = extension_status\n\n @property\n def instance_ids(self):\n \"\"\"Gets the instance_ids of this ListAgentStatusRequestBody.\n\n 机器实例id列表\n\n :return: The instance_ids of this ListAgentStatusRequestBody.\n :rtype: list[str]\n \"\"\"\n return self._instance_ids\n\n @instance_ids.setter\n def instance_ids(self, instance_ids):\n \"\"\"Sets the instance_ids of this ListAgentStatusRequestBody.\n\n 机器实例id列表\n\n :param instance_ids: The instance_ids of this ListAgentStatusRequestBody.\n :type instance_ids: list[str]\n \"\"\"\n self._instance_ids = instance_ids\n\n @property\n def uniagent_status(self):\n \"\"\"Gets the uniagent_status of this ListAgentStatusRequestBody.\n\n uniagent运行状态,不传查所有状态,none无,running运行中,silent静默中,unknown故障\n\n :return: The uniagent_status of this ListAgentStatusRequestBody.\n :rtype: str\n \"\"\"\n return self._uniagent_status\n\n @uniagent_status.setter\n def uniagent_status(self, uniagent_status):\n \"\"\"Sets the uniagent_status of this ListAgentStatusRequestBody.\n\n uniagent运行状态,不传查所有状态,none无,running运行中,silent静默中,unknown故障\n\n :param uniagent_status: The uniagent_status of this ListAgentStatusRequestBody.\n :type uniagent_status: str\n \"\"\"\n self._uniagent_status = uniagent_status\n\n @property\n def extension_name(self):\n \"\"\"Gets the extension_name of this ListAgentStatusRequestBody.\n\n 插件名称,不传查所有插件,目前仅支持telescope\n\n :return: The extension_name of this ListAgentStatusRequestBody.\n :rtype: str\n \"\"\"\n return self._extension_name\n\n @extension_name.setter\n def extension_name(self, extension_name):\n \"\"\"Sets the extension_name of this ListAgentStatusRequestBody.\n\n 插件名称,不传查所有插件,目前仅支持telescope\n\n :param extension_name: The extension_name of this ListAgentStatusRequestBody.\n :type extension_name: str\n \"\"\"\n self._extension_name = extension_name\n\n @property\n def extension_status(self):\n \"\"\"Gets the extension_status of this ListAgentStatusRequestBody.\n\n 插件状态,不传查所有状态, none未安装,running运行中,stopped已停止,fault故障(进程异常),unknown故障(连接异常)\n\n :return: The extension_status of this ListAgentStatusRequestBody.\n :rtype: str\n \"\"\"\n return self._extension_status\n\n @extension_status.setter\n def extension_status(self, extension_status):\n \"\"\"Sets the extension_status of this ListAgentStatusRequestBody.\n\n 插件状态,不传查所有状态, none未安装,running运行中,stopped已停止,fault故障(进程异常),unknown故障(连接异常)\n\n :param extension_status: The extension_status of this ListAgentStatusRequestBody.\n :type extension_status: str\n \"\"\"\n self._extension_status = extension_status\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.iteritems(self.openapi_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n if attr in self.sensitive_list:\n result[attr] = \"****\"\n else:\n result[attr] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n import simplejson as json\n if six.PY2:\n import sys\n reload(sys)\n sys.setdefaultencoding(\"utf-8\")\n return json.dumps(sanitize_for_serialization(self), ensure_ascii=False)\n\n def __repr__(self):\n \"\"\"For `print`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, ListAgentStatusRequestBody):\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n return not self == other\n","sub_path":"huaweicloud-sdk-ces/huaweicloudsdkces/v3/model/list_agent_status_request_body.py","file_name":"list_agent_status_request_body.py","file_ext":"py","file_size_in_byte":6927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"225466351","text":"# Using pytest\n# Test the clc instructions of an instance of an i4004(processor)\n\nimport sys\nimport pickle\nsys.path.insert(1, '../src')\n\nfrom hardware.processor import processor # noqa\nfrom hardware.exceptions import InvalidRamBank # noqa\n\n\ndef test_validate_instruction():\n \"\"\"Ensure instruction's characteristics are valid.\"\"\"\n chip_test = processor()\n # Validate the instruction's opcode and characteristics:\n op = chip_test.INSTRUCTIONS[241]\n known = {\"opcode\": 241, \"mnemonic\": \"clc()\", \"exe\": 10.8, \"bits\": [\"1111\", '0001'], \"words\": 1} # noqa\n assert op == known\n\n\ndef test_scenario1():\n \"\"\"Test CLC instruction functionality.\"\"\"\n chip_test = processor()\n chip_base = processor()\n\n # Perform the instruction under test:\n chip_test.PROGRAM_COUNTER = 0\n chip_test.set_carry()\n\n # Simulate conditions at end of instruction in base chip\n chip_base.PROGRAM_COUNTER = 0\n chip_base.increment_pc(1)\n chip_base.reset_carry()\n\n # Carry out the instruction under test\n # Perform a CLC operation\n\n processor.clc(chip_test)\n # Make assertions that the base chip is now at the same state as\n # the test chip which has been operated on by the instruction under test.\n\n assert chip_test.read_program_counter() == chip_base.read_program_counter()\n assert chip_test.read_carry() == chip_base.read_carry()\n\n # Pickling each chip and comparing will show equality or not.\n assert pickle.dumps(chip_test) == pickle.dumps(chip_base)\n","sub_path":"pyntel4004/test/02_accumulator/test_0200_241_instruction_clc.py","file_name":"test_0200_241_instruction_clc.py","file_ext":"py","file_size_in_byte":1495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"392185321","text":"\"\"\"\nCreated by Tom Strange\nDecember 2014\nCompiled using pyinstaller single file mode on windows 7 SP1 64 bit.\nIcon: http://simpleicon.com/wp-content/uploads/crop.png\n\nSOURCES\nhttp://docs.opencv.org/trunk/doc/py_tutorials/py_imgproc/py_morphological_ops/py_morphological_ops.html\nhttp://docs.opencv.org/doc/tutorials/core/basic_linear_transform/basic_linear_transform.html\nhttp://www.pyimagesearch.com/2014/04/21/building-pokedex-python-finding-game-boy-screen-step-4-6/\nhttp://docs.opencv.org/trunk/doc/py_tutorials/py_imgproc/py_contours/py_contour_features/py_contour_features.html#a-straight-bounding-rectangle\n\n\"\"\"\nimport os\nimport cv2\nimport numpy as np\nimport easygui as eg\nimport Tkinter as tk\n\ndef find_edges(img):\n\t\"\"\"\n\tThis takes an image, applies some transformations to ease edge detection\n\tthen finds the edges using the Canny edge detection algorithm\n\n\tInputs:\n\t\timg - img file loaded using cv2.imread\n\n\tOutputs:\n\t\tedges - an array identifying the edges in the image\n\t\"\"\"\n\t#The background grid is roughly 33x33px when resized so kernel must exceed this\n\tkernel = np.ones(((50,50)),np.uint8)\n\topening = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel)\n\tdark = cv2.add(opening,np.array([-60.]))\n\tcontrast = cv2.multiply(dark,np.array([5.]))\n\tedges = cv2.Canny(contrast,20,50,L2gradient=True)\n\treturn edges\n\nmsg = \"Enter project details\"\ntitle = \"Crop, Resize and Rename\"\nfieldNames = ['Project code', 'Number of each sample', 'Time on test']\nfieldValues = []\nfieldValues = eg.multenterbox(msg, title, fieldNames)\n\nwhile True:\n\t# Set error message to blank\n\terrmsg = \"\"\n\t# Check all field are filled\n\tfor i in range(len(fieldNames)):\n\t\tif fieldValues[i].strip() == \"\":\n\t\t\terrmsg = errmsg + ('{} is required.\\n'.format(fieldNames[i]))\n\n # If all fields are filled, check inputs are valid\n\tif errmsg == \"\":\n \t# Make project code uppercase\n\t\tfieldValues[0] = fieldValues[0].upper()\n\n\t\t# Check number of samples is an integer and that it's greater than one\n\t\ttry:\n\t\t\tfieldValues[1] = int(fieldValues[1])\n\t\texcept ValueError:\n\t\t\terrmsg = errmsg + ('{} must be an integer.\\n'.format(fieldNames[1]))\n\t\telse:\n\t\t\tif fieldValues[1] < 1:\n\t\t\t\terrmsg = errmsg + ('{} must be > 1'.format(fieldNames[1]))\n\n\t\t# Check time on test is an integer\n\t\ttry:\n\t\t\tfieldValues[2] = int(fieldValues[2])\n\t\texcept ValueError:\n\t\t\terrmsg = errmsg + ('{} must be a valid integer\\n'.format(fieldNames[2]))\n\t\telse:\n\t\t\tif fieldValues[2] < 0:\n\t\t\t\terrmsg = errmsg + ('{} must be a positive integer.\\n'.format(fieldNames[2]))\n\n\t# If no errors, break out of loop\n\tif errmsg == \"\":\n\t\tbreak\n\n\t# If errors, reopen input window with error messages\n\tfieldValues = eg.multenterbox(errmsg, title, fieldNames)\n\n# Set variables to input values\ncode, num_samples, time = fieldValues\n\nsample_letters='ABCDEFGHIJKLMNOPQRSTUVWXYZ'\nsample_current_letter = 0\nsample_count = 1\n# Keep record of failures to locate the film in an image\nfailed_crops = []\n\n# Create widget to display counter for image processing\nroot = tk.Tk()\ncanvas = tk.Canvas(root, width=150, height=150)\nroot.title(\"\")\ncanvas.pack()\n\n#print(\"Running....\")\nfor file in os.listdir('.'):\n\t#get filenames\n\tname,ext = os.path.splitext(file)\n\tif ext==\".JPG\":\n\t\t#open image file in grayscale and resize\n\t\timg = cv2.imread(file,1)\n\t\timg = cv2.resize(img,None,fx=0.2,fy=0.2,interpolation = cv2.INTER_AREA)\n\n\t\t#convert to greyscale for edge detection\n\t\tgrey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\t\tedges = find_edges(grey)\n\n\t\t#find contours in the edged image, keep only the largest ones.\n\t\t(_,cnts,_) = cv2.findContours(edges.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n\t\tcnts = sorted(cnts, key = cv2.contourArea, reverse = True)[0:5]\n\t\tfor c in cnts:\n\t\t\t#approximate the contour\n\t\t\tperi = cv2.arcLength(c, True)\n\t\t\tapprox = cv2.approxPolyDP(c, 0.08 * peri, True)\n\n\t\t\tif len(approx) == 4 and 40000 < cv2.contourArea(c) < 60000:\n\t\t\t\t#If the contour has 4 corners and a correct area, assume film edge has been found\n\t\t\t\tx,y,w,h = cv2.boundingRect(c)\n\t\t\t\tbreak\n\n\t\t#Rename original image\n\t\toriginal_image_rename = code+\" \"+sample_letters[sample_current_letter]+str(sample_count)+\" - \"+str(time)+\"hrs\"+ext\n\t\tos.rename(name+ext,original_image_rename)\n\n\t\t#Attempt to crop\n\t\ttry:\n\t\t\tcrop_x = x - 15\n\t\t\tcrop_y = y - 15\n\t\t\tcrop_width = x + w + 15\n\t\t\tcrop_height = y + h + 15\n\t\t\tcropped = img[crop_y:crop_height,crop_x:crop_width]\n\t\t\toutput_cropped_name = code+\" \"+sample_letters[sample_current_letter]+str(sample_count)+\" - \"+str(time)+\"hrs\"+\"-Btch Crp\"+ext.lower()\n\t\t\tcv2.imwrite(output_cropped_name,cropped)\n\t\texcept NameError:\n\t\t\t#catch error if rectangle to crop to is not defined\n\t\t\tcrop_x = 220\n\t\t\tcrop_y = 150\n\t\t\tcrop_width = 480\n\t\t\tcrop_height = 500\n\t\t\tcropped = img[crop_y:crop_height,crop_x:crop_width]\n\t\t\toutput_cropped_name = code+\" \"+sample_letters[sample_current_letter]+str(sample_count)+\" - \"+str(time)+\"hrs\"+\"-Btch Crp\"+ext.lower()\n\t\t\tcv2.imwrite(output_cropped_name,cropped)\n\n\t\t\tfailed_crops.append(output_cropped_name+'\\n')\n\n\t\t# Update counter widget\n\t\tcanvas.delete(tk.ALL)\n\t\timage_num = sample_count+sample_current_letter*num_samples\n\t\tcanvas.create_text(75, 10, text=\"Processing image:\", font=('Helvetica', '10'))\n\t\tcanvas.create_text(75, 75, text=image_num, font=('Helvetica', '70'))\n\t\tcanvas.update()\t\t\n\n\t\t#Increment labels\n\t\tif sample_count % num_samples == 0:\n\t\t\tsample_count = 1\n\t\t\tsample_current_letter+=1\n\t\telse:\n\t\t\tsample_count+=1\n\n# Close window showing counter\nroot.destroy()\n\nif len(failed_crops) == 0:\n\tend_msg = 'Completed.'\nelse:\n\tend_msg = 'Completed.\\n\\nThe following films were not correctly located in the images:\\n' + \"\".join(failure for failure in failed_crops)\neg.msgbox(msg=end_msg, title=title, ok_button='Exit')\n","sub_path":"Source/[TESTING-GUI]detection.py","file_name":"[TESTING-GUI]detection.py","file_ext":"py","file_size_in_byte":5672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"34390992","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\n\n\nclass attrdict(dict):\n\n '''\n Use dict key as attribute if available\n '''\n\n def __init__(self, *args, **kwargs):\n super(attrdict, self).__init__(*args, **kwargs)\n self.__dict__ = self\n\n def __getattr__(self, key):\n try:\n return self[key]\n except KeyError as e:\n raise AttributeError(e)\n\n @classmethod\n def loads(cls, value):\n if isinstance(value, dict):\n result = cls()\n result.update(value)\n for k, v in result.items():\n result[k] = cls.loads(v)\n\n elif isinstance(value, list):\n for index, item in enumerate(value):\n if type(item) in (list, dict):\n value[index] = cls.loads(item)\n result = value\n else:\n result = value\n return result\n\n @classmethod\n def json_loads(cls, value):\n import json\n data = json.loads(value)\n return cls.loads(data)\n\n\ndef identity_function(x):\n return x\n\n\ndef step_function(x):\n return np.array(x > 0, dtype=np.int)\n\n\ndef sigmoid(x):\n return 1 / (1 + np.exp(-x))\n\n\ndef relu(x):\n return np.maximum(0, x)\n\n\ndef softmax(x):\n if x.ndim == 2:\n x = x.T\n x = x - np.max(x, axis=0)\n y = np.exp(x) / np.sum(np.exp(x), axis=0)\n return y.T\n\n x = x - np.max(x) # 溢出对策\n return np.exp(x) / np.sum(np.exp(x))\n\n\ndef mean_squared_error(y, t):\n return 0.5 * np.sum((y - t)**2)\n\n\ndef cross_entropy_error(y, t):\n if y.ndim == 1:\n t = t.reshape(1, t.size)\n y = y.reshape(1, y.size)\n\n # 监督数据是one-hot-vector的情况下,转换为正确解标签的索引\n if t.size == y.size:\n t = t.argmax(axis=1)\n\n batch_size = y.shape[0]\n return -np.sum(np.log(y[np.arange(batch_size), t] + 1e-7)) / batch_size\n\n\ndef softmax_loss(X, t):\n y = softmax(X)\n return cross_entropy_error(y, t)\n","sub_path":"basic/learning.py","file_name":"learning.py","file_ext":"py","file_size_in_byte":2010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"484973567","text":"#!/usr/bin/env python\n\n\nclass Solution(object):\n def preorderTraversalIterative(self, root):\n node, stack, preorder = root, [], []\n\n while stack or node:\n if not node:\n node = stack.pop()\n node = node.right\n else:\n preorder.append(node.val)\n stack.append(node)\n node = node.left\n return preorder\n\n def preorderTraversal(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[int]\n \"\"\"\n def helper(root):\n if not root: return\n self.preorder.append(root.val)\n helper(root.left)\n helper(root.right)\n\n self.preorder = []\n helper(root)\n return self.preorder\n","sub_path":"144.Binary_Tree_Preorder_Traversal.py","file_name":"144.Binary_Tree_Preorder_Traversal.py","file_ext":"py","file_size_in_byte":776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"159168478","text":"import argparse\nimport json\nimport sys\nfrom jsonschema import Draft7Validator\nfrom jsonschema.exceptions import ValidationError\n\n\nschema = {}\n\nwith open(\"json-schema.json\", \"r\") as schema_file:\n schema = json.load(schema_file)\n\n# Validate the schema itself: this will raise an exception if it's not well formed\nvalidator = Draft7Validator(schema)\n# Make sure the schema isn't completely broken and doesn't validate anything\nvalidation_ok = False\ntry:\n validator.validate({\"foobar\": \"baz\"})\nexcept ValidationError as error:\n print(\"validation is validating :P\")\n validation_ok = True\n\nif not validation_ok:\n print(\"validation isn't validating anything, exiting\")\n exit(1)\n\n\ndef parse(args):\n with open(args.records_path) as records_file:\n records = json.load(records_file)\n if type(records) == dict:\n # It's an export from a HTTP request to Kinto, which returns a json object with a \"data\" attribute.\n records = records[\"data\"]\n\n print(f\"Validating {len(records)} records\")\n\n num_errors = 0\n for index, record in enumerate(records):\n try:\n validator.validate(record)\n except ValidationError as error:\n print(\"====================\")\n print(\"Error while validating the following record\")\n print(record)\n print(error)\n num_errors += 1\n if args.fail_fast:\n exit(1)\n if index and not index % 100:\n print(f\"Validated {index} records\")\n print(f\"Found a total of {num_errors} validation errors\")\n\n\nparser = argparse.ArgumentParser(\n description=\"Validation de records d'un export d'une collection Kinto\"\n)\nparser.add_argument(\n \"records_path\", type=str, help=\"chemin vers l'export de la collection Kinto\"\n)\nparser.add_argument(\n \"--fail-fast\",\n action=\"store_true\",\n help=\"stop at the first validation error\",\n default=False,\n)\n\nparse(parser.parse_args())\n","sub_path":"packages/import-export/validate_schema.py","file_name":"validate_schema.py","file_ext":"py","file_size_in_byte":2018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"146631116","text":"# Simple implicit component example. Component and OpenMDAO work together to solve this.\n\nfrom __future__ import print_function\nimport numpy as np\n\nfrom openmdao.api import Component, Group, Problem, ScipyGMRES, Newton\n\nclass SimpleImplicitComp(Component):\n \"\"\" A Simple Implicit Component with an additional output equation.\n\n f(x,z) = xz + z - 4\n y = x + 2z\n\n Sol: when x = 0.5, z = 2.666\n\n Coupled derivs:\n\n y = x + 8/(x+1)\n dy_dx = 1 - 8/(x+1)**2 = -2.5555555555555554\n\n z = 4/(x+1)\n dz_dx = -4/(x+1)**2 = -1.7777777777777777\n \"\"\"\n\n def __init__(self):\n super(SimpleImplicitComp, self).__init__()\n\n # Params\n self.add_param('x', 0.5)\n\n # Unknowns\n self.add_output('y', 0.0)\n\n # States\n self.add_state('z', 0.0)\n\n self.maxiter = 25\n self.atol = 1.0e-2\n\n def solve_nonlinear(self, params, unknowns, resids):\n \"\"\" Simple iterative solve. (Babylonian method).\"\"\"\n\n x = params['x']\n z = unknowns['z']\n znew = z\n\n itercount = 0\n eps = 1.0e99\n while itercount < self.maxiter and abs(eps) > self.atol:\n z = znew\n znew = 4.0 - x*z\n\n eps = x*znew + znew - 4.0\n itercount += 1\n\n # Our State\n unknowns['z'] = znew\n\n # Our Output\n unknowns['y'] = x + 2.0*znew\n\n def apply_nonlinear(self, params, unknowns, resids):\n \"\"\" Don't solve; just calculate the residual.\"\"\"\n\n x = params['x']\n z = unknowns['z']\n resids['z'] = x*z + z - 4.0\n\n # Output equations need to evaluate a residual just like an explicit comp.\n resids['y'] = x + 2.0*z - unknowns['y']\n\n def linearize(self, params, unknowns, resids):\n \"\"\"Analytical derivatives.\"\"\"\n\n J = {}\n\n # Output equation\n J[('y', 'x')] = np.array([1.0])\n J[('y', 'z')] = np.array([2.0])\n\n # State equation\n J[('z', 'z')] = np.array([params['x'] + 1.0])\n J[('z', 'x')] = np.array([unknowns['z']])\n\n return J\n\nif __name__ == '__main__':\n\n top = Problem()\n root = top.root = Group()\n root.add('comp', SimpleImplicitComp())\n\n root.ln_solver = ScipyGMRES()\n root.nl_solver = Newton()\n top.setup()\n top.print_all_convergence()\n\n top.run()\n\n print('Solution: x = %f, z = %f, y = %f' % (top['comp.x'], top['comp.z'], top['comp.y']))\n","sub_path":"bin/Python27/Lib/site-packages/openmdao/examples/implicit_nested_solve.py","file_name":"implicit_nested_solve.py","file_ext":"py","file_size_in_byte":2411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"426644413","text":"from django.conf.urls import url, include\n\n\nfrom app import pub_views, views\n\nurlpatterns = [\n # 发布商品\n url(r'^publish_goods', pub_views.publish_goods, name='publish_goods'),\n # 发布求购\n url(r'^publish_want_buy', pub_views.publish_want_buy, name='publish_want_buy'),\n # 上传图片接口\n url(r'^upload_pic', pub_views.upload_pic, name='upload_pic'),\n # 商品接口\n url(r'^api/goods/(?P\\d+)$', pub_views.sale_goods, name='goods'),\n # 评论接口\n url(r'^comment/(?P\\d+)$', pub_views.comment, name='comment'),\n # 商品展示首页\n url(r'^sale/goods', pub_views.sale, name='sale'),\n # 商品详情页\n url(r'^sale/(?P\\d+)$', pub_views.goods_detail, name='goods_detail'),\n # 全文搜索\n url(r'^search/', include('haystack.urls')),\n # 选择学校页\n url(r'^school', pub_views.school, name='school'),\n\n url(r'sale/shelvesgoods/(?P\\d+)$', views.shelves_goods),\n url(r'sale/resalegoods/(?P\\d+)$', views.resale_goods),\n url(r'sale/delgoods/(?P\\d+)$', views.del_goods),\n url(r'buy/shelvesbuy/(?P\\d+)$', views.shelves_buy),\n url(r'buy/resalebuy/(?P\\d+)$', views.resale_buy),\n url(r'buy/delbuy/(?P\\d+)$', views.del_buy),\n\n url(r'get_banners/$', views.get_banners, name='get_banners'),\n # 验证登录接口\n url(r'verify_login', pub_views.verify_login, name='verify_login'),\n # 商品类型接口\n url(r'goods_type', pub_views.get_goods_type, name='goods_type'),\n\n # 求购商品展示页\n url(r'want_to_buy/', views.want_to_buy, name='want_to_buy'),\n # 开通学校\n url(r'^add_school/', views.add_school, name='add_school'),\n # 求购接口\n url(r'^sale/order/(?P\\d+)$', views.want_buy),\n # 首页展示\n url(r'app/', views.app, name='app'),\n url(r'index/', views.index, name='index'),\n url(r'join_us/', views.join_us, name='join_us')\n\n]\n\n\n\n","sub_path":"app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"580827086","text":"from sklearn.datasets import load_iris\nfrom sklearn.datasets import load_breast_cancer\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import LabelEncoder\nimport pandas as pd\n\ndef get_iris_datasets(test_size):\n iris = load_iris()\n\n X, y = iris.data[50:, [1, 2]], iris.target[50:]\n encoder = LabelEncoder()\n y = encoder.fit_transform(y)\n\n return train_test_split(X, y, test_size=test_size, random_state=1)\n\ndef get_cancer_datasets(test_size):\n cancer = load_breast_cancer()\n\n X, y = cancer.data, cancer.target\n\n return train_test_split(X, y, test_size=test_size, random_state=1)\n\ndef get_wine_datasets(test_size):\n df_wine = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/wine/wine.data', header=None)\n df_wine.columns = ['Class label', 'Alcohol', 'Malic acid', 'Ash',\n 'Alcalinity of ash', 'Magnesium', 'Total phenols',\n 'Flavanoids', 'Nonflavanoid phenols', 'Proanthocyanins',\n 'Color intensity', 'Hue', 'OD280/OD315 of diluted wines',\n 'Proline']\n\n # drop 1 class\n df_wine = df_wine[df_wine['Class label'] != 1]\n\n X = df_wine[['Alcohol', 'Hue']].values\n y = df_wine['Class label'].values\n encoder = LabelEncoder()\n y = encoder.fit_transform(y)\n\n return train_test_split(X, y, test_size=test_size, random_state=1)\n","sub_path":"src/datasets/data_util.py","file_name":"data_util.py","file_ext":"py","file_size_in_byte":1394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"367574307","text":"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\n\nfrom wave import decode_wave\n\ndef plot_wave(file_name):\n teibai = 52\n if 'address15' in file_name:\n mon = 0\n else : \n mon = 1\n vol = decode_wave.read_wave_file(file_name)\n #offset,off2 = cal_offset(vol,teibai)\n num = len(vol[0])\n num_range = teibai * 9\n #x = range(num)\n plt.rcParams[\"font.size\"] = 24\n x = range(num_range) \n fig = plt.figure(figsize=(15,9))\n for ch in range(16):\n vol_max = np.max(vol[ch])\n vol_min = np.min(vol[ch])\n print('ch '+str(ch) +\n '\\t Max '+str(vol_max) +\n '\\t Min '+str(vol_min) +\n '\\tp-p '+str(vol_max-vol_min))\n plt.subplot(4,4,ch+1)\n [ plt.plot(x,vol[ch][i*num_range:(i+1)*num_range],c='blue',linewidth=0.5) for i in range(20)]\n [ plt.axvline(x=52*(i+1),color='black',alpha=0.5 )for i in range(9)]\n fig.suptitle(os.path.split(file_name)[1], fontsize=20)\n plt.ylabel('ADC count')\n plt.xlabel('sampling number per a turn')\n #plt.show()\n return vol,mon\n","sub_path":"analysis/wave/plot_wave.py","file_name":"plot_wave.py","file_ext":"py","file_size_in_byte":1100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"91534830","text":"from typing import List, Optional\n\n\nfrom pydantic import BaseModel\n\n\n\n\nclass GeneBase(BaseModel):\n\n name: str\n\n\n\n\n\nclass GeneCreate(GeneBase):\n\n pass\n\n\n\nclass Gene(GeneBase):\n id: int\n geneset_id: int\n\n class Config:\n orm_mode = True\n\n\n\nclass GenesetBase(BaseModel):\n\n title: str\n\n\n\n\nclass GenesetCreate(GenesetBase):\n\n title: str\n genes: List[GeneBase] = []\n\n\n\nclass Geneset(GenesetBase):\n id: int\n genes: List[Gene] = []\n\n class Config:\n orm_mode = True\n","sub_path":"backend/schemas.py","file_name":"schemas.py","file_ext":"py","file_size_in_byte":503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"290425272","text":"#!/usr/bin/env python3.6\n\n'''\nLaunch the application and any extra required processes\nlocally\n\nPart of the 'Scripts to Rule them All' suite of scripts to provide a consistent\ndeveloper experience for working on our repos\n\nhttps://githubengineering.com/scripts-to-rule-them-all/\n\n'''\n\nimport argparse\nimport logging\nimport os\n\nimport common\n\n_LOGGER = logging.getLogger(\"script.server\")\n\ndef run(*, verbose=False):\n common.run(_LOGGER, verbose=verbose)\n _LOGGER.info(\"This script currently does nothing\")\n\n\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser = argparse.ArgumentParser(\n description=(\"Launch the application and any extra required processes locally\")\n )\n parser.add_argument(\"-v\",action=\"store_true\", help=\"Verbose output\")\n\n args = parser.parse_args()\n print(args)\n\n common.setup_parent_loggers()\n run(verbose=args.v)","sub_path":"{{cookiecutter.project_slug}}/scripts/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"126454808","text":"# ####################################################\r\n# DE2-COM2 Computing 2\r\n# Individual project\r\n#\r\n# Title: main\r\n# Authors: Patrick McGuckian\r\n# Last updated: 12th January 2020\r\n# ####################################################\r\n\r\n\r\ndef Tetris(T):\r\n '''Main function that if called returns a solution to the task using the Gridfill class below. A high level overview of how\r\n it works is detailed in this function. For a more detailed description look through the gridfill class'''\r\n \r\n # Gridfill class is called and required global variables are found\r\n grid = Gridfill(T)\r\n \r\n # Method gives each position in a matrix the value of the count of the number of neighbouring positions needing filled surrounding it in the target grid T - to be used in the Greedy algorithm.\r\n grid.find_neighbours(0, 0, grid.width, grid.height)\r\n \r\n # Method starts filling pieces in the matrix at any point with only one neighbour - as this must be the start of the piece so the peice is likley to be correct.\r\n grid.fill_grid(fill_type='smart')\r\n\r\n # Method starts filling pieces in the matrix at any point that needs filled - acounting for any points missed by the previous method. Useful for high grid densities.\r\n grid.fill_grid(fill_type='dumb')\r\n\r\n # Final Method forces in pieces at any point it is possible and benfitil to do so (where at least 3 of the positions need to be filled).\r\n grid.fill_grid(fill_type='dumb', allow_force=True)\r\n\r\n return grid.filling_grid # Returns filling grid - the solution found by the code\r\n\r\n\r\n\r\n\r\n\r\nclass Gridfill():\r\n '''Grid fill class contains all the required objects and methods to complete the task. Its self.filling_grid object is the solution'''\r\n \r\n def __init__(self, T):\r\n '''Method defines all the required global variables and once at the start'''\r\n\r\n self.T = T\r\n self.height = len(T) # Dimensions of grid\r\n self.width = len(T[0])\r\n self.neighbours_grid = [[0 for i in range(self.width)] for j in range(self.height)] #Empty grid to be used as part of the greedy algorithm (see find_neighbours())\r\n self.filling_grid = [[(0,0) for i in range(self.width)] for j in range(self.height)] #Empty grid to be to be filled with pieces and returned as result\r\n self.count = 1 #Variable to keep track of piece number as the filling grid is filled\r\n\r\n # piece_walk_graph dictionary contains the unweighted graph of the tree used to find spaces to place a pieces in the grid.\r\n # The traversal begins at 'start' and can go in any direction from there.\r\n # Each pieces is broken down into steps: up (u), down (d), left (l), or right(r) from the previous point.\r\n # Pieces that have no continuous walk from start to finish end in a 1 or 2 and the coordinates of the \"jump\" to the final point are given so they can still be considered.\r\n # A program was built to optimse the pieces priorities by testing the accuracy of every possible order and returning the best dictionary.\r\n self.piece_walk_graph = {\r\n 'start': [['l'], ['d'], ['u'], ['r']], \r\n 'r': [['rr'], ['rd'], ['ru']],\r\n 'd': [['dl'], ['dr'], ['dd']],\r\n 'l': [['lu'], ['ll'], ['ld']],\r\n 'u': [['ur'], ['ul'], ['uu']],\r\n \r\n 'ru': [['ru1', [0, 2]], ['rur'], ['ruu'], ['ru2', [1, 1]]],\r\n 'rr': [['rrd'], ['rru']],\r\n 'rd': [['rdr'], ['rd1', [0, -2]],['rd2', [1, -1]], ['rdd']],\r\n \r\n 'dr': [['drr'], ['drd'], ['dr1', [-2, 0]]],\r\n 'dl': [['dld'], ['dll'], ['dl1', [2, 0]]], \r\n 'dd': [['ddr'], ['ddl'], ['dd1', [-1, -1]], ['dd2', [1, -1]]],\r\n \r\n 'lu': [['lu2', [-1, 1]], ['lu1', [0, 2]], ['lul'], ['luu']],\r\n 'll': [['lld'], ['llu']],\r\n 'ld': [['ld1', [-1, -1]], ['ldd'], ['ldl'], ['ld2', [0, -2]]],\r\n \r\n 'ur': [['urr'], ['uru'], ['ur1', [-2, 0]]],\r\n 'ul': [['ulu'], ['ul1', [2, 0]], ['ull']],\r\n 'uu': [['uu1', [-1, 1]], ['uur'], ['uul'], ['uu2', [1, 1]]]\r\n }\r\n\r\n # piece_id dirctionary contains the pieceID for all the complete pieces used when placing them in the returned grid.\r\n self.piece_id = {'rur': 16, 'ruu': 8, 'ru1': 14, 'ru2': 13, 'rru': 5, 'rrd': 9, 'rd2': 15, 'rdd': 6, 'rdr': 18, 'rd1': 14, 'dr1': 13, 'drd': 17, 'drr': 11, 'dll': 5, 'dld': 19, 'dl1': 13, 'dd2': 12, 'ddr': 4, 'ddl': 8, 'dd1': 14, 'lu1': 12, 'lu2': 13, 'luu': 4, 'lul': 18, 'lld': 7, 'llu': 11, 'ld2': 12, 'ldd': 10, 'ld1': 15, 'ldl': 16, 'urr': 7, 'ur1': 15, 'uru': 19, 'ull': 9, 'ulu': 17, 'ul1': 15, 'uul': 6, 'uur': 10, 'uu2': 12, 'uu1': 14}\r\n\r\n\r\n\r\n def find_neighbours(self, startx, starty, endx, endy):\r\n ''' Method gives each position needing filling a score equal to the number of neighbouring 1s.\r\n - Method is first passed for the entire grid. \r\n - Then when a piece is placed its passed again, for a square around the point that has changed. \r\n - Therefore only the positions with changed values are recalculated saving time. \r\n - Updating the neighbours grid each time ensures greedy decisions are accurate.'''\r\n\r\n #Runs through every position being checked\r\n for y in range(starty, endy):\r\n for x in range(startx, endx):\r\n neighbours = 0 #Variable to record neighbours for the given position\r\n\r\n try: \r\n if self.T[y][x] == 1: # If position needs filled \r\n\r\n # Checks all nieghbouring pieces and adds one to neighbours if it needs filled \r\n if y+1 < self.height: #If current row is not bottom row\r\n if self.T[y+1][x]== 1:\r\n neighbours += 1\r\n\r\n if x-1 >= 0: #If current collum is not first collum\r\n if self.T[y][x-1] == 1:\r\n neighbours += 1\r\n\r\n if x+1 < self.width: # If current collum is not the last collum\r\n if self.T[y][x+1] == 1:\r\n neighbours += 1\r\n\r\n if y-1 >= 0: # If current row is not top row\r\n if self.T[y-1][x] == 1:\r\n neighbours += 1\r\n #Sets value position of nieghbours grid to the value of surrounding neigbours \r\n self.neighbours_grid[y][x] = neighbours\r\n\r\n except:\r\n pass\r\n\r\n\r\n\r\n def fill_grid(self, fill_type, allow_force=False):\r\n ''' Method is used to search through the neighbours grid to find positions to begin filling pieces in. \r\n - If fill_type is set to smart it will begin at positions with only one neighbour as these have to be the origin of a piece.\r\n - If fill_type is set to dumb it starts filling from the first empty position, filling any spaces missed by smart - useful for high densities. \r\n - If allow_force is set to True and fill_type is dumb then it will force piecess in whenever it is benefital to do so. \r\n - The method will continue to call itself recursivley until it stops being able to place a pieces (induction). '''\r\n\r\n should_repeat = False # Variable used to see if function should be recalled\r\n\r\n # Runs through entire grid\r\n for y_point in range(self.height):\r\n for x_point in range(self.width):\r\n \r\n #Smart Fill\r\n if self.neighbours_grid[y_point][x_point] == 1 and fill_type == 'smart': # If position has only one neighbour\r\n \r\n shape = self.find_space(['start', [[y_point, x_point]]]) # Runs find_space() to try fill the space. If it fails to it sets shape variable to 0\r\n\r\n if shape != 0: # If find_space() placed a piece\r\n should_repeat = True # Sets variabe to True so method is called again\r\n\r\n #Dumb fill & dumb fill with force\r\n elif self.neighbours_grid[y_point][x_point] != 0 and fill_type == 'dumb': # If position is needs filled\r\n\r\n shape = self.find_space(['start', [[y_point, x_point]]], allow_force) \r\n\r\n if shape != 0:\r\n should_repeat = True \r\n\r\n if should_repeat:\r\n return self.fill_grid(fill_type, allow_force) # Recursivley calls method\r\n else:\r\n return 0 # Ends\r\n\r\n\r\n\r\n def find_space(self, start, allow_force = False):\r\n ''' Method is used to find a piece that fits in the space. \r\n - It uses the piece_walk_graph to transverse through the space needing filling, from the starting point (found by fill_grid), until it either finds\r\n a space to place a piece or runs out of possible pieces to fill it. \r\n - It uses greedy iterative depth first search, choosing the next step from the piece_walk_graph that has the lowest number of neighbours first. If \r\n that path leads to a dead end it backtracks - checking every possible piece before ending.\r\n - It also uses prune and search to speed up the process by not following paths that lead to a deada dead end. If the allow_force is set to True it will \r\n also save any spaces only 1 step off a complete piece and attempt to force a piece into them if no complete path can be found.''' \r\n\r\n\r\n to_visit = [start] # Creates the stack of nodes to visit\r\n could_force = [] # Creates an array for potential spaces to force pieces into\r\n\r\n # Repeats process until every potential node has been visited\r\n while len(to_visit) != 0:\r\n steps = to_visit[-1][1] # Takes the top position in the stack\r\n y_point = steps[-1][0]\r\n x_point = steps[-1][1]\r\n\r\n possible_steps = self.piece_walk_graph[to_visit[-1][0]] # Uses piece_walk_graph to find any potential possible steps\r\n\r\n # Cycles through the potential steps\r\n step_neighbours = {}\r\n step_coordinates = {}\r\n for i in possible_steps:\r\n \r\n # If it is possible to make the step and the space needs filled it's neighbours and coordinates are recorded\r\n # If the step can't be made that section of the graph is no longer followed (prune and search)\r\n if i[0][-1] == 'r' and self.possible_step(i, x_point, y_point) == 1:\r\n step_coordinates[i[0]] = [y_point, x_point+1]\r\n step_neighbours[i[0]] = self.neighbours_grid[y_point][x_point+1]\r\n\r\n elif i[0][-1] == 'd' and self.possible_step(i, x_point, y_point) == 1:\r\n step_coordinates[i[0]] = [y_point + 1, x_point]\r\n step_neighbours[i[0]] = self.neighbours_grid[y_point+1][x_point]\r\n\r\n elif i[0][-1] == 'l' and self.possible_step(i, x_point, y_point) == 1:\r\n step_coordinates[i[0]] = [y_point, x_point - 1]\r\n step_neighbours[i[0]] = self.neighbours_grid[y_point][x_point-1]\r\n\r\n elif i[0][-1] == 'u' and self.possible_step(i, x_point, y_point) == 1:\r\n step_coordinates[i[0]] = [y_point - 1, x_point]\r\n step_neighbours[i[0]] = self.neighbours_grid[y_point-1][x_point]\r\n \r\n elif (i[0][-1] == '1' or i[0][-1] == '2') and self.possible_step(i, x_point, y_point) == 1:\r\n step_coordinates[i[0]] = [y_point + i[1][1], x_point + i[1][0]]\r\n step_neighbours[i[0]] = self.neighbours_grid[y_point+i[1][1]][x_point+i[1][0]]\r\n\r\n del to_visit[-1] # The current step is removed from the list so it isn't visited again\r\n\r\n # The possible steps are sorted by the neighbour values as required by the greedy algorithm\r\n step_neighbours = sorted(step_neighbours.items(), key=lambda x: x[1], reverse=True)\r\n \r\n # The possible steps are added to the stack with the lowest neighbours count first (greedy algorithm)\r\n for i in step_neighbours:\r\n to_visit.append([i[0], steps + [step_coordinates[i[0]]]])\r\n\r\n # If allow_force is True and the length of the found path is 3 then forcing could be useful so its added to the could_force list\r\n if len(i[0]) == 2 and allow_force:\r\n could_force.append([i[0], steps + [step_coordinates[i[0]]]])\r\n\r\n\r\n if len(to_visit) == 0: #If every point has been visited\r\n if len(could_force) != 0: # If there are any points that could be forced it calls the forcing method\r\n return self.find_force(could_force)\r\n return 0\r\n \r\n elif len(to_visit[-1][0]) == 3: # If the space for a full piece has been found break and call the piece fill method\r\n return self.fill_space(to_visit[-1][1], to_visit[-1][0])\r\n\r\n #If niether of the previous cases are true it repeats the process with the next item in the stack\r\n\r\n\r\n\r\n def find_force(self, could_force): \r\n ''' Method is used to force in pieces. Pieces are only forced if there are 3 connected points needing filling and an empty space.\r\n This reduces missing pieces by 3 and increases excess pieces by 1 improving the score overall. It uses a similar method as find_space() \r\n except it only does it for one set of possible directtions and the space doesnt need to be filled.'''\r\n\r\n #Cycles through all the posistions it could force\r\n for i in could_force:\r\n steps = i[1] # Steps that make up the current position\r\n y_point = steps[-1][0] # Coordinates of the current position \r\n x_point = steps[-1][1]\r\n\r\n possible_pieces = self.piece_walk_graph[i[0]] #Finds potential pieces to force\r\n\r\n #Cycles through all potential pieces\r\n for piece in possible_pieces:\r\n\r\n #If it is possible to make the step and it doesn't overlap with another piece it's coordinates are added to the steps list\r\n if piece[0][-1] == 'r' and self.possible_step(piece, x_point, y_point) != float('inf'):\r\n steps.append([y_point, x_point+1])\r\n\r\n elif piece[0][-1] == 'd' and self.possible_step(piece, x_point, y_point) != float('inf'):\r\n steps.append([y_point+1, x_point])\r\n\r\n elif piece[0][-1] == 'l' and self.possible_step(piece, x_point, y_point) != float('inf'):\r\n steps.append([y_point, x_point-1])\r\n\r\n elif piece[0][-1] == 'u' and self.possible_step(piece, x_point, y_point) != float('inf'):\r\n steps.append([y_point-1, x_point])\r\n\r\n elif (piece[0][-1] == '1' or piece[0][-1] == '2') and self.possible_step(piece, x_point, y_point) != float('inf'):\r\n steps.append([y_point+piece[1][1], x_point+piece[1][0]]) \r\n\r\n #If any forceable piece has been found the fill_space method is called and the process ends\r\n if len(steps) == 4:\r\n return self.fill_space(steps, piece[0])\r\n\r\n #If no pieces can be forced the process stops\r\n return 0\r\n\r\n\r\n\r\n def possible_step(self, piece, x_point, y_point):\r\n ''' Method is used by find_space() and find_force() to see if a proposed step is within the borders of the grid. If it is it returns the\r\n value of the step position in the target grid to be tested to see if its empty/forcable by the find_space() and find_force() method '''\r\n\r\n if piece[0][-1] == 'r':\r\n if x_point+1 < self.width:\r\n return self.T[y_point][x_point+1]\r\n\r\n elif piece[0][-1] == 'd':\r\n if y_point+1 < self.height:\r\n return self.T[y_point+1][x_point]\r\n\r\n elif piece[0][-1] == 'l':\r\n if x_point-1 >= 0:\r\n return self.T[y_point][x_point-1]\r\n\r\n elif piece[0][-1] == 'u':\r\n if y_point-1 >= 0:\r\n return self.T[y_point-1][x_point]\r\n\r\n elif (piece[0][-1] == '1' or piece[0][-1] == '2'):\r\n if y_point+piece[1][1] >= 0 and x_point+piece[1][0] >= 0:\r\n if x_point+piece[1][0] < self.width and y_point+piece[1][1] < self.height:\r\n return self.T[y_point+piece[1][1]][x_point+piece[1][0]]\r\n\r\n # If step is not possible it returns infinity as this value will be rejected by the by find_space() and find_force()\r\n return float('inf')\r\n\r\n\r\n\r\n def fill_space(self, points, piece):\r\n ''' Method used to fill the space found using either find_space() or force_space() '''\r\n\r\n # Cycles through all the coordinates of the space needing filled\r\n for i in points:\r\n self.filling_grid[i[0]][i[1]] = (self.piece_id[piece], self.count) #Sets point in output grid to the required values\r\n self.T[i[0]][i[1]] = float('inf') #Sets the point in the target grid to infinity to desiginate it as a point that cant be changed\r\n self.neighbours_grid[i[0]][i[1]] = 0\r\n \r\n self.count += 1 # Adds one to piece count to keep it update\r\n self.find_neighbours(points[0][1]-4, points[0][0]-4, points[0][1]+4, points[0][0]+4) #Updates the neighbours grid to make sure greedy test is accurate\r\n \r\n return piece","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":17799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"636062495","text":"import readchar\nfrom Equation5 import LinearEquation, QuadEquation\n\nif __name__ == '__main__':\n print('/-------------------------------------------\\\\\\n'\n '|Калькулятор лінійних та квадратних ріванянь|\\n'\n '|-------------------------------------------|\\n'\n '| Функції |\\n'\n '|1. Розв\\'язати рівняння типу ax±b=0 |\\n'\n '|2. Розв\\'язати рівняння типу a^х2±bx±c=0 |\\n'\n '|e - Закрити програму |\\n'\n '|___________________________________________|')\n while 1:\n command = repr(readchar.readchar()).replace('\\'', '')\n if command == 'e':\n break\n elif command == '1':\n print('Вводіть значення a, b натискаючи Enter')\n while 1:\n try:\n a = int(input())\n break\n except ValueError:\n print('Введіть число!')\n while 1:\n try:\n b = int(input())\n break\n except ValueError:\n print('Введіть число!')\n\n equation = LinearEquation(a, b)\n print(equation.roots())\n\n elif command == '2':\n print('Вводіть значення a, b, c натискаючи Enter')\n while 1:\n try:\n a = int(input())\n break\n except ValueError:\n print('Введіть число!')\n while 1:\n try:\n b = int(input())\n break\n except ValueError:\n print('Введіть число!')\n while 1:\n try:\n c = int(input())\n break\n except ValueError:\n print('Введіть число!')\n\n equation = QuadEquation(a, b, c)\n print(equation.roots())\n\n","sub_path":"Object oriented programming/lab_5.py","file_name":"lab_5.py","file_ext":"py","file_size_in_byte":2180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"116962469","text":"from django.conf.urls import url\nfrom . import views\n\napp_name='music'\nurlpatterns = [\n\n #/music/\n url(r'^$', views.index, name='index'),\n\n #/music/albumid/\n url(r'^(?P[0-9]+)/$', views.details,name='detail'),\n #/music/albumid/favourite/\n url(r'^(?P[0-9]+)/favourite/$', views.favourite,name='favourite'),\n]\n","sub_path":"website/music/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"546943629","text":"# Cracking the coding interview 5th ed.\n# Arrays and Strings\n# 1.5 Implement a method to perform basic string compression using the counts of\n# repeated characters. For example, the string aabcccccaaa would become\n# a2blc5a3. If the \"compressed\" string would not become smaller than the\n# original string, your method should return the original string.\n\ndef basic_compression(string):\n # If the string is shorter than 2 characters, there is no way to compress it\n # further, we simply return it.\n if len(string) < 2:\n return string\n\n # The string can be compressed, so we set up the counter and the container.\n count = 1\n compressed = \"\"\n\n # We process each character in the string: if it is the same as the last,\n # we increment the count; if it is different, we write the current count as\n # well as the character to the compressed string, and reset the count.\n # Finally, if we have reached the end, we write the current data to the\n # compressed string before the loop terminates.\n\n for pos in range(1,len(string)):\n if string[pos] == string[pos - 1]:\n count += 1\n else:\n compressed += string[pos - 1] + str(count)\n count = 1\n\n if pos == len(string) - 1:\n compressed += string[pos] + str(count)\n\n # We only return the compressed string if it is actually shorter than the\n # original.\n \n if len(string) < len(compressed):\n return string\n else:\n return compressed\n\nif __name__ == \"__main__\":\n test_case = input(\"String: \")\n\n print(\"Original string ({} characters): {}\".format(len(test_case),test_case))\n print(\"Compressed string ({} characters): {}\".format(len(basic_compression(test_case)),basic_compression(test_case)))\n","sub_path":"ArraysAndStrings/5-stringcompression.py","file_name":"5-stringcompression.py","file_ext":"py","file_size_in_byte":1770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"77728013","text":"# Uses python3\nimport sys\n\ndef get_optimal_value(capacity, weights, values):\n value = 0.\n weight=0\n #print(values,weights)\n #sortedRes = sorted(zip(values,weights), key=lambda tup:tup[0]/tup[1], reverse=True)\n values,weights = (list(t) for t in zip(*sorted(zip(values,weights), key=lambda tup:tup[0]/tup[1], reverse=True)))\n #print(values,weights)\n #for i in range(len(weights)):\n # print(values[i],weights[i])\n i=0\n for i in range(len(weights)):\n if capacity == 0:\n return value\n a=min(weights[i],capacity)\n value += (a*(values[i]/weights[i]))\n weights[i]=weights[i]-a\n capacity=capacity-a\n return value\n\n\nif __name__ == \"__main__\":\n data = list(map(int, sys.stdin.read().split()))\n #sys.stdout.write(data)\n n, capacity = data[0:2]\n values = data[2:(2 * n + 2):2]\n weights = data[3:(2 * n + 2):2]\n #print(data, n,capacity,values,weights)\n opt_value = get_optimal_value(capacity, weights, values)\n print(\"{:.10f}\".format(opt_value))\n","sub_path":"Algo Course 1/week3_greedy_algorithms/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":1039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"323389003","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Feb 11 23:50:46 2017\n\n@author: jaures, jrcasso\n\nthings to add:\n\n EMPTY FUNCTIONS NEED FILLING. DO THEM NAO.\n (Complete) Echo functionality\n (Complete) up arrow history\n (Complete) Implement tabs into interface for different activities\n (Complete) Implement a simple toplevel menu.\n (Complete) EventHandle manual closing of the window to avoid unnessary errors!\n (Started) Implement a preferences window for keybindings and configuration saving.\n (Not started) message handshake to account for packet loss\n (Not started) LaTeX support for math tab.\n (Started) Implement exec() commands into the chat window\n (Not started) Implement fully-functional python console in Code tab\n\n\nissues:\n -Change widget size according to current window size.\n -on mac, the input history controls (up and down) cause a special character\n to be entered after the history is put in the entry widget. we can utilize\n the 'platform' module to address this. On OSX, platform.system() = 'Darwin'\n\n -(Might be solved now) augment commands to be able to take flags that have no values.\n\n -Changing font size also changes font. Fix.\n\n!!!! ALWAYS RUN A STATIC CODE ANALYSIS AFTER AUGMENTATION !!!!\n\"\"\"\nfrom time import localtime, strftime\nimport tkinter as tk\nimport platform\nif platform.system() != 'Darwin':\n import tkinter.ttk as ttk\nelse:\n import ttk as ttk\nimport sys\nimport os\n\ndef parse_input(event=None):\n global input_history\n input_history = [ENTRY_MESSAGE.get()] + input_history\n\n if len(input_history) > history_length:\n input_history = input_history[:-1]\n\n if ENTRY_MESSAGE.get() != \"\":\n if(ENTRY_MESSAGE.get()[0]) == \"-\":\n if util_list[1] is True:\n send_chat(ENTRY_MESSAGE.get())\n command_router(ENTRY_MESSAGE.get().split()[0][1:])\n elif(ENTRY_MESSAGE.get()[0]) == \">\":\n pass\n else:\n send_chat(username + \": \" + ENTRY_MESSAGE.get())\n ENTRY_MESSAGE.delete(0, tk.END)\n TEXT_CHAT.yview_scroll(1, \"units\")\n\n\ndef get_history(event):\n if platform.system() != 'Darwin':\n if event.keycode == 38:\n ENTRY_MESSAGE.delete(0, tk.END)\n ENTRY_MESSAGE.insert(0, input_history[util_list[0] % len(input_history)])\n util_list[0] += 1\n \n if event.keycode == 40:\n ENTRY_MESSAGE.delete(0, tk.END)\n ENTRY_MESSAGE.insert(0, input_history[util_list[0] % len(input_history)])\n util_list[0] -= 1\n else:\n if event.keycode == 126:\n ENTRY_MESSAGE.delete(0, tk.END)\n ENTRY_MESSAGE.insert(0, input_history[util_list[0] % len(input_history)])\n util_list[0] += 1\n \n if event.keycode == 125:\n ENTRY_MESSAGE.delete(0, tk.END)\n ENTRY_MESSAGE.insert(0, input_history[util_list[0] % len(input_history)])\n util_list[0] -= 1 \n \ndef command_router(command):\n \"\"\"RESTRUCTURE\"\"\"\n try:\n if command in command_dict:\n if command_args[command][0] is False:\n command_dict[command]()\n elif command_args[command][0] is True:\n if command_args[command][1] is False:\n command_dict[command](flags)\n elif command_args[command][1]is True:\n try:\n [flags, values] = [(((ENTRY_MESSAGE.get().split(\"|\"))[0][1:]).split())[1:],\n ((ENTRY_MESSAGE.get().split(\"|\"))[1]).split()]\n command_dict[command](flags, values)\n except:\n if \"|\" not in command:\n send_chat(\"Invalid syntax: Delimiter ('|') not found.\")\n else:\n try:\n flags = (ENTRY_MESSAGE.get().split()[1:])\n command_dict[command](flags)\n except:\n if \"|\" not in command:\n send_chat(\"Debug me.\")\n else:\n send_chat(\"Internal error when dealing with flags.\")\n else:\n send_chat(\"Invalid command: {}\".format(command))\n except:\n send_chat(\"Unexpected error: {}\".format(sys.exc_info()[0]))\n\n ENTRY_MESSAGE.delete(0, tk.END)\n\n\ndef command_font(flags, values):\n arg_dict = dict(zip(flags, values))\n for i in flags:\n try:\n if i == \"fg\":\n TEXT_CHAT['foreground'] = arg_dict[i]\n elif i == \"bg\":\n TEXT_CHAT['background'] = arg_dict[i]\n elif i == \"f\":\n TEXT_CHAT['font'] = arg_dict[i]\n elif i == \"s\":\n TEXT_CHAT.configure(font=(TEXT_CHAT['font'], arg_dict[i]))\n else:\n send_chat(\"Invalid flag: \" + i)\n except:\n send_chat(\"Invalid value: {}\".format(arg_dict[i]))\n\ndef command_echo():\n global util_list\n if util_list[1] is False:\n util_list[1] = True\n send_chat(\"Echo toggled on.\")\n else:\n util_list[1] = False\n send_chat(\"Echo toggled off.\")\n\ndef window_config(event):\n TEXT_CHAT.config(width=(event.width - 10))\n\ndef command_editor(flags, values=None):\n global util_list\n arg_dict = dict(zip(flags, values))\n for i in flags:\n try:\n if i == \"e\":\n util_list[2] = not util_list[2]\n\n elif i == \"bg\":\n pass\n else:\n pass\n except:\n send_chat(\"Invalid value: {}\".format(arg_dict[i]))\n\ndef command_help():\n send_chat(\"Get the fuck outta' here, I'm not typing out that shit...\\n\", tk.END, False)\n\ndef open_local_config():\n send_chat(\"Preferences are currently under construction.\",tk.END, False)\n\ndef load_local_config():\n #local_config = os.open()\n pass\n\ndef save_local_config():\n pass\n\ndef send_chat(msg, pos=tk.END, timestamp=True):\n if util_list[2] is True:\n if timestamp is True:\n TEXT_CHAT.insert(pos, \"\\n({}) {}\".format(strftime(\"%H:%M:%S\", localtime()), msg))\n else:\n TEXT_CHAT.insert(pos, \"\\n{}\".format(msg))\n TEXT_CHAT.insert(pos, \"\\n\" + msg)\n else:\n TEXT_CHAT.config(state=tk.NORMAL)\n if timestamp is True:\n TEXT_CHAT.insert(pos, \"\\n({}) {}\".format(strftime(\"%H:%M:%S\", localtime()), msg))\n else:\n TEXT_CHAT.insert(pos, \"\\n{}\".format(msg))\n TEXT_CHAT.config(state=tk.DISABLED)\n\ndef quit_app():\n ROOT.destroy()\n\nROOT = tk.Tk()\nROOT.title(\"jChat (beta)\")\n\nNOTEBOOK_TABS = ttk.Notebook(ROOT)\nNOTEBOOK_TABS.pack()\n\nCHAT_INTER = tk.Frame(NOTEBOOK_TABS)\nCHAT_INTER.pack(expand=tk.NO)\nCODE_INTER = tk.Frame(NOTEBOOK_TABS)\nCODE_INTER.pack(expand=tk.NO)\nROOM_INTER = tk.Frame(NOTEBOOK_TABS)\nROOM_INTER.pack(expand=tk.NO)\n\n#CHAT_INTER.bind(\"\", window_config)\nNOTEBOOK_TABS.add(CHAT_INTER, text=\"Chat\", compound=tk.TOP)\nNOTEBOOK_TABS.add(CODE_INTER, text=\"Code\", compound=tk.TOP)\nNOTEBOOK_TABS.add(ROOM_INTER, text=\"Room\", compound=tk.TOP)\n\nTEXT_CHAT = tk.Text(CHAT_INTER, width=60, wrap=tk.WORD, relief=tk.SUNKEN, tabs=('4c'))\nTEXT_CHAT.grid(row=1,column=1, columnspan=2)\n\nMENU_BAR = tk.Menu(ROOT)\nMENU_FILE = tk.Menu(MENU_BAR, tearoff=0)\nMENU_FILE.add_command(label=\"Preferences\", command=open_local_config)\nMENU_FILE.add_separator()\nMENU_FILE.add_command(label=\"Exit\", command=quit_app)\nMENU_BAR.add_cascade(label=\"File\", menu=MENU_FILE)\n\nENTRY_MESSAGE = tk.Entry(CHAT_INTER)\nENTRY_MESSAGE.grid(row=3, column=1, columnspan=2)\nENTRY_MESSAGE.bind(\"\", parse_input)\nENTRY_MESSAGE.bind(\"\", get_history)\nENTRY_MESSAGE.bind(\"\", get_history)\n\n\nusername = \"Intensive\"\n\ncommand_dict = {'ft': command_font,\n 'ed': command_editor,\n 'echo': command_echo,\n 'help': command_help}\n\n\n# {'command': [, ]}\ncommand_args = {'ft': [True, True],\n 'ed': [True, None],\n 'echo': [False],\n 'help': [False]}\n\n# It might be a good idea to simply populate the dictionary\n# from a textfile that has the documentation, to compactify\n# the code:\ncommand_help = {'ft': \"docstring help\",\n 'ed': \"docstring help\",\n 'echo': \"docstring help\",\n 'help': \"docstring help\"}\n\n\n\ninput_history = [\" \"]\nhistory_length = 20\nutil_list = [0, # [counter for input history\n False, # echo commands?\n False] # allow chat editting?]\n\nload_local_config()\nsend_chat(\"Welcome to jChat beta. Enter '-help' for a list of commands. \\n\\n\")\n\nROOT.config(menu=MENU_BAR)\nif platform.system() != 'Darwin':\n pass\nROOT.protocol(\"WM_DELETE_WINDOW\", quit_app) # If user closes window manually [X], destroy window.\nROOT.mainloop()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"367378199","text":"# https://programmers.co.kr/learn/courses/30/lessons/12930?language=python3\n\n#s에서 공백이 있는 인덱스를 저장 후 공백제거, 변환한 문자에 공백 ��가\ndef solution(s):\n answer = []\n s = s.split(\" \")\n print(s)\n for i in range(len(s)):\n for j in range(len(s[i])):\n if j % 2 == 0:\n answer.append(s[i][j].upper())\n else:\n answer.append(s[i][j].lower())\n answer.append(\" \")\n\n answer = ''.join(answer)\n answer = answer[0:len(answer)-1]\n return answer\n\nif __name__ == '__main__':\n s = \"try hello world\"\n print(solution(s))","sub_path":"maeng/programmers/Lv1/210519/210519-이상한문자만들기.py","file_name":"210519-이상한문자만들기.py","file_ext":"py","file_size_in_byte":632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"506107700","text":"#!/usr/bin/env python\n\"\"\"\nThe script to calib 2 cam\n\"\"\"\n\nfrom __future__ import print_function\nimport os\nimport logging\nimport argparse\nimport shutil\nimport time\nimport sys\nimport csv\n\n\nimu_headers = [\"timestamp\", \"omega_x\", \"omega_y\",\n \"omega_z\", \"alpha_x\", \"alpha_y\", \"alpha_z\"]\n\n\ndef utc2local(utc_dtm):\n local_tm = datetime.fromtimestamp(0)\n utc_tm = datetime.utcfromtimestamp(0)\n offset = local_tm - utc_tm\n return utc_dtm + offset\n\n\ndef local2utc(local_dtm):\n return datetime.utcfromtimestamp(local_dtm.timestamp())\n\n\ndef main():\n \"\"\"\n The main function\n \"\"\"\n parser = argparse.ArgumentParser(\n description='A script to parse raw data')\n parser.add_argument('input_dir', type=str, default='', help='the stereo dataset directory to be processed')\n parser.add_argument('output_dir', type=str, default='', help='the stereo param result')\n parser.add_argument('imagelist_file', type=str, default='', help='imagelist')\n parser.add_argument('imu_file', type=str, default='imu0_0.txt', help='raw imu data path')\n parser.add_argument('--image_timestamp_file', type=str, default='image_timestamp.txt', help='image timestamp file')\n parser.add_argument('--imu_timestamp_file', type=str, default='imu_tiemstamp.txt', help='imu timestamp file')\n parser.add_argument('--l_folder', type=str, default='left', help='left cam folder')\n parser.add_argument('--r_folder', type=str, default='right', help='right cam folder')\n parser.add_argument('--target_data_path', type=str, default='data', help='target ros data path')\n parser.add_argument('--cam_model', type=str, default='mono', help='camera model: monocular or stereo or stereo_imu')\n parser.add_argument('--imu_yaml', type=str, default=\"\", help=\" imu intrinsic file\" )\n parser.add_argument('--cams_chain_yaml', type=str, default=\"\", help=\" cams chain file\" )\n\n args = parser.parse_args()\n input_dir = args.input_dir\n output_dir = args.output_dir\n imagelist_file = args.imagelist_file\n image_ts_file = args.image_timestamp_file\n imu_file = args.imu_file\n imu_ts_file = args.imu_timestamp_file\n l_folder = args.l_folder\n r_folder = args.r_folder\n dataset_path = args.target_data_path\n cam_model = args.cam_model\n imu_yaml = args.imu_yaml\n cams_chain_yaml = args.cams_chain_yaml\n\n l_folder = os.path.join(input_dir, l_folder)\n r_folder = os.path.join(input_dir, r_folder)\n image_ts_file = os.path.join(input_dir, image_ts_file)\n imu_ts_file = os.path.join(input_dir, imu_ts_file)\n\n # mkdir\n dataset_cam0_path = os.path.join(dataset_path, 'cam0')\n dataset_cam1_path = os.path.join(dataset_path, 'cam1')\n new_imu_file = os.path.join(dataset_path, 'imu0.csv')\n\n if os.path.exists(dataset_cam0_path):\n shutil.rmtree(dataset_cam0_path)\n os.makedirs(dataset_cam0_path)\n if os.path.exists(dataset_cam1_path):\n shutil.rmtree(dataset_cam1_path)\n os.makedirs(dataset_cam1_path)\n if(os.path.exists(new_imu_file)):\n os.remove(new_imu_file)\n\n img_timestamps = {}\n # image timestamp is the unit of second\n with open(image_ts_file, 'r') as img_ts_fd:\n for line in img_ts_fd:\n if(len(line) > 0):\n img_ts = line.split()\n img_timestamps[img_ts[2]] = str(int(float(img_ts[0]) * 1000000))+'000'\n\n img_start_timestamps = float(img_timestamps['0'])/1000000\n new_imu_datas = []\n\n with open(imu_file, 'r') as imu_fd:\n imu_datas = imu_fd.readlines()\n imu_datas = [d.strip() for d in imu_datas if len(d.split()) != 0]\n imu_datas.sort(key=lambda x: x.split()[0])\n\n # import imagelist\n with open(imagelist_file, 'r') as img_fd:\n img_names = img_fd.readlines()\n img_names = [x.strip() for x in img_names]\n\n for img_name in img_names:\n l_img_path = os.path.join(l_folder, img_name)\n r_img_path = os.path.join(r_folder, img_name)\n\n img_frame_num = img_name[6:-4]\n l_img_dst_path = os.path.join(\n dataset_cam0_path, img_timestamps[img_frame_num] + '.' + img_name.split(\".\")[1])\n r_img_dst_path = os.path.join(\n dataset_cam1_path, img_timestamps[img_frame_num] + '.' + img_name.split(\".\")[1])\n\n shutil.copyfile(l_img_path, l_img_dst_path)\n if cam_model == \"stereo_imu\":\n shutil.copyfile(r_img_path, r_img_dst_path)\n\n for imu_data in imu_datas:\n new_imu_data = imu_data.split()\n imu_timestamp = float(new_imu_data[0])\n # if imu_timestamp >= img_start_timestamps:\n print(\"imu_timestamp: {}\".format(imu_timestamp))\n new_imu_tuple = (int(imu_timestamp*1000000), new_imu_data[4], new_imu_data[5],\n new_imu_data[6], new_imu_data[1], new_imu_data[2], new_imu_data[3])\n new_imu_datas.append(new_imu_tuple)\n\n # write imu.csv\n with open(new_imu_file, 'w') as f:\n f_csv = csv.writer(f)\n f_csv.writerow(imu_headers)\n f_csv.writerows(new_imu_datas)\n\n cmds = []\n if cam_model == \"stereo\":\n cmds = ['./kalibr_stereo.sh', dataset_path, output_dir]\n elif cam_model == \"mono\":\n cmds = ['./kalibr_mono.sh', dataset_path, output_dir]\n elif cam_model == \"stereo_imu\":\n cmds = ['./kalibr_stereo_imu.sh', dataset_path, output_dir, imu_yaml, cams_chain_yaml]\n elif cam_model == \"mono_imu\":\n cmds = ['./kalibr_mono_imu.sh', dataset_path, output_dir, imu_yaml, cams_chain_yaml]\n else:\n sys.exit(\"Invalid camera model!\")\n\n cmds = ' '.join(cmds)\n os.system(cmds)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"prepare_kalibr_for_backpack.py","file_name":"prepare_kalibr_for_backpack.py","file_ext":"py","file_size_in_byte":5748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"602672781","text":"from tkinter import *\n\nclass GameWindows:\n def __init__(self, master):\n self.master = master\n self.master.title('')\n self.master.resizable(False, False)\n\n self._create_main_frames()\n self._display_game_title()\n self._create_windows()\n\n def _create_main_frames(self):\n self.left_frame = Frame(self.master, bg='black')\n self.left_frame.pack(side=LEFT)\n\n self.right_frame = Frame(self.master)\n self.right_frame.pack()\n\n def _display_game_title(self):\n self.title_frame = Frame(self.right_frame)\n self.title_frame.pack()\n Label(self.title_frame, text='PROB SHOT', width=28,\n bg='blue', fg='white', font=('Verdana', 18, 'bold')).pack()\n\n def _create_windows(self):\n self.game_stats_window = GameStatsWindow(self.left_frame)\n self.overview_window = OverviewWindow(self.right_frame)\n self.difficulty_window = DifficultyWindow(self.right_frame)\n self.allocation_info_window = AllocationInfoWindow(self.right_frame)\n self.pct_allocation_window = PctAllocationWindow(self.right_frame)\n self.results_window = ResultsWindow(self.right_frame)\n self.shot_selection_window = ShotSelectionWindow(self.right_frame)\n self.prompt_window = PromptWindow(self.right_frame)\n self.game_results_window = GameResultsWindow(self.right_frame)\n\nclass GameStatsWindow:\n def __init__(self, parent):\n self.parent = parent\n\n def open(self):\n self._create_frames()\n self._display_scores_frame()\n self._display_team_stats_frame()\n\n def close(self):\n self.scores_frame.destroy()\n self.team_stats_frame.destroy()\n\n def _create_frames(self):\n self.scores_frame = Frame(self.parent, bg='black')\n self.scores_frame.pack()\n\n self.team_stats_frame = Frame(self.parent, bg='orange')\n self.team_stats_frame.pack()\n\n def _display_scores_frame(self):\n self._display_score_headers()\n self._display_round()\n self._display_scores()\n\n def _display_score_headers(self):\n Label(self.scores_frame, text='CPU', width=9,\n bg='black', fg='white', font=('Courier', 28, 'bold')\n ).grid(row=0, column=0, pady=5)\n Label(self.scores_frame, text='Score',\n bg='black', fg='red', font=('Courier', 20, 'bold')\n ).grid(row=0, column=1)\n Label(self.scores_frame, text='Team', width=9,\n bg='black', fg='white', font=('Courier', 28, 'bold')\n ).grid(row=0, column=2, pady=5)\n\n def _display_round(self):\n self.rounds_label = Label(self.scores_frame, text='', bg='black', \n fg='yellow', font=('Courier', 22, 'bold'))\n self.rounds_label.grid(row=1, column=1)\n\n def _display_scores(self):\n self.cpu_score_label = Label(self.scores_frame, text=0, \n relief=RAISED, bg='black', fg='red',\n font=('Courier', 57))\n self.cpu_score_label.grid(row=1, column=0, pady=8)\n\n self.user_score_label = Label(self.scores_frame, text=0,\n relief=RAISED, bg='black', fg='red',\n font=('Courier', 57))\n self.user_score_label.grid(row=1, column=2, pady=8)\n\n def _display_team_stats_frame(self):\n self._display_cpu_player_names_and_stats()\n self._display_team_line_separator()\n self._display_user_player_names_and_stats()\n\n def _display_cpu_player_names_and_stats(self):\n self._display_shot_types_and_points_header(columns=range(0,5))\n self._display_cpu_player_names()\n self._display_cpu_player_stats()\n\n def _display_team_line_separator(self):\n for row in range(0,7):\n Label(self.team_stats_frame, width=0, bg='black'\n ).grid(row=row, column=4) \n\n def _display_user_player_names_and_stats(self):\n self._display_shot_types_and_points_header(columns=range(5,9))\n self._display_user_player_names()\n self._display_user_player_stats()\n\n def _display_shot_types_and_points_header(self, columns):\n for text, column in zip(['FT', 'FG', '3-PT', 'Points'], columns):\n Label(self.team_stats_frame, text=text,\n bg='orange', fg='blue', font=('Courier', 18, 'bold')\n ).grid(row=0, column=column, pady=6)\n\n def _display_cpu_player_names(self):\n self.cpu_names_labels = ['CPU 1 Name', 'CPU 2 Name', 'CPU 3 Name']\n self._display_names('CPU', self.cpu_names_labels,\n rows=(1,3,5), column=0)\n\n def _display_cpu_player_stats(self):\n self.cpu1_stats_labels = ['FT:0/0', 'FG:0/0', '3-PT:0/0', 'Points:0']\n self.cpu2_stats_labels = ['FT:0/0', 'FG:0/0', '3-PT:0/0', 'Points:0']\n self.cpu3_stats_labels = ['FT:0/0', 'FG:0/0', '3-PT:0/0', 'Points:0']\n self._display_stats(self.cpu1_stats_labels, row=2, columns=range(0,4))\n self._display_stats(self.cpu2_stats_labels, row=4, columns=range(0,4))\n self._display_stats(self.cpu3_stats_labels, row=6, columns=range(0,4))\n\n def _display_user_player_names(self):\n self.p_names_labels = ['Player 1 Name',\n 'Player 2 Name',\n 'Player 3 Name'] \n self._display_names('Player', self.p_names_labels, \n rows=(1,3,5), column=5)\n\n def _display_user_player_stats(self):\n self.p1_stats_labels = ['FT:0/0', 'FG:0/0', '3-PT:0/0', 'Points:0']\n self.p2_stats_labels = ['FT:0/0', 'FG:0/0', '3-PT:0/0', 'Points:0']\n self.p3_stats_labels = ['FT:0/0', 'FG:0/0', '3-PT:0/0', 'Points:0']\n self._display_stats(self.p1_stats_labels, row=2, columns=range(5,9))\n self._display_stats(self.p2_stats_labels, row=4, columns=range(5,9))\n self._display_stats(self.p3_stats_labels, row=6, columns=range(5,9))\n\n def _display_names(self, team_name, names_label_list, rows, column):\n num_names_label = len(names_label_list)\n for i, row in zip(range(num_names_label), rows):\n names_label_list[i] = Label(self.team_stats_frame, width=16, \n text='{} {}'.format(team_name, i+1),\n bg='orange', font=('Courier', 22))\n names_label_list[i].grid(row=row, column=column, \n columnspan=4, pady=4)\n\n def _display_stats(self, stats_label_list, row, columns):\n #Display FT, FG, and 3-PT.\n num_stats_label = len(stats_label_list)\n for i, column in zip(range(num_stats_label-1), columns):\n stats_label_list[i] = Label(self.team_stats_frame, text='0/0',\n bg='orange', fg='blue', height=1,\n font=('Courier', 17))\n stats_label_list[i].grid(row=row, column=column, padx=3, pady=6)\n\n #Display points.\n stats_label_list[-1] = Label(self.team_stats_frame, text=0,\n bg='orange', fg='blue',\n font=('Courier', 17))\n stats_label_list[-1].grid(row=row, column=columns[-1])\n\nclass OverviewWindow:\n def __init__(self, parent):\n self.parent = parent\n\n def open(self):\n self._create_overview_frame()\n self._display_overview()\n self._display_overview_button()\n\n def close(self):\n self.overview_frame.destroy()\n self.button.destroy()\n\n def _create_overview_frame(self):\n self.overview_frame = Frame(self.parent)\n self.overview_frame.pack()\n\n def _display_overview(self):\n text = (\n \"Objective:\\n\"\n \"Team with most points after 10 rounds is the winner.\\n\"\n \"If teams are tied after 10. Game heads to overtime.\\n\\n\"\n \"Gameplay:\\n\"\n \"Each team consists of 3 players.\\n\"\n \"Each player is given one shot per round.\\n\"\n \"A player can choose to take either a FT, FG, or Three.\\n\\n\"\n \"Points:\\n\"\n \"1 - FT\\n\"\n \"2 - FG\\n\"\n \"3 - Three\\n\\n\"\n \"Probability of Making Shot:\\n\"\n \"Each player has a percentage associated with each shot.\\n\\n\"\n \"Heating Up/Cooling Down Factor:\\n\"\n \"2% is added/subtracted to a player's percentage for all\\n\"\n \"shot type for every consecutive shots made/miss after 2.\"\n )\n Label(self.overview_frame, text=text,\n font=('Ariel'), justify=LEFT).pack()\n\n def _display_overview_button(self):\n self.button = Button(self.parent, text='Select Difficulty >>>')\n self.button.pack()\n\nclass DifficultyWindow:\n def __init__(self, parent):\n self.parent = parent\n\n def open(self):\n self._create_difficulty_frame()\n self._display_difficulty_selection()\n self._display_difficulty_button()\n\n def close(self):\n self.diff_frame.destroy()\n\n def _create_difficulty_frame(self):\n self.diff_frame = Frame(self.parent)\n self.diff_frame.pack()\n\n def _display_difficulty_selection(self):\n Label(self.diff_frame, text='\\n\\n\\nDifficulty:\\n\\n\\n',\n font=('Courier', 16, 'bold')).pack()\n\n self._create_difficulty_selection()\n\n Label(self.diff_frame, text='\\n\\n\\n').pack()\n\n def _create_difficulty_selection(self):\n self.difficulty = StringVar()\n\n self._display_difficulty_radiobuttons()\n\n def _display_difficulty_radiobuttons(self):\n self.rbutton_values = ['Easy', 'Medium', 'Hard']\n\n num_rbuttons = len(self.rbutton_values)\n for i, diff in zip(range(num_rbuttons), self.rbutton_values):\n self.rbutton_values[i] = Radiobutton(self.diff_frame,\n text=diff, value=diff, \n variable=self.difficulty,\n font=('Courier', 22))\n self.rbutton_values[i].pack(pady=4)\n\n def _display_difficulty_button(self):\n self.button = Button(self.diff_frame, text='Percent Allocation >>>')\n self.button.pack()\n\nclass AllocationInfoWindow:\n def __init__(self, parent):\n self.parent = parent\n\n def open(self):\n self._create_allocation_info_frame()\n self._display_allocation_info()\n self._display_allocation_info_button()\n\n def close(self):\n self.allocation_info_frame.destroy()\n\n def _create_allocation_info_frame(self):\n self.allocation_info_frame = Frame(self.parent)\n self.allocation_info_frame.pack()\n\n def _display_allocation_info(self):\n Label(self.allocation_info_frame,\n text='\\nPercent Allocation Instruction',\n width=28, font=('Ariel', 20)).pack()\n\n text = (\n \"\\nDefault percentage for your players are:\\n\"\n \"\\nFT: 0.7 \\t\\tFG: 0.4 \\t\\t3-PT: 0.3\\n\"\n \"\\nYou have 10 points to increase % among your 3 players.\\n\"\n \"\\n1 point will increase FT percentage by 10%.\\n\"\n \"\\n2 points will increase FG percentage by 10%.\\n\"\n \"\\n3 points will increase 3-PT percentage by 10%.\\n\\n\\n\"\n )\n Label(self.allocation_info_frame, text=text, justify=LEFT).pack()\n\n def _display_allocation_info_button(self):\n self.button = Button(self.allocation_info_frame,\n text='Allocate Percentage >>>')\n self.button.pack()\n\nclass PctAllocationWindow:\n def __init__(self, parent):\n self.parent = parent\n\n def open(self):\n self._create_points_remaining_and_pct_allocation_frame()\n self._display_points_remaining_frame()\n self._display_pct_allocation_frame()\n\n def close(self):\n self.points_remaining_frame.destroy()\n self.pct_allocation_frame.destroy()\n self.button.destroy()\n\n def _create_points_remaining_and_pct_allocation_frame(self):\n self.points_remaining_frame = Frame(self.parent)\n self.points_remaining_frame.pack()\n\n self.pct_allocation_frame = Frame(self.parent)\n self.pct_allocation_frame.pack(pady=7)\n\n def _display_points_remaining_frame(self):\n text=('Please enter names.\\n\\n'\n 'FT: 1 Point FG: 2 Points 3-PT: 3 Points') \n Label(self.points_remaining_frame, text=text\n ).grid(row=0, column=0, columnspan=2)\n\n Label(self.points_remaining_frame, text='Points Left: ', justify=RIGHT\n ).grid(row=1, column=0)\n self.points_remaining_label = Label(self.points_remaining_frame,\n text='10', width=5)\n self.points_remaining_label.grid(row=1, column=1, pady=5, sticky=W)\n\n def _display_pct_allocation_frame(self):\n self._display_player_names_and_shot_types_labels()\n self._display_player_name_entries()\n self._display_pct_allocation_spinbox()\n self._display_pct_allocation_button()\n\n def _display_player_names_and_shot_types_labels(self):\n for i, row in zip((1,2,3), (0,2,4)):\n Label(self.pct_allocation_frame,\n text='Player {} Name: '.format(i)\n ).grid(row=row, column=0, columnspan=2, pady=3)\n\n for row in (1,3,5):\n for text, column in zip(['FT: ', 'FG: ', '3-PT: '], (0,2,4)):\n Label(self.pct_allocation_frame, text=text\n ).grid(row=row, column=column, pady=3)\n\n def _display_player_name_entries(self):\n self.p_name_entries = [StringVar(), StringVar(), StringVar()]\n names=[None]*3 \n\n num_entries = len(self.p_name_entries)\n for i, row in zip(range(num_entries), (0,2,4)):\n names[i] = Entry(self.pct_allocation_frame,\n textvariable=self.p_name_entries[i])\n names[i].grid(row=row, column=2,columnspan=4, pady=3)\n names[i].insert(0, 'Player {}'.format(i+1))\n\n def _display_pct_allocation_spinbox(self):\n #Values for spinbox.\n self.pct_range = ((0.7, 0.8, 0.9, 1.0), #FT\n (0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0), #FG\n (0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0)) #3-PT\n\n self.p1_pcts_value = ['FT%', 'FG%', '3-PT%']\n self.p2_pcts_value = ['FT%', 'FG%', '3-PT%']\n self.p3_pcts_value = ['FT%', 'FG%', '3-PT%']\n self._display_spinbox(self.p1_pcts_value, self.pct_range, row=1)\n self._display_spinbox(self.p2_pcts_value, self.pct_range, row=3)\n self._display_spinbox(self.p3_pcts_value, self.pct_range, row=5)\n\n def _display_spinbox(self, player_pcts, pct_range, row):\n num_pcts = len(player_pcts)\n for i, column, pct in zip(range(num_pcts), (1,3,5), pct_range):\n player_pcts[i] = Spinbox(self.pct_allocation_frame,\n values=pct, width=5, state='readonly')\n player_pcts[i].grid(row=row, column=column, pady=3)\n\n def _display_pct_allocation_button(self):\n self.button = Button(self.parent, text='Start Prob Shot >>>')\n self.button.pack()\n\nclass ResultsWindow:\n def __init__(self, parent):\n self.parent = parent\n\n def open(self):\n self._create_results_frame()\n self._display_result_labels()\n self._display_results_button()\n\n def close(self):\n self.results_frame.destroy()\n\n def _create_results_frame(self):\n self.results_frame = Frame(self.parent)\n self.results_frame.pack()\n Label(self.results_frame).pack(pady=5)\n\n def _display_result_labels(self):\n self.result_labels = ['Result 1', 'Result 2', 'Result 3']\n\n num_result_labels = len(self.result_labels)\n for i in range(num_result_labels):\n self.result_labels[i] = Label(self.results_frame, height=2,\n font=('Ariel', 18, 'bold'))\n self.result_labels[i].pack(pady=15)\n\n def _display_results_button(self):\n self.button = Button(self.results_frame)\n self.button.pack(pady=5)\n\nclass ShotSelectionWindow:\n def __init__(self, parent):\n self.parent = parent\n\n def open(self):\n self._create_player_shot_frames()\n self._create_player_shot_type_variables()\n self._display_player_info()\n self._display_shot_type_radiobuttons()\n self._display_shot_selection_button()\n\n def close(self):\n self.p1_shot_frame.destroy()\n self.p2_shot_frame.destroy()\n self.p3_shot_frame.destroy()\n self.button.destroy()\n\n def _create_player_shot_frames(self):\n self.p1_shot_frame = Frame(self.parent)\n self.p2_shot_frame = Frame(self.parent)\n self.p3_shot_frame = Frame(self.parent)\n self.p1_shot_frame.pack(pady=4)\n self.p2_shot_frame.pack(pady=4)\n self.p3_shot_frame.pack(pady=4)\n\n def _create_player_shot_type_variables(self):\n self.p1_shot_type = StringVar()\n self.p2_shot_type = StringVar()\n self.p3_shot_type = StringVar()\n\n def _display_player_info(self):\n self.p1_info_labels = ['Name', 'FT%', 'FG%', '3-PT%', 'Consec Shots']\n self._display_info_labels(self.p1_info_labels, self.p1_shot_frame)\n\n self.p2_info_labels = ['Name', 'FT%', 'FG%', '3-PT%', 'Consec Shots']\n self._display_info_labels(self.p2_info_labels, self.p2_shot_frame)\n\n self.p3_info_labels = ['Name', 'FT%', 'FG%', '3-PT%', 'Consec Shots']\n self._display_info_labels(self.p3_info_labels, self.p3_shot_frame)\n\n def _display_info_labels(self, info_labels, frame):\n num_info_labels = len(info_labels)\n for i in range(num_info_labels):\n info_labels[i] = Label(frame, font=('Ariel', 11))\n info_labels[i].grid(row=i, column=0, sticky=W)\n\n def _display_shot_type_radiobuttons(self):\n self.shot_type_rbutton1 = ['FT', 'FG', '3-PT']\n self._display_shot_rbutton(self.p1_shot_frame,\n self.shot_type_rbutton1,\n self.p1_shot_type)\n\n self.shot_type_rbutton2 = ['FT', 'FG', '3-PT']\n self._display_shot_rbutton(self.p2_shot_frame,\n self.shot_type_rbutton2,\n self.p2_shot_type)\n\n self.shot_type_rbutton3 = ['FT', 'FG', '3-PT']\n self._display_shot_rbutton(self.p3_shot_frame,\n self.shot_type_rbutton3,\n self.p3_shot_type)\n\n def _display_shot_rbutton(self, frame, radiobutton, variable):\n num_rbuttons = len(radiobutton)\n for i, shot in zip(range(num_rbuttons), ('FT','FG','3-PT')):\n radiobutton[i] = Radiobutton(frame, text=shot, variable=variable,\n value=shot, font=('Ariel',16))\n radiobutton[i].grid(row=2, column=i+1, padx=5)\n\n def _display_shot_selection_button(self):\n self.button = Button(self.parent, text='Take Shots >>>')\n self.button.pack()\n\nclass PromptWindow:\n def __init__(self, parent):\n self.parent = parent\n\n def open(self):\n self._display_prompt_button()\n\n def close(self):\n self.button.destroy()\n\n def _display_prompt_button(self):\n self.button = Button(self.parent, height = 20,\n text='Continue to CPU Results >>>')\n self.button.pack()\n\nclass GameResultsWindow:\n def __init__(self, parent):\n self.parent = parent\n\n def open(self):\n self._create_results_and_button_frame()\n self._display_results_frame()\n self._display_game_result_buttons()\n\n def close(self):\n self.results_frame.destroy()\n self.button_frame.destroy()\n\n def _create_results_and_button_frame(self):\n self.results_frame = Frame(self.parent)\n self.results_frame.pack()\n\n self.button_frame = Button(self.parent)\n self.button_frame.pack()\n\n def _display_results_frame(self):\n self.winner_label = Label(self.results_frame,\n font=('Courier', 20, 'bold'))\n self.winner_label.pack(pady=10)\n\n self.cpu_final_stats_label = Label(self.results_frame,\n font=('Courier', 16))\n self.cpu_final_stats_label.pack(pady=10)\n\n self.user_final_stats_label = Label(self.results_frame,\n font=('Courier', 16))\n self.user_final_stats_label.pack(pady=10)\n\n def _display_game_result_buttons(self):\n self.play_again_button = Button(self.button_frame, text='Play Again')\n self.play_again_button.grid(row=0, column=0, pady=10)\n\n self.quit_game_button = Button(self.button_frame, text='Quit Game')\n self.quit_game_button.grid(row=0, column=1, pady=10)\n","sub_path":"game_windows.py","file_name":"game_windows.py","file_ext":"py","file_size_in_byte":21153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"208923022","text":"\"\"\"The first solution is taken from leetcode and has time complexity of O(NK)\"\"\"\r\n\r\n# import collections\r\n#\r\n#\r\n# def groupAnagrams(strs):\r\n# ans = collections.defaultdict(list)\r\n# for s in strs:\r\n# count = [0] * 26\r\n# for c in s:\r\n# count[ord(c) - ord('a')] += 1\r\n# ans[tuple(count)].append(s)\r\n# return ans.values()\r\n\r\n\"\"\"This has a complexity of O(NKlogK)\"\"\"\r\ndef groupAnagrams(strs):\r\n newstrs = []\r\n dicwords = dict()\r\n finalstrs = []\r\n for i in strs:\r\n newstrs.append(''.join(sorted(i)))\r\n for i in range(len(strs)):\r\n if newstrs[i] in dicwords:\r\n dicwords[newstrs[i]].append(strs[i])\r\n else:\r\n dicwords[newstrs[i]] = [strs[i]]\r\n for key,value in dicwords.items():\r\n finalstrs.append(value)\r\n\r\n print(finalstrs)\r\n\r\n\r\nif __name__ == '__main__':\r\n groupAnagrams([\"eat\", \"tea\", \"tan\", \"ate\", \"nat\", \"bat\"])","sub_path":"Group Anagrams.py","file_name":"Group Anagrams.py","file_ext":"py","file_size_in_byte":931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"271869796","text":"import time, random\nfrom datetime import date\n\nfrom Houdini.Handlers import Handlers, XT\nfrom Houdini.Crumbs.Room import Room\n\nRoomFieldKeywords = {\n \"Id\": None,\n \"InternalId\": None,\n \"Key\": \"Igloo\",\n \"Name\": \"Igloo\",\n \"DisplayName\": \"Igloo\",\n \"MusicId\": 0,\n \"Member\": 0,\n \"Path\": \"\",\n \"MaxUsers\": 100,\n \"JumpEnabled\": False,\n \"JumpDisabled\": True,\n \"RequiredItem\": None,\n \"ShortName\": \"Igloo\"\n}\n\n@Handlers.Handle(XT.JoinWorld)\ndef handleJoinWorld(self, data):\n if int(data.ID) != self.user.ID:\n return self.transport.loseConnection()\n\n if data.LoginKey == \"\":\n return self.transport.loseConnection()\n\n if data.LoginKey != self.user.LoginKey:\n self.user.LoginKey = \"\"\n return self.sendErrorAndDisconnect(101)\n\n hasUpdatedBookCover = int(self.user.StampBook != \"1%1%0%1\")\n self.sendXt(\"js\", 1, self.agentStatus, self.user.Moderator, hasUpdatedBookCover)\n\n # Casting to integer floor's and removes the decimal\n currentTime = int(time.time())\n penguinStandardTime = currentTime * 1000\n serverTimeOffset = 7\n\n registrationDate = date.fromtimestamp(self.user.RegistrationDate)\n currentDateTime = date.fromtimestamp(currentTime)\n\n self.age = (currentDateTime - registrationDate).days\n\n for furnitureDetails in self.user.Furniture.split(\"%\"):\n if not furnitureDetails:\n break\n furnitureId, furnitureQuantity = furnitureDetails.split(\"|\")\n self.furniture[int(furnitureId)] = int(furnitureQuantity)\n\n self.sendXt(\"lp\", self.getPlayerString(), self.user.Coins, 0, 1440,\n penguinStandardTime, self.age, 0, self.age, None, serverTimeOffset)\n\n self.sendXt(\"gps\", self.user.ID, self.user.Stamps)\n\n self.user.LoginKey = \"\"\n self.user.LastLogin = currentTime\n\n self.session.commit()\n\n self.server.players[self.user.ID] = self\n\n buddyList = self.getBuddyList()\n\n for buddyId in buddyList.keys():\n if buddyId in self.server.players:\n self.server.players[buddyId].sendXt(\"bon\", self.user.ID)\n\n randomRoomId = random.choice(self.server.spawnRooms)\n self.server.rooms[randomRoomId].add(self)\n\n@Handlers.Handle(XT.JoinRoom)\ndef handleJoinRoom(self, data):\n if data.RoomId in self.server.rooms:\n self.x = data.X\n self.y = data.Y\n self.frame = 1\n\n self.room.remove(self)\n self.server.rooms[data.RoomId].add(self)\n\n@Handlers.Handle(XT.RefreshRoom)\ndef handleRefreshRoom(self, data):\n self.room.refresh(self)\n\n@Handlers.Handle(XT.JoinPlayerIgloo)\ndef handleJoinPlayerIgloo(self, data):\n if data.Id < 1000:\n return self.transport.loseConnection()\n\n playerId = data.Id - 1000\n\n if playerId != self.user.ID and playerId not in self.buddies \\\n and playerId not in self.server.openIgloos:\n return self.transport.loseConnection()\n\n if data.Id not in self.server.rooms:\n iglooFieldKeywords = RoomFieldKeywords.copy()\n iglooFieldKeywords[\"Id\"] = data.Id\n iglooFieldKeywords[\"InternalId\"] = data.Id\n\n igloo = self.server.rooms[data.Id] = Room(**iglooFieldKeywords)\n else:\n igloo = self.server.rooms[data.Id]\n\n self.room.remove(self)\n\n self.sendXt(\"jp\", data.Id)\n igloo.add(self)","sub_path":"Houdini/Handlers/Play/Navigation.py","file_name":"Navigation.py","file_ext":"py","file_size_in_byte":3269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"142739901","text":"from __future__ import print_function\nfrom dolfin import *\nimport sys\n__author__ = 'jh'\n\n# utility file to test if precomputed Bessel function (modes of Womersley flow) looks right\n\nmeshName = 'cyl_c1'\nfactor = 1.0\nprint('Mesh: '+meshName)\nmesh = Mesh(\"meshes/\" + meshName + \".xml\")\ncell_function = MeshFunction(\"size_t\", mesh, \"meshes/\" + meshName + \"_physical_region.xml\")\nfacet_function = MeshFunction(\"size_t\", mesh, \"meshes/\" + meshName + \"_facet_region.xml\")\nPS = FunctionSpace(mesh, \"Lagrange\", 2) # partial solution (must be same order as V)\n\nf = HDF5File(mpi_comm_world(), 'precomputed/precomputed_'+meshName+'.hdf5', 'r')\nprint(f)\nprint(f.has_dataset('imag0'))\nfce = Function(PS)\nf.read(fce, 'imag1')\nplot(fce, interactive=True)\n","sub_path":"test_generated.py","file_name":"test_generated.py","file_ext":"py","file_size_in_byte":740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"163594890","text":"__author__ = \"Siba Mohsen\"\n__email__ = \"mohsen@students.uni-marbug.de\"\n\nfrom Bio.Data import IUPACData\n\n\nclass Utils:\n\n \"\"\"groups the variables and static methods used in the package AminoAcidComposition in order to be used freely\"\"\"\n\n # The tuple of 20 amino acids should be immutable\n aa_20 = tuple(IUPACData.protein_letters_1to3.keys())\n\n # The tuple of 20 twins amino acids\n aa_twins = ('AA', 'CC', 'DD', 'EE', 'FF', 'GG', 'HH', 'II', 'KK', 'LL',\n 'MM', 'NN', 'PP', 'QQ', 'RR', 'SS', 'TT', 'VV', 'WW', 'YY')\n\n # The set of amino acid residues encoded in three letters code.\n # Since the .pdb dataset includes residues encoded in three letters code, we will be working\n # with them in this paper.\n aa_residues = tuple(a.upper() for a in IUPACData.protein_letters_1to3.values())\n\n @staticmethod\n def frequency(seq, aa_group):\n \"\"\"\n frequency(): calculates the frequency of a specific amino acid group in a peptide sequence (e.g. hydrophobic\n amino acid group) and returns the distance between the closest amino acids in order to classify them later\n in 6 distance classes.\n Example: Matsuda et al.(2005), § 'Distance frequency' will return after calling this function: [3,2,3,2,3].\n INPUT:\n @:param seq: String. The sequence of amino acid.\n @:param aa_group: String. The group for which the frequency distance should be calculated, e.g. basic,\n hydrophobic.\n OUTPUT:\n List. List of the distances between two successive specific amino acids.\n \"\"\"\n freq_index = [pos for pos, char in enumerate(seq) if char in aa_group]\n distance = [(freq_index[d + 1] - freq_index[d]) for d in range(0, len(freq_index) - 1)]\n return distance\n\n @staticmethod\n def reverse(tuples):\n \"\"\"\n Given a tuple, this function reverses its arguments.\n e.g. Input = tuple('a','b','c') -----reverse----> Output = tuple('c','b','a').\n :param tuples: a tuple of any size\n :return: the input tuple reversed\n NOTE: Applying -1 on the usual slice notation of lists/strings/tuples in python list[::]\n allows us to have the reverse of this lists/string/tuple. In this case, step = -1, so the iterable will start\n slicing from the last element till the first one.\n \"\"\"\n new_tup = tuples[::-1]\n return new_tup\n\n @staticmethod\n def sorted_tuple(vertex_index_1, vertex_index_2):\n \"\"\"\n This function allows us to extract the same edge of the tetrahedron only once, even if it comes in reverse\n order.\n This will limit the number of edges to exactly six edges per tetrahedron rather than counting the same edge\n twice: e.g. (ALA, SER) and (SER, ALA) in a tetrahedron containing the vertices [ALA SER CYS TYR].\n :param vertex_index_1: index of the vertex 1.\n :param vertex_index_2: index of the vertex 2.\n :return: one sorted tuple for each edge in a tetrahedron.\n \"\"\"\n return (vertex_index_1, vertex_index_2) if vertex_index_1 < vertex_index_2 else \\\n (vertex_index_2, vertex_index_1)\n\n @staticmethod\n def distance_3d(point1, point2):\n \"\"\"\n To calculate the distance between two 3D points using the Pythagorean theorem.\n :param point1: coordinates of the first point as [x1,y1,z1] or (x1,y1,z1).\n :param point2: coordinates of the second point as [x2,y2,z2] or (x2,y2,z2).\n :return: distance between two points in 3D graph.\n \"\"\"\n return (((point2[0] - point1[0]) ** 2) + ((point2[1] - point1[1]) ** 2) + (\n (point2[2] - point1[2]) ** 2)) ** (1 / 2)\n\n @staticmethod\n def generate_aa_matrix():\n \"\"\"\n Extracting the edges after applying the Delaunay triangulation on the coordinates of C-alpha (CA) atoms of a\n .pdb file consists of calculating the vertices(residues) of the Delaunay graph.\n Each of these vertices/residues represents a point with coordinates (x,y,z) in the graph and is displayed as a\n three letters code of amino acids.\n The edge (A_i, A_j) is the connection between two residues, A_i(x1,y1,z1) and A_j(x2,y2,z2).\n Since we have 20 amino acids, we will have 20x20 kinds of connection between edges.\n This is exactly a 20x20 matrix, or a so called adjacency matrix.\n In this paper, the authors focused on the upper part of the matrix, as well as on the diagonal (A_i, A_i).\n The part of the matrix below the diagonal is ignored, because it is just the reverse display of the upper\n tuples. Therefore their distances remain the same as for the upper one.\n At the end, instead of having 20x20 = 400 elements in the matrix, we will only have 210 features.\n 210 = 400 - (380/2) + 20.\n :return: a list of the 210 ordered elements of the matrix.\n The output looks like this:\n [('ALA', 'ALA'), ('ALA', 'CYS'), ('ALA', 'ASP'), ('ALA', 'GLU'), ('ALA', 'PHE'), ... , ('TYR', 'TYR')]\n \"\"\"\n matrix_elements = []\n for i in Utils.aa_residues:\n for j in Utils.aa_residues:\n if Utils.reverse((i, j)) not in matrix_elements:\n matrix_elements.append((i, j))\n return matrix_elements\n\n @staticmethod\n def reverse_imp_tuples(data_frame):\n \"\"\"\n This function reverses the important tuples in order to be considered with the 210 residue'S tuples instead\n of the 400 tuples.\n :param data_frame: data frame with a column 'residues'.\n :return: returns the same data frame with reversed tuples.\n \"\"\"\n for index, row in data_frame.iterrows():\n tuple_value = row['residues']\n if tuple_value not in Utils.generate_aa_matrix():\n data_frame.at[index, 'residues'] = tuple_value[::-1] # or reverse(tuple_value)\n return data_frame\n\n","sub_path":"nodes/encodings/delaunay/scripts/utility.py","file_name":"utility.py","file_ext":"py","file_size_in_byte":5982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"576552571","text":"from gii.core import app\nfrom .MOAIRuntime import _G, _GII\n\nimport os.path\nimport subprocess\nimport shutil\n\n##----------------------------------------------------------------##\ndef _getLuajitBinPath():\n\tplatformName = app.getPlatformName()\n\tif platformName == 'osx':\n\t\treturn app.getNativeSupportPath( 'luajit/luajit' )\n\telif platformName == 'windows':\n\t\treturn app.getNativeSupportPath( 'luajit/luajit.exe' )\n\telse:\n\t\treturn 'luajit'\n\n\n##----------------------------------------------------------------##\ndef _getLuacBinPath():\n\tplatformName = app.getPlatformName()\n\tif platformName == 'osx':\n\t\treturn app.getNativeSupportPath( 'lua/luac' )\n\telif platformName == 'windows':\n\t\treturn app.getNativeSupportPath( 'lua/luac.exe' )\n\telse:\n\t\treturn 'luac'\n\n##----------------------------------------------------------------##\ndef _isFileNewer( f1, f2 ):\n\tif os.path.exists( f1 ) and os.path.exists( f2 ):\n\t\tt1 = os.path.getmtime( f1 )\n\t\tt2 = os.path.getmtime( f2 )\n\t\treturn t1 > t2\n\telse:\n\t\treturn None\n\n\n##----------------------------------------------------------------##\ndef compileLua( srcPath, dstPath, version = 'source', checktime = False ):\n\tif version == 'lua':\n\t\treturn compilePlainLua( srcPath, dstPath, checktime = checktime, strip = False )\n\telif version == 'lua_strip':\n\t\treturn compilePlainLua( srcPath, dstPath, checktime = checktime, strip = True )\n\telif version == 'luajit':\n\t\treturn compileLuaJIT( srcPath, dstPath, checktime = checktime, strip = False )\n\telif version == 'luajit_strip':\n\t\treturn compileLuaJIT( srcPath, dstPath, checktime = checktime, strip = True )\n\telif version == 'source':\n\t\tif srcPath != dstPath:\n\t\t\tshutil.copy( srcPath, dstPath )\n\telse:\n\t\traise Exception( 'no lua version specified' )\n\n##----------------------------------------------------------------##\ndef compilePlainLua( srcPath, dstPath, checktime = False, strip = False ):\n\tif checktime:\n\t\tif _isFileNewer( dstPath, srcPath ): return #copmiled file is newer? skip\n\t\t\n\t# 'luajit -b -g $in $out'\n\targlist = [ _getLuacBinPath() ]\n\n\tif strip:\n\t\targlist += [ '-s' ]\n\t\t\n\targlist += [ '-o', dstPath ]\n\targlist += [ srcPath ]\n\n\ttry:\n\t\tcode = subprocess.call( arglist, cwd = os.path.dirname( _getLuacBinPath() ) )\n\texcept Exception as e:\n\t\traise Exception( 'error on lua compliation: %s ' % e )\n\n##----------------------------------------------------------------##\ndef compileLuaJIT( srcPath, dstPath, checktime = False, strip = False ):\n\tif checktime:\n\t\tif _isFileNewer( dstPath, srcPath ): return #copmiled file is newer? skip\n\n\t# 'luajit -b -g $in $out'\n\targlist = [ _getLuajitBinPath() ]\n\targlist += [ '-b' ]\n\n\tif not strip:\n\t\targlist += [ '-g' ]\n\t\t\n\targlist += [ srcPath, dstPath ]\n\ttry:\n\t\tcode = subprocess.call( arglist, cwd = os.path.dirname( _getLuajitBinPath() ) )\n\texcept Exception as e:\n\t\traise Exception( 'error on luajit compliation: %s ' % e )\n","sub_path":"lib/gii/moai/ScriptHelpers.py","file_name":"ScriptHelpers.py","file_ext":"py","file_size_in_byte":2849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"63273247","text":"class Str:\n\n @staticmethod\n def pos(pos, rev=False):\n return ','.join(str(e) for e in pos[::int(not rev) * 2 - 1])\n\n @staticmethod\n def points(points, rev=False):\n return ','.join((Str.pos(e, rev) for e in points))\n\n @staticmethod\n def marks(points, style=None, color=None, size=None, content=None, rev=False):\n pts = []\n for n, e in enumerate(points):\n v = []\n for sk in [style, color, size, content]:\n if sk:\n if not isinstance(sk, str) and hasattr(sk, '__getitem__'):\n if 0 <= n < len(sk):\n v.append(str(sk[n]))\n else:\n continue\n else:\n v.append(str(sk))\n pts.append(','.join([Str.pos(e, rev)] + [''.join(v)]))\n return '~'.join(pts)\n\n @staticmethod\n def curve(points, color=None, fill=None, width=None, rev=False):\n q = []\n if color is not None:\n q.append('c:%s' % (str(color),))\n if fill is not None:\n q.append('f:%s' % (str(fill),))\n if width is not None:\n q.append('w:%s' % (str(width),))\n return ','.join(q + [Str.points(points, rev)])\n\n @staticmethod\n def parameter(k, v):\n pass\n\n @staticmethod\n def query(dct):\n res = dct.copy()\n for k, v in dct.items():\n if v is None:\n pass\n elif k == 'pt':\n res[k] = '~'.join(\n [(\n Str.pos(m[0]) + ((',' + m[1]) if len(m) > 1 and m[1] else '')\n ) for m in v]\n )\n elif k == 'pl':\n polys = []\n for poly in v:\n str_args = ','.join(\n '{k}:{v}'.format(k=pk, v=pv)\n for pk, pv in poly.items()\n if pk in ['c', 'f', 'w']\n )\n curves = []\n for curve in poly['curves']:\n if hasattr(curve, 'curve'):\n pts = curve.curve()\n else:\n pts = list(curve)\n curves.append(','.join(Str.pos(p) for p in pts))\n str_curves = ';'.join(curves)\n str_poly = ''.join(\n ((str_args + ',') if str_args else '',\n str_curves)\n )\n polys.append(str_poly)\n res[k] = '~'.join(polys)\n elif isinstance(v, str) or hasattr(v, '__int__'):\n res[k] = str(v)\n elif hasattr(v, 'str_parameter'):\n res[k] = v.str_parameter()\n elif len(v) == 2 and hasattr(v[0], '__int__'):\n res[k] = Str.pos(v)\n elif hasattr(v, '__getitem__'):\n pass\n else:\n res[k] = str(v)\n return res\n\n @classmethod\n def string_query(cls, pars):\n return '&'.join(['{}={}'.format(k, v) for k, v in cls.query(pars).items()])\n\n\nclass Parse:\n\n @staticmethod\n def pos(pos, rev=False):\n return [float(e) for e in pos.split(' ')[::int(not rev) * 2 - 1]]\n","sub_path":"url_parsing.py","file_name":"url_parsing.py","file_ext":"py","file_size_in_byte":3320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"366718555","text":"import sys\nimport ast\nimport json\n\n\nclass ProtocolDefinition(object):\n def __init__(self, module):\n assigns = dict()\n for element in module.body:\n if isinstance(element, ast.Assign) and len(element.targets) == 1:\n name = element.targets[0].id\n assigns[name] = ast.literal_eval(element.value)\n self.__dict__.update(assigns)\n\n\ndef load_module(filename):\n with open(filename) as fh:\n return ast.parse(fh.read())\n\ndef load_protocol(filename):\n return ProtocolDefinition(load_module(filename))\n\n\ndef typeinfo_array_to_rs(bounds, typeid):\n yield \"TypeInfo::Array {{ bounds: IntBounds {{ min: {}, bitlen: {} }}, typeid: {} }},\".\\\n format(bounds[0], bounds[1], typeid)\n\n\ndef typeinfo_bitarray_to_rs(bounds):\n yield \"TypeInfo::BitArray {{ len: IntBounds {{ min: {}, bitlen: {} }} }},\".\\\n format(bounds[0], bounds[1])\n\ndef typeinfo_blob_to_rs(bounds):\n yield \"TypeInfo::Blob {{ len: IntBounds {{ min: {}, bitlen: {} }} }},\".\\\n format(bounds[0], bounds[1])\n\n\ndef typeinfo_bool_to_rs():\n yield \"TypeInfo::Bool,\"\n\n\ndef typeinfo_choice_to_rs(bounds, fields):\n yield \"TypeInfo::Choice {\"\n yield \" bounds: IntBounds {{ min: {}, bitlen: {} }},\".format(*bounds)\n yield \" types: phf_map! {\"\n for (key, (name, typeid)) in fields.iteritems():\n yield \" {}_u32 => ({}, {}),\".format(key, json.dumps(name), typeid)\n yield \" },\"\n yield \"},\"\n\n\ndef typeinfo_fourcc_to_rs():\n yield \"TypeInfo::FourCC,\"\n\n\ndef typeinfo_int_to_rs(bounds):\n yield \"TypeInfo::Int {{ bounds: IntBounds {{ min: {}, bitlen: {} }} }},\".\\\n format(bounds[0], bounds[1])\n\n\ndef typeinfo_null_to_rs():\n yield \"TypeInfo::Null,\"\n\n\ndef typeinfo_optional_to_rs(typeid):\n yield \"TypeInfo::Optional {{ typeid: {} }},\".\\\n format(typeid)\n\n\ndef typeinfo_real32_to_rs(args):\n yield \"TypeInfo::Real32,\"\n\n\ndef typeinfo_real64_to_rs(args):\n yield \"TypeInfo::Real64,\"\n\n\ndef typeinfo_struct_to_rs(fields):\n yield \"TypeInfo::Struct(Struct {\"\n yield \" fields: &[\"\n for (name, typeid, tag) in fields:\n yield \" ({}, {}, {}),\".format(json.dumps(name), typeid, tag)\n yield \" ],\"\n yield \"}),\"\n\n\ntypeinfo_to_rs_map = {\n '_array': typeinfo_array_to_rs,\n '_bitarray': typeinfo_bitarray_to_rs,\n '_blob': typeinfo_blob_to_rs,\n '_bool': typeinfo_bool_to_rs,\n '_choice': typeinfo_choice_to_rs,\n '_fourcc': typeinfo_fourcc_to_rs,\n '_int': typeinfo_int_to_rs,\n '_null': typeinfo_null_to_rs,\n '_optional': typeinfo_optional_to_rs,\n '_real32': typeinfo_real32_to_rs,\n '_real64': typeinfo_real64_to_rs,\n '_struct': typeinfo_struct_to_rs,\n}\n\ndef typeinfo_to_rs(typeinfo):\n return typeinfo_to_rs_map[typeinfo[0]](*typeinfo[1])\n\n\ndef game_event_type_to_rs(game_event_type):\n (gametypeid, (typeid, name)) = game_event_type\n yield \"{}_u32 => ({}, {}),\".format(gametypeid, typeid, json.dumps(name))\n\n\nif __name__ == '__main__':\n protocol = load_protocol(sys.argv[1])\n\n print('''use super::{''')\n print(''' TypeInfo,''')\n print(''' IntBounds,''')\n print(''' Struct,''')\n print('''};''')\n print('''use phf::Map as PhfMap;''')\n print('''''')\n\n print('''pub static REPLAY_HEADER_TYPEID: u32 = {};'''.format(protocol.replay_header_typeid))\n print('''''')\n\n print('''pub static GAME_EVENTID_TYPEID: u32 = {};'''.format(protocol.game_eventid_typeid))\n print('''''')\n\n print('''pub static GAME_EVENT_TYPES: PhfMap = phf_map! {''')\n for game_event_type in sorted(protocol.game_event_types.iteritems()):\n for line in game_event_type_to_rs(game_event_type):\n print(\" {}\".format(line))\n print('''};''')\n print('''''')\n\n print('''pub static MESSAGE_EVENTID_TYPEID: u32 = {};'''.format(protocol.message_eventid_typeid))\n print('''''')\n\n print('''pub static MESSAGE_EVENT_TYPES: PhfMap = phf_map! {''')\n for game_event_type in sorted(protocol.message_event_types.iteritems()):\n for line in game_event_type_to_rs(game_event_type):\n print(\" {}\".format(line))\n print('''};''')\n print('''''')\n\n\n print('''pub static TYPEINFOS: &'static [TypeInfo] = &[''')\n for (idx, typeinfo) in enumerate(protocol.typeinfos):\n print(\" // #{}\".format(idx))\n for line in typeinfo_to_rs(typeinfo):\n print(\" {}\".format(line))\n print('''];''')\n print('''''')\n","sub_path":"py2rs.py","file_name":"py2rs.py","file_ext":"py","file_size_in_byte":4496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"649380520","text":"from django.shortcuts import render, redirect\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.core.paginator import Paginator\nfrom django.core.mail import send_mail, BadHeaderError\nfrom django.contrib import messages\n\nfrom .forms import ContactForm, VendorForm\nfrom .models import Gallery, Events, Vendors\n\n\ndef home(request):\n return render(request, 'root/index.html')\n\n\ndef about(request):\n return render(request, 'about/about.html')\n\n\ndef vendor(request):\n msg = messages.get_messages(request)\n if request.method == 'POST':\n form = VendorForm(request.POST, request.FILES)\n if form.is_valid():\n email = form.cleaned_data['email']\n company_name = form.cleaned_data['company_name']\n product = form.cleaned_data['product']\n description = form.cleaned_data['description']\n image = form.cleaned_data['image']\n van = Vendors.objects.create(\n email=email,\n company_name=company_name,\n product=product,\n description=description,\n image=image)\n van.save()\n messages.success(request, \"Thank you. We will be in touch.\")\n return HttpResponseRedirect('/vendor/')\n else:\n form = VendorForm()\n\n return render(request, 'vendor/vendor.html', {'form': form, 'success_msg': msg}) # noqa\n\n\ndef gallery(request):\n galleries = Gallery.objects.all()\n\n context = {'galleries': galleries}\n return render(request, 'gallery/gallery.html', context=context)\n\n\ndef gallery_food(request):\n food = Gallery.objects.filter(category='Food')\n\n context = {'food': food}\n return render(request, 'gallery/gallery.html', context=context)\n\n\ndef gallery_vendors(request):\n vendors = Gallery.objects.filter(category='Vendors')\n\n context = {'vendors': vendors}\n return render(request, 'gallery/gallery.html', context=context)\n\n\ndef gallery_clothing(request):\n clothing = Gallery.objects.filter(category='Clothing')\n\n context = {'clothing': clothing}\n return render(request, 'gallery/gallery.html', context=context)\n\n\ndef gallery_drinks(request):\n drinks = Gallery.objects.filter(category='Drinks')\n\n context = {'drinks': drinks}\n return render(request, 'gallery/gallery.html', context=context)\n\n\ndef gallery_books(request):\n books = Gallery.objects.filter(category='Books')\n\n context = {'drinks': books}\n return render(request, 'gallery/gallery.html', context=context)\n\n\ndef gallery_homeware(request):\n homeware = Gallery.objects.filter(category='Homeware')\n\n context = {'homeware': homeware}\n return render(request, 'gallery/gallery.html', context=context)\n\n\ndef events(request):\n events = Events.objects.all()\n\n paginator = Paginator(events, 3)\n\n page = request.GET.get('page')\n\n events = paginator.get_page(page)\n\n context = {'events': events}\n return render(request, 'events/events.html', context=context)\n\n\ndef event_details(request, pk):\n event = Events.objects.get(id=pk)\n context = {\n \"object\": event\n }\n return render(request, 'events/event-details.html', context)\n\n\ndef contact(request):\n if request.method == 'GET':\n form = ContactForm()\n else:\n form = ContactForm(request.POST)\n if form.is_valid():\n subject = form.cleaned_data['subject']\n from_email = form.cleaned_data['from_email']\n message = form.cleaned_data['message']\n try:\n send_mail(subject, message, from_email, ['Mhlongolunga8@gmail.com']) # noqa\n except BadHeaderError:\n return HttpResponse('Invalid header found.')\n return redirect('success')\n return render(request, \"contact/contact.html\", {'form': form})\n\n\ndef successview(request):\n return render(request, 'contact/success.html')\n","sub_path":"market/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"301111326","text":"\"\"\"\nModule to simplify autograders\n\nI am on record as saying that there is no such thing as a useful third-party autograder.\nAll grading should be tailored to the assignment or problem. However, it is useful to\nhave a tool that can record and tabulate grades, as well as gather feedback. That is\nwhat this tool does.\n\nAuthor: Walker M. White\nDate: July 20, 2017\n\"\"\"\nimport sys, traceback\nimport numpy\nimport types\n\n\ndef _format_score(score,prev,maxv):\n \"\"\"\n Returns the score formatted for alignment.\n \n The score is padded so that numbers align at the ones digit.\n \n :param score: The raw score as a string\n :type score: ``str``\n \n :param prev: The position of the ones digit in the string\n :type prev: ``int``\n \n :param maxv: The number of spaces to pad out the string to\n :type maxv: ``int``\n \n :return: the score formatted for alignment.\n :rtype: ``str``\n \"\"\"\n pos = score.find('.')\n if pos == -1:\n pos = len(score)\n \n remp = len(score)-pos\n diff = maxv-prev\n return ' '*(prev-pos)+score+' '*(diff-remp)\n\n\ndef _rowlen(y):\n \"\"\"\n Returns a function to compute the length of a table row\n \n The function allows us to map len to 2-dimensional sequence. The attribute ``y``\n selects row position.\n \n :param y: The row position\n :type y: ``int``\n \n :return: a function to compute the length of table row ``y``\n :rtype: ``callable``\n \"\"\"\n return lambda x : len(x[y])\n\n\ndef _rowdot(y):\n \"\"\"\n Returns a function to find the decimal point in a table row.\n \n This function allows us to map ``find('.')`` to a list of strings. The attribute\n ``y`` selects the row position. The returned function will return the row length\n if there is no '.'.\n \n :param y: The row position\n :type y: ``int``\n \n :return: a function to find the decimal point in table row ``y``\n :rtype: ``callable``\n \"\"\"\n return lambda x : x[y].find('.') if '.' in x[y] else len(x[y])\n\n\nclass Scorer(object):\n \"\"\"\n An instance is object for tallying scores and providing feedback.\n \n This class is not a proper autograder. Instead, it is a framework to attach\n autograders. Those graders, then use this object to deduct points and provide\n feedback. When done, this object can print out a score sheet.\n \n When attaching graders to the scorer, you can either attach a callback function\n or a list. If you attach a callback function, it will use that function as\n the grader. If you attach a list, it will assume that these are all subparts of\n the problem. Those subparts should then attach to either a callback (to grade)\n or another list (for more subparts).\n \n :ivar _title: The title of this assignment (for display in the report)\n :vartype _title: ``str``\n \n :ivar _indent: The current indentation level (for message display)\n :vartype _indent: ``int``\n \n :ivar _cursor: The current problem being graded\n :vartype _cursor: ``str``\n \"\"\"\n @property\n def title(self):\n \"\"\"\n The title of this assignment.\n \n This is displayed by the method :meth:`report` when providing feedback.\n \n **invariant**: Value is a ``str``\n \"\"\"\n return self._title\n \n @title.setter\n def title(self,value):\n assert type(value) == str, '%s is not a string' % repr(value)\n self._title = value\n \n @property\n def indent(self):\n \"\"\"\n The current indentation level.\n \n When a message is sent by a grader function via :meth:`message`, :meth:`deduct`\n or one of the assert methods, it will be indented by this amount. Negative\n values will not indent.\n \n **invariant**: Value is an ``int``\n \"\"\"\n return self._indent\n \n @indent.setter\n def indent(self,value):\n assert type(value) == int, '%s is not an int' % repr(value)\n self._indent = value\n \n @property\n def current(self):\n \"\"\"\n The current problem being graded.\n \n While the autograder callbacks are running, they sometimes need to know what\n the current problem is (e.g. to retrieve the maximum score). This value makes\n it possible. If grading is not in progress, this value is ``None``.\n \n **invariant**: Value is ``str`` or ``None``\n \"\"\"\n return self._cursor\n \n \n def __init__(self, name):\n \"\"\"\n Creates a Scorer for the given assignment.\n \n This new Scorer will have no problems to score. Those must be attached individually\n with the :meth:`attach` method.\n \n :param name: The name of the assignment\n :type name: ``str``\n \"\"\"\n self.title = name\n self._cursor = None\n self._roots = []\n self._allkey = {}\n self._totals = {}\n self._scores = {}\n self._childs = {}\n self._master = {}\n self._output = []\n self._indent = 0\n \n def reset(self):\n \"\"\"\n Resets the scorer, erasing all feedback and deductions.\n \"\"\"\n self._cursor = None\n for name in self._totals:\n self._scores[name] = self._totals[name]\n self._output = []\n self.indent = -2\n \n def attach(self,name,child,points=None,mastery=False):\n \"\"\"\n Attaches a problem grader to this scorer.\n \n The value ``name`` should be a unique name identifying the problem to grade.\n It is then associated with ``child`` that performs the grading.\n \n The values ``child`` should either be a callback function or a list. If it is\n a callback function, then it should take a scorer as an argument. That way,\n the callback function can use this object to provide feedback and deduct points.\n The value ``points`` is the maximum number of points that can be deducted.\n \n On the other hand, if ``child`` is a list or tuple, then that sequence should\n consist of names of subparts to grade. Each subpart must be attached \n individually. Those subparts will have their own associated points. For\n this parent problem ``points`` refers to the number of parts that must be\n completed (for cases of \"best x out of y\").\n \n Finally, the value ``mastery`` only applies when ``child`` is a sequence of \n subparts. It indicates that any loss of points on one part will prevent the\n scorer from going on to the next part in the grading process.\n \n :param name: The unique problem name\n :type name: ``str``\n \n :param child: The grader or sequence of subproblems\n :type child: ``callable`` or ``iterable``\n \n :param points: The maximum number of points for this problem (or subproblems to grade)\n :type points: ``int`` or ``float`` >= 0\n \n :param mastery: Whether or not mastery is required for this problem.\n :type mastery: ``bool``\n \"\"\"\n assert type(name) == str, '%s is not a string' % repr(name)\n assert points is None or type(points) in [int,float], '%s is not an number' % repr(points)\n assert points is None or points >= 0, '%s is negative' % repr(points)\n assert type(mastery) == bool, '%s is not a bool' % repr(mastery)\n \n if not name in self._allkey:\n self._roots.append(name)\n self._allkey[name] = True\n self._childs[name] = child\n self._master[name] = mastery\n \n if not (child is None or callable(child)):\n if points is None:\n points = len(child)\n \n assert type(points) == int, '%s is not an int' % repr(points)\n assert points >= 0 and points <= len(child), '%s is not in range' % repr(points)\n \n for item in child:\n assert type(name) == str, '%s is not a string' % repr(name)\n self._allkey[item] = True\n elif points is None:\n points = 0\n \n self._totals[name] = points\n self._scores[name] = points\n \n def maximum(self,name=None):\n \"\"\"\n Returns the maximum score for the given problem.\n \n If ``name`` refers to a list of problems, it totals the score for that list\n (taking \"best x out of y\" as appropriate). If ``name`` is ``None``, it provides\n the score on the entire assignment.\n \n :param name: The problem to score\n :type name: ``str`` or ``None``\n \n :return: the maximum score for the given problem\n :rtype: ``int`` or ``float``\n \"\"\"\n if name is None:\n keyset = self._roots\n requir = len(self._roots)\n elif name in self._childs:\n keyset = self._childs[name]\n requir = self._totals[name]\n else:\n return 0\n \n if keyset is None or callable(keyset):\n return self._totals[name]\n else:\n scores = []\n for item in keyset:\n scores.append(self.maximum(item))\n scores.sort()\n \n result = 0\n for i in range(requir):\n result += scores[i]\n return result\n \n def score(self,name=None):\n \"\"\"\n Returns the current score for the given problem.\n \n If ``name`` refers to a list of problems, it totals the score for that list\n (taking \"best x out of y\" as appropriate). If ``name`` is ``None``, it provides\n the score on the entire assignment.\n \n :param name: The problem to score\n :type name: ``str`` or ``None``\n \n :return: the current score for the given problem\n :rtype: ``int`` or ``float``\n \"\"\"\n if name is None:\n keyset = self._roots\n requir = len(self._roots)\n elif name in self._childs:\n keyset = self._childs[name]\n requir = self._totals[name]\n else:\n return 0\n \n if keyset is None or callable(keyset):\n return self._scores[name]\n else:\n scores = []\n for item in keyset:\n scores.append(self.score(item))\n scores.sort()\n \n result = 0\n for i in range(requir):\n result += scores[-(i+1)]\n return result\n \n def grade(self,name=None):\n \"\"\"\n Invokes the autograder(s) attached to the given problem.\n \n It ``name`` is mapped to a callback, this function invokes that callback.\n If ``name`` is mapped to a list of problems, it grades all of those problems\n (which may have further nesting). If ``name`` is None, it grades the entire\n assignment using all attached autograders.\n \n :param name: The problem to grade\n :type name: ``str`` or ``None``\n \"\"\"\n if name is None:\n self.reset()\n keyset = self._roots\n message = 'Start grading of '+self._title+'\\n'\n master = False\n elif name in self._childs:\n keyset = self._childs[name]\n master = self._master[name]\n maxpts = self.maximum(name)\n if master:\n message = 'Grading '+name\n else:\n message = 'Max points for '+name+': '+str(maxpts)\n else:\n keyset = None\n \n if not keyset:\n return True\n \n self._cursor = name\n self._output.append((' '*self._indent)+message)\n self._indent += 2\n \n iterate = not callable(keyset)\n if iterate:\n for item in keyset:\n self.grade(item)\n if master and self.score(item) != self.maximum(item):\n break\n else:\n try:\n keyset(self)\n except:\n exc_type, exc_value, exc_traceback = sys.exc_info()\n message = 'INTERNAL ERROR: grader for '+name+' crashed'\n self._output.append((' '*self._indent)+message)\n self._output.append(traceback.format_exception_only(exc_type,exc_value)[0])\n self._output.append(traceback.format_exc()[:-1])\n self._scores[name] = 0\n \n self._indent -= 2\n if not name is None:\n self._output.append((' '*self._indent)+'Finished '+name)\n self._output.append('')\n \n def message(self,msg):\n \"\"\"\n Appends a message to the feedback list for this scorer.\n \n The message will have the current indentation.\n \n :param msg: The feedback message to display\n :type msg: ``str``\n \"\"\"\n assert not self._cursor is None, 'The scorer is not actively grading'\n assert type(msg) == str, '%s is not a string' % msg\n self._output.append((' '*self._indent)+msg)\n \n def deduct(self, msg, amt):\n \"\"\"\n Deducts points from the current problem and adds a feedback message.\n \n The deduction will be take from the current problem. Deduction will only occur \n if the maximum deduction has not been reached yet. Unless the problem is for\n mastery (in which case any deduction is bad), the feedback will include the \n number of points deducted.\n \n The message will display before the deduction feedback. It will have the current \n indentation.\n \n :param msg: The feedback message to display\n :type msg: ``str``\n \n :param amt: The number of points to deduct.\n :type amt: ``int`` or ``float``\n \"\"\"\n assert not self._cursor is None, 'The scorer is not actively grading'\n assert type(msg) == str, '%s is not a string' % msg\n assert type(amt) in [int,float], '%s is not a number' % amt\n \n name = self._cursor\n master = self._master[name]\n \n if self._scores[name] == 0:\n if not master:\n msg += ' Maximum deduction reached.'\n self._output.append((' '*self._indent)+msg)\n return 0\n else:\n pts = min(amt,self._scores[name])\n if not master:\n suff = ' point' if pts == 1 else ' points'\n msg += ' '+str(pts)+suff+' deducted.'\n self._output.append((' '*self._indent)+msg)\n self._scores[name] -= pts\n return pts\n \n def check_equals(self, msg, answer, given, amt):\n \"\"\"\n Deducts points if answer != given\n \n This problem is written to work with either floats or standard equality. \n The feedback message will used ``msg`` as its prefix to put the two values\n in context. For example, if ``msg`` is 'Variable x is', ``answer`` is 2\n and ``given`` is 1, the feedback message will be::\n \n 'Variable x is 1 but should be 2'\n \n The deduction will be take from the current problem. Deduction will only occur \n if the maximum deduction has not been reached yet. Unless the problem is for\n mastery (in which case any deduction is bad), the feedback will include the \n number of points deducted.\n \n The message will display before the deduction feedback. It will have the current \n indentation.\n \n :param msg: The feedback prefix\n :type msg: ``str``\n \n :param answer: The expected answer\n :type answer: any\n \n :param given: The student answer\n :type given: any\n \n :param amt: The number of points to deduct.\n :type amt: ``int`` or ``float``\n \"\"\"\n assert type(msg) == str, '%s is not a string' % msg\n try:\n notsame = not numpy.allclose([answer],[given])\n except:\n notsame = answer != given\n \n if notsame:\n explain = msg + ' ' + repr(given) + ' but should be ' + repr(answer) + '.'\n self.deduct(explain,amt)\n \n def check_different(self, msg, answer, given, amt):\n \"\"\"\n Deducts points if answer == given\n \n This problem is written to work with either floats or standard equality. \n The feedback message will used ``msg`` as its prefix to put the two values\n in context. For example, if ``msg`` is 'Variable x is', ``answer`` is 2\n and ``given`` is 1, the feedback message will be::\n \n 'Variable x is 1 but should be 2'\n \n The deduction will be take from the current problem. Deduction will only occur \n if the maximum deduction has not been reached yet. Unless the problem is for\n mastery (in which case any deduction is bad), the feedback will include the \n number of points deducted.\n \n The message will display before the deduction feedback. It will have the current \n indentation.\n \n :param msg: The feedback prefix\n :type msg: ``str``\n \n :param answer: The expected answer\n :type answer: any\n \n :param given: The student answer\n :type given: any\n \n :param amt: The number of points to deduct.\n :type amt: ``int`` or ``float``\n \"\"\"\n assert type(msg) == str, '%s is not a string' % msg\n try:\n same = numpy.allclose([answer],[given])\n except:\n same = answer = given\n \n if same:\n explain = msg + ' expected something different from ' + repr(answer) + '.'\n self.deduct(explain,amt)\n \n def check_copy(self, msg, answer, given, amt):\n \"\"\"\n Deducts points if answer != given or answer IS given\n \n This problem is written to work with either floats or standard equality. \n The feedback message will used ``msg`` as its prefix to put the two values\n in context. For example, if ``msg`` is 'Variable x is', ``answer`` is 2\n and ``given`` is 1, the feedback message will be::\n \n 'Variable x is 1 but should be 2'\n \n The deduction will be take from the current problem. Deduction will only occur \n if the maximum deduction has not been reached yet. Unless the problem is for\n mastery (in which case any deduction is bad), the feedback will include the \n number of points deducted.\n \n The message will display before the deduction feedback. It will have the current \n indentation.\n \n :param msg: The feedback prefix\n :type msg: ``str``\n \n :param answer: The expected answer\n :type answer: any\n \n :param given: The student answer\n :type given: any\n \n :param amt: The number of points to deduct.\n :type amt: ``int`` or ``float``\n \"\"\"\n \"\"\"If answer = given, add score to total otherwise, append error msg to output\"\"\"\n assert type(msg) == str, '%s is not a string' % msg\n try:\n notsame = not numpy.allclose([answer],[given])\n except:\n notsame = answer != given\n \n if notsame:\n explain = msg + ' ' + repr(given) + ' but should be ' + repr(answer) + '.'\n self.deduct(explain,amt)\n elif id(answer) == id(given):\n explain = msg + ' did not copy ' + repr(answer) + '.'\n self.deduct(explain,amt)\n \n def tally(self):\n \"\"\"\n Prints out a tally sheet of the scores on each problem.\n \n Currently the tally sheet only does one level of nesting. If you have subsubparts,\n it will only show the total for the parent parts.\n \"\"\"\n contents = self._gather_lines()\n \n # We need to compare the scores to line them up.\n maxlen = max(map(_rowlen(0),contents.values())) if contents else 0\n maxscr = max(map(_rowlen(1),contents.values())) if contents else 0\n maxmax = max(map(_rowlen(2),contents.values())) if contents else 0\n prescr = max(map(_rowdot(1),contents.values())) if contents else 0\n premax = max(map(_rowdot(2),contents.values())) if contents else 0\n \n # Reformat the numbers\n for name in contents:\n contents[name][1] = _format_score(contents[name][1],prescr,maxscr)\n contents[name][2] = _format_score(contents[name][2],premax,maxmax)\n \n self._print_lines(contents,maxlen)\n \n # Add the final score\n print('-'*(maxlen))\n score = str(self.score())\n maxim = str(self.maximum())\n for name in ['__pretotal__','__deductions__','__total__']:\n maxim = contents[name][2]\n suff = (contents[name][1]+' out of '+maxim) if maxim.strip() != '' else ''\n pref = contents[name][0]\n report = pref+' '*(maxlen-len(pref))+suff\n print(report)\n \n def _gather_lines(self):\n \"\"\"\n Returns a dictionary of the unaligned tally sheet.\n \n For each problem, the dictionary contains a three tuple of the row text,\n the current score, and the maximum score. These will be pasted to gether\n to produce a line of the tally sheet after the numbers are aligned properly.\n \n :return: a dictionary of the unaligned tally sheet.\n :rtype: ``dict``\n \"\"\"\n contents = {}\n index = 1\n for name in self._roots:\n value = str(index)+'. '+name\n try:\n # This only succeeds if we have a sublisting\n if self._totals[name] != len(self._childs[name]):\n value += ' (Best '+str(self._totals[name])+' out of '+str(len(self._childs[name]))+')'\n subindex = 1\n for item in self._childs[name]:\n pref = chr(64+subindex)+'. '\n score = str(self.score(item))\n maxim = self.maximum(item)\n maxim = str(maxim) if maxim > 0 else ''\n contents[item] = [' '+pref+item+' ',score,maxim]\n subindex += 1\n except:\n pass\n score = str(self.score(name))\n maxim = self.maximum(name)\n maxim = str(maxim) if maxim > 0 else ''\n contents[name] = [value+' ', score, maxim]\n index += 1\n \n contents['__pretotal__'] = ['Total',str(self.score()),str(self.maximum())]\n contents['__deductions__'] = ['Deductions:','','']\n contents['__total__'] = ['Total','',str(self.maximum())]\n \n return contents\n \n def _print_lines(self,contents,maxlen):\n \"\"\"\n Glues together the results of :meth:`_gather_lines` to produce the tally sheet.\n \n The score numbers should be padded to alignment before calling this method.\n \n :param contents: The results of :meth:`_gather_lines`, with numbers aligned.\n :type contents: ``dict``\n \n :param maxlen: The maximum line length of any line (to define padding)\n :type maxlen: ``int``\n \"\"\"\n for name in self._roots:\n maxim = contents[name][2]\n suff = (contents[name][1]+' out of '+maxim) if maxim.strip() != '' else ''\n pref = contents[name][0]\n report = pref+' '*(maxlen-len(pref))+suff\n print(report)\n try:\n for item in self._childs[name]:\n pref = contents[item][0]\n line = pref+' '*(maxlen-len(pref))\n line = line[:-1]+'('+contents[item][1]+')'\n print(line)\n except:\n pass\n \n def report(self,tally=True):\n \"\"\"\n Prints out a report of the student's performance with feedback.\n \n If ``tally`` is true, it will include a scoresheet. Otherwise, it will assume\n that the assignment was for feedback only and simply indicate whether or not\n revisions are necessary.\n \n :param tally: Whether to include a scoresheet\n :type tally: ``bool``\n \"\"\"\n self._cursor = None\n print('\\n'.join(self._output))\n \n if tally:\n self.tally()\n else:\n if self.score() == self.maximum():\n print('Assignment is complete')\n else:\n print('This assignment requires revisions')\n\n\nclass UnitChecker(object):\n \"\"\"\n An instance is a verifier for student unit tests.\n \n A checker is assigned to a single function begin tested. If a unit test actually\n involves more than one function (as is the case in Assignment 1), then the unit\n test grader will need a checker for each individual function.\n \n The unit checker wraps the function being tested with a provided hash function.\n This allows us to count the number of valid unit tests. The hash function should\n have exactly the same signature as the function being tested.\n \n The grader should use the :meth:`report` method to display the results.\n \n :ivar _name: The function name\n :vartype _name: ``str``\n \n :ivar _hash: The hash function for counting valid tests\n :vartype _hash: ``callable``\n \n :ivar _need: The number of valid tests required to be correct\n :vartype _need: ``int``\n \n :ivar _count: The number of valid tests recorded so far\n :vartype _count: ``int``\n \n :ivar _soln: The module with the solution function\n :vartype _soln: ``module`` or ``None``\n \n :ivar _orig: The original, unwrapped function (if currently wrapped)\n :vartype _orig: ``callable`` or ``None``\n \"\"\"\n \n @property\n def name(self):\n \"\"\"\n The function name as a string.\n \n This name allows us to apply the checker to any module that implements this\n function.\n \n **invariant**: This value is set at creation and cannot be changed.\n \"\"\"\n return self._name\n \n @property\n def needed(self):\n \"\"\"\n The number of valid tests required to be correct\n \n **invariant**: Value is an ``int``\n \"\"\"\n return self._need\n \n @needed.setter\n def needed(self,value):\n assert type(value) == int, '%s is not an integer' % repr(value)\n assert value >= 0, '%s is not nonnegative' % repr(value)\n self._need = value\n \n @property\n def solution(self):\n \"\"\"\n The module containing the solution to this function.\n \n If there is a solution module, then wrapping a function will replace it entirely \n with the version in the solution. Otherwise, the :meth:`wrap` method will assume\n the function being tested is correct and wrap it in place.\n \n **invariant**: Value is an ``module`` or ``None``\n \"\"\"\n return self._soln\n \n @needed.setter\n def solution(self,value):\n assert value is None or type(value) == types.ModuleType, '%s is not an module' % repr(value)\n self._soln = value\n \n @property\n def found(self):\n \"\"\"\n The number of valid tests found so far.\n \n The method :meth:`reset` will reset this value to 0. To record tests, wrap the\n function and call the unit test function.\n \n **invariant**: Value is an ``int`` >= 0\n \"\"\"\n result = 0\n for key in self._count:\n if key >= 0:\n result += 1\n return result\n \n @property\n def invalid(self):\n \"\"\"\n The number of invalid tests (those that violate the precondition)\n \n The method :meth:`reset` will reset this value to 0. To record tests, wrap the\n function and call the unit test function.\n \n **invariant**: Value is an ``int`` >= 0\n \"\"\"\n result = 0\n for key in self._count:\n if key < 0:\n result += 1\n return result\n \n def __init__(self,name,hash,need=0,soln=None):\n \"\"\"\n Creates a UnitChecker for the given function and hash.\n \n If there is a solution module, then wrapping a function will replace it entirely \n with the version in the solution. Otherwise, the :meth:`wrap` method will assume\n the function being tested is correct and wrap it in place.\n \n :param name: The function name\n :type name: ``str``\n \n :param hash: The hash function for counting valid tests\n :type hash: ``callable``\n \n :param need: The number of valid tests required to be correct\n :type need: ``int``\n \n :param _soln: The module with the solution function\n :type _soln: ``module`` or ``None``\n \"\"\"\n assert type(name) == str, '%s is not a string' % repr(name)\n assert callable(hash), '%s is not callable' % repr(hash)\n self._name = name\n self._hash = hash\n self.needed = need\n self.solution = soln\n self._orig = None\n self._count = set()\n \n def wrap(self,parent):\n \"\"\"\n Wraps the implementation of ``name`` in the module ``parent``\n \n When a function is wrapped, any future calls to it will be recorded by the\n hash function.\n \n :param parent: The module with the function\n :type parent: ``module``\n \"\"\"\n assert type(parent) == types.ModuleType, '%s is not an module' % repr(parent)\n try:\n self._orig = getattr(parent,self._name)\n src = self._soln if self._soln else parent\n src = getattr(src,self._name)\n dst = lambda *x : (self._count.add(self._hash(*x)),src(*x))[1]\n setattr(parent,self._name,dst)\n except:\n pass\n \n def unwrap(self,parent):\n \"\"\"\n Unwraps the implementation of ``name`` in the module ``parent``\n \n When a function is unwrapped, it is restored to its original version, and calls\n will no longer be recorded by the hash function.\n \n :param parent: The module with the function\n :type parent: ``module``\n \"\"\"\n assert type(parent) == types.ModuleType, '%s is not an module' % repr(parent)\n try:\n setattr(parent,self._name,self._orig)\n except:\n pass\n \n def reset(self):\n \"\"\"\n Resets the checker, erasing all recorded calls.\n \"\"\"\n self._count = set()\n \n def report(self,scorer):\n \"\"\"\n Reports the success of the unit test to the :class:`Scorer` object\n \n We assume that one point is deducted for each test case missing.\n \n :param scorer: The object recording the student's score.\n :type scorer: :class:`Scorer`\n \"\"\"\n if self.invalid > 0:\n suff = ' test ' if self.invalid == 1 else ' tests '\n scorer.deduct('You have '+self.invalid+suff+'that violate the precondition',self.invalid)\n \n if self.found == 0:\n print(self.needed)\n print(self._orig)\n scorer.deduct('There were no tests for '+self._name+'.',self.needed)\n elif self.found < self.needed-1:\n miss = self.needed-self.found\n scorer.deduct('You are missing '+repr(miss)+' tests for '+self._name+'.',miss)\n elif self.found == self.needed-1:\n scorer.deduct('You are missing an important test for '+self._name+'.',1)\n\n\n","sub_path":"data/addins/Lib/site-packages/cornell/scorer.py","file_name":"scorer.py","file_ext":"py","file_size_in_byte":31806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"452075547","text":"import matplotlib.pyplot as plt\n\nplt.rc('font', family='Malgun Gothic')\n\nmycolors = ['blue', 'green', 'red', 'c']\n\ndata = ['강호동', '유재석', '이수근', '전현무', '강호동', '유재석', '이수근', '강호동', '유재석', '강호동']\n\nmydict = {} # 빈도 수를 저장할 사전\n\nfor d in data:\n if d in mydict:\n mydict[d] += 1\n else :\n mydict[d] = 1\n\nslices = []\nmylabels = []\nfor key, value in mydict.items():\n slices.append(value)\n mylabels.append(key)\n\nplt.pie(x=slices,startangle=90,autopct='%.2f%%',labels=mylabels,explode=[0,0.1,0,0],counterclock=False,shadow=True)\n\n\nplt.legend(loc='best')\n\nfilename = 'pieGraph02.png'\nplt.savefig(filename, dpi=400, bbox_inched='tight')\nprint(filename + ' 파일이 저장되었습니다.')\nplt.show()","sub_path":"exam/data/h.py","file_name":"h.py","file_ext":"py","file_size_in_byte":790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"282495890","text":"import warnings\nimport matplotlib.pyplot as plt\nwarnings.filterwarnings('ignore')\n\nimport numpy as np\nimport tensorflow as tf\nimport tensorflow_datasets as tfds\ntfds.disable_progress_bar()\n\nprint(\"Using:\")\nprint('\\t\\u2022 Tensor flow version:', tf.__version__)\nprint('\\t\\u2022 tf.keras version:', tf.keras.__version__)\nprint('\\t\\u2022 Running on GPU' if tf.test.is_gpu_available() else '\\t\\u2022 GPU device not found. Running on CPU')\n\ntraining_set, dataset_info = tfds.load('mnist', split = 'train', as_supervised = True, with_info = True)\n\nnum_classes = dataset_info.features['label'].num_classes\nprint('There are {} classes in our dataset'.format(num_classes))\n\nnum_training_examples = dataset_info.splits['train'].num_examples\nprint('There are {:,} images in the training set'.format(num_training_examples))\n\nfor image, label in training_set.take(1):\n print('The images in the training set have:')\n print('dtype:', image.dtype)\n print('shape:', image.shape)\n\n print('The label of the images have:')\n print('dtype:', label.dtype)\n\nfor image, label in training_set.take(1):\n image = image.numpy().squeeze()\n label = label.numpy()\n\nprint('The label of this image is:',label)\n\ndef normalize(image, label):\n image = tf.cast(image, tf.float32)\n image = image / 255\n return image, label\n\nbatch_size = 64\n\ntraining_batches = training_set.cache().shuffle(num_training_examples//4).batch(batch_size).map(normalize).prefetch(1)\n\nfor image_batch, label_batch in training_batches.take(1):\n print('The images in each batch have:')\n print('\\u2022 dtype:', image_batch.dtype)\n print('\\u2022 shape:', image_batch.shape)\n\n print('\\nThere are a total of {} image labels in this batch:'.format(label_batch.numpy().size))\n print(label_batch.numpy())\n\nfor image_batch, label_batch in training_batches.take(1):\n images = image_batch.numpy().squeeze()\n print(images.shape)\n labels = label_batch.numpy()\n\ndef sigmoid(x):\n return 1/ (1+tf.exp(x))\n\n\ninputs = tf.reshape(images, [images.shape[0],-1])\nprint(inputs.shape)\ntf.random.set_seed(7)\nn_input = inputs.shape[1]\nn_hidden = 256\nn_output = 10\nweights_input_hidden = tf.random.normal((n_input, n_hidden))\nweights_hidden_output = tf.random.normal((n_hidden,n_output))\nB_hidden = tf.random.normal((1, n_hidden))\nB_output = tf.random.normal((1, n_output))\n\nhidden_output = sigmoid(tf.matmul(inputs,weights_input_hidden) + B_hidden)\n\noutput = tf.matmul(hidden_output, weights_hidden_output) + B_output\n\nexp_sum_each_col = tf.reduce_sum(tf.exp(output),axis=1,keepdims=True)\nprobabilities = tf.divide(tf.exp(output), exp_sum_each_col)\n\nprint(exp_sum_each_col)\n\n\n\n","sub_path":"Exercise2.py","file_name":"Exercise2.py","file_ext":"py","file_size_in_byte":2644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"46123032","text":"import logging\nfrom celery import shared_task\nfrom siphoner_app.nws import (\n NWSForecastRetriever, NWSHourlyForecastRetriever, NWSGridPointForecastRetriever,\n NWSObservationRetriever\n)\nfrom siphoner_app.unidata import (\n UnidataGFSRetriever, UnidataHRRRRetriever, UnidataNAMRetriever, \n UnidataGEFSRetriever, UnidataSREFRetriever\n)\nfrom siphoner_app.models import (\n NWSGridPoint, NWSObservationStation\n)\n\n\nlogger = logging.getLogger(__name__)\n\n\n@shared_task\ndef nws_forecast_etl():\n logger.info('NWS Forecast etl starting.')\n gridpoints = NWSGridPoint.objects.all()\n\n for i, gridpoint in enumerate(gridpoints):\n logger.info(f'Retrieving forecast: {gridpoint.nws_id} ({i+1}/{len(gridpoints)})')\n retriever = NWSForecastRetriever(gridpoint)\n retriever.retrieve_forecast()\n\n\n@shared_task\ndef nws_hourly_forecast_etl():\n logger.info('NWS Hourly Forecast etl starting.')\n gridpoints = NWSGridPoint.objects.all()\n\n for i, gridpoint in enumerate(gridpoints):\n logger.info(f'Retrieving forecast: {gridpoint.nws_id} ({i+1}/{len(gridpoints)})')\n retriever = NWSHourlyForecastRetriever(gridpoint)\n retriever.retrieve_forecast()\n\n\n@shared_task\ndef nws_gridpoint_forecast_etl():\n logger.info('NWS Gridpoint Forecast etl starting.')\n gridpoints = NWSGridPoint.objects.all()\n\n for i, gridpoint in enumerate(gridpoints):\n logger.info(f'Retrieving forecast: {gridpoint.nws_id} ({i+1}/{len(gridpoints)})')\n retriever = NWSGridPointForecastRetriever(gridpoint)\n retriever.retrieve_forecast()\n\n\n@shared_task\ndef nws_obs_etl():\n logger.info('NWS Observation etl starting.')\n stations = NWSObservationStation.objects.all()\n\n for i, station in enumerate(stations):\n logger.info(f'Retrieving observation: {station.station_identifier} ({i+1}/{len(stations)})')\n retriever = NWSObservationRetriever(station)\n retriever.retrieve_observation()\n\n\n@shared_task\ndef unidata_gfs_etl():\n retriever = UnidataGFSRetriever\n unidata_etl(retriever)\n\n\n@shared_task\ndef unidata_hrrr_etl():\n retriever = UnidataHRRRRetriever\n unidata_etl(retriever)\n\n\n@shared_task\ndef unidata_nam_etl():\n retriever = UnidataNAMRetriever\n unidata_etl(retriever)\n\n\n@shared_task\ndef unidata_gefs_etl():\n retriever = UnidataGEFSRetriever\n unidata_etl(retriever)\n\n\n@shared_task\ndef unidata_sref_etl():\n retriever = UnidataSREFRetriever\n unidata_etl(retriever)\n\n\ndef unidata_etl(retriever):\n\n gridpoints = NWSGridPoint.objects.all()\n\n for i, gridpoint in enumerate(gridpoints):\n model_retriever = retriever(gridpoint)\n logger.info(f'{model_retriever.name}: {gridpoint.nws_id} ({i+1}/{len(gridpoints)})')\n for var in model_retriever.variables:\n logger.info(f'Retrieving {var}')\n model_retriever.retrieve_forecast(var)\n\n\n","sub_path":"siphoner_app/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":2871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"276469483","text":"import datetime\nimport subprocess\nimport pandas as pd\nimport rich\nfrom rich.progress import Progress\n\npath_to_pdf = \"/home/janik/githubRepos/phd_thesis/thesis_documents/JanikVonAhnen_MonoHbbMET_PhD_thesis.pdf\"\n\ndef read_progress_file():\n file_path=\"/home/janik/githubRepos/timeTracker/data/thesis_progess.csv\"\n df=pd.read_csv(file_path, parse_dates=[\"time\"])\n df = df[(df.word_count!=1) | (df.word_count!=0)]\n df[\"date\"] = df.apply( lambda row: row[\"time\"].date(), axis=1)\n df[\"date\"] = pd.to_datetime(df.date)\n df = df.groupby([\"date\"]).max()\n df[\"word_count_change\"] = df[\"word_count\"] - df[\"word_count\"].shift(1)\n df[\"word_count_change\"] = df[\"word_count_change\"].fillna(0)\n df[\"7d_avg_wcc\"] = df[\"word_count_change\"].rolling(\"7d\").sum()/7.\n df[\"30d_avg_wcc\"] = df[\"word_count_change\"].rolling(\"30d\").sum()/30.\n return df\n\ndef goal_colors(measured, thresh, show_measured=True):\n if measured>thresh:\n color=\"green\"\n else:\n color=\"red\"\n if show_measured:\n return f\"[reverse {color}] {measured} [/reverse {color}]\"\n else:\n return f\"[reverse {color}] {thresh} [/reverse {color}]\"\n\n# word count\ncommand_pdftotext = [\"pdftotext\", path_to_pdf, \"-\"]\np_pdftotext = subprocess.Popen(\n command_pdftotext,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n)\ncommand_wc = [\"wc\", \"-w\"]\np_wc = subprocess.Popen(\n command_wc,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n stdin=p_pdftotext.stdout,\n)\nword_count, word_count_error = p_wc.communicate()\n\n# page count\ncommand_qpdf = [\"qpdf\", \"--show-npages\", path_to_pdf]\np_pc = subprocess.Popen(\n command_qpdf,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n)\npage_count, page_count_err = p_pc.communicate()\n\n# current date and time\nnow = datetime.datetime.now() \ntoday = now.date()\nyesterday = today - datetime.timedelta(1)\n\nprogress_df = read_progress_file()\ntry:\n ystd_wcc=progress_df.loc[yesterday.isoformat()].word_count_change\nexcept:\n ystd_wcc=0\ntry:\n today_wcc=progress_df.loc[today.isoformat()].word_count_change\nexcept:\n today_wcc=0\n\nprint(f\"{now.isoformat(sep=' ', timespec='minutes')} | {int(word_count)} | {int(page_count)}\")\n\n\nrich.print(f\"wcc: {goal_colors(today_wcc, 500)} ({goal_colors(today_wcc, ystd_wcc, False)}) [{goal_colors(today_wcc, progress_df.iloc[-1]['7d_avg_wcc'], False)} | {goal_colors(today_wcc, progress_df.iloc[-1]['30d_avg_wcc'], False)}]\")\n\n# progress bar, time\nwith Progress() as progress:\n adv=now.hour + now.minute/60. - 8\n if adv>=8:\n c=\"red\"\n elif adv>=4:\n c=\"yellow\"\n else:\n c=\"green\"\n todays_working_hours = progress.add_task(f\"[bold {c}]Working...\", total=10)\n progress.update(todays_working_hours, advance=adv)\n\n\n# progress bar, wcc\nwith Progress() as progress:\n wcc_today_goal = progress.add_task(f\"[bold green] wcc goal:\", total=500)\n progress.update(wcc_today_goal, advance=today_wcc)","sub_path":"print_thesis_status.py","file_name":"print_thesis_status.py","file_ext":"py","file_size_in_byte":2934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"570228064","text":"from transformers import RobertaTokenizer, RobertaForSequenceClassification, Trainer, TrainingArguments\nimport torch\nimport pandas as pd\nimport numpy as np\nimport random\nimport nltk\nfrom sklearn.metrics import accuracy_score, precision_recall_fscore_support\n\ndir = '/miniscratch/comp_550_project/gyafc/Family_Relationships_comb/'\n\nclass GYAFCDataset(torch.utils.data.Dataset):\n def __init__(self, encodings, labels):\n self.encodings = encodings\n self.labels = labels\n\n def __getitem__(self, idx):\n item = {key: torch.tensor(val[idx]) for key, val in self.encodings.items()}\n item['labels'] = torch.tensor(self.labels[idx])\n return item\n\n def __len__(self):\n return len(self.labels)\n \ndef pos_tags(sent):\n return ' '.join([x[1] for x in nltk.pos_tag(nltk.tokenize.word_tokenize(sent))])\n \ndef create_input(sent) :\n tags = pos_tags(sent)\n return sent + ' POS ' + tags\n \n#train data\ntrain_texts, train_labels = [], []\n\ninformal_text = open(dir + 'train.informal-formal.informal').readlines()\ntrain_texts.extend([create_input(s) for s in informal_text])\ntrain_labels.extend([0 for i in range(len(informal_text))])\n\nformal_text = open(dir + 'train.informal-formal.formal').readlines()\ntrain_texts.extend([create_input(s) for s in formal_text])\ntrain_labels.extend([1 for i in range(len(formal_text))])\n\ndata = list(zip(train_texts, train_labels))\nrandom.shuffle(data)\ntrain_texts, train_labels = zip(*data)\n\n#val data\nval_texts, val_labels = [], []\n\ninformal_text = open(dir + 'valid.informal-formal.informal').readlines()\nval_texts.extend([create_input(s) for s in informal_text])\nval_labels.extend([0 for i in range(len(informal_text))])\n\nformal_text = open(dir + 'valid.informal-formal.formal').readlines()\nval_texts.extend([create_input(s) for s in formal_text])\nval_labels.extend([1 for i in range(len(formal_text))])\n\n\n#test data\ntest_texts, test_labels = [], []\n\ninformal_text = open(dir + 'test.informal-formal.informal').readlines()\ntest_texts.extend([create_input(s) for s in informal_text])\ntest_labels.extend([0 for i in range(len(informal_text))])\n\nformal_text = open(dir + 'test.informal-formal.formal').readlines()\ntest_texts.extend([create_input(s) for s in formal_text])\ntest_labels.extend([1 for i in range(len(formal_text))])\n\n\nprint (len(train_texts), len(train_labels), len(val_texts), len(val_labels), len(test_texts), len(test_labels))\n\n#tokenize text data\ntokenizer = RobertaTokenizer.from_pretrained('roberta-base')\ntrain_encodings = tokenizer(train_texts, truncation=True, padding=True)\nval_encodings = tokenizer(val_texts, truncation=True, padding=True)\ntest_encodings = tokenizer(test_texts, truncation=True, padding=True)\n\ntrain_dataset = GYAFCDataset(train_encodings, train_labels)\nval_dataset = GYAFCDataset(val_encodings, val_labels)\ntest_dataset = GYAFCDataset(test_encodings, test_labels)\n\ndef compute_metrics(pred):\n labels = pred.label_ids\n preds = pred.predictions.argmax(-1)\n precision, recall, f1, _ = precision_recall_fscore_support(labels, preds, average='binary')\n acc = accuracy_score(labels, preds)\n return {\n 'accuracy': acc,\n 'f1': f1,\n 'precision': precision,\n 'recall': recall\n}\n\n\ntraining_args = TrainingArguments(\n output_dir='roberta-ling-results/', # output directory\n num_train_epochs=1, # total number of training epochs\n per_device_train_batch_size=16, # batch size per device during training\n per_device_eval_batch_size=16, # batch size for evaluation\n #warmup_steps=500, # number of warmup steps for learning rate scheduler\n weight_decay=0.01, # strength of weight decay\n logging_dir='./logs', # directory for storing logs\n logging_steps=25000,\n save_steps=13000,\n fp16=True,\n learning_rate=5e-5\n)\n\nmodel = RobertaForSequenceClassification.from_pretrained('roberta-base', return_dict=True)\n\ntrainer = Trainer(\n model=model, # the instantiated 🤗 Transformers model to be trained\n args=training_args, # training arguments, defined above\n train_dataset=train_dataset, # training dataset\n eval_dataset=val_dataset, # evaluation dataset\n compute_metrics=compute_metrics\n)\n\ntrainer.train()\n\npreds, labels, metrics = trainer.predict(test_dataset)\nprint('\\ntest metrics :', metrics)\npreds = ['1' if x[1]>x[0] else '0' for x in preds]\nf = open('roberta-ling-results/test_preds.txt', 'w')\nf.write('\\n'.join(preds))\nf.close()\n","sub_path":"transformer/ling-roberta.py","file_name":"ling-roberta.py","file_ext":"py","file_size_in_byte":4561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"61935773","text":"\nimport os\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\nfrom tensorflow.keras.layers import Dense, Dropout, BatchNormalization, Activation, LeakyReLU\nfrom tensorflow.keras import Model\nfrom sklearn.model_selection import StratifiedKFold\n\nprint(tf.__version__)\n\nPATH = os.getcwd()\nprint('Current Directory: ' + str(os.getcwd()))\nPATH = (os.path.abspath(os.path.join(PATH, os.pardir)))\n\nPATH += '/data'\ntrainPath = PATH + '/train'\ntestPath = PATH + '/test'\n\ndataset_L = 'lankershim'\ndataset_P = 'peachtree'\n\n\n# function used to read in the data and parse the x and y values\ndef readData(path, dataset):\n for filename in os.listdir(path):\n if filename[:-6] == dataset and filename[-5:-4] == 'X':\n fileX = np.genfromtxt(path+'/'+filename, delimiter=',')\n elif filename[:-6] == dataset and filename[-5:-4] == 'Y':\n fileY = np.genfromtxt(path+'/'+filename, delimiter=',')\n\n return fileX, fileY\n\n\n\n##### LOAD THE DATA #####\n\ntrainX, trainY = readData(trainPath, dataset_L)\ntestX, testY = readData(testPath, dataset_L)\n\nnum_samples = trainX.shape[0]\nnum_features = trainX.shape[1]\n\n\n\n##### MLP USING TENSORFLOW #####\n\n# Add a channels dimension\n#trainX = trainX[..., tf.newaxis]\n#testX = testX[..., tf.newaxis]\ntrainY=trainY[..., tf.newaxis]\ntestY=testY[..., tf.newaxis]\n\n# Use tf.data to batch and shuffle the dataset (useful because tf.data works with keras model.fit)\ntrain_ds = tf.data.Dataset.from_tensor_slices((trainX, trainY)).shuffle(1000).batch(64)\ntest_ds = tf.data.Dataset.from_tensor_slices((testX, testY)).batch(64)\n\n# define 10-fold cross validation test harness\nkfold = StratifiedKFold(n_splits=10, shuffle=True)\n\n# Build the tf.keras model using the Keras model subclassing API:\nclass MyModel(Model):\n def __init__(self):\n \t# model architecture\n super(MyModel, self).__init__()\n self.d1 = Dense(input_shape=(1,51), units=128)\n self.a1 = LeakyReLU(alpha=0.01)\n self.bn = BatchNormalization()\n self.d2 = Dense(128)\n self.a2 = LeakyReLU(alpha=0.01)\n self.dr = Dropout(0.4)\n self.d3 = Dense(1)\n self.act = Activation('sigmoid')\n\n # def order of calling\n def call(self, x):\n x = self.d1(x)\n x = self.a1(x)\n x = self.bn(x)\n x = self.d2(x)\n x = self.a2(x)\n x = self.dr(x)\n x = self.d3(x)\n return(self.act(x))\n\n# create an instance of the model\nmodel = MyModel()\n\n# choose a loss function and an optimizer\nloss_object = tf.keras.losses.BinaryCrossentropy()\n\n# create an instance of the optimizer\noptimizer = tf.keras.optimizers.Nadam()\n\n\ncheckpoint_path = \"training_1/cp.ckpt\"\ncheckpoint_dir = os.path.dirname(checkpoint_path)\n\n\n# metrics for evaluating the model\ntrain_acc = tf.keras.metrics.BinaryAccuracy(name='train_acc')\ntest_acc = tf.keras.metrics.BinaryAccuracy(name='test_acc')\n\n\n# function to train the model\n@tf.function\ndef train_step(inputs, output):\n with tf.GradientTape() as tape:\n predictions = model(inputs)\n loss = loss_object(output, predictions)\n gradients = tape.gradient(loss, model.trainable_variables)\n optimizer.apply_gradients(zip(gradients, model.trainable_variables))\n\n train_acc(output, predictions)\n\n\n# function used to test the model\n@tf.function\ndef test_step(inputs, output):\n predictions = model(inputs)\n test_acc(output, predictions)\n\n# define the number of epochs\nEPOCHS = 100\n\nfor train, test in kfold.split(trainX, trainY):\n\t# iterate through the epochs and run the training and testing functions and print out results\n\tfor epoch in range(EPOCHS):\n\t for inputs, output in train_ds:\n\t train_step(inputs, output)\n\n\t for test_input, test_output in test_ds:\n\t test_step(test_input, test_output)\n\n\t template = 'Epoch {}, Train Accuracy: {}, Test Accuracy: {}'\n\t print (template.format(epoch+1,\n\t train_acc.result(),\n\t test_acc.result()))\n\n\t#model.save_weights(checkpoint_path)\n\n\n\n\n\n","sub_path":"scripts/model-update.py","file_name":"model-update.py","file_ext":"py","file_size_in_byte":3906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"438273337","text":"import warnings\nwarnings.filterwarnings(\"ignore\")\nimport logging\nimport time\nimport numpy as np\nimport xgboost as xgb\nfrom TSSModel import TSSModel\nfrom sklearn.preprocessing import minmax_scale, scale, maxabs_scale, normalize, Binarizer\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import mean_squared_error\n\nfrom sklearn.decomposition import PCA\n\nlogger = logging.getLogger('autotvm')\n\n\ndef recall_curve(trial_ranks, top=None):\n \"\"\"\n if top is None, f(n) = sum([I(rank[i] < n) for i < n]) / n\n if top is K, f(n) = sum([I(rank[i] < K) for i < n]) / K\n\n Parameters\n ----------\n trial_ranks: Array of int\n the rank of i th trial in labels\n top: int or None\n top-n recall\n\n Returns\n -------\n curve: Array of float\n function values\n \"\"\"\n if not isinstance(trial_ranks, np.ndarray):\n trial_ranks = np.array(trial_ranks)\n\n ret = np.zeros(len(trial_ranks))\n if top is None:\n for i in range(len(trial_ranks)):\n ret[i] = np.sum(trial_ranks[:i] <= i) / (i + 1)\n else:\n for i in range(len(trial_ranks)):\n ret[i] = 1.0 * np.sum(trial_ranks[:i] < top) / top\n return ret\n\n\ndef get_rank(values):\n \"\"\"get rank of items\n\n Parameters\n ----------\n values: Array\n\n Returns\n -------\n ranks: Array of int\n the rank of this item in the input (the largest value ranks first)\n \"\"\"\n tmp = np.argsort(-values)\n ranks = np.empty_like(tmp)\n ranks[tmp] = np.arange(len(tmp))\n return ranks\n\n\ndef xgb_average_recalln_curve_score(N):\n \"\"\"evaluate average recall-n curve score for xgb\"\"\"\n\n def feval(preds, labels):\n labels = labels.get_label()\n trials = np.argsort(preds)[::-1]\n ranks = get_rank(labels[trials])\n curve = recall_curve(ranks)\n return \"a-recall@%d\" % N, np.sum(curve[:N]) / N\n\n return feval\n\n\ndef custom_callback(stopping_rounds, metric, fevals, evals=(), log_file=None,\n maximize=False, verbose_eval=True):\n \"\"\"callback function for xgboost to support multiple custom evaluation functions\"\"\"\n from xgboost.core import EarlyStopException\n from xgboost.callback import _fmt_metric\n from xgboost.training import aggcv\n\n state = {}\n metric_shortname = metric.split(\"-\")[1]\n\n def init(env):\n \"\"\"internal function\"\"\"\n bst = env.model\n\n state['maximize_score'] = maximize\n state['best_iteration'] = 0\n if maximize:\n state['best_score'] = float('-inf')\n else:\n state['best_score'] = float('inf')\n\n if bst is not None:\n if bst.attr('best_score') is not None:\n state['best_score'] = float(bst.attr('best_score'))\n state['best_iteration'] = int(bst.attr('best_iteration'))\n state['best_msg'] = bst.attr('best_msg')\n else:\n bst.set_attr(best_iteration=str(state['best_iteration']))\n bst.set_attr(best_score=str(state['best_score']))\n else:\n assert env.cvfolds is not None\n\n def callback(env):\n \"\"\"internal function\"\"\"\n if not state:\n init(env)\n\n bst = env.model\n i = env.iteration\n cvfolds = env.cvfolds\n\n res_dict = {}\n\n ##### evaluation #####\n if cvfolds is not None:\n for feval in fevals:\n tmp = aggcv([f.eval(i, feval) for f in cvfolds])\n for k, mean, std in tmp:\n res_dict[k] = [mean, std]\n else:\n for feval in fevals:\n bst_eval = bst.eval_set(evals, i, feval)\n res = [x.split(':') for x in bst_eval.split()]\n for kv in res[1:]:\n res_dict[kv[0]] = [float(kv[1])]\n\n eval_res = []\n keys = list(res_dict.keys())\n keys.sort(key=lambda x: x if metric_shortname not in x else \"a\" + x)\n for key in keys:\n v = res_dict[key]\n eval_res.append([key] + v)\n\n ##### print eval result #####\n infos = [\"XGB iter: %3d\" % i]\n for item in eval_res:\n if 'null' in item[0]:\n continue\n infos.append(\"%s: %.6f\" % (item[0], item[1]))\n\n if not isinstance(verbose_eval, bool) and verbose_eval and i % verbose_eval == 0:\n logger.debug(\"\\t\".join(infos))\n if log_file:\n with open(log_file, \"a\") as fout:\n fout.write(\"\\t\".join(infos) + '\\n')\n\n ##### choose score and do early stopping #####\n score = None\n for item in eval_res:\n if item[0] == metric:\n score = item[1]\n break\n assert score is not None\n\n best_score = state['best_score']\n best_iteration = state['best_iteration']\n maximize_score = state['maximize_score']\n if (maximize_score and score > best_score) or \\\n (not maximize_score and score < best_score):\n msg = '[%d] %s' % (\n env.iteration,\n '\\t'.join([_fmt_metric(x) for x in eval_res]))\n state['best_msg'] = msg\n state['best_score'] = score\n state['best_iteration'] = env.iteration\n # save the property to attributes, so they will occur in checkpoint.\n if env.model is not None:\n env.model.set_attr(best_score=str(state['best_score']),\n best_iteration=str(state['best_iteration']),\n best_msg=state['best_msg'])\n elif env.iteration - best_iteration >= stopping_rounds:\n best_msg = state['best_msg']\n if verbose_eval and env.rank == 0:\n logger.debug(\"XGB stopped. Best iteration: %s \", best_msg)\n raise EarlyStopException(best_iteration)\n\n return callback\n\n\ndef fit(x_train, y_train, xgb_params, plan_size, log_interval):\n # print(\"_____________fit______________\")\n tic = time.time()\n\n valid_index = y_train > 1e-6\n\n index = np.random.permutation(len(x_train))\n\n # print(\"x_train shape:\", x_train.shape)\n # print(\"y_train shape:\", y_train.shape)\n # print(\"y train[:10]\",y_train[:10])\n\n dtrain = xgb.DMatrix(x_train[index], y_train[index])\n sample_size = len(x_train)\n # print(\"sample size:\",sample_size)\n\n bst = xgb.train(xgb_params, dtrain,\n num_boost_round=8000,\n callbacks=[custom_callback(\n stopping_rounds=20,\n metric='tr-a-recall@%d' % plan_size,\n evals=[(dtrain, 'tr')],\n maximize=True,\n fevals=[xgb_average_recalln_curve_score(plan_size), ],\n verbose_eval=log_interval)])\n\n print(\"XGB train cost time:\", time.time() - tic, \"\\tobs:\", len(x_train), \"\\terror:\\t\",\n len(x_train) - np.sum(valid_index))\n return bst\n\n\ndef predict(bst, feas, output_margin=False):\n # print(\"___________predict___________\")\n # print(\"feas shape:\",feas.shape)\n dtest = xgb.DMatrix(feas)\n result = bst.predict(dtest, output_margin=output_margin)\n # print(\"predict result:\",result)\n # print(\"predict result shape:\",result.shape)\n return result\n\n\ndef load_data(datasrc, labelsrc):\n '''\n :param datasrc: 特征数据集 .txt n*m\n :param labelsrc: 标签数据集 .txt n*1\n :return:\n '''\n X = np.loadtxt(datasrc, delimiter=' ')\n Y = np.loadtxt(labelsrc, delimiter=' ')\n Y = np.array(Y).reshape((-1, 1))\n Y = np.array(Y)\n # y_max = np.max(Y)\n # Y = Y / max(y_max, 1e-8)\n print(\"X.shape:\", X.shape)\n print(\"Y.shape:\", Y.shape)\n # print(Y[:10])\n return X, Y\n\n\ndef fit_and_evaluation(x_train, y_train, x_valiation, y_valiation, xgb_params, plan_size, log_interval):\n bst = fit(x_train, y_train, xgb_params, plan_size, log_interval)\n result = predict(bst, x_valiation)\n return result\n # print(\"result:\\n\", result[:10])\n # print(\"y_valiation:\\n\", y_valiation[:10])\n # print(\"mean_squared_error:\", mean_squared_error(result, y_valiation))\n\n\nif __name__ == '__main__':\n\n '''\n 测试是否经PCA和标准化后xgboost模型的性能表现 \n '''\n datasrc = \"train/feas1.txt\"\n labelsrc = \"train/y_train.txt\"\n xgb_params = {\n 'max_depth': 3,\n 'gamma': 0.0001,\n 'min_child_weight': 1,\n 'subsample': 1.0,\n 'eta': 0.3,\n 'lambda': 1.00,\n 'alpha': 0,\n 'objective': 'reg:gamma',\n }\n plan_size = 64\n log_interval = 25\n\n\n\n input_size = 9\n tss = TSSModel(input_size=input_size)\n tss.load_data('train/feas1.txt', 'train/y_train.txt')\n\n\n\n\n print(\"xgb:situation1:split\")\n tss.split(tss.X, tss.Y)\n y_prediction = fit_and_evaluation(tss.x_train, tss.y_train, tss.X, tss.Y, xgb_params, plan_size, log_interval)\n tss.envaluation(y_prediction, tss.Y)\n\n print(\"nntss:situation1\")\n tss.pca_minmax_split(tss.X, tss.Y,pca_components=input_size)\n tss.TSS_NN_Model_fit(tss.x_train, tss.y_train, tss.x_valiation, tss.y_valiation)\n #print(\"predict(x_valiation,y_valiation)\")\n y_prediction = tss.predict(tss.x_valiation, tss.y_valiation)\n tss.envaluation(tss.y_prediction, tss.y_valiation)\n\n #\n # print(\"xgb:situation2:maxmin split\")\n # tss.minmax_split(tss.X,tss.Y)\n # fit_and_evaluation(tss.x_train, tss.y_train, tss.x_valiation, tss.y_valiation, xgb_params, plan_size, log_interval)\n #\n # print(\"xgb:situation3:maxabs split\")\n # tss.minmax_split(tss.X, tss.Y)\n # fit_and_evaluation(tss.x_train, tss.y_train, tss.x_valiation, tss.y_valiation, xgb_params, plan_size, log_interval)\n #\n # print(\"xgb:situation4:nomalize split\")\n # tss.minmax_split(tss.X, tss.Y)\n # fit_and_evaluation(tss.x_train, tss.y_train, tss.x_valiation, tss.y_valiation, xgb_params, plan_size, log_interval)\n #\n #\n # print(\"xgb:situation5:scale split\")\n # tss.minmax_split(tss.X, tss.Y)\n # fit_and_evaluation(tss.x_train, tss.y_train, tss.x_valiation, tss.y_valiation, xgb_params, plan_size, log_interval)\n #\n","sub_path":"TSS2.0(forTVM)/nn_vs_xgboost.py","file_name":"nn_vs_xgboost.py","file_ext":"py","file_size_in_byte":10148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"131151576","text":"import torch\nimport torch.distributed\nimport numpy as np\nimport time\nfrom initialize import init_distributed\nfrom arguments import parse_args, get_args\nfrom utils import print_rank_0, get_ltor_masks_and_position_ids\nfrom model.gpt2 import GPT2\nfrom profiler import Profiler\nimport os\n\n\ndef train():\n \n # Initialize torch.distributed\n init_distributed()\n\n print_rank_0('AutoMP: training GPT2...')\n\n batch_size = args.batch_size \n sequence_length = args.sequence_length\n hidden_size = args.hidden_size\n vocab_size = args.vocab_size\n hidden_dropout = args.hidden_dropout\n attention_dropout = args.attention_dropout\n num_layers = args.num_layers\n layernorm_epsilon = args.layernorm_epsilon\n num_attention_heads = args.num_attention_heads\n\n input_indices = torch.randint(low=0, high=vocab_size, size=(batch_size, sequence_length))\n input_indices = input_indices.to(torch.cuda.current_device())\n labels = torch.randint(low=0, high=vocab_size, size=(batch_size, sequence_length))\n labels = labels.to(torch.cuda.current_device())\n position_indices = torch.tile(torch.arange(start=0, end=sequence_length), (batch_size, 1))\n position_indices = position_indices.to(torch.cuda.current_device())\n \n def init_method_normal(tensor):\n return torch.nn.init.normal_(tensor, mean=0.0, std=1.0)\n def gpt2_attention_mask_func(attention_scores, ltor_mask):\n attention_scores.masked_fill_(ltor_mask, -10000.0)\n return attention_scores\n\n gpt2 = GPT2(\n hidden_size, vocab_size, sequence_length, hidden_dropout,\n gpt2_attention_mask_func, num_layers, layernorm_epsilon, \n num_attention_heads, attention_dropout,\n init_method_normal,\n )\n num_params = sum(p.numel() for p in gpt2.parameters() if p.requires_grad)\n\n attention_mask, loss_mask, position_ids = get_ltor_masks_and_position_ids(input_indices, vocab_size - 1)\n\n optimizer = torch.optim.SGD(gpt2.parameters(), lr=0.01)\n\n profiler = Profiler(os.path.join('benchmark', args.exp_name))\n\n num_epochs = 5\n tot_time = 0\n nproc = torch.distributed.get_world_size()\n\n for epoch in range(num_epochs):\n overall_name = f'gpt2_np-{nproc}_hs-{hidden_size}_nah-{num_attention_heads}_bsz-{batch_size}_num-params-{num_params}'\n profiler.start(overall_name)\n \n fname = f'gpt2_forward_np-{nproc}_hs-{hidden_size}_nl-{num_layers}_nah-{num_attention_heads}_bsz-{batch_size}_num-params-{num_params}'\n # Forward pass\n profiler.start(fname)\n loss = gpt2.forward(input_indices, position_indices, attention_mask, labels)\n train_loss = torch.mean(loss)\n # print(train_loss)\n torch.cuda.synchronize()\n profiler.stop(fname)\n # Backward pass\n bname = f'gpt2_backward_np-{nproc}_hs-{hidden_size}_nl-{num_layers}_nah-{num_attention_heads}_bsz-{batch_size}_num-params-{num_params}'\n profiler.start(bname)\n optimizer.zero_grad()\n train_loss.backward()\n optimizer.step()\n torch.cuda.synchronize()\n profiler.stop(bname)\n\n profiler.stop(overall_name)\n \n\nif __name__ == '__main__':\n # Parse command line arguments\n parse_args()\n\n args = get_args()\n\n train()","sub_path":"train_gpt2.py","file_name":"train_gpt2.py","file_ext":"py","file_size_in_byte":3251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"442084748","text":"# Surface Subnet\n\n\nimport sys\nimport torch\n\nsys.path.append(\"..\")\nfrom network.OCTOptimization import *\nfrom network.OCTAugmentation import *\nfrom network.QuadraticIPMOpt import SoftSeparationIPMModule\n\nsys.path.append(\"../..\")\nfrom framework.NetTools import *\nfrom framework.BasicModel import BasicModel\nfrom framework.ConvBlocks import *\nfrom framework.CustomizedLoss import SmoothSurfaceLoss, logits2Prob, WeightedDivLoss\nfrom framework.ConfigReader import ConfigReader\n\nclass SurfacesNet(BasicModel):\n def __init__(self, hps=None):\n '''\n inputSize: BxinputChaneels*H*W\n outputSize: (B, N, H, W)\n '''\n super().__init__()\n if isinstance(hps, str):\n hps = ConfigReader(hps)\n self.hps = hps\n C = self.hps.startFilters\n\n # input of Unet: BxinputChannelsxHxW\n self.m_downPoolings, self.m_downLayers, self.m_upSamples, self.m_upLayers = \\\n constructUnet(self.hps.inputChannels, self.hps.inputHeight, self.hps.inputWidth, C, self.hps.nLayers)\n # output of Unet: BxCxHxW\n\n # Surface branch\n self.m_surfaces = nn.Sequential(\n Conv2dBlock(C, C),\n nn.Conv2d(C, self.hps.numSurfaces, kernel_size=1, stride=1, padding=0) # conv 1*1\n ) # output size:BxNxHxW\n\n\n\n def forward(self, inputs, gaussianGTs=None, GTs=None, layerGTs=None, riftGTs=None):\n device = inputs.device\n # compute outputs\n skipxs = [None for _ in range(self.hps.nLayers)] # skip link x\n\n # down path of Unet\n for i in range(self.hps.nLayers):\n if 0 == i:\n x = inputs\n else:\n x = skipxs[i-1]\n x = self.m_downPoolings[i](x)\n skipxs[i] = self.m_downLayers[i](x) + x\n\n # up path of Unet\n for i in range(self.hps.nLayers-1, -1, -1):\n if self.hps.nLayers-1 == i:\n x = skipxs[i]\n else:\n x = x+skipxs[i]\n x = self.m_upLayers[i](x) + x\n x = self.m_upSamples[i](x)\n # output of Unet: BxCxHxW\n\n\n # N is numSurfaces\n xs = self.m_surfaces(x) # xs means x_surfaces, # output size: B*N*H*W\n B,N,H,W = xs.shape\n\n layerMu = None # referred surface mu computed by layer segmentation.\n layerConf = None\n surfaceProb = logits2Prob(xs, dim=-2)\n\n # compute surface mu and variance\n mu, sigma2 = computeMuVariance(surfaceProb, layerMu=layerMu, layerConf=layerConf) # size: B,N W\n\n # ReLU to guarantee layer order not to cross each other\n # 0: NoReLU; 1: ReLU; 2: hardSeparation;\n if 2 == self.hps.hardSeparation:\n separationIPM = SoftSeparationIPMModule()\n S = separationIPM(mu, sigma2, R=None, fixedPairWeight=self.hps.fixedPairWeight,\n learningPairWeight=None) # only use unary item\n elif 1 == self.hps.hardSeparation:\n S = mu.clone()\n for i in range(1, N):\n S[:, i, :] = torch.where(S[:, i, :] < S[:, i - 1, :], S[:, i - 1, :], S[:, i, :])\n else: #No ReLU\n S = mu.clone()\n\n\n\n loss_div = 0.0\n loss_smooth = 0.0\n loss = loss_div + loss_smooth\n if self.hps.existGTLabel:\n # hps.useWeightedDivLoss:\n surfaceWeight = None\n _, C, _, _ = inputs.shape\n if C >= 4: # at least 3 gradient channels.\n imageGradMagnitude = inputs[:, C - 1, :, :] # image gradient magnitude is at final channel since July 23th, 2020\n surfaceWeight = getSurfaceWeightFromImageGradient(imageGradMagnitude, N, gradWeight=self.hps.gradWeight)\n\n weightedDivLoss = WeightedDivLoss(weight=surfaceWeight ) # the input given is expected to contain log-probabilities\n if 0 == len(gaussianGTs): # sigma ==0 case\n gaussianGTs = batchGaussianizeLabels(GTs, sigma2, H)\n loss_div = weightedDivLoss(nn.LogSoftmax(dim=2)(xs), gaussianGTs)\n\n #hps.useSmoothSurfaceLoss:\n smoothSurfaceLoss = SmoothSurfaceLoss(mseLossWeight=10.0)\n loss_smooth = smoothSurfaceLoss(S, GTs)\n\n loss = loss_div + loss_smooth\n\n if torch.isnan(loss.sum()): # detect NaN\n print(f\"Error: find NaN loss at epoch {self.m_epoch}\")\n assert False\n\n return S, sigma2, loss # return surfaceLocation S in (B,S,W) dimension, sigma2, and loss\n\n\n\n","sub_path":"OCTMultiSurfaces/network_bestTongren/SurfacesNet.py","file_name":"SurfacesNet.py","file_ext":"py","file_size_in_byte":4490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"216996822","text":"import csv\nimport numpy as np\nfrom mapsAnalysis.utiles import bienClusterise\nfrom mapsClustering.MapsClustering import MapsClustering\n\n\nfrom itertools import izip_longest\n\nfrom mapsClustering.maps5Clustering import Maps5Clustering\n\n\ndef GenerationClustering(couche = \"conv1\", seuilSuppression = 559, seuilBonClustering = 30, fichier = True):\n\n #############################################################################################\n # Appel de MapsClustering et enregistrement des matrices des indices pour chaque algorithme de chaque couche;\n # Matrice des indices : 5 colonnes representant les 5 clusterings, et dans chaque colonne les indices de cartes\n # qui donnent bien deux classes.\n #############################################################################################\n\n pFRJA_R_KMNI, pFRJA_V_KMNI, pFR_RV_KMNI, pCIC_R_KMNI, pCIC_V_KMNI, pourcentagesFR_Rlvb0, pourcentagesFR_Rlvb1,pourcentagesFR_Rlvb2, pourcentagesFR_Rlvb3, ind = Maps5Clustering(couche, seuilSuppression, fichier)\n matKmeansNonInit = str(\"../resultats/resultats5phonemes/matKmeansNonInit_indices_bonnes_cartes.csv\")\n f1 = open(matKmeansNonInit, \"wb\")\n writer = csv.writer(f1)\n writer.writerow([\"KmeansNonInit(1)\", \"KmeansNonInit(1bis)\", \"KmeansNonInit(2)\", \"KmeansNonInit(3)\", \"KmeansNonInit(3bis)\", \" 4phonemes\"])\n for values in izip_longest(*ind):\n writer.writerow(values)\n\n\n\n #############################################################################################\n # Fichiers de cartes bon clustering\n #############################################################################################\n\n filename = str(\"../resultats/resultats5phonemes/cartes_bon_clustering_kmeans5\")\n f = open(filename, \"wb\")\n\n #############################################################################\n #appel directement avec les matrices\n ##############################################################################\n\n f.write(\"FRJA R\\n\")\n\n\n clus = bienClusterise(MatriceClustering=pFRJA_R_KMNI, seuil=seuilBonClustering, indices=ind[0])\n f.write(\"kmeansNonInit:\" + str(clus)+\"\\n\")\n\n\n f.write(\"FRJA V\\n\")\n\n clus = bienClusterise(MatriceClustering=pFRJA_V_KMNI, seuil=seuilBonClustering, indices=ind[1])\n f.write(\"kmeansNonInit:\" + str(clus)+\"\\n\")\n\n\n f.write(\"FR RV\\n\")\n\n clus = bienClusterise(MatriceClustering=pFR_RV_KMNI, seuil=seuilBonClustering, indices=ind[2])\n f.write(\"kmeansNonInit:\" + str(clus)+\"\\n\")\n\n\n\n f.write(\"JA correct/incorrect R\\n\")\n #\n clus = bienClusterise(MatriceClustering=pCIC_R_KMNI, seuil=seuilBonClustering, indices=ind[3])\n f.write(\"kmeansNonInit:\" + str(clus)+\"\\n\")\n\n\n\n f.write(\"JA correct/incorrect V\\n\")\n #\n clus = bienClusterise(MatriceClustering=pCIC_V_KMNI, seuil=seuilBonClustering, indices=ind[4])\n f.write(\"kmeansNonInit:\" + str(clus)+\"\\n\")\n\n f.write(\"FR_Rlvb\\n\")\n\n f.write(\"classe0\")\n clus = bienClusterise(MatriceClustering=pourcentagesFR_Rlvb0, seuil=seuilBonClustering, indices=ind[5])\n f.write(\"kmeansNonInit:\" + str(clus)+\"\\n\")\n f.write(\"classe1\")\n clus = bienClusterise(MatriceClustering=pourcentagesFR_Rlvb1, seuil=seuilBonClustering, indices=ind[5])\n f.write(\"kmeansNonInit:\" + str(clus)+\"\\n\")\n f.write(\"classe2\")\n clus = bienClusterise(MatriceClustering=pourcentagesFR_Rlvb2, seuil=seuilBonClustering, indices=ind[5])\n f.write(\"kmeansNonInit:\" + str(clus)+\"\\n\")\n f.write(\"classe3\")\n clus = bienClusterise(MatriceClustering=pourcentagesFR_Rlvb3, seuil=seuilBonClustering, indices=ind[5])\n f.write(\"kmeansNonInit:\" + str(clus)+\"\\n\")\n\n f.close()\n\n\n\n\nGenerationClustering(couche = \"conv1\", seuilSuppression = 559, seuilBonClustering = 30, fichier = True)\n","sub_path":"reseau/mapsClustering/generation5Clustering.py","file_name":"generation5Clustering.py","file_ext":"py","file_size_in_byte":3746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"405088774","text":"#!/usr/bin/python3\nimport os, sys\n\nIN_EXT, OUT_EXT = \".tmpl\", \".html\"\nRULES, LOCAL = sys.argv[1], sys.argv[2] if len(sys.argv) > 2 else None\n\nTXT = []\nwith open(RULES, \"r\") as rules:\n tokens = rules.read().split(\"\\n\\n\")\n for token in tokens:\n token = [x for x in [x.strip() for x in token.split(\"\\n\")] if len(x) > 0 and x[0] != '#']\n\n if len(token) != 2:\n print(\"Ignoring tokens:\\n{:s}\".format(token))\n continue\n\n TXT.append((token[0], token[1]))\n\nfor root, dirs, files in os.walk(\"./\"):\n for filename in files:\n if IN_EXT not in filename:\n continue\n\n print(\"Found \\\"{:s}\\\", processing...\".format(os.path.join(root, filename)))\n with open(os.path.join(root, filename), \"r\") as src:\n result = src.read()\n\n changed = False\n while True:\n replaced = False\n for token in TXT:\n if token[0] not in result:\n continue\n replaced, changed = True, True\n\n cmd = token[1].format(root, filename.replace(IN_EXT, \"\"))\n result = result.replace(token[0], os.popen(cmd).read())\n\n if not replaced:\n break\n\n if changed:\n with open(os.path.join(root, filename.replace(IN_EXT, OUT_EXT)), \"w\") as dest:\n dest.write(result)\n","sub_path":"dev/gen.py","file_name":"gen.py","file_ext":"py","file_size_in_byte":1367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"307402426","text":"\"\"\"Utility functions utilized by multiple files\"\"\"\nimport os\nimport json\n\nfrom tenk.users import User\nimport tenk.tkserializer as tkserializer\nfrom tenk.sessions import Session\n\ndef save(user, config):\n u_file = config['PATHS']['user_filepath']\n with open(u_file, encoding='utf-8', mode='w') as f:\n json.dump(user, f, indent=2, default=tkserializer.to_json)\n\ndef load_user(config, create=False):\n \"\"\"Load a user's tk file into a User object. If create is True,\n then a user object will be created if no tk file exists.\"\"\"\n tk_dir = config['PATHS']['tk_dir']\n if os.path.exists(tk_dir):\n u_file = config['PATHS']['user_filepath']\n with open(u_file, encoding='utf-8', mode='r') as f:\n user = json.load(f, object_hook=tkserializer.from_json)\n return user\n else:\n if create:\n os.makedirs(tk_dir)\n u_file = config['PATHS']['user_filepath']\n open(u_file, 'a').close()\n return User(\"Default\")\n else:\n return None\n","sub_path":"tenk/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"620237815","text":"import arcpy\nimport os\narcpy.env.workspace = r'C:\\Data'\noutworkspace = r'D:\\Documents\\ArcGIS\\Default.gdb'\nfclist = arcpy.ListFeatureClasses()\nfor shapefile in fclist:\n fcname = arcpy.Describe(shapefile).basename\n newfcname = arcpy.ValidateTableName(fcname)\n outfc = os.path.join(outworkspace,newfcname)\n arcpy.CopyFeatures_management(shapefile,outfc)\n","sub_path":"代码示例/7.4.2使用CopyFeatures工具将所有shapefile文件从文件夹转移到地理数据库中.py","file_name":"7.4.2使用CopyFeatures工具将所有shapefile文件从文件夹转移到地理数据库中.py","file_ext":"py","file_size_in_byte":363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"82950272","text":"#wilks\nimport dash\nimport dash_core_components as dcc\nimport dash_html_components as html\nfrom dash.dependencies import Input, Output\n\nimport pandas as pd\nimport plotly.graph_objs as go\nimport dash_table\nimport webbrowser\n\n# chrome_path = 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s'\n#\n# url = 'http://127.0.0.1:8050/'\n# webbrowser.get(chrome_path).open(url)\n#\n# print(\"Ctrl+C to quit...\")\n\n\ndef wilks(lw,bw,gender, is_lbs):\n if(is_lbs == True):\n W = lw / 2.205\n x = bw / 2.205\n else:\n W = lw\n x = bw\n if gender == 0:\n aa = 594.31747775582\n bb = -27.23842536447\n cc = 0.82112226871\n dd = -0.00930733913\n ee = 4.731582e-05\n ff = -9.054e-08\n else:\n aa = -216.0475144\n bb = 16.2606339\n cc = -0.002388645\n dd = -0.00113732\n ee = 7.01863e-06\n ff = -1.291e-08\n return(W * 500 / (aa + bb*x +cc*x**2 + dd*x**3 + ee*x**4 + ff*x**5))\n\n #\n # if __name__ == '__main__':\n # app.run_server(debug= True)\n","sub_path":"wilks.py","file_name":"wilks.py","file_ext":"py","file_size_in_byte":1025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"9230260","text":"# \"\"\"\n# This is the interface that allows for creating nested lists.\n# You should not implement it, or speculate about its implementation\n# \"\"\"\n#class NestedInteger(object):\n# def isInteger(self):\n# \"\"\"\n# @return True if this NestedInteger holds a single integer, rather than a nested list.\n# :rtype bool\n# \"\"\"\n#\n# def getInteger(self):\n# \"\"\"\n# @return the single integer that this NestedInteger holds, if it holds a single integer\n# Return None if this NestedInteger holds a nested list\n# :rtype int\n# \"\"\"\n#\n# def getList(self):\n# \"\"\"\n# @return the nested list that this NestedInteger holds, if it holds a nested list\n# Return None if this NestedInteger holds a single integer\n# :rtype List[NestedInteger]\n# \"\"\"\n\nclass Solution(object):\n def depthSum(self, nestedList):\n \"\"\"\n :type nestedList: List[NestedInteger]\n :rtype: int\n \"\"\"\n def getSum(n, depth):\n s = 0\n if n.isInteger():\n return n.getInteger() * depth\n for i in n.getList():\n s += getSum(i, depth + 1)\n return s\n \n s = 0\n for i in nestedList:\n s += getSum(i, 1)\n return s\n \n \n","sub_path":"Nested List Weight Sum/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"565472451","text":"from flask import Flask, request, json, Response\nimport time\n\napp = Flask(__name__)\n\n\n@app.route('/post', methods=['POST'])\ndef post():\n if request.headers['Content-Type'] == 'text/plain':\n return \"Text Message: \" + str(request.data)\n\n elif request.headers['Content-Type'] == 'application/json':\n # loads would take a file-like object, read the data from that object, and use that string to create an object\n request_data = json.loads(request.data)\n data = {\n 'timestamp': time.time(),\n 'request-data': request_data\n }\n # dumps takes an json object and produces a string\n js = json.dumps(data)\n\n resp = Response(js, status=200, mimetype='application/json')\n resp.headers['referer'] = 'http://localhost:5000'\n return resp\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n","sub_path":"flask/src/03_postmethod.py","file_name":"03_postmethod.py","file_ext":"py","file_size_in_byte":872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"207506041","text":"'''\nCreated on 27 Mar 2019\n\n@author: wimth\n'''\nfrom fileHandler import FileHandler\nfrom param_XML import Param_xml\nfrom preProcess import preprocess_image\nfrom spheres_DT import spheres_DT\nfrom lineager_feeder import generate_lineager_input_files\nfrom CTC_Tracking import generate_CTC_TRA_files\nfrom mpacts_input_generator import mpacts_input_generator\nfrom fig_z_trajectory import fig_z_trajectory\nimport os,datetime,sys\nimport shutil\nimport pprint\nfrom pathlib import Path\npp = pprint.PrettyPrinter(indent=4)\n\nos.system('hostname')\n# if os.popen('hostname').read().startswith('DESKTOP'):import pdb;pdb.set_trace()\n#if os.popen('hostname').read().startswith('wth'):import pdb;pdb.set_trace()\n\n\n\nd_execution_blocks = {'1':'preprocessing',\n '2':'spheresDT',\n '3':'lineager_feeder',\n '4':'CTC_TRA',\n '5':'mpacts_input_generator',\n '6':'fig_z_trajectory'\n }\n\n\ndef check_params_and_data():\n return True\n\n\n\ndef main(inputXML=None):\n def read_parms():\n l_execution_blocks = param_xml.get_value('l_execution_blocks', ['flowcontrol']) \n ix_restart = param_xml.get_value('ix_restart', ['flowcontrol']) \n l_execution_blocks = l_execution_blocks if (not ix_restart or ix_restart==0) else l_execution_blocks[ix_restart:]\n \n img_raw_file = param_xml.get_value('img_raw_file', ['paths'])\n img_exterior_outline = param_xml.get_value('img_exterior_outline', ['paths'])\n\n IMG_RAW_DIR = str(img_raw_file.parent)\n IMG_RAW_FILE= img_raw_file.name\n OUTPUT_FOLDER_ROOT = param_xml.get_value('OUTPUT_FOLDER_ROOT', ['paths'])\n ic_timestamp_subfolder = param_xml.get_value('ic_timestamp_subfolder', ['paths'])\n \n return l_execution_blocks, IMG_RAW_DIR,IMG_RAW_FILE,OUTPUT_FOLDER_ROOT,ic_timestamp_subfolder,img_exterior_outline\n \n def initialize_filehandler():\n \n filehandler = FileHandler()\n filehandler.d_save_info['save_dir']= OUTPUT_FOLDER_ROOT\n #print(\"DEBUG1: filehandler {0}, OUTPUT_FOLDER_ROOT {1}, filehandler.get_save_location() {2}\".format(filehandler.__repr__(), OUTPUT_FOLDER_ROOT,filehandler.get_save_location()))\n \n if ic_timestamp_subfolder:\n if IMG_RAW_FILE:\n filehandler.d_save_info['sub_dir_1']=str(datetime.datetime.now()).replace(\":\",\"_\").replace(\" \",\"_\") + \"_\" + IMG_RAW_FILE[0:-4]\n else:\n filehandler.d_save_info['sub_dir_1']=str(datetime.datetime.now()).replace(\":\",\"_\").replace(\" \",\"_\") \n \n filehandler.set_save_info_root()\n #print(\"DEBUG2: filehandler {0}, OUTPUT_FOLDER_ROOT {1}, filehandler.get_save_location() {2}\".format(filehandler.__repr__(), OUTPUT_FOLDER_ROOT,filehandler.get_save_location()))\n filehandler.d_load_info['load_dir']=IMG_RAW_DIR\n filehandler.take_snapshot()\n #print(\"DEBUG3: filehandler {0}, OUTPUT_FOLDER_ROOT {1}, filehandler.get_save_location() {2}\".format(filehandler.__repr__(), OUTPUT_FOLDER_ROOT,filehandler.get_save_location()))\n print('SDT_MAIN.py:all info will be written to : ',filehandler.get_save_location())\n \n return filehandler\n \n def update_filehandler_with_f_name(filename_raw):\n if not IMG_RAW_FILE or ic_timestamp_subfolder: #if input file name is not filled in , create a subfolder for each image processed\n filehandler.extend_save_info(extra_dir_1=filename_raw[0:-4],from_root=True,set_root=True)\n filehandler.store_f_name('IMG_RAW_FILE', filename_raw)\n filehandler.d_load_info['f_name']=filename_raw\n\n filehandler.store_f_name('img_exterior_outline', img_exterior_outline)\n\n\n filehandler.take_snapshot()\n \n return filehandler\n \n def load_raw_image():\n filehandler.d_load_info['load_dir'] = param_xml.get_value('IMG_RAW_DIR',['paths'], dtype='string')\n filehandler.d_load_info['f_name'] = param_xml.get_value('IMG_RAW_FILE',['paths'], dtype='string')\n return filehandler.load_tif()\n \n\n print('STEP0-SETUP------------------------------------------------------------------------------------------------------------')\n \n param_xml = Param_xml.get_param_xml(inputXML,l_main_keys = ['body','MAIN'],verbose=True)\n # file_param, param_xml,param_xml.l_main_keys = read_param_xml_file()\n l_execution_blocks,IMG_RAW_DIR,IMG_RAW_FILE,OUTPUT_FOLDER_ROOT,ic_timestamp_subfolder,img_exterior_outline = read_parms()\n \n filehandler = initialize_filehandler()\n os.makedirs(filehandler.get_save_location(),exist_ok=True)\n shutil.copyfile(str(param_xml.file), os.path.join(filehandler.get_save_location(),param_xml.file.name)) #backup param file\n \n print('checks done, proceeding...') if check_params_and_data() else print('checks failed. stopping executing')\n \n for filename_raw in Path(IMG_RAW_DIR).glob('**/*.tif'):\n # for filename_raw in os.listdir(IMG_RAW_DIR):\n # if filename_raw.endswith(\".tif\") or filename_raw==IMG_RAW_FILE:\n \n if IMG_RAW_FILE and filename_raw.name != IMG_RAW_FILE:continue #if input file is given , only process this one file\n \n update_filehandler_with_f_name(filename_raw.name)\n \n for execution_block in l_execution_blocks:\n if d_execution_blocks.get(execution_block)=='preprocessing':\n print('STEP1-PREPROCESSING---------------------------------------------------------------------------------------------------')\n preprocess_image(param_xml,filehandler)\n \n elif d_execution_blocks.get(execution_block)=='spheresDT':\n print('STEP2-SPHERES_DT------------------------------------------------------------------------------------------------------')\n spheres_DT(param_xml,filehandler)\n \n elif d_execution_blocks.get(execution_block)=='lineager_feeder':\n print('STEP3-LINEAGER_FEEDER------------------------------------------------------------------------------------------------------')\n generate_lineager_input_files(param_xml, filehandler)\n \n elif d_execution_blocks.get(execution_block)=='CTC_TRA':\n print('STEP4-CTC_TRA------------------------------------------------------------------------------------------------------')\n generate_CTC_TRA_files(param_xml, filehandler)\n \n elif d_execution_blocks.get(execution_block)=='mpacts_input_generator':\n print('STEP5-mpacts_input_generator-----------------------------------------------------------------------------------------------------')\n mpacts_input_generator(param_xml, filehandler)\n \n elif d_execution_blocks.get(execution_block)=='fig_z_trajectory':\n print('STEP6-fig_z_trajectory-----------------------------------------------------------------------------------------------------')\n fig_z_trajectory(param_xml)\n \n else:\n print('execution block not recognized')\n filehandler.set_save_info_to_root()\n #<--next executionstep\n filehandler.pop_save_info(set_root=True) #remove filename from root\n #<--next tif\n \n # if os.popen('hostname').read().startswith('DESKTOP'):ipdb.pm()\n \nif __name__ == '__main__':\n if len(sys.argv)>1:\n main(sys.argv[1])\n else:\n main()","sub_path":"SpheresDT/SCRIPTS/SDT_MAIN.py","file_name":"SDT_MAIN.py","file_ext":"py","file_size_in_byte":7582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"83910207","text":"import unittest\n\nfrom selenium import webdriver\nfrom test_utility import static_data, fields\n\n\n# Assume captcha is 1234\n\nclass Forget(unittest.TestCase):\n\n def setUp(self):\n self.driver = webdriver.Firefox()\n\n def test_forgot_sql_injection(self):\n driver = self.driver\n driver.get(static_data.base_url + \"forget\")\n components = fields.get_components_by_name(driver, [\"telegram-check\", \"phone-number=09398604014\",\n \"email=select * from users\", \"captcha=1234\", \"submit\"])\n components[0].click()\n components[4].click()\n\n assert driver.find_element_by_id(\"inValid\") is not None\n\n def tearDown(self):\n self.driver.close()\n","sub_path":"Code/Sellenium/forget/forget_SQLinjection.py","file_name":"forget_SQLinjection.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"162868278","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sep 02, 2019\n\n@author: kubilaykarapinar\n\n\"\"\"\nfrom img_pack.Img import Img\nimport glob\nimport argparse\nimport os\n\n\ndef insensitive_glob(pattern):\n def either(c):\n return '[%s%s]' % (c.lower(), c.upper()) if c.isalpha() else c\n\n return glob.glob(''.join(map(either, pattern)))\n\n\nparser = argparse.ArgumentParser(description='Convert images .png or .jpeg to .jpg')\nparser._action_groups.pop()\nrequired = parser.add_argument_group('required arguments')\noptional = parser.add_argument_group('optional arguments')\nrequired.add_argument('-s', '--source', type=str, required=True,\n help='source directory (ends with / s.t. /users/bla/bla/folder/')\nrequired.add_argument('-d', '--destination', type=str, required=True,\n help='destination directory')\nrequired.add_argument('-e', '--enum', type=str, required=True,\n help='rename images with numbers')\noptional.add_argument('-size', '--size', nargs=2, type=int,\n help='The requested size in pixels: width height')\nargs = parser.parse_args()\n\nsource = args.source\ndestination = args.destination\nenum = args.enum\nif args.size is not None:\n size = tuple(args.size)\nelse:\n size = None\n\nif not os.path.exists(destination):\n os.makedirs(destination)\n\ncounter = 0\ntypes = ('*.png', '*.jpeg', '*.jpg', '*.tif')\nfor t in types:\n for filename in insensitive_glob(source + t):\n print(counter)\n img = Img(filename)\n img.resize(size)\n if enum == \"True\" or enum == \"true\":\n img.save_as_jpg(destination, 'img_' + str(counter))\n else:\n img.save_as_jpg(destination, filename.split('.')[0].split('/')[-1])\n counter += 1\n","sub_path":"convert_to_jpg.py","file_name":"convert_to_jpg.py","file_ext":"py","file_size_in_byte":1775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"73877838","text":"# Copyright 2015 Conchylicultor. 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 os\nimport jieba\nfrom os import listdir\nfrom os.path import isfile, join\nimport re\nimport tensorflow as tf\nimport linecache\nfrom tqdm import tqdm # Progress bar\nimport subprocess\nimport time\n\"\"\"\nLoad data from a dataset of baobao data\n\n\n\"\"\"\n\n\nclass BaobaoWhisperStreamData:\n \"\"\"\n \"\"\"\n\n def __init__(self, baobaoFile):\n \"\"\"\n Args:\n lightweightFile (string): file containing our lightweight-formatted corpus\n \"\"\"\n self.conversations = None\n self.loadLines(baobaoFile )\n\n def linecount(self,path):\n count = int(subprocess.check_output([\"wc\",path]).split()[0])\n return count\n\n def loadLines(self, folderName):\n \"\"\"\n Args:\n fileName (str): file to load\n \"\"\"\n fileName = [f for f in listdir(folderName) if (isfile(join(folderName, f)) and f.endswith('txt'))]\n src_file = folderName+os.sep+fileName[0]\n dst_file = folderName+os.sep+fileName[0]+'.chat'\n self.conversations = dst_file\n if os.path.isfile(dst_file):\n return\n count = self.linecount(src_file)\n print(count)\n filtrate = re.compile(u'[^\\u4E00-\\u9FA5A-Za-z0-9_\\s]')\n emoji_pattern = re.compile(u\"(\\ud83d[\\ude00-\\ude4f])|\" # emoticons\n u\"(\\ud83c[\\udf00-\\uffff])|\" # symbols & pictographs (1 of 2)\n u\"(\\ud83d[\\u0000-\\uddff])|\" # symbols & pictographs (2 of 2)\n u\"(\\ud83d[\\ude80-\\udeff])|\" # transport & map symbols\n u\"(\\ud83c[\\udde0-\\uddff])\" # flags (iOS)\n \"+\", flags=re.UNICODE)\n\n linesBuffer = []\n lastQ = ''\n print('Read baobao whisper data:')\n with open(src_file, 'r', encoding='utf-8') as f, open(dst_file, 'w', encoding='utf-8')as fo,tqdm(total=count,desc='PreProcess') as pbar:\n for line in f:\n pbar.update(1)\n if line.startswith(\"Q: \"):\n line = line.replace(\"Q: \",'')\n line = ' '.join(jieba.cut(line)).rstrip()\n line = filtrate.sub(r'', line) # 过滤掉标点符号\n line = emoji_pattern.sub(r'', line) # 过滤emoji\n if lastQ!=line:\n lastQ = line\n fo.write(line+'\\n')\n if line.startswith(\"A: \"):\n line = line.replace(\"A: \", '')\n line = ' '.join(jieba.cut(line)).rstrip()\n line = filtrate.sub(r'', line) # 过滤掉标点符号\n line = emoji_pattern.sub(r'', line) # 过滤emoji\n fo.write(line+'\\n')\n fo.write(\"//new_chat\" + '\\n')\n def getConversations(self):\n print('path='+self.conversations)\n return self.conversations\n","sub_path":"chatbot/corpus/baobaowhisperstreamdata.py","file_name":"baobaowhisperstreamdata.py","file_ext":"py","file_size_in_byte":3583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"558780967","text":"class Solution:\n def numPairsDivisibleBy60(self, time):\n ans = [0 for _ in range(60)]\n result = 0\n\n for x in time:\n x %= 60\n result += ans[(60 - x) % 60]\n ans[x] += 1\n\n return result\n\n\nif __name__ == '__main__':\n s = Solution()\n a = [30,20,150,100,40]\n print(s.numPairsDivisibleBy60(a))\n","sub_path":"Leetcode/numPairsDivisibleBy60.py","file_name":"numPairsDivisibleBy60.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"486204825","text":"# -*- coding: utf-8 -*-\nfrom paddle import fluid\nimport numpy as np\n\n\n#在网络里面减均值除方差\ndef preprocessimg(image, mean, std):\n data_ori = fluid.layers.cast(x=image, dtype='float32')\n mean_values_numpy = np.array(mean, np.float32).reshape(\n -1, 1, 1).astype(np.float32)\n mean_values = fluid.layers.create_tensor(dtype=\"float32\")\n fluid.layers.assign(input=mean_values_numpy, output=mean_values)\n mean_values.stop_gradient = True\n\n std_values_numpy = np.array(std, np.float32).reshape(-1, 1, 1).astype(\n np.float32)\n std_values = fluid.layers.create_tensor(dtype=\"float32\")\n fluid.layers.assign(input=std_values_numpy, output=std_values)\n std_values.stop_gradient = True\n\n datasubmean = fluid.layers.elementwise_sub(data_ori, mean_values)\n datasubmean.stop_gradient = True\n inputdata = fluid.layers.elementwise_div(datasubmean, std_values)\n inputdata.stop_gradient = True\n return inputdata\n","sub_path":"image_feature/metric_learning/fluidpreprocess.py","file_name":"fluidpreprocess.py","file_ext":"py","file_size_in_byte":960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"164589937","text":"import random\r\n#check for changes\r\nfrom random import *\r\n\r\nword_letters = [] # letter of the word selected\r\nletters_guessed = []\r\nguess_chances = 5\r\nguesses_left = guess_chances\r\nuser_letter_locations = []\r\nfound_letters = []\r\ngame_on = True\r\n\r\n\r\ndef array_cleaner():\r\n user_letter_locations.clear()\r\n letters_guessed.clear()\r\n word_letters.clear()\r\n found_letters.clear()\r\n\r\n\r\ndef word_selector():\r\n words = [\"singapore\", \"berliner\", \"birmingham\", \"iclal\"]\r\n word = choice(words) # selects one of the words randomly\r\n for i in word:\r\n word_letters.append(i) # transforms the word into an array with each letter\r\n found_letters.append('_')\r\n return word # returns the selected the word\r\n\r\n\r\ndef letter_location_finder(user_letter): # finds and prints the location of the letter\r\n\r\n letter_location = 0\r\n this_letter_used = 0 # number of times this specific letter has been used\r\n\r\n for i in word_letters: # goes through every letter in the word\r\n letter_location += 1\r\n if i == user_letter: # if the letter is same as the user letter:\r\n user_letter_locations.append(letter_location) # adds the letter to the user_letter_locations list\r\n found_letters.insert(letter_location - 1, user_letter)\r\n found_letters.pop(letter_location)\r\n this_letter_used += 1\r\n # print(user_letter, \"was used\", )\r\n\r\n if this_letter_used > 1: # prints out how many times the letter was used\r\n print(\"This letter was used\", this_letter_used, \"times\")\r\n elif this_letter_used == 1:\r\n print(\"This letter was used\", this_letter_used, \"time\") # prints singular time if it was used only once\r\n # print(user_letter, \"is the letter number:\", user_letter_locations)\r\n\r\n\r\ndef check_letter():\r\n english_alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',\r\n 't', 'u', 'v', 'w', 'x', 'y', 'z'] # the english alphabet\r\n user_letter = input(\"Try a letter!\")\r\n if user_letter not in english_alphabet:\r\n print(\"That is not a letter that is in the English alphabet\")\r\n\r\n elif user_letter in letters_guessed: # checks if the letter was already guessed\r\n print(\"You have already tried that letter...\")\r\n\r\n elif user_letter in word_letters: # user guesses correctly\r\n print(\"That is one of the letters\")\r\n letters_guessed.append(user_letter)\r\n\r\n letter_location_finder(user_letter)\r\n # user_letter_location = letter_location_finder(user_letter)\r\n # print(user_letter_location)\r\n # print(letters_guessed) # TODO remove in the final version\r\n\r\n elif user_letter not in word_letters:\r\n global guesses_left\r\n print(\"That is not one of the letters\")\r\n guesses_left = guesses_left - 1\r\n print(guesses_left, \"guesses left.\")\r\n\r\n\r\ndef end_game(): # ask the user to continue or not and end the game if necessary\r\n if guesses_left <= 0:\r\n print(\"Man got hanged! Sorry...\")\r\n print(\"It was :\",word_letters)\r\n if guesses_left > 0:\r\n # clears the arrays for the next game\r\n array_cleaner()\r\n print(\"You have got it!\")\r\n play_again = input(\"Play again?\")\r\n yes = [\"y\", \"Y\", \"yes\", \"Yes\"]\r\n no = [\"no\", \"No\", \"meh\", \"n\", \"N\"]\r\n if play_again in yes:\r\n global game_on\r\n game_on = True\r\n return (False)\r\n elif play_again in no:\r\n print(\"Thanks for playing!\")\r\n game_on = False\r\n return (True)\r\n\r\n\r\ndef run():\r\n word = word_selector()\r\n # print(word) # TODO remove in the final version\r\n # print(word_letters) # TODO remove in the final version\r\n # print(found_letters)\r\n while user_letter_locations.__len__() < word_letters.__len__():\r\n check_letter()\r\n print(found_letters)\r\n global guesses_left\r\n if guesses_left <= 0 or user_letter_locations.__len__() == word_letters.__len__():\r\n end_game_bool = end_game() # ask the user if they want to play again\r\n if end_game_bool:\r\n break\r\n elif not end_game_bool:\r\n guesses_left = guess_chances\r\n run()\r\n break\r\n\r\n\r\nwhile game_on:\r\n run()\r\n","sub_path":"LearningPython/PythonExercisesAfterCamp/Hangman.py","file_name":"Hangman.py","file_ext":"py","file_size_in_byte":4292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"633544501","text":"from flask import Flask, request\nfrom flask_cors import CORS\nfrom telegram_bot import bot\n\napp = Flask(__name__)\nCORS(app)\n\n@app.route('/', methods = ['POST'])\ndef telegram_webhook():\n req = request.get_json()\n\n email = req['email']\n subject = req['subject']\n message = req['message']\n\n text = 'Email\\n' + \\\n '{}\\n'.format(email) + \\\n 'Тема\\n' + \\\n '{}\\n'.format(subject) + \\\n 'Сообщение\\n' + \\\n '{}'.format(message)\n\n return bot.send_message(text)","sub_path":"telegram_bot/flask_app.py","file_name":"flask_app.py","file_ext":"py","file_size_in_byte":528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"513688654","text":"from conectaBanco import ConectaBanco\n\nbanco = ConectaBanco() # Importa a classe\n\ntabela = \"aluno\"\n'''campos = \"idaluno, nome, dtnasc, endereco, cidade, estado, email\"\nvalores = \"default, 'Rebecao', '1999/11/09', 'Aldeinha 2', 'Itapecerica da Serra', 'SP', 'rebecao@gmail.com'\"\n\nbanco.insert(tabela, valores, campos)'''\n\n'''\nupdateset = \"nome = 'Vitória Mendes'\"\nupdatewhere = \"idaluno = 2\"\nbanco.update(tabela, updateset, updatewhere)\n'''\n\nbanco.delete(tabela, \"idaluno = 4\")\n\nregSelect = banco.select(\"*\", \"aluno\") # Executa o select atribuido o resultado na variavel redSelect\n\nfor registro in regSelect:\n print(registro) # Imprime os registros\n\n","sub_path":"atividades_python/ComandosBasicosMySQL/ConectaBanco/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"226603029","text":"def mean( a_list ) :\n\t\n m = float ( sum(a_list ) ) / len(a_list)\n \n return m\n\ndef adjacent_smoothing( Y , n = 5 ) :\n\n y = []\n l_Y = len ( Y )\n for k in range( l_Y ) :\n l = Y [ max( k - n / 2 , 0 ) : min( k + n / 2 , l_Y - 1 ) : 1 ]\n y.append( mean( l ) )\n\n\n return y\n\ndef main( ) :\n\n import read_data as rd\n import sys\n\n ( P , I ) = rd.read_data( sys.argv[1] )\n\n newI = adjacent_smoothing( I )\n\n for k, l in zip( P , newI ) :\n\t\t\n print( \"{0} {1}\".format( k , l ) )\n\n\nif __name__=='__main__':\n main()\n","sub_path":"python_scripts/adjacent_smoothing.py","file_name":"adjacent_smoothing.py","file_ext":"py","file_size_in_byte":561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"495918445","text":"from dataclasses import dataclass, field\nfrom typing import Dict, Any, Tuple, Union, List\n\n\n@dataclass\nclass Flags:\n # General\n debug: bool = True\n outdir: str = \"results/det\"\n device: str = \"cuda:0\"\n\n # Data config\n imgdir_name: str = \"vinbigdata-chest-xray-resized-png-256x256\"\n # split_mode: str = \"all_train\" # all_train or valid20\n seed: int = 111\n target_fold: int = 0 # 0~4\n label_smoothing: float = 0.0\n # Model config\n model_name: str = \"resnet18\"\n model_mode: str = \"normal\" # normal, cnn_fixed supported\n # Training config\n epoch: int = 20\n batchsize: int = 8\n valid_batchsize: int = 16\n num_workers: int = 4\n snapshot_freq: int = 5\n ema_decay: float = 0.999 # negative value is to inactivate ema.\n scheduler_type: str = \"\"\n scheduler_kwargs: Dict[str, Any] = field(default_factory=lambda: {})\n scheduler_trigger: List[Union[int, str]] = field(default_factory=lambda: [1, \"iteration\"])\n aug_kwargs: Dict[str, Dict[str, Any]] = field(default_factory=lambda: {})\n mixup_prob: float = -1.0 # Apply mixup augmentation when positive value is set.\n\n def update(self, param_dict: Dict) -> \"Flags\":\n # Overwrite by `param_dict`\n for key, value in param_dict.items():\n if not hasattr(self, key):\n raise ValueError(f\"[ERROR] Unexpected key for flag = {key}\")\n setattr(self, key, value)\n return self\n \nflags_template_dict = {\n \"debug\": False, # Change to True for fast debug run!\n \"outdir\": \"results/tmp_debug\",\n # Data\n \"imgdir_name\": \"vinbigdata-chest-xray-resized-png-256x256\",\n # Model\n \"model_name\": \"resnet18\",\n # Training\n \"num_workers\": 4,\n \"epoch\": 15,\n \"batchsize\": 8,\n \"scheduler_type\": \"CosineAnnealingWarmRestarts\",\n \"scheduler_kwargs\": {\"T_0\": 28125}, # 15000 * 15 epoch // (batchsize=8)\n \"scheduler_trigger\": [1, \"iteration\"],\n \"aug_kwargs\": {\n \"HorizontalFlip\": {\"p\": 0.5},\n \"ShiftScaleRotate\": {\"scale_limit\": 0.15, \"rotate_limit\": 10, \"p\": 0.5},\n \"RandomBrightnessContrast\": {\"p\": 0.5},\n \"CoarseDropout\": {\"max_holes\": 8, \"max_height\": 25, \"max_width\": 25, \"p\": 0.5},\n \"Blur\": {\"blur_limit\": [3, 7], \"p\": 0.5},\n \"Downscale\": {\"scale_min\": 0.25, \"scale_max\": 0.9, \"p\": 0.3},\n \"RandomGamma\": {\"gamma_limit\": [80, 120], \"p\": 0.6},\n }\n}","sub_path":"pytorch/clasification_flag_class.py","file_name":"clasification_flag_class.py","file_ext":"py","file_size_in_byte":2390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"13860467","text":"def func5(s):\n with open('names.txt', 'r') as a:\n lst = a.readlines()\n con = [i+'\\n' if i == lst[-1] else i for i in lst]\n if s+'\\n' not in con:\n con.append(s+'\\n')\n con.sort()\n res = [i[:-1] if i == con[-1] else i for i in con]\n with open('new_Names.txt', 'w') as b:\n b.writelines(res)\nif __name__ == '__main__':\n func5('Abc')","sub_path":"1stSemester_PythonCourse/work9/E05_1827406005.py","file_name":"E05_1827406005.py","file_ext":"py","file_size_in_byte":373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"266724722","text":"'''\n\n160. Intersection of Two Linked Lists\n\nWrite a program to find the node at which the intersection of two singly linked lists begins.\n\nFor example, the following two linked lists:\n\nbegin to intersect at node c1.\n\nExample 1:\n\nInput: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3\n\nOutput: Reference of the node with value = 8\n\nInput Explanation: The intersected node's value is 8 (note that this must not be 0 if the two lists intersect). \n\nFrom the head of A, it reads as [4,1,8,4,5]. \n\nFrom the head of B, it reads as [5,0,1,8,4,5]. \n\nThere are 2 nodes before the intersected node in A; \n\nThere are 3 nodes before the intersected node in B.\n \nExample 2:\n\nInput: intersectVal = 2, listA = [0,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1\n\nOutput: Reference of the node with value = 2\n\nInput Explanation: The intersected node's value is 2 (note that this must not be 0 if the two lists intersect). \n\nFrom the head of A, it reads as [0,9,1,2,4]. \n\nFrom the head of B, it reads as [3,2,4]. \n\nThere are 3 nodes before the intersected node in A; \n\nThere are 1 node before the intersected node in B.\n \nExample 3:\n\nInput: intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2\n\nOutput: null\n\nInput Explanation: From the head of A, it reads as [2,6,4]. From the head of B, it reads as [1,5].\n\nSince the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values.\n\nExplanation: The two lists do not intersect, so return null.\n \nNotes:\n\nIf the two linked lists have no intersection at all, return null.\n\nThe linked lists must retain their original structure after the function returns.\n\nYou may assume there are no cycles anywhere in the entire linked structure.\n\nYour code should preferably run in O(n) time and use only O(1) memory.\n\n'''\n\n# Solution 1\n# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.next = None\nclass Solution(object):\n def getIntersectionNode(self, headA, headB):\n \"\"\"\n :type head1, head1: ListNode\n :rtype: ListNode\n \"\"\"\n if headA is None or headB is None:\n return None\n lenA = self.getLength(headA)\n lenB = self.getLength(headB)\n return self.getDiff(headA, headB, abs(lenA - lenB)) if lenA > lenB else self.getDiff(headB, headA, abs(lenA - lenB))\n \n def getLength(self, head):\n if head is None:\n return 0\n length = 0\n while head:\n length += 1\n head = head.next\n return length\n \n def getDiff(self, longHead, shortHead, diff):\n while diff > 0:\n longHead = longHead.next\n diff -= 1\n while longHead and shortHead:\n if longHead == shortHead:\n return longHead\n longHead = longHead.next\n shortHead = shortHead.next\n return None\n \n# Solution 2\n# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution(object):\n def getIntersectionNode(self, headA, headB):\n \"\"\"\n :type head1, head1: ListNode\n :rtype: ListNode\n \"\"\"\n if headA is None or headB is None:\n return None\n indexA = headA\n indexB = headB\n while indexA != indexB:\n indexA = headB if indexA is None else indexA.next\n indexB = headA if indexB is None else indexB.next\n return indexA\n","sub_path":"0160.IntersectionofTwoLinkedLists.py","file_name":"0160.IntersectionofTwoLinkedLists.py","file_ext":"py","file_size_in_byte":3565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"334841304","text":"# -*- coding: utf-8 -*-\nfrom apollo.libs import lib\n\n__version__ = '0.1'\n\n\n# Test production line definition\nPROD_LINE = 'IOTBU_BST'\n# Test area definition\nTEST_AREA = 'PCBST'\n# PID list definition\nIR510_PID_DICT = ['68-101092-04']\nIR530_PID_DICT = ['68-101097-04']\nCGM_PID_DICT = ['68-101094-04']\n# Root Path\nIR5XX_ROOT_PATH = 'apollo.scripts.te_scripts.projects.iot.ir500.coronado'\nCGM_ROOT_PATH = 'apollo.scripts.te_scripts.projects.iot.cgr1k.cgr1k_modules.coronado'\n\nUUT = dict(protocol='dummy', timeout='300')\nPOWER = dict(protocol='terminalserver', user='', password='', timeout='300')\nKGB = dict(protocol='terminalserver', host='10.1.1.2', port=2038, user='', password='', timeout='300')\n\n\n# define UUT Qty, from which number to which number\nuut_range = range(0, 24)\n# define console range, in case it is not serial by HW setup.\n# 2003 means Terminal Server is 2900\n# 2002 means Terminal Server is 2800\npower_range = ['10.1.1.2:2018', # For IR510\n '10.1.1.2:2019',\n '10.1.1.2:2020',\n '10.1.1.2:2021',\n '10.1.1.2:2022',\n '10.1.1.2:2023',\n '10.1.1.2:2024',\n '10.1.1.2:2025',\n\n '10.1.1.2:2026', # For IR530\n '10.1.1.2:2027',\n '10.1.1.2:2028',\n '10.1.1.2:2029',\n '10.1.1.2:2030',\n '10.1.1.2:2031',\n '10.1.1.2:2032',\n '10.1.1.2:2033',\n\n '10.1.1.2:2010', # For CGM\n '10.1.1.2:2011',\n '10.1.1.2:2012',\n '10.1.1.2:2013',\n '10.1.1.2:2014',\n '10.1.1.2:2015',\n '10.1.1.2:2016',\n '10.1.1.2:2017',\n ]\n\n# it is for UUT connection to telnet to unit.\nconsole_range = ['10.1.1.2:2002', # For IR510\n '10.1.1.2:2003',\n '10.1.1.2:2004',\n '10.1.1.2:2005',\n '10.1.1.2:2006',\n '10.1.1.2:2007',\n '10.1.1.2:2008',\n '10.1.1.2:2009',\n\n '10.1.1.2:2002', # For IR530\n '10.1.1.2:2003',\n '10.1.1.2:2004',\n '10.1.1.2:2005',\n '10.1.1.2:2006',\n '10.1.1.2:2007',\n '10.1.1.2:2008',\n '10.1.1.2:2009',\n\n None, None, None, None, None, None, None, None, # CGM does not need push image\n ]\n\nir5xx_rf_config_path = '/opt/cisco/constellation/apollo/scripts/te_scripts/projects/iot/ir500/coronado'\ncgm_rf_config_path = '/opt/cisco/constellation/apollo/scripts/te_scripts/projects/iot/cgr1k/cgr1k_modules/coronado'\n\n\ndef fxcapp124_pcbst_config():\n\n config = lib.get_station_configuration()\n # production line\n pl = config.add_production_line(PROD_LINE)\n # test area\n ar = pl.add_area(TEST_AREA)\n\n # test station for Coronado\n ts = ar.add_test_station('Coronado BST')\n\n ts.add_connection(name='KGB', **KGB)\n ir510_super = ts.add_super_container(name='IR510', disable=False)\n ir530_super = ts.add_super_container(name='IR530', disable=False)\n cgm_super = ts.add_super_container(name='CGM', disable=False)\n sync_group = []\n for idx in uut_range[0:24]:\n\n if idx in uut_range[0:8]:\n container = ir510_super.add_container('UUT{:02d}'.format(idx))\n container.assign_pre_sequence('{}.pcba.area_sequences.pcbst_run.ir5xx_pre'.format(IR5XX_ROOT_PATH))\n for pid in IR510_PID_DICT:\n container.add_pid_map(pid=pid,\n sequence_definition='{}.pcba.area_sequences.pcbst_run.ir510_main'\n .format(IR5XX_ROOT_PATH))\n if idx in uut_range[8:16]:\n container = ir530_super.add_container('UUT{:02d}'.format(idx))\n container.assign_pre_sequence('{}.pcba.area_sequences.pcbst_run.ir5xx_pre'.format(IR5XX_ROOT_PATH))\n for pid in IR530_PID_DICT:\n container.add_pid_map(pid=pid,\n sequence_definition='{}.pcba.area_sequences.pcbst_run.ir530_main'\n .format(IR5XX_ROOT_PATH))\n if idx in uut_range[16:24]:\n container = cgm_super.add_container('UUT{:02d}'.format(idx))\n container.assign_pre_sequence('{}.pcba.area_sequences.cgm_pcbst_run.cgm_pre'.format(CGM_ROOT_PATH))\n for pid in CGM_PID_DICT:\n container.add_pid_map(pid=pid,\n sequence_definition='{}.pcba.area_sequences.cgm_pcbst_run.cgm_main'\n .format(CGM_ROOT_PATH))\n container.add_connection(name='UUT', **UUT)\n\n power = dict(host=power_range[idx].split(':')[0], port=power_range[idx].split(':')[1], **POWER)\n container.add_connection(name='POWER', **power)\n container.add_connection(name='KGB', shared_conn='KGB')\n\n container.add_configuration_data('console_port', console_range[idx])\n container.add_configuration_data('ip_address', '10.1.1.{}'.format(50 + idx))\n container.add_configuration_data('rf_group', 'GROUP_1')\n sync_group.append(container)\n\n ts.add_sync_group(name=\"GROUP_1\", containers=sync_group)\n\n ir5xx_uut = dict(standard='wpan',\n uut='api_ir5xx', # uut='api_ixm',\n kgb='api_ir5xx', # kgb='api_ixm',\n instruments=dict(\n analyzer=dict(model='api_gig865xx',\n self_calibrate=False,\n port_map=dict(inst_port_0='uut_port_0'),\n interface='ip', address='10.1.1.10', port='2550'),\n attenuator=dict(model='api_agj721xx',\n self_calibrate=False,\n port_map=dict(inst_port_0='uut_port_0'),\n interface='ip',\n address='10.1.1.6',\n port='inst0'),\n ))\n cgm_uut = dict(standard='wpan',\n uut='api_cgm', # uut='api_ixm',\n kgb='api_ir5xx', # kgb='api_ixm',\n instruments=dict(\n analyzer=dict(model='api_gig865xx',\n self_calibrate=False,\n port_map=dict(inst_port_0='uut_port_0'),\n interface='ip', address='10.1.1.10', port='2550'),\n attenuator=dict(model='api_agj721xx',\n self_calibrate=False,\n port_map=dict(inst_port_0='uut_port_0'),\n interface='ip',\n address='10.1.1.6',\n port='inst0'),\n ))\n\n ir5xx_rf_config = dict(path_loss='{}/pcba/rf_test/path_loss/bst_path_loss.csv'.format(ir5xx_rf_config_path),\n test_plan='{}/pcba/rf_test/test_plan/bst_test_plan.csv'.format(ir5xx_rf_config_path),\n UUT00=ir5xx_uut,\n UUT01=ir5xx_uut,\n UUT02=ir5xx_uut,\n UUT03=ir5xx_uut,\n UUT04=ir5xx_uut,\n UUT05=ir5xx_uut,\n UUT06=ir5xx_uut,\n UUT07=ir5xx_uut,\n UUT08=ir5xx_uut,\n UUT09=ir5xx_uut,\n UUT10=ir5xx_uut,\n UUT11=ir5xx_uut,\n UUT12=ir5xx_uut,\n UUT13=ir5xx_uut,\n UUT14=ir5xx_uut,\n UUT15=ir5xx_uut,\n )\n cgm_rf_config = dict(path_loss='{}/pcba/rf_test/path_loss/bst_path_loss.csv'.format(cgm_rf_config_path),\n test_plan='{}/pcba/rf_test/test_plan/bst_test_plan.csv'.format(cgm_rf_config_path),\n UUT16=cgm_uut,\n UUT17=cgm_uut,\n UUT18=cgm_uut,\n UUT19=cgm_uut,\n UUT20=cgm_uut,\n UUT21=cgm_uut,\n UUT22=cgm_uut,\n UUT23=cgm_uut,\n )\n\n ir510_super.add_configuration_data('rf_config', ir5xx_rf_config)\n ir530_super.add_configuration_data('rf_config', ir5xx_rf_config)\n cgm_super.add_configuration_data('rf_config', cgm_rf_config)\n","sub_path":"gen/te/projects/configs/trunk/foxch/ir500/fxcapp127_pcbst_config.py","file_name":"fxcapp127_pcbst_config.py","file_ext":"py","file_size_in_byte":8594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"404166424","text":"# Python imports\nimport numpy\n\n# Local imports\nfrom simple_rl.mdp.StateClass import State\nimport pandas as pd\n\n''' DataStateClass.py: Contains a State class for Data. '''\n\nclass DataState(State):\n ''' Data State class '''\n \n def __init__(self, data,is_terminal=False):\n State.__init__(self, data=data, is_terminal=is_terminal)\n \n def features(self):\n a=self.data\n b=self.data\n c=numpy.outer(a,b)\n inds=numpy.triu_indices(len(a))\n d=c[inds]\n return np.array(c).flatten()\n","sub_path":"simple_rl/tasks/data/DataStateClass.py","file_name":"DataStateClass.py","file_ext":"py","file_size_in_byte":542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"448508653","text":"\n# coding: utf-8\n\n# In[1]:\n\n\nimport pandas as pd\ntrain = pd.read_csv(\"C:/Users/GAURAV.GAURAV-UG2-2118/Downloads/Compressed/hurricanes-and-typhoons-1851-2014/pacific.csv\")\n# calculate no of rows and columns\ntrain_shape = train.shape\nprint(train_shape)\n\n\n# In[2]:\n\n\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nget_ipython().run_line_magic('matplotlib', 'inline')\nfig, ax = plt.subplots(figsize=(10,10)) # Sample figsize in inches\ncorr = train.corr()\nsns.heatmap(corr, cmap=\"YlGnBu\", annot = True,ax=ax)\n\n\n# In[5]:\n\n\nsns.distplot(train[\"Minimum Pressure\"])\nplt.show()\n\n\n# In[6]:\n\n\nsns.distplot(train[\"Maximum Wind\"])\nplt.show()\n\n\n# In[7]:\n\n\nsns.distplot(train[\"Date\"])\nplt.show()\n\n\n# In[3]:\n\n\ndef create_dummies(df,column_name):\n dummies = pd.get_dummies(df[column_name],prefix=column_name)\n df = pd.concat([df,dummies],axis=1)\n return df\n#Creating dummies for each unique value\ntrain = create_dummies(train,\"Maximum Wind\")\ntrain = train.drop(\"Maximum Wind\",axis=1)\ntrain = create_dummies(train,\"Minimum Pressure\")\ntrain = train.drop(\"Minimum Pressure\",axis=1)\ntrain = create_dummies(train,\"Date\")\ntrain = train.drop(\"Date\",axis=1)\ntrain.head()\n\n\n# In[4]:\n\n\n#Assigning 70% data to train1 and 30% data to test\nimport numpy as np\nshuffled_rows = np.random.permutation(train.index)\nshuffled_train = train.iloc[shuffled_rows]\nhighest_train_row = int(train.shape[0] * .70)\ntrain1 = shuffled_train.iloc[0:highest_train_row]\ntest = shuffled_train.iloc[highest_train_row:]\n\n\n# In[5]:\n\n\ntrain1.shape\ntest.shape\n\n\n# In[6]:\n\n\n#Making the model using the features\nfrom sklearn.linear_model import LogisticRegression\n\nunique_status = train[\"Status\"].unique()\nunique_status.sort()\n\nmodels = {}\nfeatures = [c for c in train1.columns if c.startswith(\"Maximum Wind\") or c.startswith(\"Minimum Pressure\") or c.startswith(\"Date\")]\n\nfor status in unique_status:\n model = LogisticRegression()\n \n X_train = train1[features]\n y_train = train1[\"Status\"] == status\n\n model.fit(X_train, y_train)\n models[status] = model\n\n\n# In[7]:\n\n\ntesting_probs = pd.DataFrame(columns=unique_status)\nfor status in unique_status:\n # Select testing features.\n X_test = test[features] \n # Compute probability of observation being in the status.\n testing_probs[status] = models[status].predict_proba(X_test)[:,1]\n\n\n# In[8]:\n\n\n#we use idxmax to return a Series where each value corresponds to the column or where the maximum value occurs \n#for that observation\npredicted_status = testing_probs.idxmax(axis=1)\nprint(predicted_status)\n\n\n# In[10]:\n\n\n#Measuring the accuracy of the model\nfrom sklearn.metrics import accuracy_score\n\naccuracy = accuracy_score(test[\"Status\"], predicted_status)\nprint(accuracy)\n\n\n# In[9]:\n\n\n#Finding the cross validation of the model i.e evaluating our model\nfrom sklearn.model_selection import cross_val_score\ncross_val = cross_val_score(LogisticRegression(), train[features], train[\"Status\"], scoring='accuracy', cv=10)\nprint (cross_val)\nprint (cross_val.mean())\n\n\n# In[10]:\n\n\n# Finding the confusion matrix to see the no of correct instances\nfrom sklearn import metrics\nprint (metrics.confusion_matrix(test[\"Status\"], predicted_status))\n\n\n# In[11]:\n\n\n# Doing feature selection\n#from sklearn.ensemble import RandomForestClassifier\n#from mlxtend.feature_selection import SequentialFeatureSelector as sfs\n# Build RF classifier to use in feature selection\n#clf = RandomForestClassifier(n_estimators=100, n_jobs=-1)\n\n# Build step forward feature selection\n#sfs1 = sfs(clf,\n # k_features=3,\n # forward=True,\n # floating=False,\n # verbose=2,\n # scoring='accuracy',\n # cv=0)\n\n# Perform SFFS\n#sfs1 = sfs1.fit(X_train, y_train)\n\n# Naming the final features selected\n#feat_cols = list(sfs1.k_feature_idx_)\n#print(feat_cols)\n\n\n# In[ ]:\n\n\n#import numpy as np; np.random.seed(0)\n#import seaborn as sns; sns.set()\n\n# calculate the correlation matrix\n#corr = train.corr()\n\n# plot the heatmap\n#sns.heatmap(corr, \n # xticklabels=corr.columns,\n # yticklabels=corr.columns)\n\n\n# In[9]:\n\n\nsns.violinplot(test['Status'],predicted_status) #Variable Plot\nsns.despine()\n\n\n# In[13]:\n\n\n\n\n","sub_path":"Weatherify(Final).py","file_name":"Weatherify(Final).py","file_ext":"py","file_size_in_byte":4164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"458158192","text":"from . import remoteexec\nfrom . import subprocessmap\nfrom .mylog import log\n\nimport shlex\n\ndef _check_cmd(script):\n return [\"powershell\", shlex.quote(script)]\n\ndef monitor(hosts, script):\n cmd = _check_cmd(script)\n log.debug(\"Running script %s on hosts %s.\", script, str(hosts))\n commands = list(map(lambda host: remoteexec.remote_cmd(host, cmd, ssh_config=\"ssh_config_win\"), hosts))\n pidresults = subprocessmap.map(commands)\n log.debug(\"Got results %s\", str(pidresults))\n success = True\n message = \"Successful on all hosts\"\n for ix, (retcode, stdout, stderr) in enumerate(pidresults):\n if retcode != 0:\n success = False\n message = \"Error on host {0:s}({1:d}): {2:s}\" \\\n .format(hosts[ix], retcode, stdout.decode('ascii')+stderr.decode('ascii'))\n break\n return {\"success\": success, \"message\": message}\n","sub_path":"src/checker/psscriptmonitor.py","file_name":"psscriptmonitor.py","file_ext":"py","file_size_in_byte":893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"507146090","text":"\nimport struct\nimport threading\nfrom utils.stream import BufferStream\n\n\n\nMAX_LEVEL_NUM = 8\n\nclass IndexBuilder:\n def __init__ (self, grid, minlat, minlon, maxlat, maxlon):\n global MAX_LEVEL_NUM\n self.__lock = threading.Lock()\n self.__min_lat = minlat\n self.__min_lon = minlon\n self.__max_lat = maxlat\n self.__max_lon = maxlon\n self.__coverage = MAX_LEVEL_NUM * [None]\n self.__index_size = [[(0,0), (16,16), (16,16)], \n [(0,0), (8,8), (16,16)], \n [(0,0), (8,8), (8,8)], \n [(0,0), (4,4), (8,8)],\n [(0,0), (4,4), (4,4)],\n [(0,0), (2,2), (4,4)],\n [(0,0), (2,2), (2,2)],\n [(0,0), (1,1), (2,2)]]\n\n for i in range(MAX_LEVEL_NUM):\n # parcel \n parcel_size_lat = grid.getMeshSize(i)[0]\n parcel_size_lon = grid.getMeshSize(i)[1]\n # block\n block_size_lat = parcel_size_lat * self.__index_size[i][2][0]\n block_size_lon = parcel_size_lon * self.__index_size[i][2][1]\n # blockset\n blockset_size_lat = block_size_lat * self.__index_size[i][1][0]\n blockset_size_lon = block_size_lon * self.__index_size[i][1][1]\n # level\n blockset_num_lat = (maxlat - minlat + blockset_size_lat - 1) / blockset_size_lat\n blockset_num_lon = (maxlon - minlon + blockset_size_lon - 1) / blockset_size_lon\n # set size and coverage\n self.__index_size[i][0] = (blockset_num_lat, blockset_num_lon)\n self.__coverage[i] = (self.__min_lat, \n self.__min_lon, \n self.__min_lat+blockset_num_lat*blockset_size_lat, \n self.__min_lon+blockset_num_lon*blockset_size_lon)\n self.__index_table = [None] * MAX_LEVEL_NUM\n self.__grid = grid\n\n def registerParcel (self, mesh, offset, size): \n # multithread\n self.__lock.acquire()\n # register\n level = self.__grid.getMeshLevel(mesh)\n coverage = self.__grid.getMeshRect(mesh)\n lat, lon = (coverage[0]+coverage[2])/2, (coverage[1]+coverage[3])/2\n # parcel size\n parcel_lat = self.__grid.getMeshSize(level)[0]\n parcel_lon = self.__grid.getMeshSize(level)[1]\n # block size\n block_lat = parcel_lat * self.__index_size[level][2][0]\n block_lon = parcel_lon * self.__index_size[level][2][1]\n # blockset size\n blockset_lat = block_lat * self.__index_size[level][1][0]\n blockset_lon = block_lon * self.__index_size[level][1][1]\n # blocset index\n idx_lat_1 = (lat - self.__min_lat) / blockset_lat\n idx_lon_1 = (lon - self.__min_lon) / blockset_lon\n # block index\n idx_lat_2 = ((lat - self.__min_lat) % blockset_lat) / block_lat\n idx_lon_2 = ((lon - self.__min_lon) % blockset_lon) / block_lon\n # parcel index\n idx_lat_3 = ((lat - self.__min_lat) % block_lat) / parcel_lat\n idx_lon_3 = ((lon - self.__min_lon) % block_lon) / parcel_lon\n # z-order index\n idx_1 = idx_lat_1 * self.__index_size[level][0][1] + idx_lon_1\n idx_2 = idx_lat_2 * self.__index_size[level][1][1] + idx_lon_2\n idx_3 = idx_lat_3 * self.__index_size[level][2][1] + idx_lon_3\n # level\n if not self.__index_table[level]:\n self.__index_table[level] = [None] * self.__index_size[level][0][0] * self.__index_size[level][0][1]\n mgnt = self.__index_table[level]\n # blockset \n if not mgnt[idx_1]:\n mgnt[idx_1] = [None] * self.__index_size[level][1][0] * self.__index_size[level][1][1]\n blockset = mgnt[idx_1]\n # block\n if not blockset[idx_2]:\n blockset[idx_2] = [None] * self.__index_size[level][2][0] * self.__index_size[level][2][1]\n block = blockset[idx_2]\n # parcel\n block[idx_3] = (offset, size)\n # multithread\n self.__lock.release()\n\n def save (self, stream):\n # multithread\n self.__lock.acquire()\n # map coverage\n stream.write(struct.pack('IIII', self.__min_lat, self.__min_lon, self.__max_lat, self.__max_lon))\n # level count\n stream.write(struct.pack('B', MAX_LEVEL_NUM))\n # blockset/block/parcel count\n for x in range(MAX_LEVEL_NUM):\n sz = self.__index_size[x]\n # parcel size\n parcel_lat = self.__grid.getMeshSize(x)[0]\n parcel_lon = self.__grid.getMeshSize(x)[1]\n # block size\n block_lat = parcel_lat * sz[2][0]\n block_lon = parcel_lon * sz[2][1]\n # blockset size\n blockset_lat = block_lat * sz[1][0]\n blockset_lon = block_lon * sz[1][1]\n # coverage\n stream.write(struct.pack('IIII', self.__coverage[x][0], self.__coverage[x][1], self.__coverage[x][2], self.__coverage[x][3]))\n # count\n stream.write(struct.pack('HHHHHH', sz[0][0],sz[0][1],sz[1][0],sz[1][1],sz[2][0],sz[2][1]))\n # end of coverage\n buffer = BufferStream()\n # calc header size\n self.__writeIndex(buffer, 0)\n # write index to stream\n self.__writeIndex(stream, stream.tell()+buffer.tell())\n # multithread\n self.__lock.release()\n\n def __writeIndex (self, stream, offset):\n global MAX_LEVEL_NUM\n beg = stream.tell()\n stream.seek(beg + MAX_LEVEL_NUM * 4)\n for ilevel in range(MAX_LEVEL_NUM):\n x = self.__writeBlockSet(stream, self.__index_table[ilevel], offset)\n tmp = stream.tell()\n stream.seek(beg + ilevel * 4)\n stream.write(struct.pack('I',x))\n stream.seek(tmp)\n return beg\n\n def __writeBlockSet (self, stream, blocksetlist, offset):\n if not blocksetlist:\n return 0xffffffff\n beg = stream.tell()\n num = len(blocksetlist)\n stream.seek(beg+4*num)\n for iblockset in range(num):\n x = self.__writeBlock(stream, blocksetlist[iblockset], offset)\n tmp = stream.tell()\n stream.seek(beg+iblockset*4)\n stream.write(struct.pack('I',x))\n stream.seek(tmp)\n return beg\n\n def __writeBlock (self, stream, blocklist, offset):\n if not blocklist:\n return 0xffffffff\n beg = stream.tell()\n num = len(blocklist)\n stream.seek(beg+4*num)\n for iblock in range(num):\n x = self.__writeParcel(stream, blocklist[iblock], offset) \n tmp = stream.tell()\n stream.seek(beg+iblock*4)\n stream.write(struct.pack('I',x))\n stream.seek(tmp)\n return beg\n\n def __writeParcel (self, stream, parcelist, offset):\n if not parcelist:\n return 0xffffffff\n beg = stream.tell()\n num = len(parcelist)\n i = 0\n for parcel in parcelist:\n if parcel:\n stream.write(struct.pack('II', parcel[0]+offset, parcel[1]))\n else:\n stream.write(struct.pack('II', 0xffffffff, 0))\n i += 1\n return beg\n\n\n\n","sub_path":"mc/pack/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":7346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"108968729","text":"# \n\nimport bpy\nfrom . import constants\n\n\nclass BlenderScene:\n \"\"\"Contains useful functions and methods for modifying a scene.\n\n Attributes:\n name: The name of the scene.\n \"\"\"\n\n def __init__(self, scene, new_scene, new_name=None, renderer=None):\n \"\"\"Creates a full copy of scene if new_scene is set to True.\n\n Args:\n scene: A scene object which represents the scene to copy/work on. Later referred to as the 'original scene'.\n new_scene: A boolean that if True, a full copy of scene will be created.\n new_name: An optional string representing the (new) scene's name. Must be set if new_scene is set\n to True.\n renderer: An optional string representing the (new) scene's render engine, e.g. 'CYCLES'. Must be set if\n new_scene is set to True.\n \"\"\"\n self.original_scene = scene\n\n if new_scene:\n self.name = self.copy_scene(scene, new_name, renderer)\n\n else:\n if new_name is not None:\n scene.name = new_name\n self.name = scene.name\n\n if renderer is not None:\n scene.render.engine = renderer\n\n def __str__(self):\n return ''.format(self.name, self.original_scene.name)\n\n @staticmethod\n def copy_scene(scene, new_name, renderer='CYCLES'):\n \"\"\"Creates a full copy of the scene.\n\n Args:\n scene: A scene object which represents the scene to copy.\n new_name: A string representing the new scene's name.\n renderer: A string representing the new scene's render engine, e.g. 'CYCLES'.\n\n Returns:\n A string that is the new scene's name.\n \"\"\"\n original_new_name = new_name\n bpy.context.screen.scene = scene\n bpy.ops.scene.new(type='FULL_COPY')\n\n # this is for better handling of duplicate scene names when creating a new scene\n n = 1\n while True:\n if new_name not in [scene.name for scene in bpy.data.scenes]:\n bpy.context.screen.scene.name = new_name\n break\n else:\n new_name = original_new_name + '_' + str(n).zfill(3)\n n += 1\n\n bpy.data.scenes[new_name].render.engine = renderer\n\n return new_name\n\n def get_scene(self):\n \"\"\"Returns the blender scene object linked to this instance.\"\"\"\n return bpy.data.scenes[self.name]\n\n def get_original_scene(self):\n \"\"\"Returns the original blender scene object of this instance.\"\"\"\n return self.original_scene\n\n def set_as_active(self):\n \"\"\"Sets the scene as active.\n\n Returns:\n The scene object.\n \"\"\"\n bpy.context.screen.scene = self.get_scene()\n\n return self.get_scene()\n\n def set_active_object(self, obj_types=constants.obj_types):\n \"\"\"Sets the active object to be one among the selected objects.\n\n Args:\n obj_types: An optional array consisting of strings representing the object type(s)\n that the active object is allowed to be. If none specified, all types count.\n \"\"\"\n scene = self.set_as_active()\n\n if 'ALL' in obj_types:\n obj_types = constants.obj_types\n\n for obj in scene.objects:\n if obj.select is True and obj.type in obj_types:\n scene.objects.active = obj\n break\n\n def object_on_layer(self, obj, layer_numbers):\n \"\"\"Checks if an object is on any of the layers represented by layer_numbers.\n\n Args:\n obj: The object it will check.\n layer_numbers: A list consisiting of integers representing the layers that it will check\n if the object is on.\n\n Returns:\n True if the object is on any of the layers represented by layer_numbers, False otherwise.\n \"\"\"\n scene = self.set_as_active()\n\n if obj.name in scene.objects:\n for n in layer_numbers:\n if obj.layers[n]:\n return True\n\n return False\n\n def check_any_selected(self, obj_types=constants.obj_types):\n \"\"\"Checks the scene if any object is selected.\n\n Args:\n obj_types: An optional array consisting of strings representing the object type(s)\n that the object is allowed to be. If none specified, all types count.\n\n Returns:\n True if any object is selected, False otherwise.\n \"\"\"\n scene = self.set_as_active()\n\n if 'ALL' in obj_types:\n obj_types = constants.obj_types\n\n for obj in scene.objects:\n if obj.type in obj_types and obj.select is True:\n return True\n\n return False\n\n def select(self, mode, types=None, types_excluded=None, layers=None, layers_excluded=None,\n objects=None, objects_excluded=None):\n \"\"\"Selects or deselects objects.\n\n (De)selects specific objects or objects by object types and layers.\n\n Args:\n mode: A string representing the mode, either 'SELECT' to select objects or 'DESELECT' to deselect objects.\n types: An optional set consisting of strings representing the object types that are to be (de)selected.\n If none specified, all types count.\n types_excluded: An optional set consisting of strings representing the object types that are to be\n deselected or left out if mode is set to 'DESELECT', these types will not be included among the\n select_types.\n layers: An optional set consisting of integers representing the layers whose objects\n are up for (de)selection. If none specified, all layers count.\n layers_excluded: An optional set consisting of integers representing the layers whose objects\n will be deselected or left out if mode is set to 'DESELECT', these layers will not be included among\n the layers in the layers variable.\n objects: An optional set consisting of objects that are to be (de)selected, need to be set if types\n variable is not set. If set, types and layers variables will act as filters on those objects.\n objects_excluded: An optional set consisting of objects that are to be deselected or left out if mode is set\n to 'DESELECT', these objects will not be included among the objects in the objects variable.\n \"\"\"\n scene = self.set_as_active()\n layer_numbers = set(constants.layer_numbers)\n obj_types = set(constants.obj_types)\n\n # setting up types and types excluded\n if types is None or 'ALL' in types:\n types = obj_types\n\n if types_excluded is None:\n types_excluded = set()\n\n elif 'ELSE' in types_excluded:\n types_excluded = obj_types - types\n\n types -= types_excluded\n\n # setting up layers and layers excluded\n if layers is None or 'ALL' in layers:\n layers = layer_numbers\n\n if layers_excluded is None:\n layers_excluded = set()\n\n elif 'ELSE' in layers_excluded:\n layers_excluded = layer_numbers - layers\n\n layers -= layers_excluded\n\n # setting up objects and objects excluded\n if objects_excluded is None:\n objects_excluded = set()\n\n if objects is not None:\n objects -= objects_excluded\n\n previous_area = bpy.context.area.type\n\n # can't change object select property while in the 'PROPERTIES' area\n bpy.context.area.type = 'VIEW_3D'\n\n # much quicker than looping through objects\n if 'ALL' in objects and types == obj_types and layers == layer_numbers:\n bpy.ops.object.select_all(action=mode)\n\n elif mode == 'SELECT':\n if objects is not None:\n for obj in scene.objects:\n if ((obj in objects or 'ALL' in objects) and\n obj.type in types and self.object_on_layer(obj, layers)):\n obj.select = True\n\n elif (obj in objects_excluded or 'ELSE' in objects_excluded or\n obj.type in types_excluded or self.object_on_layer(obj, layers_excluded)):\n obj.select = False\n\n else:\n for obj in scene.objects:\n if obj.type in types and self.object_on_layer(obj, layers):\n obj.select = True\n\n elif obj.type in types_excluded or self.object_on_layer(obj, layers_excluded):\n obj.select = False\n\n elif mode == 'DESELECT':\n if objects is not None:\n for obj in scene.objects:\n if ((obj in objects or 'ALL' in objects) and\n obj.type in types and self.object_on_layer(obj, layers)):\n obj.select = False\n\n else:\n for obj in scene.objects:\n if obj.type in types and self.object_on_layer(obj, layers):\n obj.select = False\n\n else:\n raise ValueError(\"No such mode as '{}'.\".format(mode))\n\n bpy.context.area.type = previous_area\n self.set_active_object(types)\n\n def move_selected_to_layer(self, to_layer):\n \"\"\"Moves the selected object(s) to the given layer(s) (to_layer).\n\n Args:\n to_layer: An array consisting of integers representing the layers to which the object(s) will be moved.\n \"\"\"\n scene = self.set_as_active()\n previous_layers = list(scene.layers)\n previous_area = bpy.context.area.type\n\n layers = [False, ] * 20\n\n for i in to_layer:\n layers[i] = True\n\n # can't move objects from inactive layers\n scene.layers = (True,) * 20\n\n # can't use operators while in the 'PROPERTIES' area\n bpy.context.area.type = 'VIEW_3D'\n\n bpy.ops.object.move_to_layer(layers=layers)\n\n bpy.context.area.type = previous_area\n scene.layers = previous_layers\n\n def copy_selected_to_layer(self, to_layer):\n \"\"\"Copies the selected object(s) to the given layer(s) (to_layer).\n\n Args:\n to_layer: An array consisting of integers representing the layers to which the object(s) will be copied.\n \"\"\"\n scene = self.set_as_active()\n previous_layers = list(scene.layers)\n previous_area = bpy.context.area.type\n\n # can't duplicate objects on inactive layers\n scene.layers = (True,) * 20\n\n # can't use operators while in the 'PROPERTIES' area\n bpy.context.area.type = 'VIEW_3D'\n\n bpy.ops.object.duplicate()\n self.move_selected_to_layer(to_layer)\n\n bpy.context.area.type = previous_area\n scene.layers = previous_layers\n\n def copy_selected_to_scene(self, to_scene):\n \"\"\"Copies the selected object(s) to the given scene (to_scene).\n\n Args:\n to_scene: A scene object representing the scene to which the objects will be copied.\n \"\"\"\n scene = self.set_as_active()\n previous_layers = list(scene.layers)\n previous_area = bpy.context.area.type\n\n # can't duplicate objects on inactive layers\n scene.layers = (True,) * 20\n\n # can't use operators while in the 'PROPERTIES' area\n bpy.context.area.type = 'VIEW_3D'\n\n bpy.ops.object.duplicate()\n bpy.ops.object.make_links_scene(scene=to_scene)\n bpy.ops.object.delete()\n\n scene.layers = previous_layers\n bpy.context.area.type = previous_area\n\n def clear_materials_on_selected(self):\n \"\"\"Removes all materials from all the selected objects in the scene.\"\"\"\n scene = self.set_as_active()\n previous_area = bpy.context.area.type\n previous_layers = list(scene.layers)\n\n bpy.context.active_object.data.materials.clear()\n\n # can't use operators while in the 'PROPERTIES' area\n bpy.context.area.type = 'VIEW_3D'\n\n # can't copy materials to objects on inactive layers\n scene.layers = (True,) * 20\n\n bpy.ops.object.material_slot_copy()\n\n bpy.context.area.type = previous_area\n scene.layers = previous_layers\n\n def selected_objects_to_set(self, obj_types=constants.obj_types):\n \"\"\"Puts all the selected objects in a set.\n\n Args:\n obj_types: An optional array consisting of strings representing the object type(s) it will affect\n of the selected objects. If none specified, all types count.\n\n Returns:\n A set containing the selected objects.\n \"\"\"\n scene = self.set_as_active()\n selected_objects = set()\n\n if 'ALL' in obj_types:\n obj_types = constants.obj_types\n\n for obj in scene.objects:\n if obj.select and obj.type in obj_types:\n selected_objects.add(obj)\n\n return selected_objects\n\n def set_up_rlayer(self, new, rlname, visible_layers=None, include_layers=None,\n exclude_layers=None, mask_layers=None):\n \"\"\"Sets up a scene render layer.\n\n Args:\n new: A boolean which if True, a new render layer will be created. The name of this render layer is\n represented by rlname.\n rlname: A string representing the name of the render layer you want to set up.\n visible_layers: An optional list consisting of integers representing the layers you want to be visible\n -i.e. all layers you want to render, which will aslo be visible in the viewport-in the new render layer.\n include_layers: An optional list consisting of integers representing the layers\n you want to be included in the new render layer (specific for this render layer).\n exclude_layers: An optional list consisting of integers representing the layers\n you want to be excluded in the new render layer (specific for this render layer).\n mask_layers: An optional list consisting of integers representing the layers\n you want to be masked in the new render layer (specific for this render layer).\n \"\"\"\n scene = self.set_as_active()\n layer_numbers = constants.layer_numbers\n\n if visible_layers is None:\n visible_layers = layer_numbers\n\n if include_layers is None:\n include_layers = layer_numbers\n\n if exclude_layers is None:\n exclude_layers = []\n\n if mask_layers is None:\n mask_layers = []\n\n if new:\n new_rlayer = scene.render.layers.new(rlname)\n scene.render.layers.active = new_rlayer\n\n # because I can't deactivate a layer if it is the only active one\n scene.layers[19] = True\n scene.render.layers[rlname].layers[19] = True\n\n for i in layer_numbers:\n if i in include_layers:\n scene.render.layers[rlname].layers[i] = True\n\n else:\n scene.render.layers[rlname].layers[i] = False\n\n if i in visible_layers:\n scene.layers[i] = True\n\n else:\n scene.layers[i] = False\n\n if i in exclude_layers:\n scene.render.layers[rlname].layers_exclude[i] = True\n\n else:\n scene.render.layers[rlname].layers_exclude[i] = False\n\n if i in mask_layers:\n scene.render.layers[rlname].layers_zmask[i] = True\n\n else:\n scene.render.layers[rlname].layers_zmask[i] = False\n\n def view3d_pivotpoint(self, action, pivotpoint=None):\n \"\"\"Manipulates the 3D view's pivot point by setting it or getting it.\n\n Args:\n action: A string representing the action. Either 'set' to set the pivot point\n or 'get' to get the current pivot point.\n pivotpoint: If action equals 'set', this string represents the pivot point you want to set.\n\n Returns:\n If action equals 'get', returns a string representing the 3D view's current pivot point.\n \"\"\"\n self.set_as_active()\n previous_area = bpy.context.area.type\n\n # can't change pivot point while in the 'PROPERTIES' area\n bpy.context.area.type = 'VIEW_3D'\n\n if action == 'set':\n bpy.context.space_data.pivot_point = pivotpoint\n bpy.context.area.type = previous_area\n\n elif action == 'get':\n pivotpoint = bpy.context.space_data.pivot_point\n bpy.context.area.type = previous_area\n return pivotpoint\n","sub_path":"scripts/addons_extern/blender-CyclesWireframeAndClay-master/b_scene.py","file_name":"b_scene.py","file_ext":"py","file_size_in_byte":16788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"85801499","text":"from apps.hello.models import LogEntrry\nfrom django.dispatch import receiver\nfrom django.db.models.signals import post_save, post_delete\n\nexclude_models_name = ['LogEntrry', 'ContentType',\n 'LogEntry', 'MigrationHistory']\n\n\n@receiver(post_save)\ndef post_save_signal(sender, created, **kwargs):\n if created and sender.__name__ in exclude_models_name:\n return\n status = 'Create' if created else 'Update'\n LogEntrry.objects.create(title=sender.__name__, status=status)\n\n\n@receiver(post_delete)\ndef post_delete_signal(sender, **kwargs):\n LogEntrry.objects.create(title=sender.__name__, status='Delete')\n return\n","sub_path":"apps/hello/signals.py","file_name":"signals.py","file_ext":"py","file_size_in_byte":651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"617368798","text":"'''\n2. Користувачем вводиться початковий і кінцевий рік. Створити цикл, який виведе \nвсі високосні роки в цьому проміжку (границі включно).\n'''\n\nstart_year = int(input('Enter first year: '))\nlast_year = int(input('Enter last year: '))\nfor i in range(start_year, last_year + 1):\n if (i%4==0 and i%100!=0) or i%400==0:\n print(i) ","sub_path":"HT_02/Task_02.py","file_name":"Task_02.py","file_ext":"py","file_size_in_byte":446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"181697719","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport math\nimport numpy as np\nimport numpy.ma as ma\nfrom scipy.ndimage import zoom as _ni_zoom\nfrom scipy.spatial.transform import Rotation\n\nfrom field_util_precomp import read_wavelet_integrals, Field, Point\n\n\nH = 1/3\nFOUR_PI = 4.*math.pi\n\n\nclass SphericalField:\n # divide by sqrt(2) to normalize edge length to one\n # keep center (0,0,0)\n CUBOCTAHEDRON_VERTICES = np.array([\n ( 1, 1, 0),\n (-1, 1, 0),\n ( 1, -1, 0),\n (-1, -1, 0),\n ( 1, 0, 1),\n (-1, 0, 1),\n ( 1, 0, -1),\n (-1, 0, -1),\n ( 0, 1, 1),\n ( 0, -1, 1),\n ( 0, 1, -1),\n ( 0, -1, -1),\n ( 0, 0, 0)\n ]) / math.sqrt(2)\n\n # divide by sqrt(3) to normalize diagonal length to one\n CUBE_VERTICES = np.array([\n ( 1, 1, 1),\n ( 1, 1, -1),\n ( 1, -1, 1),\n ( 1, -1, -1),\n (-1, 1, 1),\n (-1, 1, -1),\n (-1, -1, 1),\n (-1, -1, -1)\n ]) / math.sqrt(3)\n\n def __init__(self, Nc, Np, base, q=4, random_rotation=False,\n noise_seed=None, rotation_seed=None):\n # b**Nc: resolution of single field component\n # b**Np: resolution of result\n # q: wavelet order\n\n # basic building block of the field\n self.field = read_wavelet_integrals(base, Nc, q)\n\n # base, initial radius, component radius, initial zoom factor, number\n # of grid points\n self.b = base\n self.r = base**Np\n self.rc = base**Nc\n self.z = base**(Np-Nc)\n self.num = 2*self.r\n\n self.random_rotation = random_rotation\n self.vertices = {\n 2 : self.CUBE_VERTICES,\n 3 : self.CUBOCTAHEDRON_VERTICES\n }.get(base)\n\n # save wavelet order for noise generation\n self.q = q\n\n # RandomState instances\n self.noise_rs = np.random.RandomState(noise_seed)\n self.rotation_rs = np.random.RandomState(rotation_seed)\n\n\n def compute(self, levels):\n radius = self.r\n z = self.z\n\n # result\n v = np.zeros((self.num, self.num, self.num, 3))\n\n # center of initial sphere\n points = [Point(radius, radius, radius)]\n\n # start one level higher to fill the whole domain\n radius *= self.b\n z *= self.b\n\n for n in range(levels):\n fs, vs = self._field_and_domain_bounds(points, min(self.r, radius))\n\n # noises.shape == (len(points), 3, q, 1, 1, 1)\n noises = self._make_noise(len(points))[...,None,None,None]\n # interp_field.shape == (3, q, 2*r, 2*r, 2*r)\n interp_field = self._interpolate(z)\n\n for i in range(len(points)):\n # noise_field.shape == (3, 2*r, 2*r, 2*r)\n noise_field = ma.sum([\n noises[i,2]*interp_field.y - noises[i,1]*interp_field.z,\n noises[i,0]*interp_field.z - noises[i,2]*interp_field.x,\n noises[i,1]*interp_field.x - noises[i,0]*interp_field.y,\n ], axis=1)[(...,*fs[i])]\n noise_field = np.moveaxis(noise_field, 0, -1)\n\n v[(*vs[i],...)][~noise_field.mask] += \\\n self.b**(-n*H) * noise_field[~noise_field.mask]\n\n z /= self.b\n radius //= self.b\n points = self._subdivide_sphere(points, radius//2)\n\n # Biot-Savart: -1/(4 pi)\n return -v / FOUR_PI\n\n\n def _field_and_domain_bounds(self, points, radius):\n # field component bound functions (whole sphere)\n lower = lambda p: 0 if p-radius > 0 else radius-p\n upper = lambda p: 2*radius if p+radius < self.num else radius+self.num-p\n\n fs = []\n vs = []\n\n for point in points:\n fs.append(tuple((\n slice(lower(point.x), upper(point.x)),\n slice(lower(point.y), upper(point.y)),\n slice(lower(point.z), upper(point.z)),\n )))\n vs.append(tuple((\n slice(max(point.x-radius, 0), min(point.x+radius, self.num)),\n slice(max(point.y-radius, 0), min(point.y+radius, self.num)),\n slice(max(point.z-radius, 0), min(point.z+radius, self.num)),\n )))\n\n return fs, vs\n\n\n def _make_noise(self, num):\n return ma.asarray(self.noise_rs.randn(num, 3, self.q))\n\n\n def _interpolate(self, z):\n if z > 1:\n bound = slice(None, None) if z*self.rc < self.r \\\n else slice(int(self.rc-self.r//z), int(self.rc+self.r//z))\n return Field(self._zoom(self.field.x[...,bound,bound,bound],\n (1, z, z, z)))\n\n elif z < 1:\n step = int(1./z)\n return Field(self.field.x[...,::step,::step,::step])\n\n else:\n return self.field\n\n\n def _subdivide_sphere(self, points, radius):\n new_points = []\n vertices = radius * self.vertices\n\n for point in points:\n\n if self.random_rotation:\n vertices = Rotation.random(random_state=self.rotation_rs).apply(vertices)\n\n for vertex in vertices:\n new_points.append(point + vertex)\n\n return new_points\n\n\n @staticmethod\n def _zoom(a, z):\n out = ma.zeros(tuple([int(round(ii*zz)) for ii, zz in zip(a.shape, z)]))\n out = _ni_zoom(a.data, z, order=1, mode='nearest', output=out)\n mask = _ni_zoom(a.mask, z, order=0, mode='constant', cval=True)\n out.mask = mask\n return out\n\n\n\n# vim: set ff=unix tw=79 sw=4 ts=8 et ic ai :\n","sub_path":"field_3d_implementation_precomp.py","file_name":"field_3d_implementation_precomp.py","file_ext":"py","file_size_in_byte":5632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"138649923","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport csv\nimport copy\n\n\nclass Comparison(object):\n def __init__(self, courses):\n\n # list of courses\n self.courses = courses\n\n # to be continued...\n\n def plot_assignment_comparison(self, assignment_id, nbins=10):\n\n file_name = 'AssignmentComparison_' + assignment_id + '.png'\n\n # create the figure\n fig, ax = plt.subplots(len(self.courses), 1)\n # fig.set_size_inches(10, 16)\n\n for i in range(len(self.courses)):\n\n # find full assignment name using input assignment_id\n full_name = assignment_id\n for assignment in self.courses[i].assignments:\n if assignment_id == assignment.id:\n full_name = assignment.name\n\n # extract marks for matching assignments\n if full_name is not None:\n marks = self.courses[i].portfolio_complete[full_name]\n label = self.courses[i].title\n else:\n print('WARNING: invalid assignment id')\n break\n\n # produce histogram and label\n ax[i].hist(marks, bins=nbins, rwidth=0.9, label=label)\n ax[i].legend(loc=2)\n\n if i == 1:\n ax[i].set_xlabel('Mark')\n ax[i].set_ylabel('Frequency')\n\n # set title equal to assignment id\n ax[0].set_title('Assignment Analysis for {}'.format(assignment_id))\n\n # save the figure to requested filename\n plt.savefig(file_name, dpi=300, bbox_inches='tight', papertype='A4')\n plt.close()\n\n\nclass Course(object):\n def __init__(self, title, assignments=None, gradebook=None, aegrotats=None,\n exclude_zero_test=True, exclude_zero_exam=True, verbose=False):\n\n # course name\n self.title = title\n\n # set file names containing data relating to this course\n self.file_names = {'assignments': assignments, 'gradebook': gradebook, 'aegrotats': aegrotats}\n\n # set whether to process this course in verbose mode or not\n self.verbose = verbose\n\n # list of assignment and student objects\n self.assignments = []\n self.assignments_coursework = []\n self.assignments_test = []\n self.assignments_exam = []\n self.students = []\n\n # dictionary for students with complete portfolio and no aegrotat applications\n self.portfolio_complete = {'students': [], 'coursework': [], 'test': [], 'exam': [], 'final': []}\n\n # dictionary for students with an incomplete portfolio - may be unnecessary?\n self.portfolio_incomplete = {'students': []}\n\n # dictionary for students with one or more aegrotat applications\n self.portfolio_aegrotat = {'students': []}\n\n # weight associated with each category of assignment\n self.weight_by_assignment = {}\n self.weight_by_category = {'coursework': 0., 'test': 0., 'exam': 0., 'final': 0.}\n\n # if student mark of zero in specific assessment category should exclude them from complete portfolio\n self.exclude_zero = {'test': exclude_zero_test, 'exam': exclude_zero_exam}\n\n # process marks and populate portfolios for the course\n self.process_course_data()\n\n def process_course_data(self):\n\n # verbose: print a message to the user\n if self.verbose:\n print('\\nPROCESSING: ', self.title)\n\n # process the input assignments gradebook and aegrotat files\n if self.file_names['assignments'] is not None:\n self.read_assignments(file_name=self.file_names['assignments'])\n else:\n print('WARNING: no assignments file provided')\n\n if self.file_names['gradebook'] is not None:\n self.read_gradebook(file_name=self.file_names['gradebook'])\n else:\n print('WARNING: no gradebook file provided')\n\n if self.file_names['aegrotats'] is not None:\n self.read_aegrotats(file_name=self.file_names['aegrotats'])\n else:\n print('WARNING: no aegrotats file provided')\n\n # verbose\n if self.verbose:\n print('Processing portfolios')\n if self.exclude_zero['test']:\n print(' Excluding students with a zero mark for any test')\n if self.exclude_zero['exam']:\n print(' Excluding students with a zero mark for the final exam')\n\n # process marks for each student and populate the course portfolios\n for student in self.students:\n\n # initialise boolean(s) for adding this student to relevant portfolios\n portfolio_complete = True\n\n # check if student has applied for an aegrotat\n if student.aegrotats is not None:\n portfolio_complete = False\n self.portfolio_aegrotat['students'].append(student)\n\n # check if student has any non-float type marks\n if portfolio_complete:\n for assignment in self.assignments:\n if not isfloat(student.marks_by_assignment[assignment.id]):\n portfolio_complete = False\n\n # check if student has a zero test mark and user wants to exclude such students\n if portfolio_complete and self.exclude_zero['test']:\n for assignment in self.assignments:\n if assignment.test:\n if student.marks_by_assignment[assignment.id] < 1.e-4:\n portfolio_complete = False\n\n # check if student has a zero test mark and user wants to exclude such students\n if portfolio_complete and self.exclude_zero['exam']:\n for assignment in self.assignments:\n if assignment.exam:\n if student.marks_by_assignment[assignment.id] < 1.e-4:\n portfolio_complete = False\n\n # based on conditional checks above, store student in relevant portfolio\n if portfolio_complete:\n self.portfolio_complete['students'].append(student)\n else:\n self.portfolio_incomplete['students'].append(student)\n\n # store the original marks by assignment for all students\n for assignment in self.assignments:\n self.portfolio_complete[assignment.id] = []\n for student in self.portfolio_complete['students']:\n self.portfolio_complete[assignment.id].append(student.marks_by_assignment[assignment.id])\n\n # store the marks by category for all students in the complete portfolio\n for student in self.portfolio_complete['students']:\n for category in student.marks_by_category:\n self.portfolio_complete[category].append(student.marks_by_category[category])\n\n def read_assignments(self, file_name):\n\n if self.verbose:\n print('Reading in assignment data file: ', file_name)\n\n # open requested file in read-only mode\n with open(file_name, 'r', encoding=\"ISO-8859-1\") as f:\n\n # read in the file contents using csv.reader\n reader = csv.reader(f, delimiter=',')\n\n # read in header and use to determine which column represents which data about the assignment\n header = next(reader)\n for column in range(len(header)):\n header[column] = header[column].strip()\n if header[column] == \"Assignment Name\":\n column_name = column\n elif header[column] == \"Marks Available\":\n column_marks_available = column\n elif header[column] == \"Weight\":\n column_weight = column\n elif header[column] == \"Identifier\":\n column_id = column\n elif header[column] == \"Test\":\n column_test = column\n elif header[column] == \"Coursework\":\n column_coursework = column\n elif header[column] == \"Exam\":\n column_exam = column\n\n # iterate through line in assignment file\n for row in reader:\n\n # create assignment object and set associated properties from file data\n assignment = Assignment()\n assignment.name = row[column_name]\n assignment.id = row[column_id]\n assignment.marks_available = float(row[column_marks_available])\n assignment.weight = float(row[column_weight])\n\n # store weight for each assignment - useful for aegrotats\n self.weight_by_assignment[assignment.id] = assignment.weight\n\n # initialise booleans for assignment categories\n assignment.coursework = False\n assignment.test = False\n assignment.exam = False\n\n # update booleans for assignment categories\n if int(row[column_test]) == 1:\n assignment.test = True\n if int(row[column_coursework]) == 1:\n assignment.coursework = True\n if int(row[column_exam]) == 1:\n assignment.exam = True\n\n # add weight of current assignment to relevant category\n if assignment.coursework:\n self.weight_by_category['coursework'] += assignment.weight\n if assignment.test:\n self.weight_by_category['test'] += assignment.weight\n if assignment.exam:\n self.weight_by_category['exam'] += assignment.weight\n if assignment.coursework or assignment.test or assignment.exam:\n self.weight_by_category['final'] += assignment.weight\n\n # append this assignment to the list of assignments\n self.assignments.append(assignment)\n\n # conditionally append assignment to relevant course lists\n if assignment.coursework:\n self.assignments_coursework.append(assignment)\n if assignment.test:\n self.assignments_test.append(assignment)\n if assignment.exam:\n self.assignments_exam.append(assignment)\n\n def read_gradebook(self, file_name):\n\n if self.verbose:\n print('Reading in gradebook file: ', file_name)\n\n # open the file in read-only mode\n with open(file_name, 'r', encoding=\"ISO-8859-1\") as f:\n\n # read in the file contents using csv module\n reader = csv.reader(f, delimiter=',')\n\n # read in the first header line\n header = next(reader)\n\n # initialise columns in gradebook corresponding to student identifying information\n gradebook_column_name = None\n gradebook_column_username = None\n gradebook_column_sid = None\n\n # determine which columns contain student metadata and requested assignment marks\n for column in range(len(header)):\n\n # current row entry\n current_entry = header[column]\n\n # locate useful columns containing student identifying information\n if current_entry == \"Student\":\n gradebook_column_name = column\n\n if current_entry == \"SIS Login ID\":\n gradebook_column_username = column\n\n if current_entry == \"SIS User ID\":\n gradebook_column_sid = column\n\n for assignment in self.assignments:\n if current_entry == assignment.name:\n assignment.gradebook_column = column\n\n # read in the next header line\n header = next(reader)\n\n # check for muted assignments - if yes then true second header line is the one after this\n muted = False\n for column in range(len(header)):\n if header[column] == \"Muted\":\n muted = True\n if muted:\n header = next(reader)\n\n # check if using a read only column - if so this is a percentage i.e. set marks available to 100\n for assignment in self.assignments:\n if header[assignment.gradebook_column] == \"(read only)\":\n assignment.marks_available = 100.\n else:\n assignment.marks_available = float(header[assignment.gradebook_column])\n\n # scan through each row of gradebook\n for row in reader:\n\n read_student = True\n if not read_student:\n print(' Excluding student from reading in gradebook: ', row[gradebook_column_name])\n else:\n\n # create a new student object\n student = Student()\n\n # update their name if available\n if gradebook_column_name is not None:\n student.name = row[gradebook_column_name]\n\n # update their ID if available\n if gradebook_column_sid is not None:\n student.sid = row[gradebook_column_sid]\n\n # update their username if available\n if gradebook_column_username is not None:\n student.username = row[gradebook_column_username]\n\n # add all relevant gradebook marks for the student\n for assignment in self.assignments:\n if isfloat(row[assignment.gradebook_column]):\n student.marks_by_assignment[assignment.id] = float(row[assignment.gradebook_column])\n else:\n student.marks_by_assignment[assignment.id] = row[assignment.gradebook_column]\n\n # calculate marks by category for the student\n coursework = calculate_mark_by_category(student.marks_by_assignment, self.assignments_coursework)\n test = calculate_mark_by_category(student.marks_by_assignment, self.assignments_test)\n exam = calculate_mark_by_category(student.marks_by_assignment, self.assignments_exam)\n final = calculate_mark_by_category(student.marks_by_assignment, self.assignments)\n\n # update marks by category for the student\n student.marks_by_category['coursework'] = coursework\n student.marks_by_category['test'] = test\n student.marks_by_category['exam'] = exam\n student.marks_by_category['final'] = final\n\n # append student object to list of all students\n self.students.append(student)\n\n def read_aegrotats(self, file_name):\n\n # verbose message\n if self.verbose:\n print('Reading in aegrotat data file: ', file_name)\n\n # open the file in read-only mode\n with open(file_name, 'r', encoding=\"ISO-8859-1\") as f:\n\n # read in the file contents using csv.reader\n reader = csv.reader(f, delimiter=',')\n\n # read in and discard the first header line\n _ = next(reader)\n\n # update aegrotat information for each student in the course student list\n for row in reader:\n\n # find assignment associated with aegrotat\n for assignment in self.assignments:\n if row[0] == assignment.name or row[0] == assignment.id:\n current_assignment = assignment\n\n # find student associated with the aegrotat\n for student in self.students:\n if row[1] == student.name or row[1] == student.sid or row[1] == student.username:\n current_student = student\n\n # initialise aegrotat dictionary for current student\n if current_student.aegrotats is None:\n current_student.aegrotats = {current_assignment.id: {'method': row[2]}}\n\n if self.verbose:\n print(' Aegrotat(s) found for student: ', current_student.name)\n\n def process_aegrotats(self, plot_rank=True, plot_residual=True, write_to_file=True):\n\n for student in self.portfolio_aegrotat['students']:\n\n # initialise if a ranking method is used\n rank = False\n\n if self.verbose:\n print('PROCESSING AEGROTAT(S) FOR STUDENT:', student.name)\n\n # see if all aegrotats are shift to exam method\n number_shift = 0\n for assignment_id in student.aegrotats:\n if student.aegrotats[assignment_id]['method'] == 'ShiftToExam':\n number_shift += 1\n\n if number_shift == len(student.aegrotats):\n self.calculate_aegrotat_shifttoexam(student)\n\n # if not all shift to exam, try rank method\n else:\n\n # if student has one aegrotat, choose requested methodology\n if len(student.aegrotats) == 1:\n for assignment_id in student.aegrotats:\n\n # use invigilated work to rank the student and predict based on rank\n if student.aegrotats[assignment_id]['method'] == 'RankInvigilated':\n self.calculate_aegrotat_rank(student, invigilated_only=True)\n rank = True\n\n # use invigilated and non-invigilated work to rank the student and predict based on rank\n elif student.aegrotats[assignment_id]['method'] == 'RankAll':\n self.calculate_aegrotat_rank(student, invigilated_only=False)\n rank = True\n\n # by default, use invigilated rank method\n else:\n self.calculate_aegrotat_rank(student, invigilated_only=True)\n rank = True\n\n # if student has multiple aegrotats, use rank methodology\n else:\n self.calculate_aegrotat_rank(student, invigilated_only=True)\n rank = True\n\n # produce written summary\n if write_to_file:\n self.write_aegrotat_summary(student)\n\n # produce accompanying plots\n if plot_rank and rank:\n self.plotting_aegrotat_rank(student)\n if plot_residual and rank:\n self.plotting_aegrotat_residual(student)\n\n # if verbose mode, display some simple information to screen\n if self.verbose:\n if student.predicted_marks_by_category['final'] > student.marks_by_category['final']:\n print('AEGROTAT: RECOMMEND UPDATING FINAL MARK FOR THE STUDENT')\n else:\n print('AEGROTAT: NO RECOMMENDATION TO UPDATE FINAL MARK FOR THE STUDENT')\n print('ORIGINAL FINAL MARK: ', student.marks_by_category['final'])\n print('PREDICTED FINAL MARK: ', student.predicted_marks_by_category['final'], '\\n')\n\n def calculate_aegrotat_rank(self, student, invigilated_only=True):\n \"\"\"\n Use a ranking methodology to predict grade for specific assignment\n \"\"\"\n\n # initialise useful data regarding marks and rank\n student.rank = {\n 'marks_by_assignment': copy.deepcopy(student.marks_by_assignment),\n 'assignments': [],\n 'mark': 0.,\n 'marks': [],\n 'marks_sorted': [],\n 'rank_index': None,\n 'rank_in_class': None,\n }\n\n # remove assignments from marks by assignment dictionary if it has an aegrotat or based on invigilated only\n for assignment in self.assignments:\n\n if invigilated_only:\n if assignment.test or assignment.exam:\n keep_assignment = True\n else:\n keep_assignment = False\n else:\n if assignment.coursework or assignment.test or assignment.exam:\n keep_assignment = True\n else:\n keep_assignment = False\n\n # flag assignment to remove if it has an aegrotat pending\n if keep_assignment:\n for assignment_id in student.aegrotats:\n if assignment.id == assignment_id:\n keep_assignment = False\n\n # remove student assignment mark from the rank marks_by_assignment dictionary\n if not keep_assignment:\n del student.rank['marks_by_assignment'][assignment.id]\n\n # keep a list of assignments being used in the ranking\n if keep_assignment:\n student.rank['assignments'].append(assignment)\n\n # if no assignments suitable for ranking, warn the user\n if len(student.rank['assignments']) == 0:\n print(\"WARNING: no assignments available for use in estimating student ranking in the class\")\n return\n\n # calculate weighted marks for current student and students in complete portfolio\n student.rank['mark'] = calculate_mark_by_category(student.marks_by_assignment, student.rank['assignments'])\n for current_student in self.portfolio_complete['students']:\n mark = calculate_mark_by_category(current_student.marks_by_assignment, student.rank['assignments'])\n student.rank['marks'].append(mark)\n student.rank['marks'] = np.array(student.rank['marks'])\n student.rank['marks_sorted'] = np.sort(student.rank['marks'])\n\n # determine which index this student would rank in suitable assignments - can be used to predict marks\n student.rank['rank_index'] = np.searchsorted(student.rank['marks_sorted'], student.rank['mark'], side='right')\n student.rank['rank_in_class'] = len(self.portfolio_complete['students']) - student.rank['rank_index']\n\n # predict student mark for aegrotat assignments based on ranking\n for assignment_id in student.aegrotats:\n student.aegrotats[assignment_id]['mark'] = student.marks_by_assignment[assignment_id]\n predicted = np.sort(self.portfolio_complete[assignment_id])[student.rank['rank_index']]\n student.aegrotats[assignment_id]['predicted'] = predicted\n\n # construct a best-case set of marks by assignment for student based on predictions\n student.predicted_marks_by_assignment = copy.deepcopy(student.marks_by_assignment)\n student.predicted_marks_by_category = copy.deepcopy(student.marks_by_category)\n for assignment_id in student.aegrotats:\n if not isfloat(student.aegrotats[assignment_id]['mark']):\n student.predicted_marks_by_assignment[assignment_id] = student.aegrotats[assignment_id]['predicted']\n else:\n if student.aegrotats[assignment_id]['predicted'] > float(student.aegrotats[assignment_id]['mark']):\n student.predicted_marks_by_assignment[assignment_id] = student.aegrotats[assignment_id]['predicted']\n\n # calculate marks by category for the student\n coursework = calculate_mark_by_category(student.predicted_marks_by_assignment, self.assignments_coursework)\n test = calculate_mark_by_category(student.predicted_marks_by_assignment, self.assignments_test)\n exam = calculate_mark_by_category(student.predicted_marks_by_assignment, self.assignments_exam)\n final = calculate_mark_by_category(student.predicted_marks_by_assignment, self.assignments)\n\n # update marks by category for the student\n student.predicted_marks_by_category['coursework'] = coursework\n student.predicted_marks_by_category['test'] = test\n student.predicted_marks_by_category['exam'] = exam\n student.predicted_marks_by_category['final'] = final\n\n def calculate_aegrotat_shifttoexam(self, student):\n\n # initial copy of assignments and marks by assignment\n assignments = copy.deepcopy(self.assignments)\n student.predicted_marks_by_assignment = copy.deepcopy(student.marks_by_assignment)\n student.predicted_marks_by_category = {'final': 0.}\n\n # calculate weight of aegrotat assignment(s) and delete assignment from predicted marks dictionary\n weight_to_shift = 0.\n for assignment_id in student.aegrotats:\n i = 0\n for assignment in self.assignments:\n if assignment_id == assignment.id:\n weight_to_shift += assignment.weight\n del student.predicted_marks_by_assignment[assignment.id]\n del assignments[i]\n i += 1\n\n # shift the weight across to the final exam\n for assignment in assignments:\n if assignment.exam:\n assignment.weight += weight_to_shift\n\n # calculate marks by category for the student\n final = calculate_mark_by_category(student.predicted_marks_by_assignment, assignments)\n student.predicted_marks_by_category['final'] = final\n\n # iterate through all assignments - if aegrotat, remove from self.assignments,\n\n # current_assignments = self.assignments\n\n # # calculate weight of exam + aegrotat assignments\n # shifted_weight = 0.\n # for aegrotat_id in student.aegrotats['assignment_id']:\n # for assignment in self.assignments:\n #\n # if assignment.id == aegrotat_id:\n # shifted_weight += assignment.weight\n # if self.verbose:\n # print('Shifting ', assignment.weight, '% to Final Exam')\n #\n # if assignment.exam:\n # shifted_weight += assignment.weight\n\n # if self.verbose:\n # print('Shifted Weight: ', shifted_weight)\n\n # # copy across original assignments, then update overall weights by category\n # modified_assignmnets = copy.deepcopy(self.assignments)\n # modified_weight_by_category = {'coursework': 0., 'test': 0., 'exam': 0., 'final': 0.}\n # for assignment in modified_assignmnets:\n # if assignment.coursework:\n\n def write_aegrotat_summary(self, student):\n\n # first, determine if a ranking methodology was used or not\n write_rank = False\n for assignment_id in student.aegrotats:\n if student.aegrotats[assignment_id]['method'] == 'RankAll':\n write_rank = True\n if student.aegrotats[assignment_id]['method'] == 'RankInvigilated':\n write_rank = True\n\n f = open('Aegrotat_{}.txt'.format(student.sid), 'w', encoding=\"ISO-8859-1\")\n\n # write student identifying information\n f.write('{:20}: {}\\n'.format('Student Name', student.name,))\n f.write('{:20}: {}\\n'.format('Student ID', student.sid))\n f.write('{:20}: {}\\n'.format('Student Username', student.username))\n\n # aegrotats that have been applied for\n f.write('\\n{:20}: '.format('Aegrotats (method)'))\n i = 0\n for assignment_id in student.aegrotats:\n if i == 0:\n f.write('{} ({})\\n'.format(assignment_id, student.aegrotats[assignment_id]['method']))\n else:\n f.write('{:20}: {} ({})\\n'.format('', assignment_id, student.aegrotats[assignment_id]['method']))\n i += 1\n\n # write marks by assignment to file\n f.write('\\nMarks by Assignment\\n')\n for assignment in self.assignments:\n f.write('{:20}: {:5} out of {:5}\\n'.format(\n assignment.id,\n student.marks_by_assignment[assignment.id],\n assignment.marks_available)\n )\n\n # write marks by category to file\n f.write('\\nMarks by Category\\n')\n f.write('{:20}: {}\\n'.format('Coursework%', student.marks_by_category['coursework']))\n f.write('{:20}: {}\\n'.format('Test%', student.marks_by_category['test']))\n f.write('{:20}: {}\\n'.format('Exam%', student.marks_by_category['exam']))\n f.write('{:20}: {}\\n'.format('Final%', student.marks_by_category['final']))\n\n # predicted marks by assignment\n if write_rank:\n f.write('\\nPredicted Mark for each Aegrotat\\n')\n for assignment_id in student.aegrotats:\n f.write('{:20}: {}\\n'.format(assignment_id, student.aegrotats[assignment_id]['predicted']))\n\n # predicted marks by category\n if student.predicted_marks_by_category['final'] > student.marks_by_category['final']:\n f.write('\\nPredicted Marks by Category\\n')\n if write_rank:\n f.write('{:20}: {}\\n'.format('Coursework%', student.predicted_marks_by_category['coursework']))\n f.write('{:20}: {}\\n'.format('Test%', student.predicted_marks_by_category['test']))\n f.write('{:20}: {}\\n'.format('Exam%', student.predicted_marks_by_category['exam']))\n f.write('{:20}: {}\\n\\n'.format('Final%', student.predicted_marks_by_category['final']))\n else:\n f.write('\\nNo Predicted Improvement to Marks\\n')\n\n # write rank information\n if write_rank:\n f.write('Rank Information\\n')\n f.write('{:20}: {} out of {}'.format(\n 'Rank in class', student.rank['rank_in_class'],\n len(self.portfolio_complete['students']))\n )\n\n f.write('\\n{:20}: '.format('Rank based on'))\n i = 0\n for assignment in student.rank['assignments']:\n if i == 0:\n f.write('{}\\n'.format(assignment.id))\n else:\n f.write('{:20}: {}\\n'.format('', assignment.id))\n i += 1\n\n # close the file\n f.close()\n\n def plotting_aegrotat_rank(self, student):\n\n fig, ax = plt.subplots(len(student.aegrotats)+1, 1)\n\n # histogram of rank-suitable marks\n n1, bins1, patches1 = ax[0].hist(x=student.rank['marks_sorted'], bins=20, rwidth=0.9)\n # ax[0].set_xlabel(xlabel1)\n ax[0].set_xlabel('Rank%')\n ax[0].set_ylabel('Frequency')\n ax[0].set_title('Aegrotat for student: {}'.format(student.sid))\n ax[0].plot([student.rank['mark'], student.rank['mark']], [0, n1.max()], color='black',\n label='Student Rank%: {:2.1f}'.format(student.rank['mark']))\n ax[0].legend(loc=2)\n # ax[0].set_ylim(ymax=np.ceil(n1.max() / 10) * 10 if n1.max() % 10 else n1.max() + 10)\n\n # assignment(s) with aegrotat histogram\n i = 1\n for assignment_id in student.aegrotats:\n n, bins, patches = ax[i].hist(x=self.portfolio_complete[assignment_id], bins=20, rwidth=0.9)\n ax[i].set_xlabel('Mark for: ' + assignment_id)\n ax[i].set_ylabel('Frequency')\n if isfloat(student.aegrotats[assignment_id]['mark']):\n ax[i].plot([student.aegrotats[assignment_id]['mark'], student.aegrotats[assignment_id]['mark']],\n [0, n.max()], color='black',\n label='Student Mark: {:2.1f}'.format(student.aegrotats[assignment_id]['mark']))\n else:\n ax[i].plot([0, 0], [0, 0], color='black', label='Student Mark: DNS')\n ax[i].plot([student.aegrotats[assignment_id]['predicted'],\n student.aegrotats[assignment_id]['predicted']],\n [0, n.max()], color='red',\n label='Predicted Mark: {:2.1f}'.format(student.aegrotats[assignment_id]['predicted']))\n ax[i].legend(loc=2)\n\n # increment plot counter\n i += 1\n # ax[1].set_ylim(ymax=np.ceil(n2.max() / 10) * 10 if n2.max() % 10 else n2.max() + 10)\n\n # save the figure to file\n fig.tight_layout()\n plt.savefig('Aegrotat_{}_Rank.png'.format(student.sid), dpi=300, bbox_inches='tight', papertype='A4')\n plt.close()\n\n def plotting_aegrotat_residual(self, student):\n\n # setup the plot environment\n fig, ax = plt.subplots(len(student.aegrotats), 1)\n\n # ensure that multiple plot support is there for multiple aegrotat students\n if len(student.aegrotats) == 1:\n ax = [ax, ]\n\n i = 0\n for assignment_id in student.aegrotats:\n if isfloat(student.rank['mark']) and isfloat(student.aegrotats[assignment_id]['mark']):\n residual = student.rank['mark'] - student.aegrotats[assignment_id]['mark']\n residuals = student.rank['marks'] - self.portfolio_complete[assignment_id]\n mean = np.mean(residuals)\n std = np.std(residuals)\n\n # histogram of student residuals\n n, bins, patches = ax[i].hist(\n residuals, bins=20, alpha=0.8, rwidth=0.95,\n label='Mean of residuals: {:2.2f}\\nStandard deviation of residuals: {:2.2f}'.format(mean, std)\n )\n\n # add aegrotat student residual for comparison with other students\n if isfloat(student.rank['mark']) and isfloat(student.aegrotats[assignment_id]['mark']):\n ax[i].plot(\n [residual, residual], [0, n.max()], color='red',\n label='Student Residual: {:2.1f}'.format(residual)\n )\n\n # add some labels\n ax[i].set_ylabel('Frequency')\n ax[i].set_xlabel('Residual for: Rank% - {}'.format(assignment_id))\n ax[i].set_title('Aegrotat for student: ' + student.sid)\n\n # additional labels and layout options\n ax[i].legend()\n\n # increment plot counter\n i += 1\n\n # save the figure to file\n fig.tight_layout()\n plt.savefig('Aegrotat_{}_Residual.png'.format(student.sid), dpi=300, bbox_inches='tight', papertype='A4')\n plt.close()\n\n def plot_correlation(self, key1='test', key2='exam', img_format='png'):\n\n # set name of the file to create\n file_name = self.title + '_correlation_' + key1 + '_' + key2 + '.' + img_format\n\n if self.verbose:\n print('Producing correlation plot: ', file_name)\n\n # evaluate best fit parameters\n correlation = np.corrcoef(self.portfolio_complete[key1], self.portfolio_complete[key2])\n coefficients = np.polyfit(self.portfolio_complete[key1], self.portfolio_complete[key2], 1)\n polynomial = np.poly1d(coefficients)\n\n # plotting - correlation of test/exam marks\n fig1 = plt.figure()\n plt.subplot(111)\n\n # scatter plot of student marks\n plt.scatter(x=self.portfolio_complete[key1], y=self.portfolio_complete[key2],\n marker='.', label='Pearson correlation coefficient: {:2.2f}'.format(correlation[0, 1]))\n\n # plot the best-fit line\n x = np.linspace(0., 100., 100)\n y = polynomial(x)\n plt.plot(x, y, color='black', label='Linear best-fit')\n\n # plot theoretical line where marks are equal\n plt.plot([0, 100], [0, 100], color='red', ls='--', label='Marks are equal')\n\n # add some labels\n plt.xlabel(key1)\n plt.ylabel(key2)\n plt.title('Correlation analysis for ' + self.title)\n\n # set appropriate limits\n plt.xlim(xmin=0., xmax=100.)\n plt.ylim(ymin=0., ymax=100.)\n\n # additional labels and layout options\n plt.legend()\n fig1.tight_layout()\n\n # save the figure to requested filename\n plt.savefig(file_name, dpi=300, bbox_inches='tight', papertype='A4')\n plt.close()\n\n def plot_residual(self, key1='test', key2='exam', img_format=\"png\"):\n\n # set name of the file to create\n file_name = self.title + '_residual_' + key1 + '_' + key2 + '.' + img_format\n\n if self.verbose:\n print('Producing residuals plot: ', file_name)\n\n # calculate residuals, and mean and standard deviation of residuals (experimental)\n residuals = np.array(self.portfolio_complete[key1]) - np.array(self.portfolio_complete[key2])\n mean = np.mean(residuals)\n std = np.std(residuals)\n\n # plotting - correlation of test/exam marks\n fig1 = plt.figure()\n plt.subplot(111)\n\n # scatter plot of student grades\n plt.hist(residuals, range=(-100., 100.), bins=40, color='#0504aa', alpha=0.5, rwidth=0.95,\n label='Mean of residuals: {:2.2f}\\nStandard deviation of residuals: {:2.2f}'.format(mean, std))\n\n # add some labels\n plt.ylabel('Frequency')\n plt.xlabel('Residual = ' + key1 + ' - ' + key2)\n plt.title('Residual analysis for ' + self.title)\n\n # additional labels and layout options\n plt.legend()\n fig1.tight_layout()\n\n # save the figure to requested filename\n plt.savefig(file_name, dpi=300, bbox_inches='tight', papertype='A4')\n plt.close()\n\n\nclass Assignment(object):\n def __init__(self):\n self.name = None\n self.weight = None\n self.marks_available = None\n self.coursework = None\n self.test = None\n self.exam = None\n self.final = True\n self.gradebook_column = None\n\n\nclass Student(object):\n def __init__(self):\n self.name = None\n self.username = None\n self.sid = None\n self.marks_by_assignment = {}\n self.marks_by_category = {'coursework': 0., 'test': 0., 'exam': 0., 'final': 0.}\n self.aegrotats = None\n\n\ndef calculate_mark_by_category(marks_by_assignment, assignments):\n mark = 0.\n weight = 0.\n for assignment in assignments:\n if isfloat(marks_by_assignment[assignment.id]):\n mark += float(marks_by_assignment[assignment.id]) * assignment.weight / assignment.marks_available\n weight += assignment.weight\n mark *= 100. / weight\n return mark\n\n\ndef isfloat(value):\n try:\n float(value)\n return True\n except ValueError:\n return False\n","sub_path":"coursetools.py","file_name":"coursetools.py","file_ext":"py","file_size_in_byte":38128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"53611696","text":"import picamera\nimport time\nimport RPi.GPIO as GPIO\ncamera = picamera.PiCamera()\n##picamera.renderers.PiPreviewRenderer(camera,camera,layer=2,alpha=255,fullscreen=True,window=None,crop=None,rotation = 0,vflip=True,hflip=False)\nbouncetime=250 ## time in ms to deboune the switch to prevent multiple interrupts\nstream_bcm_pin = 4 ##stores bcm pin number of momentary switch that controls the video stream (where the number is n in the form GPIOn)\n\n\nstream_state = False ##stores to whether or not the stream is showing, is changed on button press\ncamera.vflip=True\ncamera.hflip=True\n\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(stream_bcm_pin, GPIO.IN, GPIO.PUD_DOWN)\n##GPIO.add_event_detect(stream_bcm_pin, GPIO.RISING)\ndef eval_feed(channel): ##turns on/off the stream depending on previous state of stream\n\tglobal stream_state\n\tif stream_state == False :\n\t\tcamera.start_preview()\n\t\tstream_state = True\n\telse :\n\t\tcamera.stop_preview()\n\t\tstream_state = False\n\t##print('Edge detected on channel %s'%channel)\n\t\nGPIO.add_event_detect(stream_bcm_pin, GPIO.RISING, eval_feed, bouncetime)\n\n\nwhile True :\n time.sleep(5)\n\n\n\n ##camera.capture('/home/pi/Desktop/image.jpg')\n","sub_path":"camera_preview.py","file_name":"camera_preview.py","file_ext":"py","file_size_in_byte":1159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"119970018","text":"#Game Plan(may not have been 100% faithful to actual plan)\n#read through each line and use a counter 'num_lines' to count number of lines\n#scramble every number from 1 to 'num_of_lines' and append to a list 'random'\n#1.seek(0,0)\n#2.pop 'num_of_line'[0] from the list 'random'\n#4.readline 'num_of_line'[0] number of times and store 'line' to a temporary variable\n#5.if 'num_of_line'[0] is the last number in range(num_of_lines) then append /n\n#6.write 'line' to outfile\n#iterate steps 1-6 for rest of numbers from random\nimport random\nimport copy\n\ndef count_lines(input_file):\n '''\n (file) -> (list)\n Take a file 'input_file' and return a list 'num_lines' that has the same\n number of elements as 'input_file' has lines with each element being a line\n number. The elements are arranged in increasing order.\n '''\n num_lines = []\n counter = 0\n for line in input_file:\n counter+=1\n num_lines.append(counter)\n return num_lines\n\ndef shuffle_order(num_lines):\n '''\n (list) -> (list)\n Take a list 'num_lines' with consecutive integers in increasing order as\n elements and return a list 'rand_list' with the integers rearranged in a\n random order\n '''\n rand_list = num_lines\n for i in range(len(rand_list) - 1, 0, -1):\n rand_index = random.randint(0, i)\n rand_list[i], rand_list[rand_index]= rand_list[rand_index], rand_list[i]\n return rand_list\n\ndef scramble(in_filename, out_filename):\n '''\n (string, string) ->\n Take two strings 'in_filename' and 'out_filename' and open the corresponding files. \n Write each line in 'in_filename' to 'out_filename' preceded by the line's original \n line number in 'in_filename' and a colon. Ex \"'line number':'line'\"\n '''\n in_file = open(in_filename, 'r')\n out_file = open(out_filename, 'w')\n num_lines = count_lines(in_file)\n rand_list = shuffle_order(num_lines)\n write_index = copy.deepcopy(rand_list)\n temp_line = ''\n temp_num = ''\n for i in range(len(rand_list)):\n temp_num = int(write_index.pop(0))\n in_file.seek(0,0)\n for i in range(temp_num):\n #read temp_num number of times and assign line value to temp_line\n temp_line = in_file.readline()\n if write_index == []:\n out_file.write(str(temp_num) + ':' + temp_line.rstrip('\\n'))\n else:\n out_file.write(str(temp_num) + ':' + temp_line.rstrip('\\n') + '\\n')\n out_file.close()\n\nif __name__ == '__main__':\n in_filename = 'inputfileS.txt'\n out_filename = 'outputfileS.txt'\n scramble(in_filename, out_filename)\n","sub_path":"CSC180_Introduction_to_Computer_Programming/Assignment 6/L6_S.py","file_name":"L6_S.py","file_ext":"py","file_size_in_byte":2605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"603503548","text":"import numpy as np\nfrom array import array\nimport ROOT\nfrom ROOT import gROOT, TCanvas, TF1, TFile, gStyle, TFormula, TGraph, TGraphErrors, TH1F, TCutG, TH2D, gDirectory, TLegend, TNtuple, TTree\nimport matplotlib.pyplot as plt\nfrom matplotlib.backends.backend_pdf import PdfPages\nfrom matplotlib.colors import LogNorm\n\n\ndef openPDF(outfile,canvas):\n\tcanvas.Print(outfile+\".pdf[\")\n\ndef closePDF(outfile,canvas):\n\tcanvas.Print(outfile+\".pdf]\")\n\ndef ctau(mass,eps):\n\thbar_c = 1.973e-13\n\treturn 3 * hbar_c/ (1 * mass * 1/137. * eps**2)\n\ndef DrawZHisto(events,histo,nBins,minX,maxX):\n\tevents.Draw(\"{0}>>{1}({2},{3},{4})\".format(\"triEndZ\",histo,nBins,minX,maxX))\n\thisto = ROOT.gROOT.FindObject(histo)\n\treturn histo\n\ndef shapeHisto(gammact,nBins,targetz,maxZ):\n\thisto = TH1F(\"histo\",\"histo\",nBins,targetz,maxZ)\n\tzbin = (maxZ - targetz) / nBins\n\tfor i in range(nBins):\n\t\tibin = i + 1\n\t\tz = targetz + (i + 0.5) * zbin\n\t\thisto.Fill(z,np.exp((targetz - z)/gammact) / gammact)\n\thisto.Scale(1./histo.Integral())\n\treturn histo\n\ndef multiplyHisto(histo1, histo2, n):\n\thisto = histo1.Clone(\"histo\")\n\thisto.Multiply(histo2)\n\thisto.Scale(float(n)/histo.Integral())\n\treturn histo\n\ndef divideHisto(histo1, histo2):\n\thisto = histo1.Clone(\"histo\")\n\thisto.Divide(histo2)\n\treturn histo\n\ninput_truth = TFile(\"ap_100MeV_truth.root\")\ninput_sig = TFile(\"ap_100MeV_L1L1_cleanup_nPos_1.root\")\n\nevents = input_sig.Get(\"ntuple\")\nevents_truth = input_truth.Get(\"ntuple\")\n\ngStyle.SetOptStat(0)\nc = TCanvas(\"c\",\"c\",800,600);\noutfile = \"test\"\n\nnBins = 70\nzTarg = -4.3\nmaxZ = 70 + zTarg\n\neps = np.sqrt(10**-9.)\nnp.random.seed(1)\n#eps = np.sqrt(4*10**-10.)\n#np.random.seed(2)\n#eps = np.sqrt(4*10**-9.)\n#np.random.seed(3)\n\nmass = 0.100\neBeam = 2.3\navg_gamma = 0.95\nn_samples = 100000\n\ngamma = avg_gamma * eBeam / mass\nct = ctau(mass,eps)\ngammact = gamma * ct\n\n#openPDF(outfile,c)\nrecon_shape = DrawZHisto(events,\"recon_shape\",nBins,zTarg,maxZ)\n#recon_shape.Draw(\"histp\")\n#c.Print(outfile+\".pdf\")\ninput_shape = DrawZHisto(events_truth,\"input_shape\",nBins,zTarg,maxZ)\n#input_shape.Draw(\"histp\")\n#c.Print(outfile+\".pdf\")\ntruth_shape = shapeHisto(gammact,nBins,zTarg,maxZ)\n#truth_shape.Draw(\"histp\")\n#c.Print(outfile+\".pdf\")\nacceptance_shape = divideHisto(recon_shape,input_shape)\nacceptance_shape.Scale(1./acceptance_shape.Integral())\n#acceptance_shape.Draw(\"histp\")\n#c.Print(outfile+\".pdf\")\nsignal_shape = multiplyHisto(truth_shape,acceptance_shape,n_samples)\n#signal_shape.Draw(\"histp\")\n#c.Print(outfile+\".pdf\")\nreweight = divideHisto(signal_shape,recon_shape)\n#reweight = divideHisto(truth_shape,input_shape)\n#reweight.Draw(\"histp\")\n#c.Print(outfile+\".pdf\")\n\n#closePDF(outfile,c)\n\n\ngROOT.Reset()\n\nrootfile = TFile(outfile + \".root\",\"RECREATE\")\n\ntree = TTree( 'tree', 'tree' )\n\ntriEndZ = array('d',[0])\nuncVX = array('d',[0])\nuncVY = array('d',[0])\nuncVZ = array('d',[0])\nuncP = array('d',[0])\nuncChisq = array('d',[0])\nuncM = array('d',[0])\nuncTargProjX = array('d',[0])\nuncTargProjY = array('d',[0])\nuncTargProjXErr = array('d',[0])\nuncTargProjYErr = array('d',[0])\nuncCovXX = array('d',[0])\nuncCovYY = array('d',[0])\nuncCovZZ = array('d',[0])\nbscChisq = array('d',[0])\ntarChisq = array('d',[0])\neleP = array('d',[0])\neleTrkChisq = array('d',[0])\neleTrkHits = array('d',[0])\neleTrkD0 = array('d',[0])\neleTrkLambda = array('d',[0])\neleTrkZ0 = array('d',[0])\neleTrkD0Err = array('d',[0])\neleTrkLambdaErr = array('d',[0])\neleTrkZ0Err = array('d',[0])\nposP = array('d',[0])\nposTrkChisq = array('d',[0])\nposTrkHits = array('d',[0])\nposTrkD0 = array('d',[0])\nposTrkLambda = array('d',[0])\nposTrkZ0 = array('d',[0])\nposTrkD0Err = array('d',[0])\nposTrkLambdaErr = array('d',[0])\nposTrkZ0Err = array('d',[0])\n\ntree.Branch(\"triEndZ\",triEndZ,\"triEndZ/D\")\ntree.Branch(\"uncVX\",uncVX,\"uncVX/D\")\ntree.Branch(\"uncVX\",uncVX,\"uncVX/D\")\ntree.Branch(\"uncVY\",uncVY,\"uncVY/D\")\ntree.Branch(\"uncVZ\",uncVZ,\"uncVZ/D\")\ntree.Branch(\"uncP\",uncP,\"uncP/D\")\ntree.Branch(\"uncChisq\",uncChisq,\"uncChisq/D\")\ntree.Branch(\"uncM\",uncM,\"uncM/D\")\ntree.Branch(\"uncTargProjX\",uncTargProjX,\"uncTargProjX/D\")\ntree.Branch(\"uncTargProjY\",uncTargProjY,\"uncTargProjY/D\")\ntree.Branch(\"uncTargProjXErr\",uncTargProjXErr,\"uncTargProjXErr/D\")\ntree.Branch(\"uncTargProjYErr\",uncTargProjYErr,\"uncTargProjYErr/D\")\ntree.Branch(\"uncCovXX\",uncCovXX,\"uncCovXX/D\")\ntree.Branch(\"uncCovYY\",uncCovYY,\"uncCovYY/D\")\ntree.Branch(\"uncCovZZ\",uncCovZZ,\"uncCovZZ/D\")\ntree.Branch(\"bscChisq\",bscChisq,\"bscChisq/D\")\ntree.Branch(\"tarChisq\",tarChisq,\"tarChisq/D\")\ntree.Branch(\"eleP\",eleP,\"eleP/D\")\ntree.Branch(\"eleTrkChisq\",eleTrkChisq,\"eleTrkChisq/D\")\ntree.Branch(\"eleTrkHits\",eleTrkHits,\"eleTrkHits/D\")\ntree.Branch(\"eleTrkD0\",eleTrkD0,\"eleTrkD0/D\")\ntree.Branch(\"eleTrkLambda\",eleTrkLambda,\"eleTrkLambda/D\")\ntree.Branch(\"eleTrkZ0\",eleTrkZ0,\"eleTrkZ0/D\")\ntree.Branch(\"eleTrkD0Err\",eleTrkD0Err,\"eleTrkD0Err/D\")\ntree.Branch(\"eleTrkLambdaErr\",eleTrkLambdaErr,\"eleTrkLambdaErr/D\")\ntree.Branch(\"eleTrkZ0Err\",eleTrkZ0Err,\"eleTrkZ0Err/D\")\ntree.Branch(\"posP\",posP,\"posP/D\")\ntree.Branch(\"posTrkChisq\",posTrkChisq,\"posTrkChisq/D\")\ntree.Branch(\"posTrkHits\",posTrkHits,\"posTrkHits/D\")\ntree.Branch(\"posTrkD0\",posTrkD0,\"posTrkD0/D\")\ntree.Branch(\"posTrkLambda\",posTrkLambda,\"posTrkLambda/D\")\ntree.Branch(\"posTrkZ0\",posTrkZ0,\"posTrkZ0/D\")\ntree.Branch(\"posTrkD0Err\",posTrkD0Err,\"posTrkD0Err/D\")\ntree.Branch(\"posTrkLambdaErr\",posTrkLambdaErr,\"posTrkLambdaErr/D\")\ntree.Branch(\"posTrkZ0Err\",posTrkZ0Err,\"posTrkZ0Err/D\")\n\nfor entry in xrange(events.GetEntries()):\n\tevents.GetEntry(entry)\n\ttriEndZ[0] = events.triEndZ\n\tuncVX[0] = events.uncVX\n\tuncVY[0] = events.uncVY\n\tuncVZ[0] = events.uncVZ\n\tuncP[0] = events.uncP\n\tuncChisq[0] = events.uncChisq\n\tuncM[0] = events.uncM\n\tuncTargProjX[0] = events.uncTargProjX\n\tuncTargProjY[0] = events.uncTargProjY\n\tuncTargProjXErr[0] = events.uncTargProjXErr\n\tuncTargProjYErr[0] = events.uncTargProjYErr\n\tuncCovXX[0] = events.uncCovXX\n\tuncCovYY[0] = events.uncCovYY\n\tuncCovZZ[0] = events.uncCovZZ\n\tbscChisq[0] = events.bscChisq\n\ttarChisq[0] = events.tarChisq\n\teleP[0] = events.eleP\n\teleTrkChisq[0] = events.eleTrkChisq\n\teleTrkHits[0] = events.eleTrkHits\n\teleTrkD0[0] = events.eleTrkD0\n\teleTrkLambda[0] = events.eleTrkLambda\n\teleTrkZ0[0] = events.eleTrkZ0\n\teleTrkD0Err[0] = events.eleTrkD0Err\n\teleTrkLambdaErr[0] = events.eleTrkLambdaErr\n\teleTrkZ0Err[0] = events.eleTrkZ0Err\n\tposP[0] = events.posP\n\tposTrkChisq[0] = events.posTrkChisq\n\tposTrkD0[0] = events.posTrkD0\n\tposTrkLambda[0] = events.posTrkLambda\n\tposTrkZ0[0] = events.posTrkZ0\n\tposTrkD0Err[0] = events.posTrkD0Err\n\tposTrkLambdaErr[0] = events.posTrkLambdaErr\n\tposTrkZ0Err[0] = events.posTrkZ0Err\n\tzbin = reweight.FindBin(events.triEndZ)\n\tcopy = reweight.GetBinContent(zbin)\n\tfor i in range(int(copy)):\n\t\ttree.Fill()\n\tif((copy - int(copy)) > np.random.random()):\n\t\ttree.Fill()\n\nrootfile.Write()\nrootfile.Close()","sub_path":"final/data_aug/ReweightSignal.py","file_name":"ReweightSignal.py","file_ext":"py","file_size_in_byte":6765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"602418401","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport glob\nimport datetime\nimport glob\nimport stanza\nimport pandas as pd\nimport time\nimport sys\n\n\n# In[2]:\n\n\ndef filetime(file):\n year=file.split('/')[-1][5:9]\n month=file.split('/')[-1][10:12]\n day=file.split('/')[-1][13:15]\n hour=file.split('/')[-1][16:18]\n return [int(each) for each in [year, month, day, hour]]\n\n\n# In[3]:\n\n\nstanza.download('hu')\nnlp = stanza.Pipeline('hu')\n\n\n# In[ ]:\n\n\ndef onlywithneighbours(ofthislist):\n try:\n filtered = [each for each in ofthislist \n if each+1 in ofthislist or each-1 in ofthislist]\n except TypeError:\n filtered = [each for each in ofthislist \n if str(int(each)+1) in ofthislist or str(int(each)-1) in ofthislist]\n return filtered\n\n\n# In[ ]:\n\n\ndef split_into_numerical_sequences(inlist):\n\n inlist=sorted(inlist)\n\n breakindeces=[i for i,j in enumerate(inlist)\n if (j+1 not in inlist and j in inlist)]\n\n sublists=[]\n for index, each in enumerate(breakindeces):\n if index==0:\n sublists.append([x for x in inlist\n if x<=inlist[each]])\n if index!=0:\n sublists.append([x for x in inlist\n if x<=inlist[each] and x>inlist[breakindeces[index-1]]])\n\n return sublists\n\n\n# In[ ]:\n\n\ndef stanzanamesearch(text):\n\n try: doc = nlp(text)\n except IndexError: return []\n \n propns_and_their_positions_dictlist = [{\n #word.id:word.lemma\n word.id:word.text\n for word in sentence.words if word.upos == 'PROPN'}\n for sentence in doc.sentences]\n\n propns_with_at_least_one_propn_neighbour = [[\n eachdict[eachkey]\n for eachkey in sorted(onlywithneighbours(list(eachdict.keys())))]\n for eachdict in propns_and_their_positions_dictlist]\n\n propn_ids_with_at_least_one_propn_neighbour = [[\n int(eachkey)\n for eachkey in sorted(onlywithneighbours(list(eachdict.keys())))]\n for eachdict in propns_and_their_positions_dictlist]\n\n propn_id_sequences_with_at_least_one_propn_neighbour=[\n split_into_numerical_sequences(eachsublist)\n for eachsublist in propn_ids_with_at_least_one_propn_neighbour]\n\n res=[]\n for sentenceindex, eachsentence in enumerate(propn_id_sequences_with_at_least_one_propn_neighbour):\n for sequenceindex, eachsequence in enumerate(eachsentence):\n name=[]\n for wordindex, eachword in enumerate(eachsequence):\n name.append(propns_and_their_positions_dictlist[sentenceindex][str(eachword)])\n name=' '.join(name)\n res.append(name)\n\n return list(set(res))\n\n\n# In[ ]:\n\n\ndef validalias(alias):\n if len(alias.strip()) > 5 and len(alias.strip().split(' ')) > 1: return True\n else: return False\n\n\n# In[ ]:\n\n\ndef matchfinder(text,searchforthese):\n matches=[alias\n for persondata_searchtarget in searchforthese\n for alias in persondata_searchtarget\n if validalias(alias) and alias.lower() in str(text).lower()]\n return matches\n\n\n# In[ ]:\n\n\ndef fillextracols(whichdictionary, whichrowtofill, withthislist, unlessitslongerthanthis):\n if not len(withthislist) > unlessitslongerthanthis and len(withthislist)>0:\n for i, e in enumerate(withthislist):\n targetdf.loc[whichrowtofill,whichdictionary+str(i)]=e\n\n\n# In[ ]:\n\n\ndef prepare_extra_columns(num_of_columns_for_each_dict):\n for each in num_of_columns_for_each_dict:\n for index in range(num_of_columns_for_each_dict[each]):\n targetdf[each + str(index)]=''\n\n\n# In[ ]:\n\n\nclass dictionary_class:\n def __init__(self, name, maxcolnum, searchlist=None, geo=False):\n self.name = name\n self.maxcolnum = maxcolnum\n self.searchlist = searchlist\n self.geo = geo\n\n\n# In[ ]:\n\n\ndef searchlist_maker(csv,excelfile=False,multisheet=False,headerwechoose='name_list',**kwargs):\n \n if not multisheet:\n if excelfile: persondatadict = pd.read_excel(csv)\n\n else:\n persondatadict = pd.read_csv(csv)\n\n if 'alias_separator' in kwargs:\n persondata_searchlist = [[eachalias.strip()\n for eachalias in eachperson.split(kwargs['alias_separator'])]\n for eachperson in persondatadict[headerwechoose]\n if type(eachperson) != float]\n else:\n persondata_searchlist = [[each]\n for each in persondatadict[headerwechoose]]\n\n if multisheet:\n xls=pd.ExcelFile(csv)\n dfs=[pd.read_excel(xls,sheet) for i, sheet in enumerate(xls.sheet_names)]\n persondata_searchlist=[[name] for df in dfs for name in df['name_list'] if type(name) is not float]\n \n return persondata_searchlist\n\n\n# In[ ]:\n\n\ndictionaries=[\ndictionary_class('person_data',\n 10,\n searchlist_maker('/mnt/volume/jupyter/szokereso/person_data-1592394309231_utf8.csv',alias_separator='|')),\ndictionary_class('wikilist',\n 5,\n searchlist_maker('/mnt/volume/jupyter/szokereso/A_negyedik_Orbán-kormany_allamtitkarainak_listaja.csv')),\ndictionary_class('stanza',\n 10),\ndictionary_class('settlement_list',\n 5,\n searchlist_maker('/mnt/volume/jupyter/szokereso/List of Settlements_m2.xlsx', excelfile=True,headerwechoose='settlement_name'),\n geo=True),\ndictionary_class('szotar_2.1',\n 10,\n searchlist_maker('/mnt/volume/jupyter/szokereso/szotar_2.1.xlsx',multisheet=True))\n ]\n\n\n# In[ ]:\n\n\ndef get_files_sorted_by_date_after_a_date(look_for_this_pattern,cutoffdate):\n \n csvs = glob.glob(look_for_this_pattern)\n datetimes=[datetime.datetime(int(each.split('/')[-1][5:9]),\n int(each.split('/')[-1][10:12]),\n int(each.split('/')[-1][13:15]),\n int(each.split('/')[-1][16:18]),\n int(each.split('/')[-1][19:21]),\n int(each.split('/')[-1][22:24])) for each in csvs]\n\n dt_csvs_filtered=[[dt, csv] for dt, csv in zip(datetimes,csvs) if dt > datetime.datetime(*cutoffdate)]\n \n sorted_filtered_csvs = [csv\n for _, csv in sorted(\n zip([eachpair[0] for eachpair in dt_csvs_filtered],\n [eachpair[1] for eachpair in dt_csvs_filtered]))]\n \n return sorted_filtered_csvs\n\n\n# In[ ]:\n\n\ndebugmode = False\nwildcard = '/mnt/volume/anagy/mediascraper/mediaScraper/output/data*csv'\n\ntodofiles=get_files_sorted_by_date_after_a_date('/mnt/volume/anagy/mediascraper/mediaScraper/output/data*csv',\n [2020,7,6,0])\nwhile len(todofiles) != 0:\n print('processing: '+todofiles[0]) \n \n targetcsv=todofiles[0]\n try:\n targetdf = pd.read_csv(targetcsv)\n\n prepare_extra_columns({dictionary.name: dictionary.maxcolnum for dictionary in dictionaries})\n\n cells = list(targetdf['TEXT'])\n\n start_time = time.time()\n for idictionary, dictionary in enumerate(dictionaries):\n if idictionary==2 or not debugmode:\n for icell, cell in enumerate(cells):\n if type(cell) is not float:\n if icell > -1 or not debugmode:\n if icell%10==0: print(icell)\n if dictionary.searchlist is not None:\n fillextracols(dictionary.name,icell,matchfinder(cell,dictionary.searchlist),dictionary.maxcolnum)\n if dictionary.searchlist is None:\n fillextracols(dictionary.name,icell,stanzanamesearch(cell),dictionary.maxcolnum)\n end_time = time.time()\n print(\"--- %s seconds ---\" % (time.time() - start_time))\n targetdf.to_csv('/mnt/volume/jupyter/szokereso/resultfiles/'+targetcsv.split('/')[-1].split('.')[0]+'_szokereso_result.csv')\n print(targetcsv)\n except KeyboardInterrupt:\n print('KeyboardInterrupt')\n break\n except:\n the_type, the_value, the_traceback = sys.exc_info()\n outlist = [the_type, the_value, targetcsv, dictionary.name, icell]\n with open('/mnt/volume/jupyter/szokereso/resultfiles/'+targetcsv.split('/')[-1].split('.')[0]+'_ERRORLOG.txt', 'w') as f:\n for item in outlist:\n f.write(\"%s\\n\" % item)\n \n todofiles=get_files_sorted_by_date_after_a_date('/mnt/volume/anagy/mediascraper/mediaScraper/output/data*csv',\n filetime(todofiles[0])[:3]+[filetime(todofiles[0])[-1]+1]) # hour increased by 1\n\n\n# In[ ]:\n\n\nget_ipython().system('ls')\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"ujfajlnezo2.py","file_name":"ujfajlnezo2.py","file_ext":"py","file_size_in_byte":8859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"180780964","text":"#!/usr/bin/python\n#coding=utf-8\n#gridlayout2.py\n\nimport sys\nfrom PyQt4 import QtGui\n\nclass GridLayout(QtGui.QWidget):\n def __init__(self,parent = None):\n QtGui.QWidget.__init__(self)\n\n self.setWindowTitle('grid layout')\n\n title = QtGui.QLabel('title')\n author = QtGui.QLabel('Author')\n review = QtGui.QLabel('Review')\n\n titleEdit = QtGui.QLineEdit()\n authorEdit = QtGui.QLineEdit()\n reviewEdit = QtGui.QLineEdit()\n\n grid = QtGui.QGridLayout()\n grid.setSpacing(10)#同行间隔10个字距\n\n grid.addWidget(title,1,0)\n grid.addWidget(titleEdit,1,1)\n\n grid.addWidget(author,2,0)\n grid.addWidget(authorEdit,2,1)\n\n grid.addWidget(review,3,0)\n grid.addWidget(reviewEdit,3,1,5,1)#行跨度为5 列跨度为1\n\n self.setLayout(grid)\n self.resize(350,300)\n\napp = QtGui.QApplication(sys.argv)\nqb = GridLayout()\nqb.show()\nsys.exit(app.exec_())","sub_path":"04_4.py","file_name":"04_4.py","file_ext":"py","file_size_in_byte":960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"95627101","text":"# 输入文件解析\n# 修正指定位置的数值参数\n\n# by twocui\n# 20170322\n# v 0.1\n\n\ndef Input(Path, Ifile_name, Ilocal, x):\n # file-原始文件 local-需调整变量位置\n import re\n\n # 输入文件完整路径\n Ipath = Path + '/' + Ifile_name\n\n # 定义匹配规则\n p = re.compile(r'[-+]?[0-9]*\\.?[0-9]')\n\n # 查找并修正内容\n f = open(Ipath, \"r\")\n lines = f.readlines()\n for i in range(len(Ilocal)):\n line = lines[Ilocal[i][0]]\n line_findall = p.findall(line)\n line_split = p.split(line)\n print(line_split)\n line_pro = ''\n for j in range(len(line_findall)):\n if j is Ilocal[i][1]:\n line_findall[j] = x[i]\n line_pro += line_split[j] + str(line_findall[j])\n line_pro += line_split[j + 1]\n lines[Ilocal[i][0]] = line_pro\n\n # 写入修改后的内容\n # open(Ipath, 'w').writelines(lines)\n\n return lines\n\n\n#################################################################\n# ########################定义测试函数###########################\n#################################################################\n\n# 定义输入\nPath = 'D:/GitHub/IEO/test/Abaqus_beam'\nIfile_name = 'Beam.py'\n\nIlocal = [[37, 0]]\nx = [0.12]\n\n# 执行运算\nlines = Input(Path, Ifile_name, Ilocal, x)\n","sub_path":"Input.py","file_name":"Input.py","file_ext":"py","file_size_in_byte":1324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"609371024","text":"import cv2\nfrom cv2 import cv\n\n\nout_dir=\"/home/brl/crop_images/\"\nimg_file=\"/home/brl/55.jpg\"\nimg=cv2.imread(img_file)\nwidth=img.shape[0]\nheight=img.shape[1]\nresize_width=300\nresize_height=300\nwidth_ratio=width/resize_width\nheight_ratio=height/resize_height\ncount=0\nfor i in range(width_ratio):\n for j in range(height_ratio):\n resize_img=img[i*resize_width:(i+1)*resize_width,j*resize_height:(j+1)*resize_height]\n cv2.imwrite(out_dir+img_file.split(\"/\")[-1].split(\".\")[0]+\"_\"+str(count)+\".jpg\",resize_img)\n count=count+1\n\n\n","sub_path":"util/crop_images.py","file_name":"crop_images.py","file_ext":"py","file_size_in_byte":547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"598181588","text":"from threading import *\r\n\r\nimport time\r\n\r\n\r\nclass RacingCircuit:\r\n\r\n def busyTracks(self):\r\n\r\n t = current_thread()\r\n\r\n print(\"{} Entered Busy Tracks\".format(t.name))\r\n\r\n lap = 0\r\n\r\n while (lap < 5):\r\n\r\n if (t.name == \"Car\"):\r\n\r\n print(\"brrrommsss\")\r\n\r\n else:\r\n\r\n print(\"vrrrommsss\")\r\n\r\n time.sleep(1)\r\n\r\n lap += 1\r\n\r\n print(\"Lap = {}\".format(lap))\r\n\r\n print(\"{} Leaving Busy Tracks\".format(t.name))\r\n\r\n\r\nclass Bike(Thread):\r\n\r\n def __init__(self):\r\n Thread.__init__(self, name=\"Bike\")\r\n\r\n def run(self):\r\n print(\"Bike Starts Journey\")\r\n\r\n b = RacingCircuit()\r\n\r\n b.busyTracks()\r\n\r\n print(\"Bike Ends Journey\")\r\n\r\n\r\nclass Car(Thread):\r\n\r\n def __init__(self):\r\n Thread.__init__(self, name=\"Car\")\r\n\r\n def run(self):\r\n print(\"Car Starts Journey\")\r\n\r\n a = RacingCircuit()\r\n\r\n a.busyTracks()\r\n\r\n print(\"Car Ends Journey\")\r\n\r\n\r\nmycar = Car()\r\n\r\nmycar.start()\r\n\r\nmybike = Bike()\r\n\r\nmybike.start()\r\n","sub_path":"Thread Synchronization/LocalVariable.py","file_name":"LocalVariable.py","file_ext":"py","file_size_in_byte":1095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"372591797","text":"import config\nimport subprocess\nimport os\nimport numpy as np\nimport scipy.stats\nimport random\n\nimport tensorflow as tf\n\nimport load_data\nimport model\nimport argparse\n\nCONF = config.load_config()\nFLAGS = None\n\ndef predict(sess, maps_placeholder, is_training, logits, filename):\n\n # mapping protein\n print('# Scoring '+filename)\n mapFilename = CONF.TEMP_PATH + 'map_'+str(os.getpid())+ '_pred.bin'\n subprocess.call(\n [CONF.MAP_GENERATOR_PATH, \"--mode\", \"map\", \"-i\", filename, \"--native\", \"-m\", \"24\", \"-v\", \"0.8\", \"-o\",\n mapFilename])\n if not os.path.exists(mapFilename):\n print('# Mapping failed, ignoring protein')\n return None\n predDataset = load_data.read_data_set(mapFilename)\n os.remove(mapFilename)\n\n\n preds = []\n # compute prediction res by res\n for i in range(predDataset.num_res):\n f_map = np.reshape(predDataset.maps[i], (1, model.GRID_VOXELS * model.NB_TYPE))\n feed_dict = {maps_placeholder: f_map, is_training: False}\n pred = sess.run(logits,feed_dict=feed_dict)\n preds.append(pred)\n outline='RES {:4d} {:c} {:5.4f}'.format(predDataset.meta[i][0], predDataset.meta[i][1], pred)\n print(outline)\n #print(predDataset.meta[i][0]+)\n #print(pred)\n\ndef main():\n sess = tf.Session()\n print('Restore existing model: %s' % CONF.MODEL_PATH)\n saver = tf.train.import_meta_graph(CONF.MODEL_PATH + '.meta')\n saver.restore(sess, CONF.MODEL_PATH)\n\n graph = tf.get_default_graph()\n\n # getting placeholder for input data and output\n maps_placeholder = graph.get_tensor_by_name('main_input:0')\n is_training = graph.get_tensor_by_name('is_training:0')\n logits = graph.get_tensor_by_name(\"main_output:0\")\n\n if FLAGS.structure != None :\n predict(sess, maps_placeholder, is_training, logits, FLAGS.structure)\n if FLAGS.directory != None :\n for filename in os.listdir(FLAGS.directory):\n predict(sess, maps_placeholder, is_training, logits, FLAGS.directory+'/'+filename)\n\n\n\n\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument(\n '-d',\n '--directory',\n type=str,\n help='Path to the validation data'\n )\n parser.add_argument(\n '-s',\n '--structure',\n type=str,\n help='Path to the structure to score (in pdb format)'\n ) \n FLAGS = parser.parse_args()\n main()\n\n\n","sub_path":"tools/Ornate/score.py","file_name":"score.py","file_ext":"py","file_size_in_byte":2373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"574071743","text":"from django.core.management.base import BaseCommand\nfrom django.contrib.auth.models import User\n\nimport random\n\nfrom enadum_login.models import Professor, Aluno\nfrom enadum_instituicao.models import Instituicao, Curso, Turma\nfrom enadum_prof.models import (\n Disciplina, Questao, Resposta, Prova\n)\nfrom enadum_result.models import ResultadoProva\n\nclass Command(BaseCommand):\n help = 'Pré-popula banco com dados.'\n \n def _generator_provas(self, professor, disciplina):\n # cria Questões\n questoes = []\n for n in range(1,11):\n num = str(n)\n enunciado = '{} * {} = ?'.format(num, num)\n questao = Questao.objects.create(\n professor=professor,\n disciplina=disciplina,\n enunciado=enunciado\n )\n questoes.append(questao)\n\n # cria Respostas\n i = 1\n for questao in questoes:\n for n in range(i,i+5):\n status = True if n is i else False\n resposta = Resposta.objects.create(\n questao=questao,\n sentenca=str(n*n),\n correta=status\n )\n i += 1\n\n # cria Prova\n num = Prova.objects.all().count()\n num += 1\n prova = Prova.objects.create(\n professor=professor,\n disciplina=disciplina,\n titulo='Prova #' + str(num) + ' de ' + disciplina.nome\n )\n for questao in questoes:\n prova.questoes.add(questao)\n\n self.stdout.write(\n self.style.SUCCESS(\n 'Questões, Respostas e Provas de ' + disciplina.nome + \\\n ' criadas.'\n )\n )\n\n return prova\n\n def _generator_resultados(self, aluno, prova):\n resultado = ResultadoProva.objects.create(\n prova=prova,\n aluno=aluno\n )\n\n # associa respostas do aluno, com uma pequena randomização\n respostas = []\n questoes = prova.questoes.all()\n for questao in questoes:\n flip = random.randint(0, 7)\n if flip >= 4:\n resposta = questao.respostas.get(correta=True)\n else:\n resposta = questao.respostas.filter(correta=False)[flip]\n respostas.append(resposta)\n\n resultado.respostas.add(*respostas)\n\n self.stdout.write(\n self.style.SUCCESS(\n 'ResultadoProva de ' + prova.titulo + ' do aluno ' + \\\n aluno.user.get_full_name() + ' criado.'\n )\n )\n\n def _generator(self):\n # cria User do Professor\n userAgesandro = User(\n username='p00001',\n first_name='Agesandro',\n last_name='Scarpioni',\n email='vitorsermino@gmail.com'\n )\n userAgesandro.set_password('123')\n userAgesandro.save()\n userSelmini = User(\n username='p00002',\n first_name='Marcos',\n last_name='Selmini',\n email='vitorsermino@gmail.com'\n )\n userSelmini.set_password('123')\n userSelmini.save()\n\n self.stdout.write(\n self.style.SUCCESS('Users criados.')\n )\n \n # cria Professores\n agesandro = Professor.objects.create(user=userAgesandro)\n selmini = Professor.objects.create(user=userSelmini)\n self.stdout.write(\n self.style.SUCCESS('Professores criados.')\n )\n\n # cria Instituição\n fiap = Instituicao.objects.create(\n nome='Faculdade de Informática e Administração Paulista',\n abreviacao='FIAP',\n )\n self.stdout.write(\n self.style.SUCCESS('Instituição %s criada.' % fiap)\n )\n\n # cria Cursos\n sistemas = Curso.objects.create(\n nome='Sistemas de Informação',\n codigo=Curso.SIS_INF,\n instituicao=fiap,\n )\n engenharia = Curso.objects.create(\n nome='Engenharia de Software',\n codigo=Curso.ENG_SOFT,\n instituicao=fiap,\n )\n\n self.stdout.write(\n self.style.SUCCESS('Cursos criados.')\n )\n\n # cria Disciplinas\n tecnicas = Disciplina.objects.create(\n nome='Técnicas de Programação III',\n curso=sistemas,\n )\n fundamentos = Disciplina.objects.create(\n nome='Fundamentos da Programação',\n curso=engenharia,\n )\n\n self.stdout.write(\n self.style.SUCCESS('Disciplinas criadas.')\n )\n\n # cria User do Aluno\n userVitor = User(\n username='rm69013',\n first_name='Vitor',\n last_name='Sermino Rosa',\n email='vitorsermino@gmail.com',\n )\n userVitor.set_password('123')\n userVitor.save()\n\n userJoao = User(\n username='rm00001',\n first_name='João',\n last_name='da Silva',\n email='vitorsermino@gmail.com',\n )\n userJoao.set_password('123')\n userJoao.save()\n\n self.stdout.write(\n self.style.SUCCESS('Users criados.')\n )\n\n # cria Aluno\n vitor = Aluno.objects.create(\n user=userVitor,\n instituicao=fiap,\n )\n joao = Aluno.objects.create(\n user=userJoao,\n instituicao=fiap,\n )\n\n self.stdout.write(\n self.style.SUCCESS('Alunos criados.')\n )\n\n # cria Turmas\n sis = Turma.objects.create(\n curso=sistemas,\n ano=4,\n nome='4SIS',\n )\n eng = Turma.objects.create(\n curso=engenharia,\n ano=4,\n nome='4ENG',\n )\n\n self.stdout.write(\n self.style.SUCCESS('Turmas criadas.')\n )\n\n # cria Questoes, Respostas e Provas\n provaTecnicas1 = self._generator_provas(agesandro, tecnicas)\n self._generator_resultados(vitor, provaTecnicas1)\n self._generator_resultados(joao, provaTecnicas1)\n provaTecnicas2 = self._generator_provas(agesandro, tecnicas)\n self._generator_resultados(vitor, provaTecnicas2)\n self._generator_resultados(joao, provaTecnicas2)\n\n provaFundamentos = self._generator_provas(selmini, fundamentos)\n self._generator_resultados(vitor, provaFundamentos)\n\n # realiza associações ManyToMany\n fiap.professores.add(agesandro)\n\n agesandro.cursos.add(sistemas)\n agesandro.disciplinas.add(tecnicas)\n selmini.cursos.add(engenharia)\n selmini.disciplinas.add(fundamentos)\n\n vitor.cursos.add(sistemas, engenharia)\n joao.cursos.add(sistemas)\n\n sis.alunos.add(vitor, joao)\n sis.professores.add(agesandro)\n eng.alunos.add(vitor)\n eng.professores.add(selmini)\n\n self.stdout.write(\n self.style.SUCCESS('Associações entre os modelos realizadas.')\n )\n\n def handle(self, *args, **kwargs):\n self._generator()\n\n","sub_path":"enadum/apps/enadum_login/management/commands/gera_dados.py","file_name":"gera_dados.py","file_ext":"py","file_size_in_byte":7087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"190300663","text":"from __future__ import unicode_literals\nfrom django.db import models\n\nimport datetime\nimport operator\n\nfrom account.models import Account\nfrom service.models import Service\nfrom source_utils.starters import CommonInfo, CommonAccountDetails\nfrom django.db import models\nfrom django.db.models.signals import pre_save, post_save\nfrom django.shortcuts import get_object_or_404\nfrom django.urls import reverse\nfrom django.utils.text import slugify\nfrom django.utils.translation import ugettext_lazy as _\n\n\n# def update_serv():\n# services = Service.objects.all()\n# for service in services:\n# service.save()\n\n\ndef upload_location(instance, filename):\n return \"%s/%s\" %(instance.slug, filename)\n\nclass StaffMember(CommonAccountDetails):\n\n base_account = models.OneToOneField(\n Account,\n verbose_name = 'Staff Member',\n related_name='staff_account',\n on_delete=models.CASCADE\n )\n\n # skills = models.ForeignKey(\n # Service,\n # null=True,\n # blank=True,\n # verbose_name = 'skills',\n # related_name='skill_set',\n # on_delete=models.CASCADE\n # )\n\n skill_set = models.ManyToManyField(\n # 'Available Skills',\n Service,\n related_name='staff_skills',\n # null=True,\n blank=True\n )\n\n def __str__(self):\n return \"{} {} ({})\".format(\n self.base_account.user.first_name,\n self.base_account.user.last_name,\n self.pk\n )\n\n def get_absolute_url(self):\n return reverse(\n \"staff:staff_update\",\n kwargs={'pk': self.pk}\n )\n\n # def get_avail_url(self):\n # return reverse(\n # \"staff:staff_avail\",\n # kwargs={'slug': self.slug}\n # )\n\n def get_friendly_name(self):\n return \"{} {}.\".format(\n self.base_account.user.first_name,\n self.base_account.user.last_name[0]\n )\n\n def get_address(self):\n return \"{}\\n{}, {} {}\".format(\n self.street_address, \n self.city, \n self.state, \n self.zip_code\n )\n\n def save(self, *args, **kwargs):\n super(StaffMember, self).save(*args, **kwargs)\n self.base_account.user.is_staff = True\n self.base_account.user.save()\n # services = Service.objects.all()\n # for service in services:\n # service.save()\n # service.save_m2m()\n\n # def update_serv(self):\n # services = Service.objects.all()\n # for service in services:\n # service.save()\n\ndef pre_save_staff(sender, instance, *args, **kwargs):\n instance.slug = slugify(instance.__str__())\n\npre_save.connect(pre_save_staff, sender=StaffMember)\n\n# def post_save_staff(sender, instance, *args, **kwargs):\n# post_save.connect(post_save_staff, sender=StaffMember)\n\n# update_serv()\n\n# # print(hjkh)\n\n# post_save.connect(post_save_staff, sender=StaffMember)\n","sub_path":"staffer/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"430317676","text":"import numpy as np\nfrom math import pi\nfrom pymicro.crystal.lattice import *\nfrom matplotlib import pyplot as plt, cm\nfrom pymicro.xray.laue import *\nfrom pymicro.crystal.microstructure import Orientation\nfrom itertools import cycle\nfrom scipy import interpolate\n\n# lattice parameter for Nickel\na = 0.352 # nm\nni = Lattice.face_centered_cubic(a)\norientation = Orientation.cube()\n\nenergy = []\ntheta2 = []\nmin_theta = 0.1\nmax_order = 3 # maximum order considered here\n\nlines = [':', '--', '-.', '-', '.']\nline_cycler = cycle(lines)\npoint = ['<', 'o', 's']#, '*']\npoint_cycler = cycle(point)\n\n# Define a function to have most simple family planes\ndef simple_family(hkl, lattice=None, n_order=1, Verbose=False):\n orders = range(1, n_order + 1)\n if not len(hkl) == 3:\n raise ValueError('warning, family not supported: %s' % hkl)\n family = []\n l = list(hkl)\n l.sort() # miller indices are now sorted by increasing order\n (h, k, l) = (int(l[0]), int(l[1]), int(l[2]))\n if (l == k):\n hkl_list = [(k, k, h), (h, k, k)]\n elif (h == l):\n hkl_list = [(h, k, h), (k, h, h)]\n elif (k == h):\n hkl_list = [(h, h, k), (k, h, h)]\n elif (h == k == l):\n hkl_list = [(h, h, h)]\n else:\n hkl_list = [(h, k, l), (k, l, h), (l, h, k)]\n for (h, k, l) in hkl_list:\n for n in orders :\n plane = HklPlane(n * h, n * k, n * l, lattice)\n if not plane.is_in_list(family):\n family.append(plane)\n\n return family\n\n# chose families of planes\nd_hkl = []\nplanes = []\nmil_ind = []\n#family_to_plot = ['105','012','001','110','111','112','104','122','013','113','123']\nfamily_to_plot = ['112','122','133', '111']\n\n# sort the family in function of the iso : (h^2 + k^2 + l^2)\niso_list = []\nimport operator\nfamily = []\nfor hkl in family_to_plot:\n l = list(hkl)\n (h, k, l) = (int(l[0]), int(l[1]), int(l[2]))\n iso = h**2 + k**2 + l**2\n iso_list.append((iso, hkl))\n iso_list.sort(key=operator.itemgetter(0))\nfor i in range(len(iso_list)):\n (num, iso_p) = iso_list[i]\n family.append(iso_p)\n\n\n# Compute pic position for all the hkl planes\nfor i in range(len(family)):\n planes.append(simple_family(family[i], ni, max_order))\n for hkl in planes[i]:\n (E, theta) = select_lambda(hkl, orientation)\n if E < 0:\n E *= -1.\n theta *= -1.\n if abs(theta) < min_theta * np.pi / 180: # skip angles < min_theta deg\n continue\n energy.append(E)\n theta2.append(2 * theta * 180 / pi)\n d_hkl.append(hkl.interplanar_spacing())\n mil_ind.append(hkl.miller_indices())\n print(hkl.miller_indices(), E, 2 * theta * 180 / pi)\n\n'''\nBragg relation gives:\n\n2d\\sin\\theta = \\lambda or (h^2 + k^2 + l^2) = 2.E.a\\sin\\theta / 1.24\n\nwith d = a / (h^2 + k^2 + l^2)^0.5 (cubic lattice)\n\n(h^2 + k^2 + l^2) is inversely prop to the d spacing, and contains the multiplicity n\n'''\n\n# construct a map of the accessible d-spacing = f(E, 2*\\theta)\nenergies = np.linspace(0, 120, 600, endpoint=False) + 0.2\ntt_angles = np.linspace(0, 90, 360, endpoint=False) + 0.5\nd_spacing = np.empty((len(energies), len(tt_angles)), dtype=float)\naa, ee = np.meshgrid(tt_angles, energies) ## aa and ee are 2D arrays containing the angle and energie values\nd_spacing = 1.24 / (2 * ee * np.sin(0.5 * aa * np.pi / 180)) # just apply Bragg formula\n\nvalues = []\nfor i in range(len(family)):\n hkl_indices = list(family[i])\n (h, k, l) = (int(hkl_indices[0]), int(hkl_indices[1]), int(hkl_indices[2]))\n values.append(h**2 + k**2 + l**2)\n\n# create a figure to display our results\nfig = plt.figure(1, figsize=(18, 6))\nax1 = fig.add_subplot(121)\nim1 = plt.imshow(d_spacing.T, origin='lower', extent=[0, 120, 0, 90], interpolation='nearest')\nfor N in values:\n plt.plot(energies, 2 * np.arcsin(1.24 * np.sqrt(N) / (2 * a * energies)) * 180 / np.pi,\n line_cycler.next(), color='0.75', linewidth=2.5, label = 'iso = %d' % N)\nplt.plot(energy, theta2, 'w*', markersize=12)\nplt.clim(0, a)\nplt.ylim(0, 90)\nplt.ylabel(r'Angle $2\\theta$ (degrees)')\nplt.xlim(0, 120)\nplt.xlabel('Energy (keV)')\nplt.colorbar(im1, fraction=0.034, pad=0.04)\nplt.title('Accessible d-spacing by X-ray diffraction (nm)')\nplt.legend()\n\n\n# now plot (h^2 + k^2 + l^2)\nax2 = fig.add_subplot(122)\nim2 = plt.imshow((a / d_spacing).T, origin='lower', extent=[0, 120, 0, 90], interpolation='nearest')\n\nfor i in range (len(energy)):\n (h, k, l) = mil_ind[i]\n plt.plot(energy[i], theta2[i], 'w' + point_cycler.next(), markersize=5, label= mil_ind[i])\n plt.annotate('(%d.%d.%d)' % (h, k, l), xy = (energy[i]+1, theta2[i]), horizontalalignment='left',\n verticalalignment='center', fontsize=10)\nplt.xlabel('Energy (keV)')\nplt.xlim(0, 120)\nplt.ylabel(r'Angle $2\\theta$ (degrees)')\nplt.ylim(0, 90)\nplt.title(r'$\\sqrt{h^2 + k^2 + l^2}$, order = %d' % max_order)\nplt.colorbar(im2, fraction=0.034, pad=0.04)\nplt.clim(0, 26)\n#plt.legend(numpoints=1)\nplt.savefig('Xray_illustrations/theta_source.pdf')\nplt.show()\n\n# New plot to put in the beamer for meeting #3\nmy_dpi = 96\nplt.figure(figsize=(800 / my_dpi, 600 / my_dpi), dpi=my_dpi)\nplt.imshow(d_spacing.T, origin='lower', extent=[0, 120, 0, 90], interpolation='nearest')\nfor N in values:\n plt.plot(energies, 2 * np.arcsin(1.24 * np.sqrt(N) / (2 * a * energies)) * 180 / np.pi,\n line_cycler.next(), color='0.75', linewidth=2.5, label = 'iso = %d' % N)\nplt.plot(energy, theta2, 'w*', markersize=12)\nplt.clim(0, a)\nplt.ylim(0, 90)\nplt.ylabel(r'Angle $2\\theta$ (degrees)')\nplt.xlim(0, 120)\nplt.xlabel('Energy (keV)')\nplt.colorbar(fraction=0.034, pad=0.04)\nplt.title('Accessible d-spacing by X-ray diffraction (nm)')\nplt.legend()\nplt.show()\n\nplt.figure(figsize=(800 / my_dpi, 600 / my_dpi), dpi=my_dpi)\nplt.imshow((a / d_spacing).T, origin='lower', extent=[0, 120, 0, 90], interpolation='nearest')\n\nfor i in range (len(energy)):\n (h, k, l) = mil_ind[i]\n plt.plot(energy[i], theta2[i], 'w' + point_cycler.next(), markersize=5, label= mil_ind[i])\n plt.annotate('(%d.%d.%d)' % (h, k, l), xy = (energy[i]+1, theta2[i]), horizontalalignment='left',\n verticalalignment='center', fontsize=10)\nplt.xlabel('Energy (keV)')\nplt.xlim(0, 120)\nplt.ylabel(r'Angle $2\\theta$ (degrees)')\nplt.ylim(0, 90)\nplt.title(r'$\\sqrt{h^2 + k^2 + l^2}$, order = %d' % max_order)\nplt.colorbar(fraction=0.034, pad=0.04)\nplt.clim(0, 40)\nplt.show()\n\n'''Compute the impact of absorption of the Nickel'''\n\nrho_ni = 8.909 # density g.cm^-3\nthickness = 2. # mm\nenergy_max = 120 # keV - from experiments\npath = '/home/aarnaud/Documents/pymicro/pymicro/xray/data/'\nmu_rho = np.genfromtxt(os.path.join(path, 'Ni' + '.txt'), usecols=(0, 1), comments='#')\nenergy_th = mu_rho[:, 0]\ntrans = 100 * np.exp(-mu_rho[:, 1] * rho_ni * thickness / 10)\n\nf = interpolate.interp1d(energy_th, trans) # interpolate the result to have more points\nnew_energy = np.arange(5, 193, 0.1)\nnew_trans = f(new_energy)\n\n# Construct a map to see the transmission beam\ndata = np.empty([len(new_trans),len(new_energy)])\nfor i in range(len(new_trans)):\n data[i,:] = new_trans[i]\n\n\nfig = plt.figure(2, figsize=(18, 6))\nax3 = fig.add_subplot(121)\nim3 = plt.imshow(data.T, origin='lower', extent=[0, 200, 0, 90], interpolation='nearest')\nplt.plot(new_energy, new_trans, 'k-', linewidth=2.5)\nplt.ylabel('Transmission I/I0 (%)')\nplt.xlabel('Photon Energy (keV)')\nplt.colorbar(im3, fraction=0.034, pad=0.04)\nplt.title('Transmitted intensity of a X-ray beam through %d mm of Ni' %thickness)\n\n\nax4 = fig.add_subplot(122)\nim4 = plt.imshow(data.T, origin='lower', extent=[0, 200, 0, 90], interpolation='nearest')\nfor i in range (len(energy)):\n (h, k, l) = mil_ind[i]\n plt.plot(energy[i], theta2[i], 'ko', markersize=7, label= mil_ind[i])\n plt.annotate('(%d.%d.%d)' % (h, k, l), xy = (energy[i]+1, theta2[i]), horizontalalignment='left',\n verticalalignment='center', fontsize=10)\nplt.ylim(0, 90)\nplt.xlabel('Energy (keV)')\nplt.xlim(0, 120)\nplt.ylabel(r'Angle $2\\theta$ (degrees)')\nplt.title('Transmitted intensity on diffracted spots')\nplt.colorbar(im4, fraction=0.034, pad=0.04)\nplt.savefig('Xray_illustrations/transmission.pdf')\nplt.show()\n\n\n\n\nplt.figure(figsize=(800 / my_dpi, 600 / my_dpi), dpi=my_dpi)\nplt.imshow(data.T, origin='lower', extent=[0, 120, 0, 90], interpolation='nearest')\nfor i in range (len(energy)):\n (h, k, l) = mil_ind[i]\n plt.plot(energy[i], theta2[i], 'wo', markersize=7, label= mil_ind[i])\n plt.annotate('(%d.%d.%d)' % (h, k, l), xy = (energy[i]+1, theta2[i]), horizontalalignment='left',\n verticalalignment='center', fontsize=10)\nplt.ylim(0, 90)\nplt.xlabel('Energy (keV)')\nplt.xlim(0, 120)\nplt.ylabel(r'Angle 2theta (degrees)')\nplt.title('Transmitted intensity on diffracted spots for %d mm Ni' %thickness)\nplt.colorbar(fraction=0.034, pad=0.04)\nplt.clim(0,100)\nplt.savefig('Xray_illustrations/transmission.pdf')\nplt.show()\n'''\n# chose a plane and build a list of with the multiple orders from 1 to n=orders\n\nplanes = [HklPlane(n * 1, n * 0, n * 0, ni) for n in orders] # 180 deg\nplanes = [HklPlane(n * 1, n * 1, n * 0, ni) for n in orders] # 90 deg\nplanes = [HklPlane(n * 1, n * 1, n * 1, ni) for n in range(1, orders + 1)] # 70 deg\nplanes = [HklPlane(n * 0, n * 1, n * 2, ni) for n in range(1, orders + 1)] # 128 deg\nplanes = [HklPlane(n * 1, n * 1, n * 2, ni) for n in range(1, orders + 1)] # 48 deg\nplanes = [HklPlane(n * 1, n * 2, n * 2, ni) for n in range(1, orders + 1)] # 39 deg\nplanes = [HklPlane(n * 0, n * 1, n * 3, ni) for n in range(1, orders + 1)] # 143 deg\nplanes = [HklPlane(n * 1, n * 1, n * 3, ni) for n in range(1, orders + 1)] # 35 deg\nplanes = [HklPlane(n * 1, n * 2, n * 3, ni) for n in range(1, orders + 1)] # 31 deg\nplanes = [HklPlane(n * 1, n * 0, n * 5, ni) for n in range(1, orders + 1)] # 23 deg\nplanes = [HklPlane(n * 1, n * 0, n * 4, ni) for n in orders] # 28 deg\n\nplanes = [HklPlane(n * 1, n * 2, n * 3, ni) for n in orders]\np = planes[0]\nprint(p.miller_indices())\n(p_h, p_k, p_l) = p.miller_indices()\nprint('d_hkl=', p.interplanar_spacing())\n\n\n# plot the 2\\theta=f(E) for all possibles values of (h^2 + k^2 + l^2)\nvalues = [1, 2, 3, 5, 6, 9, 10, 11, 14, 17, 26] # no 7, no 22 but 26\nfor N in values:\n plt.plot(energies, 2 * np.arcsin(1.24 * np.sqrt(N) / (2 * a * energies)) * 180 / np.pi,\n '-', color='0.75')\n# now plot these curves for the chosen family and n = 1, 2, 3\nfor n in orders:\n plt.plot(energies, 2 * np.arcsin(1.24 * n / (2 * p.interplanar_spacing() * energies)) * 180 / np.pi,\n 'k' + line_cycler.next(), label='n=%d' % n)\nplt.plot(energy, theta2, 'k*', markersize=12, label='{%d%d%d}' % (p_h, p_k, p_l))\nplt.xlabel('Energy (keV)')\nplt.xlim(0, 120)\nplt.ylabel(r'Angle $2\\theta$ (degrees)')\nplt.ylim(0, 90)\nplt.legend(numpoints=1)\n'''\n'''\nenergies = np.linspace(0, 120, len(new_energy), endpoint=False) + 0.2 # same as before\nfsc_transmis = np.linspace(0, 90, 360, endpoint=False) + 0.5\ntrans_map = np.empty((len(energies), len(tt_angles)), dtype=float)\naa, ee = np.meshgrid(tt_angles, energies) ## aa and ee are 2D arrays containing the angle and energie values\n\ndata = np.zeros(len(new_trans))\nfor i in range(len(new_trans)):\n data[i,:] = new_trans[i]\n'''","sub_path":"Xray_dimensioning/theta_source.py","file_name":"theta_source.py","file_ext":"py","file_size_in_byte":11251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"344463709","text":"import re\n\n\ndef main():\n \"\"\"\n Part 1\n\n \"\"\"\n fin = open('day3.txt')\n matrix = [[0 for x in range(1000)] for y in range(1000)]\n for line in fin:\n claim = re.split('# | @ |: ', line.strip())\n i, j = claim[1].split(sep=',')\n i = int(i)\n j = int(j)\n dim = claim[2]\n m, n = dim.split(sep='x')\n for a in range(int(m)):\n for b in range(int(n)):\n matrix[i-1+a][j-1+b] += 1\n count = 0\n for i in range(1000):\n for j in range(1000):\n if matrix[i][j] > 1:\n count += 1\n\n print(count)\n \"\"\"\n Part 2\n \"\"\"\n fin = open('day3.txt')\n for line in fin:\n claim = re.split('# | @ |: ', line.strip())\n i, j = claim[1].split(sep=',')\n i = int(i)\n j = int(j)\n dim = claim[2]\n m, n = dim.split(sep='x')\n product = int(m)*int(n)\n count = 0\n for a in range(int(m)):\n for b in range(int(n)):\n if matrix[i - 1 + a][j - 1 + b] == 1:\n count += 1\n if count == product:\n print(claim)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Day3/Day3.py","file_name":"Day3.py","file_ext":"py","file_size_in_byte":1163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"545680561","text":"import os\nimport sys\nimport math\nimport csv\nimport shutil\nimport requests\nimport re\nfrom datetime import datetime\nfrom difflib import SequenceMatcher\nfrom feedgen.feed import FeedGenerator\nfrom git import Repo\nimport time\n\nminPrice = 1720\nmaxPrice = 2700\nminBeds = 1\nmaxBeds = None\nbHasPic = True\n\n# Only focus on the last __ hrs\ntimeRangeHrs = 24*3\n\n# File to which data is stored\ncsvFilename = \"listings.txt\"\n\n# folder to which we'll save things\nsaveFolder = \"feeds\"\n\n# Url to which rss feeds are exported\ngithubRepoURL = \"https://raw.githubusercontent.com/bensnell/apts-nyc/master/\"\nrepoName = \"apts-nyc\"\n\n# Refresh Minutes\nrefreshMin = 20\n\n# Maximum number of apartments to retrieve (takes a long time to get a ton)\nmaxAptsToSearch = 3000\n\n# Timeout in seconds\ntimeoutSec = 3\n\n# Tool: https://codepen.io/jhawes/pen/ujdgK\nbOneHoodPerListing = True\nbounds = {}\nbounds[((40.691111, -73.997705), (40.679219, -74.003612), (40.674112, -73.996844), (40.679467, -73.988390), (40.686652, -73.983583))] = \"CarollGardens_CobbleHill_F\"\nbounds[((40.674112, -73.996844), (40.679467, -73.988390), (40.681648, -73.975694), (40.672457, -73.969629), (40.659928, -73.980828), (40.667024, -73.995189))] = \"ParkSlope_Gowanus_DR\"\nbounds[((40.667332, -73.996660), (40.656607, -74.012609), (40.647140, -74.011767), (40.649853, -74.001741), (40.662371, -73.988654))] = \"Greenwood_DR\"\nbounds[((40.664352, -73.964613), (40.663630, -73.955147), (40.652422, -73.954009), (40.652995, -73.966709))] = \"ProspectLeffertsGardens_Q\"\nbounds[((40.666418, -73.962165), (40.665446, -73.950871), (40.669550, -73.945130), (40.678323, -73.946887), (40.683929, -73.977162), (40.672776, -73.969809))] = \"ProspectHeights_CrownHeightsNorth_245_A\"\nbounds[((40.678323, -73.946887), (40.683929, -73.977162), (40.689866, -73.980422), (40.689510, -73.972085), (40.683267, -73.950200), (40.680979, -73.916911), (40.676524, -73.917107))] = \"ClintonHill_BedStudy_AC\"\nbounds[((40.692564, -73.934033), (40.695982, -73.922097), (40.696990, -73.907325), (40.702205, -73.908643), (40.701456, -73.934403), (40.708992, -73.950296), (40.712757, -73.959701), (40.706696, -73.963308), (40.701887, -73.950095))] = \"Bushwick_Williamsburg_M\"\nbounds[((40.769745, -73.946294), (40.777085, -73.963851), (40.787943, -73.955907), (40.780391, -73.937319))] = \"Yorkville_UpperUpperEast_NQ_456\"\nbounds[((40.787943, -73.955907), (40.780391, -73.937319), (40.789252, -73.937042), (40.795049, -73.950689))] = \"LowerEastHarlem_6\"\nbounds[((40.753439, -73.913582), (40.752022, -73.930194), (40.756178, -73.936548), (40.772891, -73.921646), (40.769315, -73.913367), (40.762741, -73.915868), (40.759388, -73.908732))] = \"Astoria_MR_NW\"\nbounds[((40.753439, -73.913582), (40.757988, -73.909784), (40.748521, -73.887961), (40.743805, -73.891471))] = \"Woodside_MR\"\nbounds[((40.757962, -74.007400), (40.749790, -73.987766), (40.737340, -73.996881), (40.744125, -74.013123))] = \"Chelsea_AE_12\"\nbounds[((40.769745, -73.946294), (40.777085, -73.963851), (40.764321, -73.973008), (40.757599, -73.957019))] = \"LowerUpperEast_6_NQ\"\nbounds[((40.806426, -73.972133), (40.800501, -73.958118), (40.768016, -73.981694), (40.774089, -73.996288))] = \"UpperWest_12_BC\"\nbounds[((40.720470, -73.994254), (40.714504, -73.974829), (40.707670, -73.979015), (40.709433, -74.001661))] = \"LowerEast_F_BD\"\nbounds[((40.689678, -73.992394), (40.684185, -73.977565), (40.707027, -73.981427), (40.705107, -73.997907), (40.693915, -74.007863))] = \"BrooklynHeights_R_245_AG_F\"\n\n\n# =============================================================\n\n\ndef getWorkingDir():\n\treturn os.path.dirname(os.path.abspath(__file__))\n\ncsvPath = getWorkingDir() + \"/\" + csvFilename\nsaveFolderPath = getWorkingDir() + \"/\" + saveFolder\nif not os.path.exists(saveFolderPath):\n\tos.makedirs(saveFolderPath)\n\ndef datetime2RSSString(dt):\n\treturn dt.strftime('%Y-%m-%d %H:%M:%S') + \"-05:00\"\n\ndef inside_polygon(x, y, points):\n \"\"\"\n Return True if a coordinate (x, y) is inside a polygon defined by\n a list of verticies [(x1, y1), (x2, x2), ... , (xN, yN)].\n\n Reference: http://www.ariel.com.au/a/python-point-int-poly.html\n \"\"\"\n n = len(points)\n inside = False\n p1x, p1y = points[0]\n for i in range(1, n + 1):\n p2x, p2y = points[i % n]\n if y > min(p1y, p2y):\n if y <= max(p1y, p2y):\n if x <= max(p1x, p2x):\n if p1y != p2y:\n xinters = (y - p1y) * (p2x - p1x) / (p2y - p1y) + p1x\n if p1x == p2x or x <= xinters:\n inside = not inside\n p1x, p1y = p2x, p2y\n return inside\n\ndef clDate(stringDate):\n\treturn datetime.strptime(stringDate, '%Y-%m-%d %H:%M')\n\ndef elapsedTimeHrs(was):\n\n\tdelta = datetime.now() - was\n\thrs = delta.total_seconds() / 3600\n\treturn abs(hrs)\n\ndef similarity(a, b):\n\treturn SequenceMatcher(None, str(a), str(b)).ratio()\n\n# Load a csv (tab-separated) as an array\ndef loadCsv(path):\n\tlistOut = []\n\tif (os.path.exists(path)):\n\t\twith open(path, 'r') as fin:\n\t\t\tdata = fin.readlines()\n\t\t\tlistOut = [[i.strip(\"\\n\") for i in x.split(\"\\t\")] for x in data]\n\treturn listOut\n\n# Save (append if exists) a tab csv from a 2d array\ndef saveCsv(array2d, path):\n\twith open(path, 'a+') as fout:\n\t\tfor line in array2d:\n\t\t\tline = [str(i) for i in line]\n\t\t\tfout.write(\"\\t\".join(line) + \"\\n\")\n\n# Get 120 listings from 0 to 3000\ndef urlCL(startIndex):\n\n\turl = \"https://newyork.craigslist.org/search/aap?\"\n\turl += \"&s=\" + str(startIndex)\n\tif bHasPic: \n\t\turl += \"&hasPic=1\"\n\turl += \"&bundleDuplicates=1\"\n\tif minPrice != None:\n\t\turl += \"&min_price=\" + str(minPrice)\n\tif maxPrice != None:\n\t\turl += \"&max_price=\" + str(maxPrice)\n\tif minBeds != None:\n\t\turl += \"&min_bedrooms=\" + str(minBeds)\n\tif maxBeds != None:\n\t\turl += \"&max_bedrooms=\" + str(maxBeds)\n\turl += \"&availabilityMode=0\"\n\turl += \"&sale_date=all+dates\"\n\turl += \"&sort=date\"\n\treturn url\n\n# Remove elements from the inList that are also in the refList by a given threshold\ndef removeMatches(inList, refList, indexKeys, threshold):\n\n\tnewList = []\n\tif indexKeys == -1:\n\n\t\tfor a in inList:\n\t\t\tbAdd = True\n\t\t\tfor b in refList:\n\t\t\t\tif similarity(a, b) > threshold:\n\t\t\t\t\tbAdd = False\n\t\t\t\t\tbreak\n\t\t\tif bAdd:\n\t\t\t\tnewList.append(a)\n\n\telse:\n\n\t\tfor a in inList:\n\n\t\t\tbAdd = True\n\t\t\tfor b in refList:\n\n\t\t\t\tbAllSimilar = True\n\t\t\t\tfor index in indexKeys:\n\t\t\t\t\tbSimilar = similarity(a[index], b[index]) > threshold\n\t\t\t\t\tbAllSimilar = bAllSimilar and bSimilar\n\t\t\t\t\tif not bAllSimilar:\n\t\t\t\t\t\tbreak\n\t\t\t\tif bAllSimilar:\n\t\t\t\t\tbAdd = False\n\n\t\t\tif bAdd:\n\t\t\t\tnewList.append(a)\n\n\treturn newList\n\n\n# Remove duplicates from a list or list of lists (provided indices)\n# below a threshold of similarity\ndef removeDuplicates(thisList, indexKeys, threshold):\n\n\tnewList = []\n\tif indexKeys == -1:\n\n\t\t# Match the elements of the list itself\n\t\tskipIndices = []\n\t\tfor i in range(len(thisList)):\n\t\t\tbAdd = True\n\t\t\tfor j in range(len(thisList)):\n\t\t\t\tif i == j: continue\n\t\t\t\tif i in skipIndices: \n\t\t\t\t\tbAdd = False\n\t\t\t\t\tbreak\n\t\t\t\tif similarity(thisList[i], thisList[j]) > threshold:\n\t\t\t\t\tskipIndices.append(j)\n\t\t\tif bAdd:\n\t\t\t\tnewList.append(thisList[i])\n\n\telse:\n\t\tskipIndices = []\n\t\tfor i in range(len(thisList)):\n\n\t\t\t# Flag whether we're adding this one\n\t\t\tbAdd = True\n\n\t\t\t# Iterate through all other items\n\t\t\tfor j in range(len(thisList)):\n\n\t\t\t\t# Don't compare the same element\n\t\t\t\tif i == j: continue\n\n\t\t\t\t# Skip elements that are repeated\n\t\t\t\tif i in skipIndices: \n\t\t\t\t\tbAdd = False\n\t\t\t\t\tbreak\n\n\t\t\t\tbAllSimilar = True\n\t\t\t\tfor index in indexKeys:\n\t\t\t\t\tbSimilar = similarity(thisList[i][index], thisList[j][index]) > threshold\n\t\t\t\t\tbAllSimilar = bAllSimilar and bSimilar\n\t\t\t\t\tif not bAllSimilar:\n\t\t\t\t\t\tbreak\n\t\t\t\tif bAllSimilar:\n\t\t\t\t\tskipIndices.append(j)\n\n\t\t\tif bAdd:\n\t\t\t\tnewList.append(thisList[i])\n\t\n\treturn newList\n\n# Save a feed as an xml file\ndef saveFeed(listings, title, path):\n\n\turl = githubRepoURL + title + \".xml\"\n\n\t# Create a feed generator\n\tfg = FeedGenerator()\n\n\t# Create the feed's title\n\tfg.id(url)\n\tfg.title(title)\n\tfg.author({'name':'Ben Snell'})\n\tfg.description(\"NYC 2BR Apartment Listings in \" + title)\n\tfg.link( href=url, rel='alternate' )\n\tfg.language('en')\n\ttime = datetime.now().strftime('%Y-%m-%d %H:%M:%S') + \"-05:00\"\n\tfg.pubDate(time)\n\tfg.updated(time)\n\n\tfor apt in listings:\n\n\t\te = fg.add_entry()\n\t\t\n\t\te.id( apt[0] )\n\t\te.title( \"$\" + apt[1] + \" // \" + apt[4] )\n\t\te.link( href=apt[0] )\n\n\t\ttext = \"\"\n\t\tif apt[5] != \"\":\n\t\t\timgs = apt[5].split(\" \")\n\t\t\tfor i in range(len(imgs)):\n\t\t\t\ttext += \" \"\n\t\t\t\tif i == 0:\n\t\t\t\t\ttext += \"

\" + apt[8] + \"

\"\n\t\telse:\n\t\t\ttext += \"

\" + apt[8] + \"

\"\n\t\te.content( type=\"html\", content=text )\n\n\t\t# This doesn't seem to work:\n\t\te.pubDate( datetime2RSSString(clDate(apt[2])) )\n\t\te.updated( datetime2RSSString(clDate(apt[2])) )\n\n\tfg.atom_str(pretty=True)\n\tfg.atom_file(path)\n\ndef scrapeCL():\n\n\tallApts = []\n\n\t# Iterate through all possible apartments\n\tmaxSearch = maxAptsToSearch\n\tfor i in range(0, maxSearch, 120):\n\n\t\tprint(\"Got CL Apartments \" + str(i) + \" / \" + str(maxSearch))\n\t\t\n\t\t# Get the html text\n\t\ttext = \"\"\n\t\ttry:\n\t\t\ttext = requests.get(urlCL(i), stream=False, timeout=timeoutSec).text\n\t\texcept:\n\t\t\tprint(\"Unable to retrieve the url: \" + allApts[i][0])\n\t\t\tcontinue\n\n\t\t# parse into a list\n\t\tobj = re.findall(r'\\\\$(.*?)\\.*?datetime=\\\"(.*?)\\\".*?data-id=\\\"(.*?)\\\" class=\\\"result-title hdrlnk\\\"\\>(.*?)\\', text, re.I | re.M | re.S)\n\n\t\t# add to the existing lists\n\t\tallApts.extend(obj)\n\n\t# Remove duplicates\n\tallApts = list(set(allApts))\n\n\tprint(\"Removed Duplicates, now only: \", len(allApts))\n\n\t# Convert into a list of lists (instead of tuples)\n\tallApts = [list(i) for i in allApts]\n\n\t# Load the csv to remove any of the post ID's\n\toldApts = loadCsv(csvPath)\n\tallApts = removeMatches(allApts, oldApts, [3], 0.99)\n\n\tprint(\"Removed matches, now only: \", len(allApts));\n\n\t# For each apartment, retrieve the listing and get information for an rss feed\n\tfor i in range(len(allApts)):\n\n\t\tif i % 100 == 0:\n\t\t\tprint(\"Retrieved listing for \" + str(i) + \" / \" + str(len(allApts)) + \" apts\")\n\n\t\t# get the webpage\n\t\t# print(\"Getting \" + allApts[i][0])\n\t\ttext = \"\"\n\t\ttry:\n\t\t\ttext = requests.get(allApts[i][0], stream=False, timeout=timeoutSec).text\n\t\texcept:\n\t\t\tprint(\"Unable to retrieve the url: \" + allApts[i][0])\n\t\t\tcontinue\n\t\t# print(\"\\tGot \" + allApts[i][0])\n\n\t\t# Get all the images' urls and separate them by spaces\n\t\tobj = [i for i in re.findall(r'\\\"(https://images.craigslist.org/.*?)\\\"', text, re.I | re.M | re.S) if \"600x450\" in i]\n\t\tobj = list(set(obj))\n\t\tallApts[i].append(\" \".join(obj))\n\n\t\t# Get the location\n\t\tobjLat = re.findall(r'data-latitude=\\\"(.*?)\\\"', text, re.I | re.M | re.S)\n\t\tobjLon = re.findall(r'data-longitude=\\\"(.*?)\\\"', text, re.I | re.M | re.S)\n\t\tif len(objLat) == 0 or len(objLon) == 0:\n\t\t\tallApts[i].append(0)\n\t\t\tallApts[i].append(0)\n\t\telse:\n\t\t\tallApts[i].append(float(objLat[0]))\n\t\t\tallApts[i].append(float(objLon[0]))\n\n\t\t# Get the full description\n\t\t# r'data-location=\\\"'+allApts[i][0]+\n\t\tobj = re.findall(r'\\
.*?\\\\n \\(.*?)\\', text, re.I | re.M | re.S)\n\t\tif len(obj) == 0:\n\t\t\tallApts[i].append(\"\")\n\t\telse:\n\t\t\t# obj[0] = obj[0].replace(\"
\", \"\") # remove breaks\n\t\t\tobj[0] = obj[0].replace(\"\\t\", \"\") # remove tabs\n\t\t\tobj[0] = obj[0].replace(\"\\n\", \"\") # remove tabs\n\t\t\tallApts[i].append(obj[0])\n\n\treturn allApts\n\ndef process():\n\n\tprint(\"Starting a new process...\")\n\n\t# Get all craigslist apartments\n\tallApts = scrapeCL();\n\n\tprint(\"Scraped all CL Apartments\")\n\n\t# Only take the ones that have been posted in the last 72 hrs\n\tallApts = [i for i in allApts if elapsedTimeHrs(clDate(i[2])) <= timeRangeHrs]\n\n\tprint(\"Removed apartments < 3 days\")\n\n\t# Only take the ones that have a location within the neighborhoods set already\n\tselectApts = []\n\tfor apt in allApts:\n\n\t\t# Check whether this one is in any of the neighborhoods\n\t\tfor key, value in bounds.items():\n\t\t\tif inside_polygon(apt[6], apt[7], list(key)):\n\n\t\t\t\t# Add the hood\n\t\t\t\tapt.append(value)\n\n\t\t\t\t# Save this into select\n\t\t\t\tselectApts.append(apt)\n\n\t\t\t\t# print(apt[4], apt[-1], apt[0])\n\n\t\t\t\t# one to one mapping\n\t\t\t\tif bOneHoodPerListing:\n\t\t\t\t\tbreak\n\n\tprint(\"Narrowed down to specific hoods\")\n\n\t# Sort by date to get the newest first\n\tselectApts.sort(key=lambda d: clDate(d[2]))\n\tselectApts.reverse()\n\n\tprint(\"Sorted by date \", len(selectApts))\n\n\t# Load those apartments that have already been saved\n\toldApts = loadCsv(csvPath)\n\n\tprint(\"Loaded old apartments: \", len(oldApts))\n\n\t# Compare the new ones to the old ones for any matches and remove repeats\n\tselectApts = removeMatches(selectApts, oldApts, [4, 8], 0.5)\n\n\tprint(\"Removed matches \", len(selectApts))\n\n\t# Remove duplicate listings (with the same title and body)\n\tselectApts = removeDuplicates(selectApts, [4, 8], 0.95)\n\n\tprint(\"Removed self duplicates \", len(selectApts))\n\n\t# Save the old and new ones to file\n\tsaveCsv(selectApts, csvPath)\n\n\tprint(\"Saved new apts to file\")\n\n\t# Get all neighborhoods\n\tfeeds = {}\n\tfor key, value in bounds.items():\n\t\tfeeds[ value ] = []\n\t# Separate listings into represented hoods\n\tfor apt in selectApts:\n\t\tif apt[9] in feeds:\n\t\t\tfeeds[ apt[9] ].append( apt )\n\t\telse:\n\t\t\tfeeds[ apt[9] ] = [ apt ]\n\n\t# Export new ones to an RSS feed file\n\tuploads = []\n\tfor key, value in feeds.items():\n\n\t\tfilename = key + \".xml\"\n\t\tuploadName = saveFolderPath + \"/\" + filename\n\t\tsaveFeed(value, key, uploadName)\n\n\t\tuploads.append(saveFolder + \"/\" + filename)\n\tuploads.append(csvFilename)\n\n\tprint(\"Exported all to RSS Feeds\")\n\n\t# Upload these files to github\n\trepo = Repo(\"../\" + repoName)\n\trepo.index.add(uploads)\n\trepo.index.commit(\"Updated feeds\")\n\torigin = repo.remote('origin')\n\torigin.push()\n\n\tprint(\"Exported all to github\")\n\n\tfor apt in selectApts:\n\t\tprint(\"\\tNew Apartment added: \" + apt[0] + \" in \" + apt[9])\n\nwhile True:\n\n\tprint(\"Starting Process ------------------------\")\n\n\t# Run code\n\tstart = time.time()\n\tprocess()\n\tstop = time.time()\n\n\tprint(\"Ending Process ------------------------Waiting...\")\n\n\t# Get duration in seconds\n\tduration = stop - start\n\n\t# Wait for no more than 15 minutes\n\ttime.sleep(max(refreshMin*60 - duration, 0))\n\n\tprint(\"... Done waiting\")\n","sub_path":".backup/takeMeHome-Sep-2018.py","file_name":"takeMeHome-Sep-2018.py","file_ext":"py","file_size_in_byte":14205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"43110833","text":"'''\nBuilding neural network skills.\nI have one input layer with one input node, one output layer with one output node, and one edge connecting them.\nThe data will have random values x between 0 and 1, and the labels will all be a constant Q * x.\nHypothesis: the weight will eventually converge to Q given enough trials.\n'''\n\n''' \nPart 1: zero convergence\n1. make test cases\n2. process single case computation\n 2.1. take in input from test case\n 2.2. multiply it by weight\n 2.3. take difference with test_label and square it\n3. make for loop for processing all test cases\n4. average cost over the number of test cases\n5. repeat process over trials\n6. show graph of cost function vs trial\n 6.1. as a sanity check, i can try setting the weight to be very close to 0 and very far from 0,\n which should induce a very low cost and very high cost respectively\n7. compute gradient of cost function, which in this case is the derivative of the cost function\nwith respect to the single edge weight\n8. since I am trying to minimize the cost, add the negative of the gradient to the weight\n9. ideally, the cost should become 0, as the weight will become 0, and every test case will have a cost of 0.\n\nPart 2: one convergence\n10. ok it seems to be working when all the labels are 0, lets try a data set \nwhere the test_input and test_label are the same. In this case the weight should approach 1.\n\nPart 3: Q convergence\n11. Make the test cases (x, Q * x) where x is taken uniformly from (0, 1)\n12. w should converge to Q\n\n'''\n\nimport random\nimport pylab\n\na = 0.5\ndef RELU(x):\n if x > 0:\n return x\n else:\n return a*x\n\n# test based design: always create tests first\ndef createQTests(numTrials, numTests, Q):\n testSamples = []\n for trial in range(numTrials):\n tests = []\n for i in range(numTests):\n data = random.uniform(0, 1) * 2\n test = (data, Q * data)\n tests.append(test)\n testSamples.append(tests)\n return testSamples\n\ndef computeChanges(tests, w):\n total_c = 0\n total_grad_c = 0\n for test in tests:\n # compute preliminaries\n test_input = test[0]\n test_label = test[1]\n zL = test_input * w\n aL = RELU(zL)\n\n # compute cost\n difference = aL - test_label\n c = pow(difference, 2)\n total_c += c\n\n # compute grad\n dCdaL = 2 * (aL - test_label)\n daLdzL = 1 if zL >= 0 else a\n dzLdwL = test_input\n grad_c = dCdaL * daLdzL * dzLdwL\n total_grad_c += grad_c\n return total_c, total_grad_c\n\nif __name__ == \"__main__\":\n\n # constants\n random.seed(3)\n numTrials = 100\n numTests = 10\n\n # make tests\n Q = 1\n testSamples = createQTests(numTrials, numTests, Q)\n print(testSamples)\n\n # hold data\n xVals = []\n yVals1 = []\n yVals2 = []\n\n w1 = 50\n for k in range(numTrials):\n # we will compute the cost C1 given the current w, and the cost C2 with w + delta_w\n # where delta_w is the derivative of C1 with respect to w\n # then w will become the weighted sum\n # b1 * w + b2 * (w + delta_w)\n # This is to ensure that the function doesnt overshoot while trying to optimize\n\n # get a new Sample\n tests = testSamples[k]\n\n # iterate over every test case in tests\n results = computeChanges(tests, w1)\n avg_c1 = results[0] / numTests\n avg_grad_c = results[1] / numTests\n\n w2 = w1 + -1 * avg_grad_c\n\n results = computeChanges(tests, w2)\n # i only need the cost and not the gradient here\n avg_c2 = results[0] / numTests\n\n if avg_c2 + avg_c1 == 0:\n # I am already at a local min\n print(\"found local min at \" + str(w1))\n break\n\n b1 = 1 - avg_c1/(avg_c1 + avg_c2)\n # b2 = 1 - avg_c2/(avg_c1 + avg_c2)\n b2 = 1 - b1\n\n # record data\n xVals.append(k)\n yVals1.append(avg_c1)\n yVals2.append(w1)\n\n # print(\"prop1 {} w {} prop2 {} tempw {}\".format(prop1, w, prop2, tempw))\n # print(\"avg_c1 {} avg_c2 {}\".format(avg_c1, avg_c2))\n\n w1 = b1 * w1 + b2 * w2\n\n print(yVals2)\n\n pylab.subplot(211)\n pylab.plot(xVals, yVals1, 'b--')\n\n pylab.subplot(212)\n pylab.plot(xVals, yVals2, 'r--')\n\n pylab.show()\n print(\"w1 is {}\".format(w1))\n\n\ndef old():\n pass\n # without averaging\n # for test in tests:\n # test_input = test[0]\n # test_label = test[1]\n #\n # zL = test_input * w\n # aL = RELU(zL)\n # # aL = sigmoid(zL)\n # difference = aL - test_label\n # # print(\"test_input {} test_label {} aL {} difference {}\".format(test_input, test_label, aL, difference))\n # c = pow(difference, 2)\n #\n # total_c += c\n #\n # calculate derivative for the given test case\n # dCdaL = 2 * (aL - test_label)\n # daLdzL = 1 if zL >= 0 else a\n # # numerator = 1 * pow(2.71, -1 * zL)\n # # denominator = 1 / pow((1 + pow(2.71, -1 * zL)), 2)\n # # daLdzL = numerator / denominator\n #\n # # print(\"check \" + str(daLdzL))\n # dzLdwL = test_input\n # grad_c = dCdaL * daLdzL * dzLdwL\n # total_grad_c += grad_c\n #\n # adding the negative of the gradient to the weight should make it cost lower on the next trial\n # proportion = 0.1\n # w += -1 * avg_grad_c #* proportion\n #\n #\n # avg_c = total_c / numTests\n # avg_grad_c = total_grad_c / numTests\n # print(avg_grad_c)\n","sub_path":"OneEdgeConvergence.py","file_name":"OneEdgeConvergence.py","file_ext":"py","file_size_in_byte":5496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"289833462","text":"import asyncio\nimport random\n\nimport riotlink\nimport phantom_util\n\nphantom_mention = None\nphantom_url = 'http://nowzerix.com/phantom.html'\nactive_tokens = {}\ntokens_guard = asyncio.Lock()\n\ndef set_mention(mention):\n global phantom_mention\n phantom_mention = mention\n\ndef control(message_author, message_content):\n if phantom_mention != None and message_content == phantom_mention:\n reply = ('Hello {0}! Read about me at: {1}.\\n' +\n 'I am a utility bot developed for the First Blood community.'\n ).format(message_author, phantom_url)\n return (True, reply)\n elif phantom_mention != None and \\\n message_content.startswith(phantom_mention + ' '):\n return (True, None)\n else:\n return (False, None)\n\nasync def bind(argv, message):\n if len(argv) == 0:\n return (False, 'Command bind requires a token')\n token = argv[0]\n with (await tokens_guard):\n if token not in active_tokens:\n return (False, 'Specified token has expired or does not exist.')\n\n (valid, content) = await riotlink.summonerid_from_name(active_tokens[token])\n if not valid:\n return (False, content)\n (summoner_id, summoner_name) = content\n\n (valid, content) = await riotlink.summoner_runes(summoner_id)\n if not valid:\n return (False, content)\n rune_pages = content\n\n verified = False\n for rune_page in rune_pages:\n if rune_page['name'] == token:\n verified = True\n del active_tokens[token]\n break\n if verified:\n reply = ('Successfully verified {0.author.mention}' +\n ' as {1}! I am in development. Bindings are not presently' +\n ' being saved.').format(message, summoner_name)\n return (True, reply)\n else:\n return (False, 'No matching rune page for specified token.') \n\nasync def kill_token(token):\n await asyncio.sleep(10 * 60.0)\n with (await tokens_guard):\n del active_tokens[token]\nasync def hold(argv, message):\n if len(argv) == 0:\n return (False, 'Command hold requires a summoner name.')\n arg = argv[0] if len(argv) == 1 else ''.join(argv[0:])\n with (await tokens_guard):\n while True:\n token = str(random.randint(0, 100000))\n if token not in active_tokens:\n break\n active_tokens[token] = arg\n asyncio.ensure_future(kill_token(token))\n reply = ('{0.author.mention} your token is: ```{1}``` Please name a rune'+\n ' page to this token within 10 minutes. Do ' + phantom_mention +\n ' bind {1} when complete.').format(message, token)\n return (True, reply)\n\nasync def lu(argv, message):\n return await lookup(argv, message)\nasync def lookup(argv, message):\n if(len(argv) == 0):\n return (True, 'Command lookup requires a summoner name.')\n arg = argv[0] if len(argv) == 1 else ''.join(argv[0:])\n \n # Find summoner ID\n (valid, content) = await riotlink.summonerid_from_name(arg)\n if not valid:\n return (False, content)\n summoner_id, summoner_name = content\n\n #Lookup summoner ranked stats\n (valid, content) = await riotlink.summoner_leagues(summoner_id)\n if not valid:\n return (False, content)\n leagues = content\n\n reply = '```Season ranked stats for: ' + summoner_name + '\\n' + \\\n phantom_util.league_summary(leagues) + '```'\n return (True, reply)","sub_path":"phantom_callable.py","file_name":"phantom_callable.py","file_ext":"py","file_size_in_byte":3259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"165229199","text":"# 신규 아이디 추천 (2021 KAKAO BLIND RECRUITMENT)\n\nimport re\n\ndef solution(new_id):\n # ^: 괄호 안의 문자를 제외한 모든 문자\n # 1단계, 2단계: 소문자로 변환, 소문자/숫자/-/_/. 제외한 문자 모두 제거\n answer = re.sub(\"[^-_.a-z0-9]\", \"\", new_id.lower())\n # 3단계: '.' 문자가 2번 이상 연속된 부분을 1개로 변환\n if answer: \n tmp = answer[0]\n chk = False\n if tmp=='.':\n chk = True # '.' 문자가 나온 경우 True\n for i in range(1, len(answer)):\n if answer[i]!='.':\n tmp+=answer[i]\n chk=False\n elif not chk: # 첫 '.' 문자일 경우\n tmp+=answer[i]\n chk=True\n # 4단계: 맨 앞, 맨 뒤 \".\" 문자 제거\n answer = tmp.strip('.')\n # 5단계, 6단계: 빈 문자열일 경우 'a' 대입, 15자리까지 슬라이싱 + 마지막 '.' 문자 제거\n answer = 'a' if not answer else answer[:15].rstrip('.')\n # 7단계: 길이가 2 이하일 경우 마지막 문자를 길이 3이 될 때까지 반복\n if len(answer)<=2:\n answer+=answer[-1]*(3-len(answer))\n return answer\n\nprint(solution(\"...!@BaT#*..y.abcdefghijklm\"))\nprint(solution(\"z-+.^.\"))\nprint(solution(\"=.=\"))\nprint(solution(\"123_.def\"))\nprint(solution(\"abcdefghijklmn.p\"))","sub_path":"Programmers/[코테연습]신규아이디추천.py","file_name":"[코테연습]신규아이디추천.py","file_ext":"py","file_size_in_byte":1364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"96062398","text":"def New_array(b):\n\ta = [int(i) for i in input().split()]\n\tfor i in range(0, len(a), 2):\n\t\tprint(a[i])\nprint(\"Прога\")\na = 1531351351951945815915\nfor i in range (1, a, 10):\n\tprint(\"NUMBER_GROUPING\" , i)\n\tif (i > 1000000000000):\n\t\tprint(\"REAdY\")\n\t\tNew_array(i)","sub_path":"Learn/lists.py","file_name":"lists.py","file_ext":"py","file_size_in_byte":262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"576372036","text":"# Header used to check if it's an UPX file\nUPX_STRING = b\"UPX!\"\n\n# Header used to find the config offset ([ss] after unxor)\nCONFIG_HEADER = b\"\\x15\\x15\\x29\\xD2\"\n\n# Size of every element in the config space\nCONFIG_SIZE = 428\nSIGNATURE1_SIZE = 96\nSIGNATURE2_SIZE = 96\nCONFIG_VERSION_SIZE = 4\nCONFIG_TOTAL_SIZE = CONFIG_SIZE + \\\n SIGNATURE1_SIZE + \\\n SIGNATURE2_SIZE + \\\n CONFIG_VERSION_SIZE\n\n# Hardcoded XOR key used to encrypt the config\nXOR_KEY = b\"\\x4E\\x66\\x5A\\x8F\\x80\\xC8\\xAC\\x23\\x8D\\xAC\\x47\\x06\\xD5\\x4F\\x6F\\x7E\"\n\n# The first signature public key used to authenticate the encrypted config\nSIGNATURE1_KEY = \"\\x02\\xc0\\xa1\\x43\\x78\\x53\\xbe\\x3c\\xc4\\xc8\\x0a\\x29\\xe9\\x58\" \\\n \"\\xbf\\xc6\\xa7\\x1b\\x7e\\xab\\x72\\x15\\x1d\\x64\\x64\\x98\\x95\\xc4\" \\\n \"\\x6a\\x48\\xc3\\x2d\\x6c\\x39\\x82\\x1d\\x7e\\x25\\xf3\\x80\\x44\\xf7\" \\\n \"\\x2d\\x10\\x6b\\xcb\\x2f\\x09\\xc6\"\n\n# The second signature public key used to authenticate the decrypted config\nSIGNATURE2_KEY = \"\\x02\\xd5\\xd5\\xe7\\x41\\xee\\xdc\\xc8\\x10\\x6d\\x2f\\x48\\x0d\\x04\" \\\n \"\\x12\\x21\\x27\\x39\\xc7\\x45\\x0d\\x2a\\xd1\\x40\\x72\\x01\\xd1\\x8b\" \\\n \"\\xcd\\xc4\\x16\\x65\\x76\\x57\\xc1\\x9d\\xe9\\xbb\\x05\\x0d\\x3b\\xcf\" \\\n \"\\x6e\\x70\\x79\\x60\\xf1\\xea\\xef\"\n\n# All tags that can be present in a Mozi config\nCONFIG_TAGS = {\n \"ss\":\t\"Bot role\",\n \"ssx\": \"enable/disable tag [ss]\",\n \"cpu\": \"CPU architecture\",\n \"cpux\": \"enable/disable tag [cpu]\",\n \"nd\": \"new DHT node\",\n \"hp\": \"DHT node hash prefix\",\n \"atk\": \"DDoS attack type\",\n \"ver\": \"Value in V section in DHT protcol\",\n \"sv\": \"Update config\",\n \"ud\": \"Update bot\",\n \"dr\": \"Download and execute payload from the specified URL\",\n \"rn\": \"Execute specified command\",\n \"dip\": \"ip:port to download Mozi bot\",\n \"idp\": \"report bot\",\n \"count\": \"URL that used to report bot\"\n}\n\n# List of the bootstrap nodes hardcoded in Mozi\nBOOTSTRAP_NODES = [\n (\"router.bittorrent.com\", 6881),\n (\"dht.transmissionbt.com\", 6881),\n (\"router.utorrent.com\", 6881),\n (\"bttracker.debian.org\", 6881),\n (\"212.129.33.59\", 6881),\n (\"82.221.103.244\", 6881),\n (\"130.239.18.159\", 6881),\n (\"87.98.162.88\", 6881),\n]\n\n# ELK Settings to import Mozi configurations\nELK_HOSTS = \"https://admin:admin@opendistro-opendistro-es-client-service \" \\\n \".monitoring.svc.cluster.local:9200\"\nELK_SSL = True\nELK_INDEX = \"mozitools\"\nELK_BULK_SIZE = 100\n\n# Number of node to remember. Nodes in cache aren't queried.\nNODES_CACHE_SIZE = 10000\n","sub_path":"mozitools/conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":2543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"574253829","text":"from pyramid.response import Response\nfrom pyramid.view import view_config\nimport beepaste.pasteFunctions as func\nfrom beepaste.models.api import API\nimport json\n\ndef verifyKey(apikey, request):\n api_count = request.dbsession.query(API).filter_by(apikey=apikey).count()\n if api_count == 0:\n raise Exception('api-key is not valid.')\n\n@view_config(route_name='api', renderer='templates/apiView.jinja2')\ndef apiView(request):\n title = 'API' + \" - \" + request.registry.settings['beepaste.siteName']\n return {'title': title}\n\n@view_config(route_name='api_create', renderer='templates/apiReturn.jinja2')\ndef apiCreate(request):\n try:\n if request.method == \"POST\" and request.json_body:\n data = request.json_body\n\n apikey = func.fetchData(data, 'api-key')\n verifyKey(apikey, request)\n\n pasteRaw = func.fetchData(data, 'pasteRaw')\n\n pasteLanguage = func.fetchData(data, 'pasteLanguage')\n func.verifyLanguage(pasteLanguage)\n\n pasteTitle = func.fetchData(data, 'pasteTitle', False)\n if pasteTitle:\n func.verifyTitleAndAuthor(pasteTitle)\n else:\n data['pasteTitle'] = pasteTitle\n\n pasteAuthor = func.fetchData(data, 'pasteAuthor', False)\n if pasteAuthor:\n func.verifyTitleAndAuthor(pasteAuthor)\n else:\n data['pasteAuthor'] = pasteAuthor\n\n pasteExpire = func.fetchData(data, 'pasteExpire', False)\n if pasteExpire:\n func.verifyExpire(pasteExpire)\n else:\n data['pasteExpire'] = \"0\"\n\n pasteEncryption = func.fetchData(data, 'pasteEncryption', False)\n if pasteEncryption:\n func.verifyEncryption(pasteEncryption)\n else:\n data['pasteEncryption'] = pasteEncryption\n\n newPasteURI = func.createPasteFromData(data, request)\n\n resp = Response()\n resp.status_int = 201\n resp.text = request.route_url('view_paste', pasteID=newPasteURI) + '\\n'\n\n return resp\n else:\n raise Exception('invalid request.')\n\n except Exception as e:\n resp = Response()\n resp.status_int = 409\n resp.text = str(e) + '\\n'\n return resp\n","sub_path":"beepaste/views/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"465084642","text":"# Author: Vidhi Panda \n# API call in python\n\nimport requests\n\n\ndef main():\n testcases = int(input())\n for a in range(testcases):\n emp_id = input()\n get(emp_id)\n\n\ndef get(id):\n url = \"http://dummy.restapiexample.com/api/v1/employees\"\n x = requests.get(url)\n emp_list = x.json()['data']\n found = 0\n for emp in emp_list:\n if str(emp['id']) == str(id):\n print(\"id =\", id)\n print(\"name =\", emp['employee_name'])\n print(\"age =\", emp['employee_age'])\n found = 1\n break\n if found == 0:\n print('ID not found')\n\n\nmain()\n","sub_path":"call.py","file_name":"call.py","file_ext":"py","file_size_in_byte":640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"390840538","text":"from dingtalk.client import *\nimport requests\nfrom pwdselfservice.local_settings import *\n\n\ndef ding_get_access_token():\n \"\"\"\n 获取钉钉access token\n :return:\n \"\"\"\n resp = requests.get(\n url=DING_URL + \"/gettoken\",\n params=dict(appid=DING_SELF_APP_ID, appsecret=DING_SELF_APP_SECRET)\n )\n resp = resp.json()\n if resp['access_token']:\n return resp['access_token']\n else:\n return None\n\n\ndef ding_get_persistent_code(code, token):\n \"\"\"\n 获取钉钉当前用户的unionid\n :return:\n \"\"\"\n resp = requests.post(\n url=\"%s/get_persistent_code?access_token=%s\" % (DING_URL, token),\n json=dict(tmp_auth_code=code),\n )\n resp = resp.json()\n if resp['unionid']:\n return resp['unionid']\n else:\n return None\n\n\ndef ding_client_connect():\n \"\"\"\n 钉钉连接器\n :return:\n \"\"\"\n client = AppKeyClient(corp_id=DING_CORP_ID, app_key=DING_APP_KEY, app_secret=DING_APP_SECRET)\n return client\n\n\ndef ding_get_dept_user_list_detail(dept_id, offset, size):\n \"\"\"\n 获取部门中的用户列表详细清单\n :param code:\n :return:\n \"\"\"\n client = ding_client_connect()\n result = client.user.list(department_id=dept_id, offset=offset, size=size)\n return result\n\n\ndef ding_get_userinfo_by_code(code):\n \"\"\"\n :param code: requestAuthCode接口中获取的CODE\n :return:\n \"\"\"\n client = ding_client_connect()\n resutl = client.user.getuserinfo(code)\n return resutl\n\n\ndef ding_get_userid_by_unionid(unionid):\n \"\"\"\n :param unionid: 用户在当前钉钉开放平台账号范围内的唯一标识\n :return:\n \"\"\"\n client = ding_client_connect()\n resutl = client.user.get_userid_by_unionid(unionid)\n if resutl['userid']:\n return resutl['userid']\n else:\n return None\n\n\ndef ding_get_org_user_count():\n \"\"\"\n 企业员工数量\n only_active – 是否包含未激活钉钉的人员数量\n :return:\n \"\"\"\n client = ding_client_connect()\n resutl = client.user.get_org_user_count('only_active')\n return resutl\n\n\ndef ding_get_userinfo_detail(user_id):\n \"\"\"\n user_id – 用户ID\n :return:\n \"\"\"\n client = ding_client_connect()\n resutl = client.user.get(user_id)\n return resutl\n","sub_path":"resetpwd/utils/dingding.py","file_name":"dingding.py","file_ext":"py","file_size_in_byte":2288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"252066894","text":"def main(K, S):\n ans = S\n if len(S) <= K:\n return ans\n else:\n return ans[:K] + '...'\n\nif __name__ == '__main__':\n K = int(input())\n S = input()\n ans = main(K, S)\n print(ans)\n\n","sub_path":"Python_codes/p02676/s543313095.py","file_name":"s543313095.py","file_ext":"py","file_size_in_byte":210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"629468596","text":"\"\"\"Luca HULOT; 25/9/2019\r\n But du programme :\r\n\"\"\"\r\n### Input/Variable ###\r\njoueur = int(input())\r\nnumeroSortant = int(input())\r\nmise = 10\r\n\r\n### Print ###\r\nif joueur == numeroSortant:\r\n print(12 * mise)\r\nelif not numeroSortant % 2 and joueur == 13:\r\n print(2 * mise)\r\nelif numeroSortant % 2 and joueur == 14:\r\n print(2 * mise)\r\nelif numeroSortant in [1, 3, 5, 7, 9, 12] and joueur == 15:\r\n print(2 * mise)\r\nelif numeroSortant in [2, 4, 6, 8, 10, 11] and joueur == 16:\r\n print(2 * mise)\r\nelse:\r\n print(0)\r\n","sub_path":"INFO-H100/UpyLab/section 3/3.6 Casino.py","file_name":"3.6 Casino.py","file_ext":"py","file_size_in_byte":526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"592151868","text":"import re\nimport sys\n\nfile = sys.argv[1]\n\ndef main(file):\n\n\ttry:\n\t\tinput_file = open(file, 'r')\n\n\texcept IOError as e:\n\t\tprint('Error: Unable to read the file')\n\t\texit()\n\n\tlits = {}\n\tline_number = 0\n\n\tfor line in input_file:\n\t\tfor lit in re.findall(r'[\\']\\w+[\\']', line) + re.findall(r'[\\\"]\\w+[\\\"]', line):\n\n\t\t\tlit = lit[1:-1]\n\n\t\t\tif not lit in lits.keys():\n\t\t\t\tlits[lit] = [str(line_number)]\n\n\t\t\telse:\n\t\t\t\tif str(line_number) not in lits[lit]:\n\t\t\t\t\tlits[lit].append(str(line_number))\n\t\t\n\t\tline_number += 1\n\n\tfor i in lits.keys():\n\t\tif len(lits[i]) > 1:\n\t\t\tprint('Lines with \\'{0}\\': {1}'.format(i, ', '.join(lits[i])))\n\n\tinput_file.close()\n\nmain(file)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"152459885","text":"import os\nimport sys\nimport json\nfrom json.decoder import JSONDecodeError\n\n# Programa que gestiona una base de datos simple (un diccionario almacenado en un fichero)\n\nclass Database():\n \"\"\" Clase que modela la BD sobre la que trabaja el programa. Incluye los métodos necesarios para cargarla y actualizarla en el disco\"\"\"\n def __init__(self,nombre_fichero):\n \"\"\"Inicializa el objeto BD y carga en memoria los datos\"\"\"\n self.nombre_fichero = nombre_fichero\n self.diccionario = {}\n self.__cargar_archivo()\n\n def __comprobar_archivo(self):\n \"\"\"Comprueba si existe el archivo. En caso afirmativo, devuelve True. En caso negativo, lo crea y devuelve False.\"\"\"\n if(not(os.path.isfile(nombre_archivo))):\n with open(nombre_archivo,'w') as archivo:\n archivo.close\n return False\n else:\n return True # sí que existe el archivo \n\n def __cargar_archivo(self):\n \"\"\"Carga la BD en la memoria RAM\"\"\"\n if(self.__comprobar_archivo()):\n try:\n archivo = open(nombre_archivo,'r')\n self.diccionario.update(json.load(archivo))\n archivo.close\n except JSONDecodeError:\n print('Error al leer el fichero JSON: formato incorrecto')\n sys.exit(1) # termina la ejecución del programa con error\n except Exception:\n print('Error ineseperado al leer la base de datos')\n sys.exit(1) # termina la ejecución del programa con error\n\n \"\"\"Métodos públicos de la clase: CRUD\"\"\" \n \n def actualizar_archivo(self):\n \"\"\"Actualiza el archivo de texto en el que se almacena la BD\"\"\"\n archivo = open(nombre_archivo,'w')\n archivo.write(json.dumps(self.diccionario))\n archivo.close \n\n def crear_entrada(self,clave, valor):\n \"\"\"Añade una entrada al diccionario con la clave y valor especificados\"\"\"\n if(clave in self.diccionario):\n print(\"Ya existe una entrada con la clave \" + clave)\n else:\n # No hay entradas con esa clave\n self.diccionario[clave] = valor\n print(\"Entrada creada correctamente\")\n self.actualizar_archivo() \n \n def ver_entradas(self):\n \"\"\"Muestra en pantalla las entradas del diccionario\"\"\"\n print(\"Número de entradas: \" + str(len(self.diccionario)) + '\\n')\n for clave,valor in self.diccionario.items():\n print(('\\t %s --> %s') %(clave,valor))\n\n def eliminar_entrada(self,clave):\n \"\"\"Elimina del diccionario la entrada con la clave especificada\"\"\"\n if(clave in self.diccionario):\n del self.diccionario[clave]\n print(('Entrada con clave \"%s\" borrada correctamente' %(clave,)))\n self.actualizar_archivo()\n else:\n # No existe ninguna entrada con esa clave\n print(\"No existe ninguna entrada con la clave \" + clave)\n\n def modificar_entrada(self,clave):\n \"\"\"Modifica una entrada ya creada en el diccionario\"\"\" \n if(clave in self.diccionario):\n nuevo_valor = input(\"Introduzca el nuevo valor para \" + clave + \": \")\n self.diccionario[clave] = nuevo_valor\n print('Entrada actualizada')\n self.actualizar_archivo()\n else:\n # No existe ninguna entrada con esa clave\n print(\"No existe ninguna entrada con la clave \" + clave) \n\n# Carga la base de datos desde el fichero de texto\nnombre_archivo = 'archivo.json' # nombre por defecto\nif(len(sys.argv)==2):\n nombre_archivo = sys.argv[1] # nombre de fichero especificado en los argumentos del programa\n\nbase_datos = Database(nombre_archivo)\n\ndef mostrar_menu():\n \"\"\"Muestra un menú para que el usuario pueda interactuar con la aplicación\"\"\"\n print(\"Base de datos: \" + nombre_archivo)\n while(True):\n print(\"\\nSelecciona una opción: \") \n print(\"1) Ver entradas en la BD\")\n print(\"2) Crear nueva entrada en la BD\")\n print(\"3) Eliminar entrada de la BD\")\n print(\"4) Modificar entrada de la BD\")\n print(\"0) Salir del programa\")\n seleccion = input(\"Opción: \")\n if(not(seleccion.isdigit())):\n print(\"Selección incorrecta. Inténtelo de nuevo.\")\n else:\n # Comprueba la opción elegida\n if(int(seleccion)==1):\n # Ver entradas en la BD\n print('\\n')\n base_datos.ver_entradas()\n elif(int(seleccion)==2):\n # Crear nueva entrada en la BD\n clave = input('\\nIntroduzca la clave: ')\n valor = input('Introduzca el valor: ')\n base_datos.crear_entrada(clave, valor)\n elif(int(seleccion)==3):\n # Eliminar entrada de la BD\n print('\\n')\n clave = input(\"Clave de la entrada que desea eliminar: \")\n base_datos.eliminar_entrada(clave)\n elif(int(seleccion)==4):\n # Modificar entrada de la BD\n print('\\n')\n clave = input(\"Clave de la entrada que desea modificar: \")\n base_datos.modificar_entrada(clave)\n elif(int(seleccion)==0):\n # Salir del programa \n sys.exit(0)\n else:\n # Selección no válida\n print(\"Selección incorrecta. Inténtelo de nuevo.\")\n\n# Muestra el menú de usuario\nmostrar_menu()\n","sub_path":"diccionariojson.py","file_name":"diccionariojson.py","file_ext":"py","file_size_in_byte":5570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"70983628","text":"from reward_function import reward_function\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nclass StateActionFeatureVectorWithTile():\n def __init__(self,\n state_low:np.array,\n state_high:np.array,\n num_actions:int,\n num_tilings:int,\n tile_width:np.array,\n max_action,\n min_action\n ):\n \"\"\"\n state_low: possible minimum value for each dimension in state\n state_high: possible maimum value for each dimension in state\n num_actions: the number of possible actions\n num_tilings: # tilings\n tile_width: tile width for each dimension\n \"\"\"\n self.state_low = state_low\n self.num_actions = num_actions\n self.levels = num_actions\n self.num_tilings = num_tilings\n self.tile_width = tile_width\n self.min_action = min_action\n self.max_action = max_action\n self.n_dimensions = state_low.shape[0]\n self.n_tiles = np.ceil(np.round((state_high - state_low) / tile_width, 2)).astype(np.int) + 2\n self.action_tile_width = np.round((max_action - min_action) / (self.levels - 1), 4)\n self.offset = np.linspace(-1. * tile_width, 0, num=num_tilings)\n self.all_dimensions = np.concatenate((np.array([self.num_actions, self.num_tilings]), self.n_tiles), axis=0)\n\n def feature_vector_len(self) -> int:\n \"\"\"\n return dimension of feature_vector: d = num_actions * num_tilings * num_tiles\n \"\"\"\n return self.num_actions * self.num_tilings * np.prod(self.n_tiles)\n\n def __call__(self, s, done, a) -> np.array:\n \"\"\"\n implement function x: S+ x A -> [0,1]^d\n if done is True, then return 0^d\n \"\"\"\n def get_index(idx, a, n_tile):\n position = 0\n super_idx = np.concatenate((np.array([a, idx]), n_tile), axis=0)\n for dimi, super_idxi in zip(self.all_dimensions, super_idx):\n position *= dimi\n position += super_idxi\n return position\n s = s[0]\n x = np.zeros((self.feature_vector_len()))\n if done: return x\n indices = np.array((np.array([s[0], s[-1]]) - self.offset - self.state_low) // self.tile_width, dtype=np.int)\n for i, idx in enumerate(indices):\n x[get_index(i, a, idx)] = 1.\n return x\n\n def discretize_actions(self, actions, min_action, n_actions):\n return np.array( (actions - self.min_action) // self.action_tile_width, dtype=np.int)\n\n def undiscretize_actions(self, actions, min_action, n_actions):\n a = self.min_action + actions * self.action_tile_width\n return a \n \ndef SarsaLambda(\n env, # openai gym environment\n gamma:float, # discount factor\n lam:float, # decay rate\n alpha:float, # step size\n X:StateActionFeatureVectorWithTile,\n num_episode:int,\n num_action: int,\n min_action: float,\n) -> np.array:\n \"\"\"\n Implement True online Sarsa(\\lambda)\n \"\"\"\n\n def epsilon_greedy_policy(s,done,w,epsilon=.0):\n nA = num_action\n Q = [np.dot(w, X(s,done,a)) for a in range(nA)]\n\n if np.random.rand() < epsilon:\n return np.random.randint(nA)\n else:\n return np.argmax(Q)\n\n w = np.zeros((X.feature_vector_len()))\n cost, cum_reward = np.zeros((num_episode,)), np.zeros((num_episode,))\n\n epsilon = 0.2\n k = 0\n for episode in range(num_episode):\n cum_reward[episode] = 0\n s, done = env.reset(), False\n a = epsilon_greedy_policy(s, done, w, epsilon)\n x = X(s, done, a)\n z, q_old = np.zeros(x.shape), 0\n while not done:\n if (k)%10000==0:\n print('hour: '+str(k+1)+' of '+str(2500*num_episode)+'\\r', end='')\n s_dash, r, done, _ = env.step([np.expand_dims(X.undiscretize_actions(a, min_action, num_action), axis=0)])\n reward = reward_function(r)\n a_dash = epsilon_greedy_policy(s_dash, done, w, epsilon)\n x_dash = X(s_dash, done, a_dash)\n q, q_dash = w.dot(x), w.dot(x_dash)\n delta = reward + gamma * q_dash - q\n z = gamma * lam * z + (1 - alpha * gamma * lam * z.dot(x)) * x\n w += alpha * (delta + q - q_old) * z - alpha * (q - q_old) * x\n q_old, x, a = q_dash, x_dash, a_dash\n cum_reward[episode] += reward[0]\n k+=1\n cost[episode] = env.cost()\n\n s, done = env.reset(), False\n a = epsilon_greedy_policy(s, done, w)\n while not done:\n s_dash, r, done, _ = env.step([np.expand_dims(X.undiscretize_actions(a, min_action, num_action), axis=0)])\n reward = reward_function(r)\n a = epsilon_greedy_policy(s_dash, done, w)\n print('Cost:', env.cost())\n","sub_path":"sarsa.py","file_name":"sarsa.py","file_ext":"py","file_size_in_byte":4829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"399716700","text":"# Copyright (c) 2009 StudioNow, Inc \n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\nimport os\nimport sys\nimport StringIO\nimport ConfigParser\n\nUSER_CONFIG_PATH = os.path.expanduser('~/.pybrightcove')\nCONFIG_PATH = '/etc/pybrightcove.cfg'\nCONFIG_LOCATIONS = [CONFIG_PATH, USER_CONFIG_PATH]\n\nVersion = '1.1'\nUserAgent = 'PyBrightcove/%s (%s)' % (Version, sys.platform)\n\n\nclass Config(ConfigParser.SafeConfigParser):\n\n def __init__(self, path=None, fp=None):\n ConfigParser.SafeConfigParser.__init__(self, {'working_dir': '/tmp',\n 'debug': '0'})\n if path:\n self.read(path)\n elif fp:\n self.readfp(fp)\n else:\n self.read(CONFIG_LOCATIONS)\n\n def save_option(self, path, section, option, value):\n \"\"\"\n Write the specified Section.Option to the config file specified by\n path. Replace any previous value. If the path doesn't exist, create\n it. Also add the option the the in-memory config.\n \"\"\"\n config = ConfigParser.SafeConfigParser()\n config.read(path)\n if not config.has_section(section):\n config.add_section(section)\n config.set(section, option, value)\n fp = open(path, 'w')\n config.write(fp)\n fp.close()\n if not self.has_section(section):\n self.add_section(section)\n self.set(section, option, value)\n\n def save_user_option(self, section, option, value):\n self.save_option(USER_CONFIG_PATH, section, option, value)\n\n def save_system_option(self, section, option, value):\n self.save_option(CONFIG_PATH, section, option, value)\n\n def get_value(self, section, name, default=None):\n return self.get(section, name, default)\n\n def get(self, section, name, default=None):\n try:\n val = ConfigParser.SafeConfigParser.get(self, section, name)\n except:\n val = default\n return val.strip(\"'\")\n\n def getint(self, section, name, default=0):\n try:\n val = ConfigParser.SafeConfigParser.getint(self, section, name)\n except:\n val = int(default)\n return val\n\n def getfloat(self, section, name, default=0.0):\n try:\n val = ConfigParser.SafeConfigParser.getfloat(self, section, name)\n except:\n val = float(default)\n return val\n\n def getbool(self, section, name, default=False):\n if self.has_option(section, name):\n val = self.get(section, name)\n if val.lower() == 'true':\n val = True\n else:\n val = False\n else:\n val = default\n return val\n\n def setbool(self, section, name, value):\n if value:\n self.set(section, name, 'true')\n else:\n self.set(section, name, 'false')\n\n\nconfig = Config()\n","sub_path":"pybrightcove/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":3937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"33923859","text":"#!/usr/bin/env python3\n\n\"\"\"\nPython script for combining several journal abbreviation lists\nand producing an alphabetically sorted list. If the same journal\nnames are repeated, only the version found last is retained.\n\nThis version of the script specifically combines the lists following the ISO4\nstandard WITHOUT dots after abbreviated words.\n\nUsage: combine_journal_lists.py\nInput: see list of files below\nOutput: writes file 'journalList_dotless.csv'\n\"\"\"\n\nimport sys\n\nimport_order = [\n 'journals/journal_abbreviations_entrez.csv',\n 'journals/journal_abbreviations_medicus.csv',\n 'journals/journal_abbreviations_webofscience-dotless.csv'\n]\n\nif len(sys.argv) == 1:\n out_file = 'journalList_dotless.csv'\nelse:\n out_file = sys.argv[1]\nprint(f\"Writing : {out_file}\")\n\njournal_dict = {}\n\nfor in_file in import_order:\n count = 0\n f = open(in_file, \"r\")\n for line in f:\n if \";\" in line and line[0] != \"#\":\n count += 1\n parts = line.partition(\";\")\n journal_dict[parts[0].strip()] = line.strip()\n f.close()\n print(f\"{in_file}: {count}\")\n\nprint(f\"Combined key count: {len(journal_dict)}\")\n\nf = open(out_file, \"w\")\nfor key in sorted(journal_dict.keys()):\n f.write(journal_dict[key]+\"\\n\")\nf.close()\n","sub_path":"scripts/combine_journal_lists_dotless.py","file_name":"combine_journal_lists_dotless.py","file_ext":"py","file_size_in_byte":1254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"174231932","text":"# -*- coding: utf-8 -*-\n##############################################################################\n#\n# OpenERP, Open Source Management Solution\n# Copyright (C) 2004-2010 Tiny SPRL ().\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n#\n##############################################################################\n\nfrom osv import osv\nfrom osv import fields\nfrom datetime import date\n\nclass res_partner(osv.osv):\n \n def get_sequence_registration_number(self, cr, uid, ids, context=None):\n \n res = {}\n today = date.today()\n \n self.write(cr, uid, ids, {\n 'dichiarazione_intento_registration_number': self.pool.get('ir.sequence').get(cr, uid, 'partner.dichiarazioni.intento'),\n 'dichiarazione_intento_registration_date': today,\n }, context=context)\n \n return res\n \n #_name = 'res.partner'\n _inherit = 'res.partner'\n \n _columns = {\n 'dichiarazione_intento_partner_number': fields.char('Dichiarazione numero', size=64),\n 'dichiarazione_intento_partner_date': fields.date('Dichiarazione data'),\n 'dichiarazione_intento_registration_number': fields.char('Registrazione numero', size=64),\n 'dichiarazione_intento_registration_date': fields.date('Registrazione data'),\n }\n\n _defaults = {\n }\n \n #-----------------------------------------------------------------------------\n # EVITARE LA COPIA DI 'NUMERO della registrazione di intento'\n #-----------------------------------------------------------------------------\n def copy(self, cr, uid, id, default={}, context=None):\n default.update({'dichiarazione_intento_registration_number': '',\n 'dichiarazione_intento_registration_date': 0,\n })\n return super(res_partner, self).copy(cr, uid, id, default, context)\n \n \nres_partner()","sub_path":"account_vat_dichiarazioni_intento/partner/partner.py","file_name":"partner.py","file_ext":"py","file_size_in_byte":2559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"31245766","text":"from ch_model_base import *\n\ndir_path = os.path.dirname(os.path.realpath(__file__))\nhome_stdout = sys.stdout\n\nprint(sys.argv, len(sys.argv))\nif(len(sys.argv) < 5) :\n print(\"Please provide more arguments\")\n sys.exit(0)\n\n\ntemplate_file = sys.argv[1]\nrun_mode = sys.argv[2]\nnum_models = int(sys.argv[3])\nchain = sys.argv[4]\nif len(sys.argv) > 5:\n inp_pdb_path = sys.argv[5]\nelse:\n inp_pdb_path = dir_path + '/pdbs/'\n\nstructure_name = 'TCR'\n\n\ntemplate_list = modeller_search_templates(template_file)\nprint(template_list)\nif len(template_list) == 0:\n print('len(template_list) == 0')\n sys.exit(0)\n\nlog.verbose()\nenv = environ()\nenv.io.atom_files_directory = ['.', inp_pdb_path]\nenv.libs.topology.read(file='$(LIB)/top_heav.lib')\nenv.libs.parameters.read(file='$(LIB)/par.lib') # read parameters\n\naln = alignment(env)\n\nfor template_code in template_list:\n mdl = model(env, file=template_code)#, model_segment=('FIRST:', ':LAST'))#('FIRST:', '+{0}:'.format(numaa) + chain))\n aln.append_model(mdl, atom_files=template_code, align_codes=template_code)\n\naln = modeller_struct_multiple_alignment(aln, 'templates.ali')\naln.append(file='TCR.ali', align_codes='TCR')\n\naln = modeller_alignment_add_sequence(aln, 'TCR-mult.ali')\n\nf = open('gnuplotfile', 'w')\nf.write('plot ')\n\na = automodel(env, alnfile='TCR-mult.ali',\n knowns=template_list,\n sequence='{0}'.format(structure_name),assess_methods=(assess.DOPE))\na.starting_model = 1\na.ending_model = num_models\na.make()\n\n#profile for template\ntemplate_code = template_list[0]\ntemplate_mdlch = complete_pdb(env, '{0}'.format(template_code))\nalignments_out = 'TCR-mult.ali'\n\nts = selection(template_mdlch)\nts.assess_dope(output=\"ENERGY_PROFILE NO_REPORT\", file='{0}{1}.profile'.format(structure_name, 0),\n normalize_profile=True, smoothing_window=15)\n\n#profile for structures\nfor n in range(1, num_models+1):\n mdlch = complete_pdb(env, '{0}.B9999{1:{fill}{align}4}'.format(structure_name, n, fill=0, align='>'))\n s = selection(mdlch)\n s.assess_dope(output=\"ENERGY_PROFILE NO_REPORT\", file='{0}{1}.profile'.format(structure_name, n),\n normalize_profile=True, smoothing_window=15)\n\nremove_files(num_models)\n","sub_path":"ch_scripts/modeller/ch_model_structures.py","file_name":"ch_model_structures.py","file_ext":"py","file_size_in_byte":2227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"400374993","text":"import unittest\n\nimport Loggers.logger\n\n\nclass TestLogger(unittest.TestCase):\n def test_default(self):\n config_options = {}\n logger = Loggers.logger.Logger(config_options)\n self.assertEqual(\n logger.dependencies, [], \"logger did not set default dependencies\"\n )\n\n def test_dependencies(self):\n config_options = {\"depend\": [\"a\", \"b\"]}\n logger = Loggers.logger.Logger(config_options)\n self.assertEqual(\n logger.dependencies,\n [\"a\", \"b\"],\n \"logger did not set dependencies to given list\",\n )\n with self.assertRaises(TypeError):\n logger.dependencies = \"moo\"\n logger.dependencies = [\"b\", \"c\"]\n self.assertEqual(\n logger.check_dependencies([\"a\"]),\n True,\n \"logger thought a dependency had failed\",\n )\n self.assertEqual(\n logger.connected, True, \"logger did not think it was connected\"\n )\n self.assertEqual(\n logger.check_dependencies([\"a\", \"b\"]),\n False,\n \"logger did not think a dependency failed\",\n )\n self.assertEqual(logger.connected, False, \"logger thought it was connected\")\n","sub_path":"tests/test_logger.py","file_name":"test_logger.py","file_ext":"py","file_size_in_byte":1232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"215329619","text":"from hasTable import HashTable\n\n#constructor\ndef test_initEmpty():\n testTable = HashTable()\n assert testTable.table == [[],[]]\n\ndef test_initItemCountIsZero():\n testTable = HashTable()\n assert testTable.itemCount == 0\n\n#insert\ndef test_insertItem_itemCount():\n testTable = HashTable()\n testTable.insert(\"Don Draper\", \"555-5555\")\n assert testTable.itemCount == 1\n\ndef test_updateItem_itemCount():\n testTable = HashTable()\n testTable.insert(\"Don Draper\", \"555-5556\")\n assert testTable.itemCount == 1\n\ndef test_insertItem_notEmpty():\n testTable = HashTable()\n testTable.insert(\"Don Draper\", \"555-5555\")\n assert testTable.table != [[],[]]\n\n#delete\ndef test_deleteItem_itemCount():\n testTable = HashTable()\n testTable.insert(\"Don Draper\", \"555-5555\")\n testTable.delete(\"Don Draper\")\n assert testTable.itemCount == 0\n\ndef test_deleteItem_emptyTable():\n testTable = HashTable()\n testTable.insert(\"Don Draper\", \"555-5555\")\n testTable.delete(\"Don Draper\")\n assert testTable.table == [[]]\n\n#search\ndef test_search():\n testTable = HashTable()\n testTable.insert(\"Romeo\", \"333-3333\")\n testTable.insert(\"Juliet\", \"444-4444\")\n testTable.insert(\"RobinHood\", \"555-5555\")\n assert testTable.search(\"Juliet\") == \"444-4444\"\n\n#grow\ndef test_tableGrows():\n testTable = HashTable()\n assert len(testTable.table) == 2\n testTable.insert(\"Romeo\", \"333-3333\")\n testTable.insert(\"Juliet\", \"444-4444\")\n assert len(testTable.table) == 4\n testTable.insert(\"RobinHood\", \"555-5555\")\n testTable.insert(\"Don Draper\", \"555-5555\")\n assert len(testTable.table) == 8\n\n#shrink\ndef test_tableShrinks():\n testTable = HashTable()\n testTable.insert(\"Romeo\", \"333-3333\")\n testTable.insert(\"Juliet\", \"444-4444\")\n testTable.insert(\"Robin Hood\", \"555-5555\")\n testTable.insert(\"Don Draper\", \"555-5555\")\n testTable.insert(\"Roger Sterling\", \"777-7777\")\n assert len(testTable.table) == 8\n testTable.delete(\"Roger Sterling\") #4 items, 8 lists. do nothing\n assert len(testTable.table) == 8\n testTable.delete(\"Don Draper\") #3 items, 8 lists, shrink to 4 lists\n assert len(testTable.table) == 4\n","sub_path":"algorithmsReview/test_hashTable.py","file_name":"test_hashTable.py","file_ext":"py","file_size_in_byte":2176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"46778728","text":"'''\nModule for construction of tau -->MuMuMu stripping selections and lines\n\nExported symbols (use python help!):\n - \n'''\n\n__author__ = ['Jon Harrison', 'Paul Seyfert', 'Marcin Chrzaszcz']\n__date__ = '05/05/2015'\n__version__ = '$Revision: 3.0 $'\n\n__all__ = ('Tau23MuLinesConf',\n 'default_config',\n 'makeTau23Mu',\n 'makeDs23PiTIS',\n 'makeDs23Pi',\n 'makeDsPhiPi',\n 'makeTau25Mu',\n 'makeTau2PMuMu'\n )\n\nfrom Gaudi.Configuration import *\nfrom Configurables import FilterDesktop, CombineParticles\nfrom PhysSelPython.Wrappers import Selection, DataOnDemand\nfrom StrippingConf.StrippingLine import StrippingLine\nfrom StrippingUtils.Utils import LineBuilder\nfrom GaudiKernel.PhysicalConstants import c_light\n\ndefault_config = {\n 'NAME' : 'Tau23Mu',\n 'WGs' : ['RD'],\n 'BUILDERTYPE' : 'Tau23MuLinesConf',\n 'CONFIG' : {\n 'TauPrescale' :1.,\n 'TauPostscale' :1.,\n 'Ds23PiTISPrescale' :0.0,\n 'Ds23PiPrescale' :0.0,\n 'Ds2PhiPiPrescale' :1.,\n 'Tau25Prescale' :1.,\n 'Tau2PMuMuPrescale' :1.,\n 'TrackGhostProb' :0.45\n },\n 'STREAMS' : { 'Leptonic' : ['StrippingTau23MuTau23MuLine','StrippingTau23MuDs2PhiPiLine','StrippingTau23MuTau2PMuMuLine','StrippingTau23MuDs23PiLine','StrippingTau23MuTau25MuLine']}\n }\n\n\n\nclass Tau23MuLinesConf(LineBuilder) :\n \"\"\"\n Builder \n\n \n \"\"\"\n\n __configuration_keys__ = ( 'TauPrescale',\n 'TauPostscale',#universal for all lines\n 'Ds23PiTISPrescale',\n 'Ds23PiPrescale',\n 'Ds2PhiPiPrescale',\n 'Tau25Prescale',\n 'Tau2PMuMuPrescale',\n 'TrackGhostProb'\n )\n\n \n \n def __init__(self, \n name = 'Tau23Mu',\n config = None) :\n\n LineBuilder.__init__(self, name, config)\n #checkConfig(Bs2MuMuLinesConf.__configuration_keys__,config)\n\n tau_name=name+'Tau23Mu'\n ds23PiTIS_name = name+'Ds23PiTIS'\n ds23Pi_name=name+'Ds23Pi'\n ds2PhiPi_name=name+'Ds2PhiPi'\n tau25_name=name+'Tau25Mu'\n tau2pmm_name=name+'Tau2PMuMu'\n\n \n\n self.selTau23Mu = makeTau23Mu(tau_name,config)\n #self.selDs23PiTIS = makeDs23PiTIS(self,ds23PiTIS_name)\n self.selDs23Pi = makeDs23Pi(ds23Pi_name,config)\n self.selDs2PhiPi = makeDs2PhiPi(ds2PhiPi_name,config)\n self.selTau25Mu = makeTau25Mu(tau25_name,config)\n self.selTau2PMuMu = makeTau2pmm(tau2pmm_name,config)\n\n\n self.tau23MuLine = StrippingLine(tau_name+\"Line\",\n prescale = config['TauPrescale'],\n postscale = config['TauPostscale'],\n MDSTFlag = True,\n RequiredRawEvents = [\"Calo\"],\n algos = [ self.selTau23Mu ],\n RelatedInfoTools = [{ 'Type' : 'RelInfoConeVariables', 'ConeAngle' : 1.,\n 'Variables' : ['CONEANGLE', 'CONEMULT', 'CONEPT', 'CONEPTASYM'],\n 'RecursionLevel' : 1,\n 'Location':'ConeIsoInfo' },\n {'Type': 'RelInfoVertexIsolation',\n 'Location':'VtxIsoInfo' },\n { 'Type': 'RelInfoTrackIsolationBDT',\n 'RecursionLevel' : 2,\n 'Variables' : 0,\n 'Locations': {'Phys/StdAllLooseMuons' : [\"MuonTrackIsoBDTInfo1\",\"MuonTrackIsoBDTInfo2\",\"MuonTrackIsoBDTInfo3\"]},\n }\n ]\n )\n \n #self.ds23PiTISLine = StrippingLine(ds23PiTIS_name+\"Line\",\n # prescale = config['Ds23PiTISPrescale'],\n # postscale = config['TauPostscale'],\n # algos = [ self.selDs23PiTIS ]\n # )\n\n self.ds23PiLine = StrippingLine(ds23Pi_name+\"Line\",\n prescale = config['Ds23PiPrescale'],\n postscale = config['TauPostscale'],\n MDSTFlag = True,\n RequiredRawEvents = [ ],\n algos = [ self.selDs23Pi ]\n )\n \n self.ds2PhiPiLine = StrippingLine(ds2PhiPi_name+\"Line\",\n prescale = config['Ds2PhiPiPrescale'],\n postscale = config['TauPostscale'],\n MDSTFlag = True,\n RequiredRawEvents = [\"Calo\"],\n algos = [ self.selDs2PhiPi ],\n RelatedInfoTools = [{ 'Type' : 'RelInfoConeVariables', 'ConeAngle' : 1.,\n 'Variables' : ['CONEANGLE', 'CONEMULT', 'CONEPT', 'CONEPTASYM'],\n 'RecursionLevel' : 1,\n 'Location':'ConeIsoInfo' },\n {'Type': 'RelInfoVertexIsolation',\n 'Location':'VtxIsoInfo' },\n { 'Type': 'RelInfoTrackIsolationBDT',\n 'RecursionLevel' : 2,\n 'Variables' : 0,\n 'Locations': {'Phys/StdAllLooseMuons' : [\"MuonTrackIsoBDTInfo1\",\"MuonTrackIsoBDTInfo2\"],\n 'Phys/StdAllLoosePions' : [\"PionTrackIsoBDTInfo\"]},\n }\n ]\n )\n\n self.tau25MuLine = StrippingLine(tau25_name+\"Line\",\n prescale = config['Tau25Prescale'],\n postscale = config['TauPostscale'],\n MDSTFlag = True,\n RequiredRawEvents = [ ],\n algos = [ self.selTau25Mu ]\n )\n\n self.tau2PMuMuLine = StrippingLine(tau2pmm_name+\"Line\",\n prescale = config['Tau2PMuMuPrescale'],\n postscale = config['TauPostscale'],\n MDSTFlag = True,\n RequiredRawEvents = [\"Calo\"],\n algos = [ self.selTau2PMuMu ] ,\n RelatedInfoTools = [{ 'Type' : 'RelInfoConeVariables', 'ConeAngle' : 1.,\n 'Variables' : ['CONEANGLE', 'CONEMULT', 'CONEPT', 'CONEPTASYM'],\n 'RecursionLevel' : 1,\n 'Location':'ConeIsoInfo' },\n {'Type': 'RelInfoVertexIsolation',\n 'Location':'VtxIsoInfo' },\n { 'Type': 'RelInfoTrackIsolationBDT',\n 'RecursionLevel' : 2,\n 'Variables' : 0,\n 'Locations': {'Phys/StdAllLooseMuons' : [\"MuonTrackIsoBDTInfo1\",\"MuonTrackIsoBDTInfo2\"],\n 'Phys/StdAllLooseProtons' : [\"ProtonTrackIsoBDTInfo\"]},\n }\n ]\n )\n \n self.registerLine(self.tau23MuLine)\n #self.registerLine(self.ds23PiTISLine)\n self.registerLine(self.ds23PiLine)\n self.registerLine(self.ds2PhiPiLine)\n self.registerLine(self.tau25MuLine)\n self.registerLine(self.tau2PMuMuLine)\n \n\ndef makeTau23Mu(name, config):\n \"\"\"\n Please contact Johannes Albrecht if you think of prescaling this line!\n \n Arguments:\n name : name of the Selection.\n \"\"\"\n \n Tau2MuMuMu = CombineParticles(\"Comine\"+name)\n Tau2MuMuMu.DecayDescriptor = \" [ tau+ -> mu+ mu+ mu- ]cc\"\n Tau2MuMuMu.DaughtersCuts = { \"mu+\" : \" ( PT > 300 * MeV ) & ( TRGHOSTPROB < %(TrackGhostProb)s ) & ( TRCHI2DOF < 3 ) \"\\\n \"& ( BPVIPCHI2 () > 9 ) \" % config}\n Tau2MuMuMu.CombinationCut = \"(ADAMASS('tau+')<400*MeV)\"\n\n Tau2MuMuMu.MotherCut = \"\"\"\n ( VFASPF(VCHI2) < 15 ) &\n ( (BPVLTIME () * c_light) > 100 * micrometer ) &\n ( BPVIPCHI2() < 225 )\n \"\"\" \n \n _stdLooseMuons = DataOnDemand(Location = \"Phys/StdLooseMuons/Particles\")\n\n return Selection (name,\n Algorithm = Tau2MuMuMu,\n RequiredSelections = [ _stdLooseMuons ])\n\ndef makeDs23Pi(name, config):\n \"\"\"\n Please contact Johannes Albrecht if you think of prescaling this line!\n \n Arguments:\n name : name of the Selection.\n \"\"\"\n \n Ds2PiPiPi = CombineParticles(\"Comine\"+name)\n Ds2PiPiPi.DecayDescriptor = \" [ D_s+ -> pi+ pi+ pi- ]cc \" \n Ds2PiPiPi.DaughtersCuts = { \"pi+\" : \" ( PT > 300 * MeV ) & ( TRGHOSTPROB < %(TrackGhostProb)s ) & ( TRCHI2DOF < 3 ) & ( BPVIPCHI2 () > 9 ) \" % config}\n Ds2PiPiPi.CombinationCut = \"(ADAMASS('D_s+')<80*MeV)\"\n\n Ds2PiPiPi.MotherCut = \"\"\"\n ( VFASPF(VCHI2) < 15 ) &\n ( (BPVLTIME () * c_light) > 100 * micrometer ) &\n ( BPVIPCHI2() < 225 )\n \"\"\" \n \n _stdLoosePions = DataOnDemand(Location = \"Phys/StdLoosePions/Particles\")\n\n return Selection (name,\n Algorithm = Ds2PiPiPi,\n RequiredSelections = [ _stdLoosePions ])\n\ndef makeDs23PiTIS(self, name, config):\n \"\"\"\n Please contact Johannes Albrecht if you think of prescaling this line!\n \n Arguments:\n name : name of the Selection.\n \"\"\"\n def makeTISTOS( name, _input, _trigger ) :\n from Configurables import TisTosParticleTagger\n _tisTosFilter = TisTosParticleTagger( name + \"Tagger\" )\n _tisTosFilter.TisTosSpecs = { _trigger : 0 }\n #_tisTosFilter.ProjectTracksToCalo = False\n #_tisTosFilter.CaloClustForCharged = False\n #_tisTosFilter.CaloClustForNeutral = False\n #_tisTosFilter.TOSFrac = { 4:0.0, 5:0.0 }\n return Selection( name\n , Algorithm = _tisTosFilter\n , RequiredSelections = [ _input ]\n ) \n\n self.combDs2pipipi=makeDs23Pi(name, config)\n\n self.selDs23PiHlt1TIS = makeTISTOS( self.name() + \"Ds23PiHlt1TIS\"\n , self.combDs2pipipi#makeDs23Pi#self.combPiPiPi\n , \"Hlt1.*Decision%TIS\"\n )\n self.selDs23PiHlt2TIS = makeTISTOS( self.name() + \"Ds23PiHlt2TIS\"\n , self.selDs23PiHlt1TIS\n , \"Hlt2.*Decision%TIS\"\n )\n \n return self.selDs23PiHlt2TIS\n\n# return Selection (name,\n# Algorithm = Ds2PiPiPiTIS,\n# RequiredSelections = [ Ds2PiPiPi ])\n\n\ndef makeDs2PhiPi(name, config):\n \"\"\"\n Please contact Johannes Albrecht if you think of prescaling this line!\n \n Arguments:\n name : name of the Selection.\n \"\"\"\n \n Ds2PhiPi = CombineParticles(\"Comine\"+name)\n Ds2PhiPi.DecayDescriptor = \" [ D_s+ -> pi+ mu+ mu- ]cc \"\n Ds2PhiPi.DaughtersCuts = { \"pi+\" : \" ( PT > 300 * MeV ) & ( TRGHOSTPROB < %(TrackGhostProb)s ) & ( TRCHI2DOF < 3 ) & ( BPVIPCHI2 () > 9 ) \" % config,\n \"mu+\" : \" ( PT > 300 * MeV ) & ( TRGHOSTPROB < %(TrackGhostProb)s ) & ( TRCHI2DOF < 3 ) & ( BPVIPCHI2 () > 9 ) \" % config}\n\n Ds2PhiPi.CombinationCut = \"(ADAMASS('D_s+')<250*MeV) & in_range ( 970 * MeV , AM23 , 1070 * MeV )\"\n\n Ds2PhiPi.MotherCut = \"\"\"\n ( VFASPF(VCHI2) < 15 ) &\n ( (BPVLTIME () * c_light) >100 * micrometer ) &\n ( BPVIPCHI2() < 225 )\n \"\"\" \n \n _stdLoosePions = DataOnDemand(Location = \"Phys/StdLoosePions/Particles\")\n _stdLooseMuons = DataOnDemand(Location = \"Phys/StdLooseMuons/Particles\")\n\n return Selection (name,\n Algorithm = Ds2PhiPi,\n RequiredSelections = [ _stdLooseMuons, _stdLoosePions ])\n\n\n\ndef makeTau25Mu(name, config):\n \"\"\"\n Please contact Johannes Albrecht if you think of prescaling this line!\n \n Arguments:\n name : name of the Selection.\n \"\"\"\n \n Tau2MuMuMuMuMu = CombineParticles(\"Comine\"+name)\n Tau2MuMuMuMuMu.DecayDescriptor = \" [ tau+ -> mu+ mu+ mu+ mu- mu-]cc\"\n Tau2MuMuMuMuMu.DaughtersCuts = { \"mu+\" : \" ( PT > 300 * MeV ) & ( TRGHOSTPROB < %(TrackGhostProb)s ) & ( TRCHI2DOF < 3 ) & ( BPVIPCHI2 () > 9 ) \" % config }\n Tau2MuMuMuMuMu.CombinationCut = \"(ADAMASS('tau+')<400*MeV)\"\n\n Tau2MuMuMuMuMu.MotherCut = \"\"\"\n ( VFASPF(VCHI2) < 30 ) &\n ( (BPVLTIME () * c_light) > 100 * micrometer ) &\n ( BPVIPCHI2() < 225 )\n \"\"\" \n \n _stdLooseMuons = DataOnDemand(Location = \"Phys/StdLooseMuons/Particles\")\n\n return Selection (name,\n Algorithm = Tau2MuMuMuMuMu,\n RequiredSelections = [ _stdLooseMuons ])\n\n\ndef makeTau2pmm(name, config):\n \"\"\"\n Please contact Jon Harrison if you think of prescaling this line!\n \n Arguments:\n name : name of the Selection.\n \"\"\"\n \n Tau2PMuMu = CombineParticles(\"Comine\"+name)\n Tau2PMuMu.DecayDescriptors = [\" [ tau+ -> p+ mu+ mu- ]cc\",\" [ tau+ -> p~- mu+ mu+ ]cc\",\n \" [ Lambda_c+ -> p+ mu+ mu- ]cc\",\" [ Lambda_c+ -> p~- mu+ mu+ ]cc\" ]\n Tau2PMuMu.DaughtersCuts = { \"mu+\" : \" ( PT > 300 * MeV ) & ( TRCHI2DOF < 3 ) & ( BPVIPCHI2 () > 9 ) \"\\\n \"& ( PIDmu > -5 ) & ( (PIDmu - PIDK) > 0 ) & ( TRGHOSTPROB < %(TrackGhostProb)s )\"% config,\n \"p+\" : \" ( PT > 300 * MeV ) & ( TRCHI2DOF < 3 ) & ( BPVIPCHI2 () > 9 ) \"\\\n \"& (PIDp>10) & ( TRGHOSTPROB < %(TrackGhostProb)s )\" % config}\n\n Tau2PMuMu.CombinationCut = \"( (ADAMASS('tau+')<150*MeV) | (ADAMASS('Lambda_c+')<150*MeV) )\"\n\n Tau2PMuMu.MotherCut = \"\"\"\n ( VFASPF(VCHI2) < 15 ) &\n ( (BPVLTIME () * c_light) > 100 * micrometer ) &\n ( BPVIPCHI2() < 225 )\n \"\"\" \n \n _stdLooseMuons = DataOnDemand(Location = \"Phys/StdLooseMuons/Particles\")\n _stdLooseProtons = DataOnDemand(Location = \"Phys/StdLooseProtons/Particles\")\n\n return Selection (name,\n Algorithm = Tau2PMuMu,\n RequiredSelections = [ _stdLooseMuons, _stdLooseProtons ])\n \n","sub_path":"DaVinciDev_v38r1p1/Phys/StrippingArchive/python/StrippingArchive/Stripping23/StrippingRD/StrippingTau23MuLines.py","file_name":"StrippingTau23MuLines.py","file_ext":"py","file_size_in_byte":16611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"135103175","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.6 (3379)\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/betsee/util/io/guierror.py\n# Compiled at: 2019-08-01 01:03:54\n# Size of source mod 2**32: 13416 bytes\n\"\"\"\nHigh-level :mod:`QMessageBox`-based error handling facilities.\n\nSee Also\n----------\n:mod:`betsee.util.widget.guimessage`\n Error-agnostic :class:`QMessageBox` facilities.\n\"\"\"\nimport re, sys, traceback\nfrom PySide2.QtWidgets import QMessageBox\nfrom betse.util.type.obj import objects\nfrom betsee.util.app import guiapp\n\ndef install_exception_hook() -> None:\n \"\"\"\n Install a global exception hook overriding :mod:`PySide2`'s default insane\n exception handling behaviour with sane exception handling.\n\n By default, :mod:`PySide2`:\n\n #. Catches **uncaught exceptions** (i.e., exceptions automatically\n propagated up the call stack without being caught) raised during the\n GUI's event loop processing.\n #. Prints the tracebacks for these exceptions to standard error.\n #. Ignores these exceptions by silently returning control back to the main\n event handling loop.\n\n This behaviour is entirely invisible to end users and hence insane. This\n function addresses this by installing a new handler both interactively\n displaying *and* non-interactively logging exceptions.\n\n Caveats\n ----------\n Ideally, this function should be called *before* entering this event loop\n (i.e., calling the :meth:`betsee.util.app.guiapp.GUI_APP._exec` method).\n \"\"\"\n default_exception_handler = sys.excepthook\n\n def exception_hook(exception_type, exception, exception_traceback):\n try:\n from betse.util.io.log import logs\n logs.log_exception(exception)\n show_exception(exception)\n except Exception as exception_exception:\n default_exception_handler(type(exception_exception), exception_exception, traceback.extract_stack(exception_exception))\n sys.exit(1)\n\n sys.excepthook = exception_hook\n\n\ndef show_error(title: str, synopsis: str, exegesis: str=None, details: str=None) -> None:\n \"\"\"\n Display the passed error message(s) as a :mod:`QMessageBox`-driven modal\n message box of the :class:`QApplication` singleton for this application.\n\n Caveats\n ----------\n This function necessarily instantiates and initializes this singleton if\n needed. Doing so commonly invites chicken-and-egg issues between the\n :func:`init` and :func:`betse.lib.libs.reinit` methods and hence is\n inadvisable; in this case, however, the need to instantiate this singleton\n to display critical errors subsumes the need to instantiate this singleton\n in a more controlled manner.\n\n Parameters\n ----------\n title : str\n Title of this error to be displayed as the title of this message box.\n synopsis : str\n Synopsis of this error to be displayed as the text of this message box.\n exegesis : optional[str]\n Exegesis (i.e., explanation) of this error to be displayed as the\n so-called \"informative text\" of this message box below the synopsis of\n this error. Defaults to ``None``, in which case no such text is\n displayed.\n details : optional[str]\n Technical details of this error to be displayed as the so-called\n \"detailed text\" of this message box in monospaced font below both the\n synopsis and exegesis of this error in a discrete fold-down text area.\n Defaults to ``None``, in which case no such text is displayed.\n \"\"\"\n if not isinstance(title, str):\n raise AssertionError('\"{}\" not a string.'.format(title))\n else:\n assert isinstance(synopsis, str), '\"{}\" not a string.'.format(synopsis)\n TITLE_MAX_LEN = 80\n SYNOPSIS_MAX_LEN = 640\n EXEGESIS_MAX_LEN = 1280\n DETAILS_MAX_LEN = 2560\n guiapp.init()\n title_truncated = _truncate(text=title, max_len=TITLE_MAX_LEN)\n synopsis_truncated = _truncate(text=synopsis, max_len=SYNOPSIS_MAX_LEN)\n error_box = QMessageBox()\n error_box.setWindowTitle(title_truncated)\n error_box.setText(synopsis_truncated)\n error_box.setIcon(QMessageBox.Critical)\n error_box.setStandardButtons(QMessageBox.Ok)\n if exegesis is not None:\n assert isinstance(exegesis, str), '\"{}\" not a string.'.format(exegesis)\n exegesis_truncated = _truncate(text=exegesis, max_len=EXEGESIS_MAX_LEN)\n error_box.setInformativeText(exegesis_truncated)\n if details is not None:\n assert isinstance(details, str), '\"{}\" not a string.'.format(details)\n details_truncated = _truncate(text=details, max_len=DETAILS_MAX_LEN)\n error_box.setDetailedText(details_truncated)\n error_box.show()\n error_box.exec_()\n\n\ndef show_exception(exception: Exception) -> None:\n \"\"\"\n Display the passed exception as a :mod:`QMessageBox`-driven modal message\n box in the current application widget, creating this widget if necessary.\n\n Parameters\n ----------\n exception : Exception\n Exception to be displayed.\n \"\"\"\n if not isinstance(exception, Exception):\n raise AssertionError('\"{}\" not an exception.'.format(exception))\n else:\n exception_synopsis = getattr(exception, 'synopsis', None)\n exception_exegesis = getattr(exception, 'exegesis', None)\n if exception_synopsis is None:\n exception_synopsis = str(exception)\n if not exception_synopsis:\n exception_synopsis = objects.get_class_name_unqualified(exception)\n if hasattr(exception, 'title'):\n exception_title = exception.title\n else:\n exception_classname = type(exception).__name__\n exception_title = re.sub('([a-z])([A-Z])', '\\\\1 \\\\2', exception_classname)\n try:\n from betse.util.io import ioexceptions\n _, exception_traceback = ioexceptions.get_metadata(exception)\n except ImportError:\n exception_traceback = None\n\n show_error(title=exception_title,\n synopsis=exception_synopsis,\n exegesis=exception_exegesis,\n details=exception_traceback)\n\n\ndef _truncate(text: str, max_len: int) -> str:\n \"\"\"\n Passed string truncated to the passed maximum length by replacing the\n substring of this string exceeding that length with the conventional ASCII\n ellipses (i.e., ``...``).\n\n Parameters\n ----------\n text : str\n String to be truncated.\n max_len : int\n Maximum number of characters to truncate this string to.\n\n Returns\n ----------\n str\n Passed string truncated to this maximum length, as detailed above.\n\n See Also\n ----------\n :func:`betse.util.type.text.strs.truncate`\n General-purpose truncater from which this error-specific equivalent is\n derived. As the top-level of this submodule suggests, BETSE modules are\n *not* guaranteed to exist at this point. Ergo, this function pastes the\n :func:`betse.util.type.text.strs.truncate` function into this codebase.\n \"\"\"\n replacement = '...'\n if len(text) <= max_len:\n return text\n else:\n truncate_chars_count = len(text) - max_len + len(replacement)\n if truncate_chars_count > len(text):\n return replacement[:max_len]\n return text[:-truncate_chars_count] + replacement","sub_path":"pycfiles/betsee-1.1.1.0-py3.6/guierror.cpython-36.py","file_name":"guierror.cpython-36.py","file_ext":"py","file_size_in_byte":7492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"310040658","text":"from datetime import timedelta\n\nimport arrow\nimport pytz\nfrom django.conf import settings\nfrom django.db.models import F, Q, Count, OuterRef, Subquery, IntegerField, Exists\nfrom django.core.management.commands import dumpdata\nfrom django.contrib.auth.decorators import permission_required\nfrom django.http import HttpResponse, JsonResponse, HttpResponseBadRequest\nfrom django.shortcuts import render, get_object_or_404\nfrom django.utils import timezone\nfrom django.views.decorators.csrf import csrf_protect\n\nfrom urllib.parse import urlparse, parse_qs\n\n\nfrom clist.templatetags.extras import get_timezones\nfrom clist.models import Resource, Contest, Banner\nfrom true_coders.models import Party, Coder, Filter\nfrom ranking.models import Rating, Statistics\nfrom utils.regex import verify_regex\n\n\ndef get_timeformat(request):\n ret = settings.TIME_FORMAT_\n if request.user.is_authenticated:\n ret = request.user.coder.settings.get(\"time_format\", ret)\n return ret\n\n\ndef get_timezone(request):\n tz = request.GET.get(\"timezone\", None)\n if tz:\n result = None\n try:\n pytz.timezone(tz)\n result = tz\n except Exception:\n if tz.startswith(\" \"):\n tz = tz.replace(\" \", \"+\")\n for tzdata in get_timezones():\n if str(tzdata[\"offset\"]) == tz or tzdata[\"repr\"] == tz:\n result = tzdata[\"name\"]\n break\n\n if result:\n if \"update\" in request.GET:\n if request.user.is_authenticated:\n request.user.coder.timezone = result\n request.user.coder.save()\n else:\n request.session[\"timezone\"] = result\n return\n return result\n\n if request.user.is_authenticated:\n return request.user.coder.timezone\n return request.session.get(\"timezone\", settings.DEFAULT_TIME_ZONE_)\n\n\ndef get_view_contests(request, coder):\n user_contest_filter = Q()\n group_list = settings.GROUP_LIST_\n\n if coder:\n user_contest_filter = coder.get_contest_filter(['list'])\n group_list = bool(coder.settings.get(\"group_in_list\", group_list))\n\n group = request.GET.get('group')\n if group is not None:\n group_list = bool(group)\n\n now = timezone.now()\n result = []\n for group, query, order, limit in (\n (\"past\", Q(start_time__gt=now - timedelta(days=1), end_time__lt=now), \"-end_time\", settings.COUNT_PAST_),\n (\"running\", Q(start_time__lte=now, end_time__gte=now), \"end_time\", None),\n (\"coming\", Q(start_time__gt=now), \"start_time\", None),\n ):\n group_by_resource = {}\n contests = Contest.visible.filter(query).filter(user_contest_filter).order_by(order)\n contests = contests.prefetch_related('resource')\n if limit:\n contests = contests[:limit]\n if order.startswith('-'):\n contests = list(contests)\n contests.reverse()\n for contest in contests:\n contest.state = group\n if group_list:\n group_by_resource.setdefault(contest.resource.id, []).append(contest)\n\n if group_list:\n for contest in contests:\n rid = contest.resource.id\n if rid in group_by_resource:\n contest.group_size = len(group_by_resource[rid]) - 1\n result.append(contest)\n for c in group_by_resource[rid][1:]:\n c.sub_contest = True\n result.append(c)\n del group_by_resource[rid]\n else:\n result.extend(contests)\n return result\n\n\ndef get_timezone_offset(tzname):\n now = timezone.now()\n total_seconds = now.astimezone(pytz.timezone(tzname)).utcoffset().total_seconds()\n return int(round(total_seconds / 60, 0))\n\n\n@csrf_protect\ndef get_events(request):\n if request.user.is_authenticated:\n coder = request.user.coder\n else:\n coder = None\n\n referer = request.META.get('HTTP_REFERER')\n if referer:\n parsed = urlparse(referer)\n as_coder = parse_qs(parsed.query).get('as_coder')\n if as_coder and request.user.has_perm('as_coder'):\n coder = Coder.objects.get(user__username=as_coder[0])\n\n tzname = get_timezone(request)\n offset = get_timezone_offset(tzname)\n\n query = Q()\n categories = request.POST.getlist('categories')\n ignore_filters = request.POST.getlist('ignore_filters')\n if coder:\n query = coder.get_contest_filter(categories, ignore_filters)\n\n if not coder or coder.settings.get('calendar_filter_long', True):\n if categories == ['calendar'] and '0' not in ignore_filters:\n query &= Q(duration_in_secs__lt=timedelta(days=1).total_seconds())\n\n start_time = arrow.get(request.POST.get('start', timezone.now())).datetime\n end_time = arrow.get(request.POST.get('end', timezone.now() + timedelta(days=31))).datetime\n query = query & Q(end_time__gte=start_time) & Q(start_time__lte=end_time)\n\n search_query = request.POST.get('search_query', None)\n if search_query:\n search_query_re = verify_regex(search_query)\n query &= Q(host__iregex=search_query_re) | Q(title__iregex=search_query_re)\n\n party_slug = request.POST.get('party')\n if party_slug:\n party = get_object_or_404(Party.objects.for_user(request.user), slug=party_slug)\n query = Q(rating__party=party) & query\n\n contests = Contest.objects if party_slug else Contest.visible\n try:\n result = []\n for contest in contests.filter(query):\n c = {\n 'id': contest.pk,\n 'title': contest.title,\n 'host': contest.host,\n 'url': contest.url,\n 'start': (contest.start_time + timedelta(minutes=offset)).strftime(\"%Y-%m-%dT%H:%M:%S\"),\n 'end': (contest.end_time + timedelta(minutes=offset)).strftime(\"%Y-%m-%dT%H:%M:%S\"),\n 'countdown': contest.next_time,\n 'color': contest.resource.color,\n }\n result.append(c)\n except Exception as e:\n return JsonResponse({'message': f'query = `{search_query}`, error = {e}'}, safe=False, status=400)\n return JsonResponse(result, safe=False)\n\n\ndef main(request, party=None):\n viewmode = settings.VIEWMODE_\n open_new_tab = settings.OPEN_NEW_TAB_\n add_to_calendar = settings.ADD_TO_CALENDAR_\n hide_contest = settings.HIDE_CONTEST_\n\n if request.user.is_authenticated:\n if request.GET.get('as_coder') and request.user.has_perm('as_coder'):\n coder = Coder.objects.get(user__username=request.GET['as_coder'])\n else:\n coder = request.user.coder\n viewmode = coder.settings.get(\"view_mode\", viewmode)\n hide_contest = coder.settings.get(\"hide_contest\", hide_contest)\n open_new_tab = coder.settings.get(\"open_new_tab\", open_new_tab)\n add_to_calendar = coder.settings.get(\"add_to_calendar\", add_to_calendar)\n else:\n coder = None\n viewmode = request.GET.get(\"view\", viewmode)\n hide_contest = request.GET.get(\"hide_contest\", hide_contest)\n\n hide_contest = int(str(hide_contest).lower() in settings.YES_)\n\n time_format = get_timeformat(request)\n\n action = request.GET.get(\"action\")\n if action is not None:\n if action == \"party-contest-toggle\" and request.user.is_authenticated:\n party = get_object_or_404(Party.objects.for_user(request.user), slug=request.GET.get(\"party\"), author=coder)\n contest = get_object_or_404(Contest, pk=request.GET.get(\"pk\"))\n rating, created = Rating.objects.get_or_create(contest=contest, party=party)\n if not created:\n rating.delete()\n return HttpResponse(\"ok\")\n if action == \"hide-contest-toggle\":\n contest = get_object_or_404(Contest, pk=request.GET.get(\"pk\"))\n filt, created = Filter.objects.get_or_create(coder=coder, contest=contest, to_show=False)\n if not created:\n filt.delete()\n return HttpResponse(\"deleted\")\n return HttpResponse(\"created\")\n return HttpResponseBadRequest(\"fail\")\n\n tzname = get_timezone(request)\n if tzname is None:\n return HttpResponse(\"accepted\")\n\n if coder:\n ignore_filters = coder.ordered_filter_set.filter(categories__contains=['calendar'])\n ignore_filters = ignore_filters.filter(name__isnull=False).exclude(name='')\n ignore_filters = list(ignore_filters.values('id', 'name'))\n else:\n ignore_filters = []\n\n if not coder or coder.settings.get('calendar_filter_long', True):\n ignore_filters = ignore_filters + [{'id': 0, 'name': 'Disabled fitler'}]\n\n context = {\n \"ignore_filters\": ignore_filters,\n \"contests\": get_view_contests(request, coder),\n }\n\n if isinstance(party, Party):\n context[\"party\"] = {\n \"id\": party.id,\n \"toggle_contest\": 1,\n \"has_permission_toggle\": int(party.has_permission_toggle_contests(coder)),\n \"contest_ids\": party.rating_set.values_list('contest__id', flat=True),\n }\n\n now = timezone.now()\n banners = Banner.objects.filter(end_time__gt=now)\n if not settings.DEBUG:\n banners = banners.filter(enable=True)\n\n offset = get_timezone_offset(tzname)\n timezone_hm = f'{\"+\" if offset > 0 else \"-\"}{abs(offset // 60):02d}:{abs(offset % 60):02d}'\n\n context.update({\n \"offset\": offset,\n \"now\": now,\n \"viewmode\": viewmode,\n \"hide_contest\": hide_contest,\n \"timezone\": tzname,\n \"timezone_hm\": timezone_hm,\n \"time_format\": time_format,\n \"open_new_tab\": open_new_tab,\n \"add_to_calendar\": settings.ACE_CALENDARS_[add_to_calendar]['id'],\n \"banners\": banners,\n })\n\n return render(request, \"main.html\", context)\n\n\ndef resources(request):\n contests = Resource.objects.annotate(n_contests=Count('contest')).filter(pk=OuterRef('pk'))\n accounts = Resource.objects.annotate(n_accounts=Count('account')).filter(pk=OuterRef('pk'))\n resources = Resource.objects.select_related('module').annotate(\n n_contests=Subquery(contests.values('n_contests'), output_field=IntegerField()),\n n_accounts=Subquery(accounts.values('n_accounts'), output_field=IntegerField()),\n )\n resources = resources.annotate(priority=F('n_accounts') + F('n_contests'))\n resources = resources.order_by('-priority')\n return render(request, 'resources.html', {'resources': resources})\n\n\ndef resource(request, host):\n now = timezone.now()\n resource = get_object_or_404(Resource, host=host)\n has_statistics = Statistics.objects.filter(contest__resource=resource, contest_id=OuterRef('pk'))\n contests = resource.contest_set.filter(invisible=False).annotate(has_statistics=Exists(has_statistics))\n context = {\n 'resource': resource,\n 'accounts': resource.account_set.filter(coders__isnull=False).order_by('-modified'),\n 'contests': [\n ('running', contests.filter(start_time__lt=now, end_time__gt=now).order_by('start_time')),\n ('coming', contests.filter(start_time__gt=now).order_by('start_time')),\n ('past', contests.filter(end_time__lt=now).order_by('-end_time')),\n ],\n }\n return render(request, 'resource.html', context)\n\n\n@permission_required('clist.view_resources_dump_data')\ndef resources_dumpdata(request):\n response = HttpResponse(content_type=\"application/json\")\n dumpdata.Command(stdout=response).run_from_argv([\n 'manage.py',\n 'dumpdata',\n 'clist.resource',\n 'ranking.module',\n '--format', 'json'\n ])\n return response\n","sub_path":"clist/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":11777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"584300258","text":"import json\nimport time\n\nimport pymysql\nimport requests\n\n\n# 主函数\ndef home_page():\n url = \"https://api.shuidihuzhu.com/api/hz/order/v3/allocationSummary\"\n headers = {'cache-control': \"no-cache\", }\n response = requests.request(\"GET\", url, headers=headers)\n print(response.text)\n storage(response)\n\n\n# 存储数据函数\ndef storage(response):\n response_text = json.loads(response.text)\n print(response_text)\n data = response_text.get('data')\n total_member = int(data.get('totalMember'))\n total_amount = int(data.get('totalAllocationAmountInYuan'))\n localtime = time.localtime(time.time())\n str_time = time.strftime(\"%Y-%m-%d\", localtime)\n db = pymysql.connect(\"192.168.103.31\", \"root\", \"adminadmin\", \"water_safe\")\n # 使用 cursor() 方法创建一个游标对象 cursor\n cursor = db.cursor()\n # SQL 插入语句\n sql = \"\"\"INSERT INTO HOME(totalMember,totalAllocationAmountInYuan,times)VALUES (\"%d\",\"%d\",\"%s\")\"\"\" % (\n total_member, total_amount, str_time)\n\n # 执行sql语句\n cursor.execute(sql)\n # 提交到数据库执行\n db.commit()\n # 关闭数据库连接\n db.close()\n\n\nif __name__ == '__main__':\n home_page()\n","sub_path":"IDGdemo/crowdfuding/crowdfuding/home_page/home_page.py","file_name":"home_page.py","file_ext":"py","file_size_in_byte":1200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"14099540","text":"from django.shortcuts import render\nfrom django.http import JsonResponse\nfrom assets.models import GameProject\nfrom assets.models import HostInitialize\nfrom assets.models import HostInitializeLog\nfrom assets.models import Room\nfrom assets.models import Business\nfrom assets.models import TecentCloudAccount\nfrom assets.models import Area\nfrom assets.utils import get_ip\nfrom myworkflows.models import SpecialUserParamConfig\nfrom txcloud.TXCloud import TXCloudTC3\nfrom txcloud.TXCloud import TXCloudV2\nfrom txcloud.utils import gen_password\nfrom txcloud.utils import get_host_init_business\nfrom txcloud.utils import get_syndic_ip\nfrom txcloud.models import Region\nfrom txcloud.models import ServerZoneNumber\nfrom txcloud.models import MysqlZoneConfig\nfrom mysql.models import MysqlInstance\nfrom mysql.models import MyqlHistoryRecord\nfrom mysql.utils import ws_update_mysql_list\nfrom tasks import do_query_txserver_status\nfrom tasks import query_mysql_info\nfrom tasks import query_txcloud_async_result\nfrom cmdb.settings import PRODUCTION_ENV\nfrom cmdb.logs import PurchaseCloudServerLog\nfrom collections import defaultdict\n\nimport json\nimport time\n\n\ndef get_cloud_platform_administrator():\n \"\"\"获取云平台管理员\"\"\"\n obj, created = SpecialUserParamConfig.objects.get_or_create(param='CLOUD_PLATFORM_ADMINISTRATOR',\n defaults={\n 'param': 'CLOUD_PLATFORM_ADMINISTRATOR',\n 'remark': '云平台管理员'})\n return obj.get_user_obj_list()\n\n\ndef purchase_server(request):\n \"\"\"购买腾讯云服务器\"\"\"\n if request.method == 'GET':\n if request.user in get_cloud_platform_administrator():\n projects = GameProject.objects.prefetch_related('cloud_account').filter(status=1)\n projects = [{'id': p.id, 'text': p.project_name, 'cloud_account': 1 if p.cloud_account else 0} for p in\n projects]\n rooms = [{'id': r.id, 'text': r.area.chinese_name + '-' + r.room_name} for r in Room.objects.all()]\n success, business = get_host_init_business()\n business = [{'id': b, 'text': b} for b in business]\n period = {1: '1个月', 2: '2个月', 3: '3个月', 6: '半年', 12: '1年', 24: '2年', 36: '3年', 48: '4年', 60: '5年'}\n period = sorted(period.items(), key=lambda x: x[0], reverse=False)\n return render(request, 'purchase_txcloud_server.html',\n {'projects': projects, 'period': period, 'rooms': rooms, 'business': business})\n else:\n return render(request, '403.html')\n\n\ndef get_server_region(request):\n \"\"\"获取服务器地域\"\"\"\n if request.method == 'POST':\n raw_data = json.loads(request.body.decode('utf-8'))\n success = True\n data = ''\n try:\n if request.user not in get_cloud_platform_administrator():\n raise Exception('权限受限')\n project_id = raw_data.get('project', '0')\n if project_id == '0':\n # 选择其中一个帐号即可\n cloud_account = TecentCloudAccount.objects.last()\n else:\n project_obj = GameProject.objects.prefetch_related('cloud_account').get(pk=project_id)\n cloud_account = project_obj.cloud_account\n obj = TXCloudTC3(cloud_account.secret_id, cloud_account.secret_key, region='', action='DescribeRegions')\n success, msg = obj.python_request()\n if success:\n data = [\n {'code': x['region'], 'region': x['region_name'].replace(')', '').replace('(', '-').split('-')[0],\n 'city': x['region_name'].replace(')', '').replace('(', '-').split('-')[1]} for x in msg]\n data.sort(key=lambda x: x['city'])\n data.sort(key=lambda x: x['region'])\n Region.objects.all().delete()\n for r in data:\n Region.objects.create(**r)\n else:\n raise Exception(msg)\n\n except Exception as e:\n success = False\n data = str(e)\n finally:\n return JsonResponse({'success': success, 'data': data})\n\n\ndef get_server_zone(request):\n \"\"\"获取服务器可用区\"\"\"\n if request.method == 'POST':\n raw_data = json.loads(request.body.decode('utf-8'))\n success = True\n data = ''\n try:\n if request.user not in get_cloud_platform_administrator():\n raise Exception('权限受限')\n project_id = raw_data.get('project', '0')\n project_obj = GameProject.objects.prefetch_related('cloud_account').get(pk=project_id)\n cloud_account = project_obj.cloud_account\n region_code = raw_data.get('region_code', '0')\n obj = TXCloudTC3(cloud_account.secret_id, cloud_account.secret_key, region=region_code,\n action='DescribeZones')\n success, msg = obj.python_request()\n if success:\n data = msg\n else:\n raise Exception(msg)\n\n except Exception as e:\n success = False\n data = str(e)\n finally:\n return JsonResponse({'success': success, 'data': data})\n\n\ndef get_instance_type(request):\n \"\"\"获取实例机型\"\"\"\n if request.method == 'POST':\n raw_data = request.POST\n data = []\n try:\n if request.user not in get_cloud_platform_administrator():\n raise Exception('权限受限')\n project_id = raw_data.get('project', '0')\n project_obj = GameProject.objects.prefetch_related('cloud_account').get(pk=project_id)\n cloud_account = project_obj.cloud_account\n region_code = raw_data.get('region_code', '0')\n zone = raw_data.get('zone', '0')\n obj = TXCloudTC3(cloud_account.secret_id, cloud_account.secret_key, region=region_code,\n action='DescribeInstanceTypeConfigs',\n params={\"Filters\": [{\"Name\": \"zone\", \"Values\": [zone]}]})\n success, msg = obj.python_request()\n if success:\n q = raw_data.get('q', None)\n if q:\n data = [x for x in msg if q in x['text']]\n else:\n data = msg\n else:\n raise Exception(msg)\n\n except Exception as e:\n data = [str(e)]\n finally:\n return JsonResponse(data, safe=False)\n\n\ndef get_instance_config_info(request):\n \"\"\"获取实例配置\"\"\"\n if request.method == 'POST':\n raw_data = request.POST\n data = []\n try:\n if request.user not in get_cloud_platform_administrator():\n raise Exception('权限受限')\n project_id = raw_data.get('project', '0')\n project_obj = GameProject.objects.prefetch_related('cloud_account').get(pk=project_id)\n cloud_account = project_obj.cloud_account\n region_code = raw_data.get('region_code', '0')\n zone = raw_data.get('zone', '0')\n charge_mode = raw_data.get('charge_mode', '0')\n obj = TXCloudTC3(cloud_account.secret_id, cloud_account.secret_key, region=region_code,\n action='DescribeZoneInstanceConfigInfos',\n params={\"Filters\": [{\"Name\": \"zone\", \"Values\": [zone]},\n {\"Name\": \"instance-charge-type\", \"Values\": [charge_mode]}]})\n success, msg = obj.python_request()\n if success:\n # cpu/内存筛选\n instance_cpu = raw_data.get('instance_cpu', '0')\n instance_memory = raw_data.get('instance_memory', '0')\n if instance_cpu != '0':\n msg = [x for x in msg if x['cpu'] == instance_cpu]\n if instance_memory != '0':\n msg = [x for x in msg if x['memory'] == instance_memory]\n msg = [{'id': x['id'],\n 'text': 'CPU:' + x['cpu'] + '核' + ' / ' + '内存:' + x['memory'] + 'GB' + ' / ' + x['text']} for\n x in msg]\n\n # 下拉框搜索\n q = raw_data.get('q', None)\n if q:\n data = [x for x in msg if q in x['text']]\n else:\n data = msg\n else:\n raise Exception(msg)\n\n except Exception as e:\n data = [str(e)]\n finally:\n return JsonResponse(data, safe=False)\n\n\ndef get_image_version(request):\n \"\"\"获取镜像版本\"\"\"\n if request.method == 'POST':\n raw_data = request.POST\n data = []\n try:\n if request.user not in get_cloud_platform_administrator():\n raise Exception('权限受限')\n project_id = raw_data.get('project', '0')\n project_obj = GameProject.objects.prefetch_related('cloud_account').get(pk=project_id)\n cloud_account = project_obj.cloud_account\n region_code = raw_data.get('region_code', '0')\n image_type = raw_data.get('image_type', '0')\n system_framework = raw_data.get('system_framework', '0')\n operation_system = raw_data.get('operation_system', '0')\n obj = TXCloudTC3(cloud_account.secret_id, cloud_account.secret_key, region=region_code,\n action='DescribeImages',\n params={\"Filters\": [{\"Name\": \"image-type\", \"Values\": [image_type]}]})\n success, msg = obj.python_request()\n if success:\n msg = [x for x in msg if system_framework in x['text'] and operation_system in x['text']]\n q = raw_data.get('q', None)\n if q:\n data = [x for x in msg if q in x['text']]\n else:\n data = msg\n else:\n raise Exception(msg)\n\n except Exception as e:\n data = [str(e)]\n finally:\n return JsonResponse(data, safe=False)\n\n\ndef get_server_project(request):\n \"\"\"获取服务器项目列表数据\"\"\"\n if request.method == 'POST':\n raw_data = json.loads(request.body.decode('utf-8'))\n data = []\n try:\n if request.user not in get_cloud_platform_administrator():\n raise Exception('权限受限')\n project_id = raw_data.get('project', '0')\n project_obj = GameProject.objects.prefetch_related('cloud_account').get(pk=project_id)\n cloud_account = project_obj.cloud_account\n config = {\"Action\": \"DescribeProject\"}\n obj = TXCloudV2(config, cloud_account.secret_id, cloud_account.secret_key, domain='account.api.qcloud.com')\n success, msg = obj.post()\n if success:\n q = raw_data.get('q', None)\n if q:\n data = [x for x in msg if q in x['text']]\n else:\n data = msg\n else:\n raise Exception(msg)\n\n except Exception as e:\n data = [str(e)]\n finally:\n return JsonResponse(data, safe=False)\n\n\ndef get_security_group(request):\n \"\"\"获取安全组\"\"\"\n if request.method == 'POST':\n raw_data = json.loads(request.body.decode('utf-8'))\n data = []\n try:\n if request.user not in get_cloud_platform_administrator():\n raise Exception('权限受限')\n project_id = raw_data.get('project', '0')\n project_obj = GameProject.objects.prefetch_related('cloud_account').get(pk=project_id)\n cloud_account = project_obj.cloud_account\n region_code = raw_data.get('region_code', '0')\n obj = TXCloudTC3(cloud_account.secret_id, cloud_account.secret_key, region=region_code,\n action='DescribeSecurityGroups', host=\"vpc.tencentcloudapi.com\", service='vpc')\n success, msg = obj.python_request()\n if success:\n q = raw_data.get('q', None)\n if q:\n data = [x for x in msg if q in x['text']]\n else:\n data = msg\n else:\n raise Exception(msg)\n\n except Exception as e:\n data = [str(e)]\n finally:\n return JsonResponse(data, safe=False)\n\n\ndef inquiry_price(request):\n \"\"\"服务器购买前面询价\"\"\"\n if request.method == 'POST':\n raw_data = json.loads(request.body.decode('utf-8'))\n success = True\n data = ''\n try:\n if request.user not in get_cloud_platform_administrator():\n raise Exception('权限受限')\n project_id = raw_data.pop('cmdb_project', '0')\n project_obj = GameProject.objects.prefetch_related('cloud_account').get(pk=project_id)\n cloud_account = project_obj.cloud_account\n region_code = raw_data.pop('Region', '')\n data_disk = raw_data.get('DataDisks', [])\n if not data_disk:\n raw_data.pop('DataDisks', [])\n obj = TXCloudTC3(cloud_account.secret_id, cloud_account.secret_key, region=region_code,\n action='InquiryPriceRunInstances', params=raw_data)\n success, msg = obj.python_request()\n if success:\n data = msg\n else:\n raise Exception(msg)\n\n except Exception as e:\n success = False\n data = str(e)\n finally:\n return JsonResponse({'success': success, 'data': data})\n\n\ndef run_instance(request):\n \"\"\"购买服务器\"\"\"\n if request.method == 'POST':\n success = True\n data = ''\n log = PurchaseCloudServerLog()\n try:\n if request.user not in get_cloud_platform_administrator():\n raise Exception('权限受限')\n raw_data = json.loads(request.body.decode('utf-8'))\n project_id = raw_data.pop('cmdb_project', '0')\n project_obj = GameProject.objects.prefetch_related('cloud_account').get(pk=project_id)\n cloud_account = project_obj.cloud_account\n room = Room.objects.get(pk=raw_data.pop('room'))\n result, syndic_ip = get_syndic_ip(project_obj, room)\n business = Business.objects.get(business_name=raw_data.pop('business'))\n region_code = raw_data.pop('Region', '')\n random_pass = gen_password()\n raw_data['LoginSettings']['Password'] = random_pass\n data_disk = raw_data.get('DataDisks', [])\n if not data_disk:\n raw_data.pop('DataDisks', [])\n action = 'RunInstances'\n if PRODUCTION_ENV:\n obj = TXCloudTC3(cloud_account.secret_id, cloud_account.secret_key, region=region_code, action=action,\n params=raw_data)\n success, data = obj.python_request()\n else:\n data = ['ins-r4g9mlye']\n if success:\n log.logger.info('购买腾讯云服务器提交成功: {}'.format(data))\n instance_set = data\n # 插入主机初始化表\n for i in instance_set:\n host_initialize, created = HostInitialize.objects.update_or_create(instance_id=i,\n defaults={\n 'password': random_pass,\n 'project': project_obj,\n 'add_user': request.user,\n 'instance_id': i,\n 'room': room,\n 'business': business,\n 'syndic_ip': syndic_ip,\n 'instance_state': 'PENDING'})\n HostInitializeLog.objects.create(host_initialize=host_initialize)\n\n # 异步查询实例创建后运行状态\n do_query_txserver_status.delay([i], cloud_account.secret_id, cloud_account.secret_key,\n cloud_account.__str__(), region_code)\n else:\n raise Exception(data)\n\n except Exception as e:\n success = False\n data = str(e)\n log.logger.error('购买腾讯云服务器提交失败: {}'.format(data))\n finally:\n return JsonResponse({'success': success, 'data': data})\n\n\ndef get_server_zone_number(request):\n \"\"\"获取实例机型可用区数量\"\"\"\n if request.method == 'POST':\n success = True\n data = 'ok'\n try:\n if request.user not in get_cloud_platform_administrator():\n raise Exception('权限受限')\n # 选择其中一个帐号即可\n cloud_account = TecentCloudAccount.objects.last()\n action = 'DescribeZoneInstanceConfigInfos'\n zone_dict = defaultdict(set)\n for r in Region.objects.all():\n obj = TXCloudTC3(cloud_account.secret_id, cloud_account.secret_key, region=r.code, action=action)\n success, data = obj.python_request()\n for d in data:\n zone_dict[d['instance_type']].add(d['zone'])\n for i, z in zone_dict.items():\n ServerZoneNumber.objects.update_or_create(instance_type=i,\n defaults={'zone_detail': json.dumps(list(z))})\n except Exception as e:\n success = False\n data = str(e)\n finally:\n return JsonResponse({'success': success, 'data': data})\n\n\ndef mysql_purchase(request):\n \"\"\"购买腾讯云数据库填单页面\"\"\"\n if request.method == 'GET':\n if request.user in get_cloud_platform_administrator():\n projects = GameProject.objects.prefetch_related('cloud_account').filter(status=1)\n projects = [{'id': p.id, 'text': p.project_name, 'cloud_account': 1 if p.cloud_account else 0} for p in\n projects]\n areas = [{'id': a.id, 'text': a.chinese_name} for a in Area.objects.all()]\n purchase_period = [\n {'id': 1, 'text': '1个月'},\n {'id': 2, 'text': '2个月'},\n {'id': 3, 'text': '3个月'},\n {'id': 4, 'text': '4个月'},\n {'id': 5, 'text': '5个月'},\n {'id': 6, 'text': '半年'},\n {'id': 7, 'text': '7个月'},\n {'id': 8, 'text': '8个月'},\n {'id': 9, 'text': '9个月'},\n {'id': 10, 'text': '10个月'},\n {'id': 11, 'text': '11个月'},\n {'id': 12, 'text': '1年'},\n {'id': 24, 'text': '2年'},\n {'id': 36, 'text': '3年'},\n ]\n return render(request, 'txcloud_mysql_purchase.html',\n {'projects': projects, 'areas': areas, 'purchase_period': purchase_period})\n else:\n return render(request, '403.html')\n\n\ndef get_mysql_config(request):\n \"\"\"获取云数据库mysql可售配置信息\"\"\"\n if request.method == 'POST':\n success = True\n data = ''\n try:\n if request.user not in get_cloud_platform_administrator():\n raise Exception('权限受限')\n # 选择其中一个帐号即可\n cloud_account = TecentCloudAccount.objects.last()\n host = 'cdb.tencentcloudapi.com'\n service = 'cdb'\n action = 'DescribeDBZoneConfig'\n version = '2017-03-20'\n region = json.loads(request.body.decode('utf-8')).get('region_code', '')\n obj = TXCloudTC3(cloud_account.secret_id, cloud_account.secret_key, region=region, action=action,\n version=version, host=host, service=service)\n success, data = obj.python_request()\n if success:\n MysqlZoneConfig.objects.all().delete()\n for d in data:\n for zone in d['zones']:\n MysqlZoneConfig.objects.create(region=d['region'], region_name=d['region_name'],\n zone=zone['zone'], zone_name=zone['zone_name'],\n config_data=json.dumps(zone['sell_type']),\n protect_mode=json.dumps(zone['protect_mode']))\n\n else:\n raise Exception(data)\n except Exception as e:\n success = False\n data = str(e)\n finally:\n return JsonResponse({'success': success, 'data': data})\n\n\ndef get_mysql_region(request):\n \"\"\"获取云数据库mysql地域\"\"\"\n if request.method == 'POST':\n success = True\n data = ''\n try:\n if request.user not in get_cloud_platform_administrator():\n raise Exception('权限受限')\n\n configs = MysqlZoneConfig.objects.values('region', 'region_name').distinct()\n data = [{'code': x['region'], 'city': x['region_name']} for x in configs]\n data.sort(key=lambda x: x['code'])\n\n except Exception as e:\n success = False\n data = str(e)\n finally:\n return JsonResponse({'success': success, 'data': data})\n\n\ndef get_mysql_zone(request):\n \"\"\"获取云mysql数据库可用区\"\"\"\n if request.method == 'POST':\n success = True\n data = ''\n try:\n if request.user not in get_cloud_platform_administrator():\n raise Exception('权限受限')\n region = json.loads(request.body.decode('utf-8')).get('region_code', '')\n zone_list = MysqlZoneConfig.objects.filter(region=region).values('zone', 'zone_name').distinct()\n data = [{'zone': zone['zone'], 'zone_name': zone['zone_name']} for zone in zone_list]\n data.sort(key=lambda x: x['zone'])\n\n except Exception as e:\n success = False\n data = str(e)\n finally:\n return JsonResponse({'success': success, 'data': data})\n\n\ndef get_mysql_framework(request):\n \"\"\"获取云mysql数据库架构\"\"\"\n if request.method == 'POST':\n success = True\n data = ''\n try:\n if request.user not in get_cloud_platform_administrator():\n raise Exception('权限受限')\n raw_data = json.loads(request.body.decode('utf-8'))\n region = raw_data.get('region', '')\n zone = raw_data.get('zone', '')\n obj = MysqlZoneConfig.objects.filter(region=region, zone=zone)\n if not obj:\n raise Exception('找不到mysql配置信息')\n\n config_data = json.loads(obj[0].config_data)\n data = list(set([f['framework'] for c in config_data for f in c['configs']]))\n\n except Exception as e:\n success = False\n data = str(e)\n finally:\n return JsonResponse({'success': success, 'data': data})\n\n\ndef get_mysql_engine(request):\n \"\"\"获取云mysql数据库版本\"\"\"\n if request.method == 'POST':\n success = True\n data = ''\n try:\n if request.user not in get_cloud_platform_administrator():\n raise Exception('权限受限')\n raw_data = json.loads(request.body.decode('utf-8'))\n region = raw_data.get('region', '')\n zone = raw_data.get('zone', '')\n framework = raw_data.get('framework', '')\n obj = MysqlZoneConfig.objects.filter(region=region, zone=zone)\n if not obj:\n raise Exception('找不到mysql配置信息')\n\n config_data = json.loads(obj[0].config_data)\n protect_mode = json.loads(obj[0].protect_mode)\n config_data = list(filter(lambda x: x['configs'][0]['framework'] == framework, config_data))\n if not config_data:\n raise Exception('该可用区不支持')\n config_data = config_data[0]\n data = {\n 'engine_version': json.loads(config_data['engine_version']),\n 'configs': config_data['configs'],\n 'protect_mode': protect_mode,\n }\n\n except Exception as e:\n success = False\n data = str(e)\n finally:\n return JsonResponse({'success': success, 'data': data})\n\n\ndef get_mysql_price(request):\n \"\"\"获取云数据库mysql实例价格\"\"\"\n if request.method == 'POST':\n success = True\n data = ''\n try:\n if request.user not in get_cloud_platform_administrator():\n raise Exception('权限受限')\n raw_data = json.loads(request.body.decode('utf-8'))\n project = raw_data.pop('project', None)\n if project is None:\n # 选择其中一个帐号即可\n cloud_account = TecentCloudAccount.objects.last()\n else:\n project_obj = GameProject.objects.prefetch_related('cloud_account').get(pk=project)\n cloud_account = project_obj.cloud_account\n region = raw_data.pop('region', '')\n action = 'DescribeDBPrice'\n version = '2017-03-20'\n host = 'cdb.tencentcloudapi.com'\n service = 'cdb'\n obj = TXCloudTC3(cloud_account.secret_id, cloud_account.secret_key, region=region, action=action,\n version=version, host=host, service=service, params=raw_data)\n success, data = obj.python_request()\n except Exception as e:\n success = False\n data = str(e)\n finally:\n return JsonResponse({'success': success, 'data': data})\n\n\ndef get_mysql_default_params(request):\n \"\"\"获取腾讯云数据库初始化参数\"\"\"\n if request.method == 'POST':\n success = True\n data = ''\n try:\n if request.user not in get_cloud_platform_administrator():\n raise Exception('权限受限')\n raw_data = json.loads(request.body.decode('utf-8'))\n project = raw_data.pop('project', '0')\n if project == '0':\n # 选择其中一个帐号即可\n cloud_account = TecentCloudAccount.objects.last()\n else:\n project_obj = GameProject.objects.prefetch_related('cloud_account').get(pk=project)\n cloud_account = project_obj.cloud_account\n\n region = raw_data.pop('Region', '')\n action = 'DescribeDefaultParams'\n version = '2017-03-20'\n host = 'cdb.tencentcloudapi.com'\n service = 'cdb'\n obj = TXCloudTC3(cloud_account.secret_id, cloud_account.secret_key, region=region, action=action,\n version=version, host=host, service=service, params=raw_data)\n success, data = obj.python_request()\n if success:\n data = data[0]\n else:\n raise Exception(data)\n\n except Exception as e:\n success = False\n data = str(e)\n finally:\n return JsonResponse({'success': success, 'data': data})\n\n\ndef create_txcloud_mysql(request):\n \"\"\"创建云数据库实例mysql\"\"\"\n if request.method == 'POST':\n success = True\n data = ''\n password = ''\n port = ''\n try:\n if request.user not in get_cloud_platform_administrator():\n raise Exception('权限受限')\n raw_data = json.loads(request.body.decode('utf-8'))\n cmdb_project = raw_data.pop('cmdb_project')\n project_obj = GameProject.objects.get(pk=cmdb_project)\n cloud_account = project_obj.cloud_account\n area = raw_data.pop('area')\n area_obj = Area.objects.get(pk=area)\n purpose = raw_data.pop('purpose')\n pay_type = raw_data.pop('pay_type')\n if pay_type == 'PRE_PAID':\n action = 'CreateDBInstance'\n elif pay_type == 'HOUR_PAID':\n action = 'CreateDBInstanceHour'\n raw_data.pop('Period')\n else:\n raise Exception('未知的计费类型')\n region = raw_data.pop('region')\n is_init = raw_data.pop('is_init', '0')\n\n if is_init == '1':\n # 增加初始化参数\n password = gen_password()\n raw_data['Password'] = password\n lower_case_table_names = raw_data.pop('lower_case_table_names')\n character_set_server = raw_data.pop('character_set_server')\n raw_data['ParamList'] = {'lower_case_table_names': lower_case_table_names,\n 'character_set_server': character_set_server}\n port = raw_data.get('Port')\n else:\n raw_data.pop('Port')\n\n version = '2017-03-20'\n host = 'cdb.tencentcloudapi.com'\n service = 'cdb'\n if PRODUCTION_ENV:\n obj = TXCloudTC3(cloud_account.secret_id, cloud_account.secret_key, version=version, region=region,\n action=action, params=raw_data, host=host, service=service)\n success, data = obj.python_request()\n else:\n data = ['cdb-pxdvxhnk']\n if success:\n # 插入数据库实例列表\n tx_region, created = Region.objects.get_or_create(code=region, defaults={'code': region, 'city': '',\n 'region': ''})\n for i in data:\n mysql = MysqlInstance.objects.create(project=project_obj, area=area_obj.chinese_name,\n purpose=purpose,\n port=port, user='root', password=password, cmdb_area=area_obj,\n instance_id=i, status=0, open_wan=0, tx_region=tx_region)\n # 新增记录\n source_ip = get_ip(request)\n MyqlHistoryRecord.objects.create(mysql=mysql, create_user=request.user, type=1, source_ip=source_ip)\n # 查询实例状态\n query_mysql_info.delay(region, cloud_account.secret_id, cloud_account.secret_key,\n cloud_account.__str__(), [i])\n else:\n raise Exception(data)\n\n except Exception as e:\n success = False\n data = str(e)\n finally:\n return JsonResponse({'success': success, 'data': data})\n\n\ndef open_mysql_wan(request):\n \"\"\"开通数据库外网访问\"\"\"\n if request.method == 'POST':\n success = True\n data = 'ok'\n try:\n if not request.user.is_superuser:\n raise Exception('权限受限')\n raw_data = json.loads(request.body.decode('utf-8'))\n mysql_obj = MysqlInstance.objects.get(pk=raw_data.get('id', 0))\n region = mysql_obj.get_tx_region_code()\n instance_id = mysql_obj.instance_id\n if not instance_id:\n raise Exception('InstanceId为空')\n project = mysql_obj.project\n cloud_account = project.cloud_account\n if not cloud_account:\n raise Exception('该项目没有关联云帐号')\n\n if PRODUCTION_ENV:\n action = 'OpenWanService'\n version = '2017-03-20'\n host = 'cdb.tencentcloudapi.com'\n service = 'cdb'\n params = {\n 'InstanceId': instance_id,\n }\n obj = TXCloudTC3(cloud_account.secret_id, cloud_account.secret_key, version=version, region=region,\n action=action, params=params, host=host, service=service)\n success, data = obj.python_request()\n else:\n data = '7227cd44-f628f69e-a30b684c-52783f84'\n\n if success:\n mysql_obj.status = 3\n mysql_obj.save()\n ws_update_mysql_list()\n # 异步查询腾讯云任务执行结果\n query_txcloud_async_result.delay(region, cloud_account.secret_id, cloud_account.secret_key,\n cloud_account.__str__(), instance_id, data)\n\n except MysqlInstance.DoesNotExist:\n success = False\n data = '找不到数据库实例'\n except Exception as e:\n success = False\n data = str(e)\n finally:\n return JsonResponse({'success': success, 'data': data})\n","sub_path":"txcloud/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":33801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"472684209","text":"# Copyright 2018 The TensorFlow Authors All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Helper functions used for training PBA models.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom autoaugment.helper_utils import setup_loss, decay_weights, cosine_lr # pylint: disable=unused-import\n\nfrom sklearn.metrics import accuracy_score\n\nfrom sklearn.metrics import balanced_accuracy_score\n\nfrom sklearn.metrics import classification_report\n\n\ndef detail_eval(preds,targets):\n print('preds:',preds.shape)\n print('targets:',targets.shape)\n #print('np.unique(targets):',np.unique(targets))\n #print('np.unique(preds): ',np.unique(preds))\n from sklearn.metrics import classification_report\n from sklearn.metrics import accuracy_score\n print(accuracy_score(targets, preds))\n cr = classification_report(targets, preds,output_dict= True)\n a1,a2,a3 = cr['macro avg']['f1-score'] ,cr['macro avg']['precision'],cr['macro avg']['recall'] \n topover = (a1+a2+a3)/3 \n print(classification_report(targets, preds))\n from sklearn.metrics import balanced_accuracy_score\n from sklearn.metrics import accuracy_score\n from sklearn.metrics import confusion_matrix\n matrix = confusion_matrix(targets, preds)\n #print(matrix.diagonal()/matrix.sum(axis=1))\n #print(matrix)\n\ndef eval_child_model(session, model, data_loader, mode):\n \"\"\"Evaluates `model` on held out data depending on `mode`.\n\n Args:\n session: TensorFlow session the model will be run with.\n model: TensorFlow model that will be evaluated.\n data_loader: DataSet object that contains data that `model` will evaluate.\n mode: Will `model` either evaluate validation or test data.\n\n Returns:\n Accuracy of `model` when evaluated on the specified dataset.\n\n Raises:\n ValueError: if invalid dataset `mode` is specified.\n \"\"\"\n print('#####################MODE#####################')\n print(mode)\n if mode == 'val':\n images = data_loader.val_images\n labels = data_loader.val_labels\n names = []\n elif mode == 'test':\n images = data_loader.test_images\n labels = data_loader.test_labels\n names = data_loader.names\n else:\n raise ValueError('Not valid eval mode')\n assert len(images) == len(labels)\n tf.logging.info('model.batch_size is {}'.format(model.batch_size))\n eval_batches = int(len(images) / model.batch_size)\n if len(images) % model.batch_size != 0:\n eval_batches += 1\n correct = 0\n count = 0\n data_pred = []\n logits = []\n data_target = []\n d = []\n for i in range(eval_batches):\n eval_images = images[i * model.batch_size:(i + 1) * model.batch_size]\n eval_labels = labels[i * model.batch_size:(i + 1) * model.batch_size]\n preds = session.run(\n model.predictions,\n feed_dict={\n model.images: eval_images,\n model.labels: eval_labels,\n })\n correct += np.sum(\n np.equal(np.argmax(eval_labels, 1), np.argmax(preds, 1)))\n count += len(preds)\n #data_target.append(eval_labels)\n #get categoric prediction from logit\n for p in preds:\n data_pred.append(np.argmax(p))\n if(mode == 'test'):\n logits.append(p)\n for l in eval_labels:\n data_target.append(np.argmax(l))\n assert count == len(images)\n tf.logging.info('correct: {}, total: {}'.format(correct, count))\n data_pred = np.asarray(data_pred)\n data_target = np.asarray(data_target)\n detail_eval(data_pred,data_target)\n #if mode == 'test':\n acc = accuracy_score(data_target, data_pred)\n cr=classification_report(data_target, data_pred,output_dict= True)\n print(\"SAVING SCORE\")\n log_score = open(\"log_score.txt\",\"a\")\n log_score.write('logits: '+str(logits) + \"\\n\")\n log_score.write('names: '+str(names) + \"\\n\")\n log_score.write('balanced accuracy: '+str(balanced_accuracy_score(data_target, data_pred))+'\\n')\n log_score.write('accuracy:'+str(acc)+'\\n')\n log_score.write('report: '+str(cr)+'\\n')\n log_score.close()\n import pickle\n try:\n statsDict = pickle.load(open('statsDict.p','rb'))\n except IOError:\n statsDict = {}\n statsDict['type'] = []\n statsDict['logits'] = []\n statsDict['names'] = []\n statsDict['acc'] = []\n statsDict['report'] = []\n \n statsDict['type'].append(mode)\n statsDict['logits'].append(logits)\n statsDict['names'].append(names)\n statsDict['acc'].append(acc)\n statsDict['report'].append(str(cr))\n pickle.dump(statsDict,open('statsDict.p','wb'))\n print(\"SAVED!!\")\n\n return correct / count\n\n\ndef step_lr(learning_rate, epoch):\n \"\"\"Step Learning rate.\n\n Args:\n learning_rate: Initial learning rate.\n epoch: Current epoch we are one. This is one based.\n\n Returns:\n The learning rate to be used for this current batch.\n \"\"\"\n if epoch < 80:\n return learning_rate\n elif epoch < 120:\n return learning_rate * 0.1\n else:\n return learning_rate * 0.01\n\n\ndef get_lr(curr_epoch, hparams, iteration=None):\n \"\"\"Returns the learning rate during training based on the current epoch.\"\"\"\n assert iteration is not None\n batches_per_epoch = int(hparams.train_size / hparams.batch_size)\n if 'svhn' in hparams.dataset and 'wrn' in hparams.model_name:\n lr = step_lr(hparams.lr, curr_epoch)\n elif 'cifar' in hparams.dataset or ('svhn' in hparams.dataset and\n 'shake_shake' in hparams.model_name):\n lr = cosine_lr(hparams.lr, curr_epoch, iteration, batches_per_epoch,\n hparams.num_epochs)\n else:\n lr = cosine_lr(hparams.lr, curr_epoch, iteration, batches_per_epoch,\n hparams.num_epochs)\n tf.logging.log_first_n(tf.logging.WARN, 'Default to cosine learning rate.', 1)\n return lr\n\n\ndef run_epoch_training(session, model, data_loader, curr_epoch):\n \"\"\"Runs one epoch of training for the model passed in.\n\n Args:\n session: TensorFlow session the model will be run with.\n model: TensorFlow model that will be evaluated.\n data_loader: DataSet object that contains data that `model` will evaluate.\n curr_epoch: How many of epochs of training have been done so far.\n\n Returns:\n The accuracy of 'model' on the training set\n \"\"\"\n steps_per_epoch = int(model.hparams.train_size / model.hparams.batch_size)\n tf.logging.info('steps per epoch: {}'.format(steps_per_epoch))\n curr_step = session.run(model.global_step)\n assert curr_step % steps_per_epoch == 0\n\n # Get the current learning rate for the model based on the current epoch\n curr_lr = get_lr(curr_epoch, model.hparams, iteration=0)\n tf.logging.info('lr of {} for epoch {}'.format(curr_lr, curr_epoch))\n\n correct = 0\n count = 0\n for step in range(steps_per_epoch):\n curr_lr = get_lr(curr_epoch, model.hparams, iteration=(step + 1))\n # Update the lr rate variable to the current LR.\n model.lr_rate_ph.load(curr_lr, session=session)\n if step % 20 == 0:\n tf.logging.info('Training {}/{}'.format(step, steps_per_epoch))\n\n train_images, train_labels = data_loader.next_batch(curr_epoch)\n _, step, preds = session.run(\n [model.train_op, model.global_step, model.predictions],\n feed_dict={\n model.images: train_images,\n model.labels: train_labels,\n })\n\n correct += np.sum(\n np.equal(np.argmax(train_labels, 1), np.argmax(preds, 1)))\n count += len(preds)\n train_accuracy = correct / count\n\n tf.logging.info('Train accuracy: {}'.format(train_accuracy))\n return train_accuracy\n\n","sub_path":"pba/helper_utils.py","file_name":"helper_utils.py","file_ext":"py","file_size_in_byte":8465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"317724578","text":"import json\nimport logging\nimport signal\nimport subprocess\nfrom functools import lru_cache\nfrom pprint import pprint\nfrom subprocess import PIPE, CalledProcessError\n\nimport semver\nfrom cached_property import cached_property\n\nBRIGHTSIDE_NAME = \"Brightside\"\nlog = logging.getLogger(__name__)\n_version = None\n\n\nclass BrightCallError(Exception):\n def __init__(self, returncode, cmd, arguments, output=None, stderr=None):\n self.returncode = returncode\n self.cmd = cmd\n self.arguments = arguments\n self.output = self.stdout = output\n self.stderr = stderr\n self.errors = None\n self.message = None\n\n def __str__(self):\n if self.returncode and self.returncode < 0:\n return \"Command '%s' died with %d.\" % (self.cmd, -self.returncode)\n else:\n if self.stderr:\n return \"%s command with arguments '%s' returned non-zero exit status %d and error: %s\" % (\n BRIGHTSIDE_NAME, self.arguments, self.returncode, self.stderr)\n else:\n return \"%s command with arguments '%s' returned non-zero exit status %d.\" % (\n BRIGHTSIDE_NAME, self.arguments, self.returncode)\n\n def __repr__(self):\n return \"BrightCallError(%s, %s, %s, %s, %s)\" % (repr(self.returncode), repr(self.cmd), repr(self.arguments), repr(self.stdout), repr(self.stderr))\n\n\n@lru_cache(maxsize=None)\ndef version():\n \"\"\"\n Returns full version of the CA Brightside that is installed globally as ``bright`` commmand as a string - e.g. ``1.0.2-next.201806261725``.\n\n The version obtained only once. Subquent calls to this function return the same value.\n\n You can use ``semver`` module to parse it and compare:\n\n if not semver.match(version(), \">=1.0.1\")):\n ...\n \"\"\"\n return _version()\n\n\ndef _version():\n data = bright(\"--version\")\n return data[\"version\"].strip()\n\n\ndef _call_command_and_parse_json(command):\n cp = subprocess.run(command, shell=True, stdout=PIPE,\n stderr=PIPE, encoding=\"utf8\", check=True)\n if cp.stdout: \n j = json.loads(cp.stdout)\n else:\n j = None\n log.debug(\"JSON: j\")\n log.debug(\"command_response: %s \" % cp)\n return j, cp\n\n\ndef bright(args, return_data=True):\n \"\"\"\n Executes CA Brightside with arguments of this function. The response is returned as Python data structures.\n\n Parameter ``return_data`` is by default ``True`` and it caused to return only the data section without metadata.\n\n Metadata are processed automatically and if they mean that commands was not successful and ``BrightCallError`` exception\n is raised.\n\n Example:\n\n jobs = bright(\"zos-jobs list jobs\")\n\n # jobs is equal to:\n [{'class': 'A',\n 'files-url': 'https://ca32.ca.com:1443/zosmf/restjobs/jobs/J0038667USILCA11D4B949F2.......%3A/files',\n 'job-correlator': 'J0038667USILCA11D4B949F2.......:',\n 'jobid': 'JOB38667',\n 'jobname': 'PLAPALLC',\n 'owner': 'PLAPE03',\n 'phase': 20,\n 'phase-name': 'Job is on the hard copy queue',\n 'retcode': 'SEC ERROR',\n 'status': 'OUTPUT',\n 'subsystem': 'JES2',\n 'type': 'JOB',\n 'url': 'https://ca32.ca.com:1443/zosmf/restjobs/jobs/J0038667USILCA11D4B949F2.......%3A'}]\n \"\"\"\n if not isinstance(args, str):\n args = subprocess.list2cmdline(args)\n\n command = f\"bright --rfj {args}\"\n try:\n j, cp = _call_command_and_parse_json(command)\n if j is None:\n return None\n if not j.get(\"success\"):\n be = BrightCallError(cp.returncode, command,\n args, output=cp.stdout, stderr=cp.stderr)\n be.errors = j.get(\"errors\")\n be.message = j.get(\"message\")\n else:\n if \"data\" in j and return_data:\n return j[\"data\"]\n return j\n\n except CalledProcessError as e:\n log.debug(\"error: %s, output=%s\" % (repr(e), e.output))\n if e.stderr:\n raise BrightCallError(e.returncode, e.cmd,\n args, output=e.output, stderr=e.stderr)\n else:\n j = json.loads(e.output)\n be = BrightCallError(e.returncode, e.cmd, args, output=j.get(\n \"stdout\"), stderr=j.get(\"stderr\"))\n be.errors = j.get(\"errors\")\n be.message = j.get(\"message\")\n raise be\n\n\ndef check_brightside_version():\n v = version()\n log.debug(\"%s version: %s\" % (BRIGHTSIDE_NAME, v))\n required_version = \">=1.0.1\"\n if not semver.match(v, required_version):\n print(\"pybright requires %s %s but it is %s\" %\n (BRIGHTSIDE_NAME, required_version, v))\n\n\ncheck_brightside_version()\n","sub_path":"cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":4797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"495860188","text":"import keras\nimport tensorflow as tf\nimport numpy as np\n\nchar_to_index = dict( (chr(i+96), i) for i in range(1,27))\nchar_to_index[' '] = 0\nchar_to_index['-'] = 27\nchar_to_index['.'] = 28\n\nindex_to_char = dict( (i, chr(i+96)) for i in range(1,27))\nindex_to_char[0] = ' '\nindex_to_char[27] = '-'\nindex_to_char[28] = '.'\nmax_char = 19\nchar_dim = 29\n\nx = np.zeros((1, max_char, char_dim))\n\nmodel = tf.keras.models.load_model('boy_name.h5')\n\ndef make_name(): \n name = []\n x = np.zeros((1, max_char, char_dim))\n end = False\n i = 0\n while end==False:\n probs = list(model.predict(x)[0,i])\n probs = probs / np.sum(probs)\n index = np.random.choice(range(char_dim), p=probs)\n if i == max_char-2:\n character = '.'\n end = True\n else:\n character = index_to_char[index]\n name.append(character)\n x[0, i+1, index] = 1\n i += 1\n if character == '.':\n end = True\n \n print(''.join(name))\n\n\ndef make_name2(start_ch): \n name = []\n x = np.zeros((1, max_char, char_dim))\n ii = char_to_index[start_ch]\n x[0,0,ii] = 1\n end = False\n i = 1\n name.append(start_ch)\n while end==False:\n probs = list(model.predict(x)[0,i])\n probs = probs / np.sum(probs)\n index = np.random.choice(range(char_dim), p=probs)\n if i == max_char-2:\n character = '.'\n end = True\n else:\n character = index_to_char[index]\n name.append(character)\n x[0, i+1, index] = 1\n i += 1\n if character == '.':\n end = True\n \n print(''.join(name))\n \na = int(input('Do you want to enter first character of name: 0 for No / 1 for Yes'))\n\nif a == 0:\n for i in range(10):\n make_name()\nelse:\n b = input('enter first character')\n b = b.lower()\n for i in range(10): \n make_name2(b)\ninput() \n","sub_path":"get_boy_name.py","file_name":"get_boy_name.py","file_ext":"py","file_size_in_byte":1895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"338042667","text":"def prod(a):\n p = 1\n for x in a:\n p = p * x\n return p\n\ndef gen_sol(k, attempt, result, n):\n\n if len(attempt) == n:\n if sum(attempt) == prod(attempt):\n result.append(attempt)\n\n return\n\n else:\n lower_bound = 1\n if len(attempt) != 0:\n lower_bound = attempt[-1]\n \n for i in range(lower_bound, 2*k+1):\n gen_sol(k+1, attempt + [i], result, n)\n \n return result\n\n\ndef a(n):\n result = []\n gen_sol(1, [], result, n)\n return len(result)\n\n\nfor i in range(2, 40):\n print(a(i))\n","sub_path":"first_attempt.py","file_name":"first_attempt.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"124046966","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nfrom hwt.simulator.simTestCase import SimTestCase\nfrom hwtLib.logic.crcPoly import CRC_32\nfrom hwtLib.mem.cuckooHashTable import CuckooHashTable\nfrom hwt.hdl.constants import Time\n\n\nclass CuckooHashTableTC(SimTestCase):\n def setUp(self):\n SimTestCase.setUp(self)\n self.TABLE_SIZE = 32\n u = self.u = CuckooHashTable([CRC_32, CRC_32])\n u.KEY_WIDTH.set(16)\n u.DATA_WIDTH.set(8)\n u.LOOKUP_KEY.set(True)\n u.TABLE_SIZE.set(self.TABLE_SIZE)\n self.TABLE_CNT = 2\n self.prepareUnit(u)\n self.TABLE_MEMS = [getattr(self.model, \"tables_%d_inst\" % i).table_inst.ram_memory._val.val\n for i in range(self.TABLE_CNT)]\n\n def cleanupMemory(self):\n for ti in range(self.TABLE_CNT):\n table = getattr(self.model, \"tables_%d_inst\" % ti).table_inst\n mem = table.ram_memory.defVal\n for i in range(mem._dtype.size):\n mem.val[i] = mem._dtype.elmType.fromPy(0)\n\n def checkContains(self, reference):\n d = self.hashTableAsDict()\n for key, data in d.items():\n self.assertIn(key, reference)\n self.assertValEqual(data, reference[key])\n del reference[key]\n self.assertEqual(reference, {})\n\n def hashTableAsDict(self):\n d = {}\n for t in self.TABLE_MEMS:\n self.assertEqual(len(t), self.TABLE_SIZE)\n for i in range(self.TABLE_SIZE):\n key, data, vldFlag = self.parseItem(t[i])\n if vldFlag:\n key = int(key)\n d[key] = data\n return d\n\n def parseItem(self, item):\n \"\"\"\n :return: tuple (key, data, vldFlag)\n \"\"\"\n return self.u.tables[0].parseItem(item)\n\n def test_clean(self):\n u = self.u\n u.clean._ag.data.append(1)\n self.runSim(400 * Time.ns)\n for t in self.TABLE_MEMS:\n self.assertEqual(len(t), self.TABLE_SIZE)\n for i in range(self.TABLE_SIZE):\n _, _, vldFlag = self.parseItem(t[i])\n self.assertValEqual(vldFlag, 0, i)\n\n def test_simpleInsert(self):\n u = self.u\n u.clean._ag.data.append(1)\n reference = {56: 11,\n 99: 55,\n 104: 78,\n 15: 79,\n 16: 90}\n\n def planInsert(sim):\n yield sim.wait(30 * Time.ns)\n for k, v in sorted(reference.items(), key=lambda x: x[0]):\n u.insert._ag.data.append((k, v))\n\n self.procs.append(planInsert)\n\n self.runSim(650 * Time.ns)\n self.checkContains(reference)\n\n def test_simpleInsertAndLookup(self):\n u = self.u\n self.cleanupMemory()\n reference = {56: 11,\n 99: 55,\n 104: 78,\n 15: 79,\n 16: 90}\n expected = []\n found = 1\n occupied = 1\n for k, v in sorted(reference.items(), key=lambda x: x[0]):\n u.insert._ag.data.append((k, v))\n u.lookup._ag.data.append(k)\n expected.append((k, v, found, occupied))\n\n self.runSim(800 * Time.ns)\n self.checkContains(reference)\n self.assertValSequenceEqual(u.lookupRes._ag.data, expected)\n\n def test_80p_fill(self):\n u = self.u\n self.cleanupMemory()\n CNT = int(self.TABLE_SIZE * self.TABLE_CNT * 0.8)\n reference = {i + 1: i + 2 for i in range(CNT)}\n for k, v in sorted(reference.items(), key=lambda x: x[0]):\n u.insert._ag.data.append((k, v))\n\n self.runSim(CNT * 60 * Time.ns)\n self.checkContains(reference)\n\n def test_delete(self):\n u = self.u\n self.cleanupMemory()\n reference = {56: 11,\n 99: 55,\n 104: 78,\n 15: 79,\n 16: 90}\n toDelete = [15, 99]\n\n for k, v in sorted(reference.items(), key=lambda x: x[0]):\n u.insert._ag.data.append((k, v))\n\n def doDelete(sim):\n yield sim.wait(350 * Time.ns)\n u.delete._ag.data.extend(toDelete)\n self.procs.append(doDelete)\n\n self.runSim(500 * Time.ns)\n for k in toDelete:\n del reference[k]\n self.checkContains(reference)\n\n\nif __name__ == \"__main__\":\n import unittest\n suite = unittest.TestSuite()\n # suite.addTest(CuckooHashTableTC('test_lookupInEmpty'))\n suite.addTest(unittest.makeSuite(CuckooHashTableTC))\n runner = unittest.TextTestRunner(verbosity=3)\n runner.run(suite)\n","sub_path":"hwtLib/mem/cuckooHashTable_test.py","file_name":"cuckooHashTable_test.py","file_ext":"py","file_size_in_byte":4653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"324258112","text":"import sqlite3\n\n\ncon = sqlite3.connect('docdatabase.db')\n\nwith con:\n\n cur = con.cursor()\n cur.execute(\"select * from docdetails WHERE specialization='Cardiologist'\")\n col_names = [cn[0] for cn in cur.description]\n\n rows = cur.fetchall()\n\n print (\"{:6} {:10} {:2} {:2} {:10} {:10}\".format(col_names[0], col_names[1], col_names[2],col_names[3],col_names[4],col_names[5]))\n list = []\n for row in rows:\n data = \"{:<6} {:<10} {:2} {:2} {:10} {:10}\".format(row[0], row[1], row[2],row[3],row[4],row[5])\n list.append(data)\n \n for value in list:\n print (value)\n\n ","sub_path":"testdb.py","file_name":"testdb.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"494564305","text":"# \n# mpo_entg.py\n# Toric_Code-Python\n# calculate entanglement entropy in MPO\n#\n# created on Feb 18, 2019 by Yue Zhengyuan\n#\n\nimport numpy as np\nimport mps, mpo, gnd_state\nimport para_dict as p\nimport lattice as lat\nimport sys, os, datetime, time, json, ast\nfrom copy import copy\nfrom tqdm import tqdm\nfrom itertools import product\n\nargs = copy(p.args)\nnx = 6\nny = args['ny']\nsep = 10\nhz = args['hz']\n\nresult_dir = \"mpopair_bm-tevol_2019-05-09_20-09/\"\nlabel = \"quasi\"\nt_list = np.linspace(0, p.args['ttotal'], num=11, endpoint=True)\nt_list = np.delete(t_list, 0)\nfor t in [0.6]:\n op = np.load(result_dir + '{}_op_{}by{}_sep-{}_hz-{:.2f}_t-{:.2f}.npy'.format(label, nx, ny, sep, hz, t))\n op = list(op)\n entg_file = result_dir + '/entg_{}_{}by{}_sep-{}_t-{:.2f}.txt'.format(label, nx, ny, sep, t)\n with open(entg_file, 'w+') as file:\n pass\n\n for site in tqdm(range(len(op))):\n op, entg = mpo.position(op, site, args, oldcenter=site - 1, compute_entg=True)\n y = int(site / (nx - 1))\n x = site % (nx - 1)\n if y % 2 == 0:\n bonddir = 'r'\n else:\n bonddir = 'd'\n with open(entg_file, 'a+') as file:\n file.write(\"{}\\t{}\\t{}\\t{}\\t{}\\n\".format(site, x, int(y/2), bonddir, entg))\n","sub_path":"mpo_entg.py","file_name":"mpo_entg.py","file_ext":"py","file_size_in_byte":1272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"259646132","text":"from __future__ import print_function\nfrom __future__ import absolute_import\nfrom builtins import str\nfrom builtins import range\nfrom builtins import object\nimport os\nimport random\nfrom datetime import datetime\n\nimport requests\nfrom deprecation import deprecated\nfrom django.conf import settings\n\nfrom . import common_utils\nfrom .cache import Cache\n\n\nclass GenericCrawler(object):\n PREFIX = \"GENERIC CRAWLER\"\n PROXY_LIST = [\n {'http': u'http://46.225.241.6:8080'},\n {'http': u'http://66.119.180.104:80'},\n {'http': u'http://202.51.17.246:80'},\n {'http': u'http://202.179.190.210:8080'},\n {'http': u'http://103.94.64.90:8080'},\n {'http': u'http://202.138.254.29:8080'},\n {'http': u'http://197.159.16.2:8080'},\n {'http': u'http://host131-186-static.58-217-b.business.telecomitalia.it:8080'},\n {'http': u'http://182.253.142.16:8080'},\n {'http': u'http://152.231.29.210:8080'},\n {'http': u'http://103.234.137.158:8080'},\n {'http': u'http://131.161.124.36:3128'},\n {'http': u'http://195.138.91.117:8080'},\n {'http': u'http://185.36.172.190:8080'},\n {'http': u'http://client-90-123-107-176.kk-net.cz:8080'},\n {'http': u'http://46.209.25.1:8080'},\n {'http': u'http://165.16.113.210:8080'},\n {'http': u'http://168.232.157.142:8080'}\n ]\n USER_AGENT = {\"User-Agent\": \"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:53.0) Gecko/20100101 Firefox/53.0\",\n \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\",\n \"Accept-Language\": \"en-US,en;q=0.5\", \"Accept-Encoding\": \"gzip, deflate, br\"}\n\n REQUEST_CONNECTION_TIMEOUT = 10\n REQUEST_READ_TIMEOUT = 10\n REQUEST_RETRY_LIMIT = 10\n\n def __init__(self, crawl_options=None):\n if crawl_options is None:\n crawl_options = {}\n self.fdir = os.environ[\"HOME\"] + \"/html/\" + crawl_options.get(\"source\", \"misc\")\n self.crawl_options = crawl_options\n if hasattr(settings, \"REQUEST_CONNECTION_TIMEOUT\"):\n self.REQUEST_CONNECTION_TIMEOUT = settings.REQUEST_CONNECTION_TIMEOUT\n\n if hasattr(settings, \"REQUEST_READ_TIMEOUT\"):\n self.REQUEST_READ_TIMEOUT = settings.REQUEST_READ_TIMEOUT\n\n if hasattr(settings, \"REQUEST_RETRY_LIMIT\"):\n self.REQUEST_RETRY_LIMIT = settings.REQUEST_RETRY_LIMIT\n\n def run(self):\n crawl_cache = Cache(\"stocksense\")\n content = crawl_cache.get(self.url)\n if content:\n return content\n else:\n content = self.fetch_content(self.url)\n crawl_cache.put(self.url, content)\n return content\n\n def get_proxy(self):\n import random\n get_number = random.randint(0, len(self.PROXY_LIST) + 1)\n return self.PROXY_LIST[get_number]\n\n def download_using_proxy(self, url):\n temp_proxy = self.get_proxy()\n print(self.PREFIX, \"Requesting New Page using proxy -->\", temp_proxy, url)\n return requests.get(url, headers=self.USER_AGENT, proxies=temp_proxy, timeout=(\n self.REQUEST_CONNECTION_TIMEOUT,\n self.REQUEST_READ_TIMEOUT))\n\n def download_without_using_proxy(self, url):\n print(self.PREFIX, \"Requesting New Page without proxy -->\", url)\n return requests.get(url)\n\n def fetch_content(self, url, use_cache=False):\n \"\"\"\n For a given url fetch content from the internet\n :param url:\n :return:\n \"\"\"\n content = \"\"\n crawl_cache = Cache(\"stocksense\")\n if use_cache:\n content = crawl_cache.get(url)\n\n if content:\n return content\n content = self.__download_content_with_retry(url)\n crawl_cache.put(url, content)\n return content\n\n def __download_content_with_retry(self, url):\n \"\"\"\n Download content with\n :param url:\n :return:\n \"\"\"\n for i in range(self.REQUEST_RETRY_LIMIT):\n print(self.PREFIX, \"Trying for {0} time.\".format(i), url)\n\n try:\n if 0 == i:\n resp = self.download_without_using_proxy(url)\n else:\n resp = self.download_using_proxy(url)\n content = resp.content\n\n if resp.status_code == 200:\n break\n except Exception as err:\n print(self.PREFIX, err)\n return content\n\n @deprecated(details=\"use fetch content instead\")\n def get_data(self, url=\"\", crawl_options={}):\n if not crawl_options:\n crawl_options = self.crawl_options\n if not url:\n url = self.url\n\n if 'date_of_crawl' in crawl_options:\n if crawl_options['date_of_crawl'] == True:\n print(\"Asked today's Fresh Page?\")\n fname = self.fdir + \"/\" + common_utils.get_sha(url + str(datetime.now().date()))\n elif \"fresh\" in crawl_options:\n if crawl_options['fresh'] == True:\n print(\"Asked Fresh Page?\")\n fname = self.fdir + \"/\" + common_utils.get_sha(url + str(random.randint(99999999, 100000000000)))\n else:\n print(\"Asked for Archieved Page?\")\n fname = self.fdir + \"/\" + common_utils.get_sha(url)\n\n content = \"\"\n if os.path.exists(fname):\n print(\"Cache hit\")\n obj = open(fname)\n content = obj.read()\n else:\n for i in range(settings.REQUEST_RETRY_LIMIT):\n print(\"Trying for {0} time.\".format(i))\n\n if 0 == i:\n resp = self.download_without_using_proxy(url)\n else:\n resp = self.download_using_proxy(url)\n try:\n print(\"Got Response\")\n content = resp.content\n html_dir = os.path.dirname(fname)\n if not os.path.exists(html_dir):\n os.makedirs(html_dir)\n obj = open(fname, \"w\")\n obj.write(content)\n obj.close()\n break\n except Exception as err:\n print(err)\n return content\n","sub_path":"api/StockAdvisor/crawling/generic_crawler.py","file_name":"generic_crawler.py","file_ext":"py","file_size_in_byte":6250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"245046400","text":"def addTOList(listcontainer):\n listcontainer += [50]\n print(len(listcontainer))\nmylistContainer = [ 10, 20,30,40]\naddTOList(mylistContainer)\nprint(len(mylistContainer))\n\n# def addTOList(listcontainer):\n# listcontainer = listcontainer + [50]\n# print(len(listcontainer))\n# mylistContainer = [ 10, 20,30,40]\n# addTOList(mylistContainer)\n# print(len(mylistContainer))\n\n# def f1():\n# global x\n# x+= 1\n# print(x)\n# x = 12\n# print(\"x\")\n\n\n# def san(x):\n# print(x+1)\n# x = -2\n# x = 4\n# san(12)\n# def f1():\n# x=100\n# print(x)\n# x =+ 1\n# f1()\n\n# def func():\n# print(\"good morning\")\n# print(func())\n\n# variable length argument\n# value is passed as tuple\n# def sum(*n):\n# total= 0\n# for i in n:\n# total = total + i\n# return total;\n# print(sum(10)) #(10)\n# print(sum(10,20)) #(10,20)\n# print(sum()) # tuple willl be passed here as well but it will be empty as well\n\n\n\n","sub_path":"IshanScript2/conto.py","file_name":"conto.py","file_ext":"py","file_size_in_byte":916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"468482066","text":"from random import sample\n\ns = \"I couldn't believe that I could actually understand what I was reading \\\n : the phenomenal power of the human mind .\"\n\nresult = []\nfor w in s.split():\n if len(w) <= 4:\n result.append(w)\n else:\n result.append(w[0] + \"\".join(sample(w[1:-1], len(w[1:-1]))) + w[-1])\n\nprint(\" \".join(result))\n\n# random.shuffle()\n","sub_path":"yoshimura/chapter01/knock09.py","file_name":"knock09.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"48183335","text":"import pygame, sys\nfrom pygame.locals import *\n\n#make color\n\nBLACK = (0,0,0)\nWHITE = (255,255,255)\n\nwindow_height=300\nwindow_width=400\n\ndisplay_surf=pygame.display.set_mode((window_width,window_height)) #tuple, hàm tạo ra 1 cửa sổ\npygame.display.set_caption(\"ping pong\")\n\nfps = 60\nfps_clock=pygame.time.Clock()\n\nclass Paddle:\n def __init__(self,x,w,h):\n self.w=w\n self.h=h\n self.x=x\n self.y=int(window_height/2)\n self.rect=pygame.Rect(self.x,self.y,self.w,self.h)\n def draw(self):\n pygame.draw.rect(display_surf,WHITE,self.rect)\n def move(self,pos):\n self.rect.y=pos[1]\n self.draw()\n\nclass Autopaddle(Paddle):\n def __init__(self,x,w,h,speed,ball):\n super().__init__(x,w,h)\n self.speed=speed\n self.ball=ball\n def move(self):\n if self.ball.dir_x==1:\n if self.rect.y+self.rect.h/2self.ball.bottom:\n self.rect.y-=self.speed\n\nclass Scoreboard:\n def __init__(self,fontSize=20,score=0):\n self.x=window_width-150\n self.y=20\n self.score=score\n self.font=pygame.font.Font('freesansbold.ttf',fontSize)\n def display(self):\n result_srf=self.font.render('Score: = %s'%score,True,WHITE)\n result_rect=result_srf.rect_get()\n result_rect.topLeft=(window_width-150,20)\n display_surf.blit(result_srf,result_rect)\n\nclass Ball():\n def __init__(self,x,y,w,h,speed):\n self.x=x\n self.y=y\n self.w=w\n self.h=h\n self.speed=speed\n self.dir_x=-1 #left=-1, right=1\n self.dir_y=-1 #up=-1, down=1\n self.rect=pygame.Rect(x,y,w,h)\n def draw(self):\n pygame.draw.rect(display_surf,WHITE,self.rect)\n def bounce(self,axis):\n if axis =='x':\n self.dir_y*=-1\n if axis == 'y':\n self.dir_x*=-1\n def hit_ceiling(self):\n if self.dir_y==-1 and self.rect.top<=self.h:\n return True\n else:\n return False\n def hit_floor(self):\n if self.dir_y==1 and self.rect.bottom>=window_height-self.h:\n return True\n else:\n return False\n def hit_wall(self):\n if (self.dir_x==-1 and self.rect.left<=self.w) or (self.dir_x==1 and self.rect.right>=window_width-self.w):\n return True\n else:\n return False\n def hit_paddle(self,paddle):\n if self.rect.left<=paddle.rect.right and self.rect.bottom>=paddle.rect.top and self.rect.top<=paddle.rect.bottom:\n return True\n elif self.rect.right>=paddle.rect.left and self.rect.bottom>=paddle.rect.top and self.rect.top<=paddle.rect.bottom:\n return True\n else:\n return False\n def move(self):\n self.rect.x+=(self.dir_x*self.speed)\n self.rect.y+=(self.dir_y*self.speed)\n if self.hit_ceiling() or self.hit_floor():\n self.bounce('x')\n # if self.hit_wall():\n\nclass Game:\n def __init__(self,line_thickness=10,speed=1):\n self.line_thickness=line_thickness\n self.speed=speed\n #create a ball\n ball_x=int(window_width/2)\n ball_y=int(window_height/2)\n ball_w=self.line_thickness\n ball_h=self.line_thickness\n self.ball=Ball(ball_x,ball_y,ball_w,ball_h,self.speed)\n #create paddle\n self.paddles={}\n paddle_x=20\n paddle_w=self.line_thickness\n paddle_h=50\n self.paddles['user']=Paddle(paddle_x,paddle_w,paddle_h)\n self.paddles['computer']=Autopaddle(window_width-paddle_x,paddle_w,paddle_h,self.speed,self.ball)\n #score\n self.score=Scoreboard()\n def draw_arena(self):\n display_surf.fill((0,0,0))\n pygame.draw.line(display_surf,WHITE,(int(window_width/2),0),(int(window_width/2),window_height))\n #pygame.draw.rect(display_surf,white,(0,0,window_width,window_height))\n def update(self):\n self.ball.move()\n self.paddles['computer'].move()\n if self.ball.hit_paddle_user(self.paddles['user']):\n self.ball.bounce('y')\n self.score.score+=1\n self.score.display(self.score.score)\n if self.ball.hit_paddle_computer(self.paddles['computer']):\n self.ball.bounce('y')\n self.draw_arena()\n self.ball.draw()\n self.paddles['user'].draw()\n self.paddles['computer'].draw()\n\n\ndef main():\n pygame.init()\n game=Game()\n while True:\n for event in pygame.event.get():\n if event.type == QUIT:\n pygame.quit()\n sys.exit()\n if event.type==MOUSEMOTION:\n game.paddles['user'].move(event.pos)\n game.update()\n pygame.display.update()\n fps_clock.tick(fps)\n\nif __name__=='__main__':\n main()","sub_path":"Session04/lesson4/lesson.py","file_name":"lesson.py","file_ext":"py","file_size_in_byte":4889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"196971266","text":"from RobotArm import RobotArm\nrobotArm = RobotArm('exercise 9')\nrobotArm.speed = 2\n\n# Jouw python instructies zet je vanaf hier:\nrobotArm.grab()\n\naantal = 0\n\nfor i in range(4):\n\n aantal += 1\n\n for c in range(0,aantal,1):\n robotArm.grab()\n\n for g in range(5):\n robotArm.moveRight()\n\n robotArm.drop()\n for g in range(5):\n robotArm.moveLeft()\n\n robotArm.moveRight()\n# Na jouw code wachten tot het sluiten van de window:\nrobotArm.wait()\n\n\n#Verplaats alle stapels vijf stappen naar rechts.\n\n#Je mag maximaal 12 regels code gebruiken inclusief de import, het laden van de robotarm en de wait\n","sub_path":"robotarm/opdracht8.py","file_name":"opdracht8.py","file_ext":"py","file_size_in_byte":645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"250018289","text":"from apiclient.http import MediaFileUpload\nfrom GoolgeDrAPI.myconfig import file_name, file_path, mimeType, number_retry_upload\nfrom GoolgeDrAPI.utils import slack\nimport os \nimport sys\nimport logging\nimport time\n\nlogger = logging.getLogger('GoolgeDrAPI')\n\ndef upload(service, *args, **kargs):\n\n if not os.path.exists(file_path):\n msg = f'File not found {file_path}'\n logger.debug(msg)\n slack(msg) \n sys.exit()\n else:\n msg = f'Upload file, src_file {file_path}, size {os.path.getsize(file_path)} bytes'\n logger.debug(msg)\n slack(msg) \n base_metadata = {\n 'name': file_name, \n 'mimeType': mimeType\n }\n if 'parents_id' in kargs:\n base_metadata['parents'] = kargs['parents_id']\n \n msg = f'File metadata {base_metadata}'\n logger.debug(msg)\n slack(msg)\n\n base_payload = MediaFileUpload(file_path, chunksize=1024*1024, resumable = True)\n request = service.files().create(body=base_metadata,media_body=base_payload)\n\n upload_sucess = \"No\"\n upload_failed_count = 0\n while upload_sucess == \"No\":\n try: \n response = None\n while response is None:\n\n status, response = request.next_chunk()\n if status:\n logger.debug(f\"Upload progress {int(100*status.progress())}%\")\n else:\n msg = f'Uploaded done, detail {response}' \n logger.debug(msg)\n slack(msg)\n \n upload_sucess = 'Yes'\n\n except Exception as err:\n msg = f'Upload error, detail {err}'\n logger.debug(msg)\n slack(msg)\n\n upload_sucess = \"No\"\n upload_failed_count += 1\n\n msg = f'Try upload again, try count {upload_failed_count}'\n logger.debug(msg)\n slack(msg)\n\n time.sleep(5) \n if upload_failed_count == number_retry_upload:\n msg = \"Maximum number of retry upload, Stop upload job\"\n logger.debug(msg)\n slack(msg)\n sys.exit()\n","sub_path":"GoolgeDrAPI/file.py","file_name":"file.py","file_ext":"py","file_size_in_byte":2368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"103794256","text":"import numpy\nfrom random import sample\nfrom collections import deque\n\nfrom keras import backend as K\n\n\n# ref: https://github.com/farizrahman4u/qlearning4k/blob/master/qlearning4k/memory.py\nclass ExperienceReplay:\n\n def __init__(self, memory_size=100, fast=True):\n self.fast = fast\n self.memory = deque() if memory_size == -1 else deque(maxlen=memory_size)\n self.memory_size = memory_size\n self.input_shape = None\n self.batch_function = None\n\n # Log\n self.memory_filled = False\n\n def remember(self, state, action_index, reward, state_next, game_over):\n self.input_shape = state.shape[1:]\n self.memory.append(numpy.concatenate(\n [state.flatten(), numpy.array(action_index).flatten(), numpy.array(reward).flatten(),\n state_next.flatten(), 1 * numpy.array(game_over).flatten()]))\n\n # Log\n if not self.memory_filled and not len(self.memory) % (self.memory_size / 10):\n print('-- Memory:', len(self.memory))\n if not self.memory_filled and len(self.memory) == self.memory_size:\n self.memory_filled = True\n print('-- Memory: filled')\n\n def get_batch(self, model, target_model, batch_size, gamma=0.9):\n if self.fast:\n return self.get_batch_fast(model, target_model, batch_size, gamma)\n if len(self.memory) < batch_size:\n batch_size = len(self.memory)\n\n num_actions = model.get_output_shape_at(0)[-1]\n samples = numpy.array(sample(self.memory, batch_size))\n input_dim = numpy.prod(self.input_shape)\n\n state = samples[:, 0: input_dim]\n action_index = samples[:, input_dim]\n reward = samples[:, input_dim + 1]\n next_state = samples[:, input_dim + 2: 2 * input_dim + 2]\n game_over = samples[:, 2 * input_dim + 2]\n\n reward = reward.repeat(num_actions).reshape((batch_size, num_actions))\n game_over = game_over.repeat(num_actions).reshape((batch_size, num_actions))\n state = state.reshape((batch_size,) + self.input_shape)\n next_state = next_state.reshape((batch_size,) + self.input_shape)\n\n q_next_state = numpy.max(target_model.predict(next_state), axis=1).repeat(num_actions).reshape(\n (batch_size, num_actions))\n\n delta = numpy.zeros((batch_size, num_actions))\n action_index = numpy.cast['int'](action_index)\n delta[numpy.arange(batch_size), action_index] = 1\n targets = (1 - delta) * model.predict(state) + delta * (reward + gamma * (1 - game_over) * q_next_state)\n return state, targets\n\n def reset_memory(self):\n self.memory.clear()\n\n def set_batch_function(self, model, target_model, input_shape, batch_size, num_actions, gamma):\n input_dim = numpy.prod(input_shape)\n samples = K.placeholder(shape=(batch_size, input_dim * 2 + 3))\n\n state = samples[:, 0: input_dim]\n action_index = samples[:, input_dim]\n reward = samples[:, input_dim + 1]\n next_state = samples[:, input_dim + 2: 2 * input_dim + 2]\n game_over = samples[:, 2 * input_dim + 2: 2 * input_dim + 3]\n\n reward = K.reshape(reward, (batch_size, 1))\n reward = K.repeat(reward, num_actions)\n reward = K.reshape(reward, (batch_size, num_actions))\n game_over = K.repeat(game_over, num_actions)\n game_over = K.reshape(game_over, (batch_size, num_actions))\n state = K.reshape(state, (batch_size,) + input_shape)\n next_state = K.reshape(next_state, (batch_size,) + input_shape)\n\n q_next_state = K.max(target_model(next_state), axis=1)\n q_next_state = K.reshape(q_next_state, (batch_size, 1))\n q_next_state = K.repeat(q_next_state, num_actions)\n q_next_state = K.reshape(q_next_state, (batch_size, num_actions))\n\n delta = K.reshape(K.one_hot(K.reshape(K.cast(action_index, \"int32\"), (-1, 1)), num_actions),\n (batch_size, num_actions))\n\n targets = (1 - delta) * model(state) + delta * (reward + gamma * (1 - game_over) * q_next_state)\n self.batch_function = K.function(inputs=[samples], outputs=[state, targets])\n\n def get_batch_fast(self, model, target_model, batch_size, gamma):\n if len(self.memory) < batch_size:\n return None\n samples = numpy.array(sample(self.memory, batch_size))\n if not hasattr(self, 'batch_function') or self.batch_function is None:\n self.set_batch_function(model, target_model, self.input_shape, batch_size,\n model.get_output_shape_at(0)[-1], gamma)\n state, targets = self.batch_function([samples])\n return state, targets\n","sub_path":"trainer/memory.py","file_name":"memory.py","file_ext":"py","file_size_in_byte":4691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"110725254","text":"import os, fnmatch\n\ndef find(pattern, dir = os.curdir):\n\tfor (thisDir, subDir, file) in os.walk(dir):\n\t\tfor name in subDir + file:\n\t\t\tif fnmatch.fnmatch(name, pattern):\n\t\t\t\tfullPath = os.path.join(thisDir, name)\n\t\t\t\tyield fullPath\n\t\t\t\t\ndef findList(pattern, dir = os.curdir, sorted = False):\n\tmatches = list(find(pattern, dir))\n\tif sorted:\n\t\tmatches.sort()\n\treturn matches\n\t\n\t\nif __name__ == '__main__':\n\timport sys\n\tpattern, dir = sys.argv[1], sys.argv[2]\n\tfor name in find(pattern, dir): print(name)\n\t\n\t\n","sub_path":"old/Python/OLD/OLD/dir/find.py","file_name":"find.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"153987384","text":"# coding=utf-8\nimport urllib,urllib.request,re,os\n\nuser_agent='Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0'\nheaders={'User_Agent':user_agent}\n\nclass Tool:\n\treplaceIphoto=re.compile('lthumb')\n\tdef replace(self,x):\n\t\tx=re.sub(self.replaceIphoto,'lphoto',x)\n\n\nclass DOUBAN:\n\tdef __init__(self,baseUrl):\n\t\tself.baseUrl=baseUrl\n\t\tself.tool=Tool()\n#得到网页url\n\tdef getPage(self,url):\n\t\ttry:\n\t\t\trequest=urllib.request.Request(url)\n\t\t\tresponse=urllib.request.urlopen(request)\n\t\t\treturn response.read().decode('utf-8')\n\t\texcept urllib.request.URLError as e:\n\t\t\tif hasattr(e,'reason'):\n\t\t\t\tprint(u'连接失败原因:',e.reason)\n\t\t\t\treturn None\n#得到相册页数\n\tdef getPageNum(self,url):\n\t\tpage=self.getPage(url)\n\t\tpattern=re.compile('1')\n\t\tm=re.findall(pattern,page)\n\t\tnum=int(m[0])\n\t\treturn num\n\n#得到图片url\n\tdef getContent(self,url):\n\t\titems=[]\n\t\tfor x in range(self.getPageNum(url)):\n\t\t\tpageurl=url+'?start='+str(x*18)\n\t\t\tpage_response=self.getPage(pageurl)\t\n\t\t\tpattern=re.compile('')\n\t\t\titems.extend(re.findall(pattern,page_response))\n\t\treturn items\n\t\tprint(items)\n\n#小图换大图url\n\tdef replaceName(self,url):\n\t\titems=self.getContent(url)\n\t\tpattern=re.compile('lthumb')\n\t\tsub_url=[re.sub(pattern,'lphoto',x) for x in items]\n\t\treturn sub_url\n#保存路径\n\tdef mkdir(self,path):\n\t\tisExists=os.path.exists(path)\n\t\tif not isExists:\n\t\t\tos.mkdir(path)\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\n#保存单张图片\n\tdef save_single(self,url):\n\t\t#得到相册名\n\t\t'''pattern=re.compile('(.*?)')\n\t\tresponse=urllib.request.urlopen(urllib.request.Request(url)).read().decode('utf-8')\n\t\tname=re.findall(pattern,response)\n\t\t#print(name)\n\t\tpattern_=re.compile('-')\n\t\tname_final=re.sub(pattern_,'_',name[0])\n\t\tself.mkdir(name_final)\n\t\t#为相片命名\n\t\t'''\n\t\titems=self.replaceName(url)\n\t\tprint(len(items))\n\t\tfor item in items:\n\t\t\tpattern=re.compile('https.*?public/p(\\d+)')\n\t\t\tx=re.findall(pattern,item)\n\t\t\t#print(x)\n\t\t\tfilename=x[0]+'.jpg'\n\t\t\turllib.request.urlretrieve(item,filename)\n\t\t\t\n\t\t\nif __name__=='__main__':\n\turl=input('plz input the album url:')\n\tdouban=DOUBAN(url)\n\tdouban.save_single(url)\n","sub_path":"scrapy_douban/douban.py","file_name":"douban.py","file_ext":"py","file_size_in_byte":2220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"207622376","text":"#############################################################################\n# Copyright (c) 2017-present, Opus One Energy Solutions Corporation\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n#############################################################################\n\nfrom collections import OrderedDict\nimport re\n\nimport networkx\n\n\ndef graph_from_ascii(network_string):\n \"\"\" Produces a networkx graph, based on an ascii drawing\n of a network\n \"\"\"\n EDGE_CHAR_NEIGHBOURS = {\n \"-\": [Point(-1, 0), Point(1, 0)],\n \"\\\\\": [Point(-1, -1), Point(1, 1)],\n \"/\": [Point(-1, 1), Point(1, -1)],\n \"|\": [Point(0, -1), Point(0, 1)]\n }\n EDGE_CHARS = {\"\\\\\", \"-\", \"/\", \"|\"}\n nodes = list(node_iter(network_string))\n\n node_chars = OrderedDict()\n line_labels = {}\n line_label_char_positions = set()\n for node_label, root_position in nodes:\n node_label_char_positions = {\n root_position + Point(offset, 0)\n for offset, _ in enumerate(node_label)\n }\n if node_label.startswith(\"(\") and node_label.endswith(\")\"):\n label_value = node_label[1:-1]\n line_labels[root_position] = label_value\n line_label_char_positions |= node_label_char_positions\n else:\n node_chars.update(\n (pos, node_label) for pos in node_label_char_positions\n )\n\n # we'll treat edge labels (e.g. \"(my_label)\") as consecutive \"-\" edge chars\n edge_chars = OrderedDict(\n (pos, (char if char in EDGE_CHARS else \"-\"))\n for pos, char in char_iter(network_string)\n if char in EDGE_CHARS or pos in line_label_char_positions\n )\n\n edge_char_to_edge_map = {}\n edges = []\n\n for pos, char in edge_chars.items():\n\n neighbors_in_edges = [\n pos+pos_offset\n for pos_offset in EDGE_CHAR_NEIGHBOURS[char]\n if pos+pos_offset in edge_char_to_edge_map\n ] # assume for now these are all `-` characters\n\n if len(neighbors_in_edges) == 1: # Add this node to the edge\n neighbor = neighbors_in_edges[0]\n edge_char_to_edge_map[pos] = edge_char_to_edge_map[neighbor]\n edge_char_to_edge_map[pos][\"points\"].append(pos)\n elif len(neighbors_in_edges) == 0: # Make a new edge\n edge_char_to_edge_map[pos] = dict(points=[pos], nodes=[])\n edges.append(edge_char_to_edge_map[pos])\n else:\n raise BadEdgeException(\"Edge character '{}' at <{}> has too\"\n \"many neighbors.\".format(char, pos))\n\n neighboring_nodes = [\n node_chars[pos+pos_offset]\n for pos_offset in EDGE_CHAR_NEIGHBOURS[char]\n if pos+pos_offset in node_chars\n ]\n edge_char_to_edge_map[pos][\"nodes\"] += neighboring_nodes\n\n ascii_graph = networkx.OrderedGraph()\n ascii_graph.add_nodes_from(\n (node, {\"position\": position})\n for node, position in nodes\n if position not in line_label_char_positions\n )\n ascii_graph.add_edges_from(\n tuple(edge[\"nodes\"])\n for edge in edges if edge[\"nodes\"]\n )\n networkx.set_edge_attributes(ascii_graph, name=\"length\", values={\n tuple(edge[\"nodes\"]): len(edge[\"points\"])\n for edge in edges if edge[\"nodes\"]\n })\n networkx.set_edge_attributes(\n ascii_graph, name=\"label\",\n values={\n tuple(edge_char_to_edge_map[pos][\"nodes\"]): label\n for pos, label in line_labels.items()\n }\n )\n return ascii_graph\n\n\nclass Point(object):\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n def __add__(self, other):\n return Point(self.x + other.x, self.y + other.y)\n\n def __iter__(self):\n for el in (self.x, self.y):\n yield el\n\n def __repr__(self):\n return \"Point({}, {})\".format(self.x, self.y)\n\n def __eq__(self, other):\n return (type(self) == type(other) and\n self.x == other.x and\n self.y == other.y\n )\n\n def __hash__(self):\n return hash((self.__class__, self.x, self.y))\n\n\ndef char_iter(network_string):\n return (\n (Point(col, row), char)\n for row, line in enumerate(network_string.split(\"\\n\"))\n for col, char in enumerate(line)\n )\n\n\ndef node_iter(network_string):\n for row, line in enumerate(network_string.split(\"\\n\")):\n for match in re.finditer('\\(?([0-9A-Za-z_{}]+)\\)?', line):\n yield (match.group(0), Point(match.start(), row))\n\n\nclass BadEdgeException(Exception):\n pass\n","sub_path":"asciigraf/asciigraf.py","file_name":"asciigraf.py","file_ext":"py","file_size_in_byte":4691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"466917254","text":"#MASTER\nmenu = \"\"\"\nBienvenido al conversor de monedas\n1- Pesos Colombianos\n2- Pesos Argentinos\n3- Pesos Mexicanos\n4- Pesos Chilenos\nElige una Opción\n\"\"\"\nopcion = int(input(menu)) #ingresamos el valor en texto\n\nif opcion == 1:\n pesos = input(\"Cuántos $$ pesos Colombianos tienes: \")\n pesos = float(pesos)\n valor_dolar = 3489\n dolares = pesos / valor_dolar\n dolares = round(dolares, 2)\n dolares = str(dolares)\n print(\"Tienes $$\"+ \" \" + dolares + \" \" + \"Dólares\")\nelif opcion == 2:\n pesos = input(\"Cuántos $$ pesos Argentinos tienes: \")\n pesos = float(pesos)\n valor_dolar = 65\n dolares = pesos / valor_dolar\n dolares = round(dolares, 2)\n dolares = str(dolares)\n print(\"Tienes $$\"+ \" \" + dolares + \" \" + \"Dólares\")\nelif opcion == 3:\n pesos = input(\"Cuántos $$ pesos Mexicanos tienes: \")\n pesos = float(pesos)\n valor_dolar = 24\n dolares = pesos / valor_dolar\n dolares = round(dolares, 2)\n dolares = str(dolares)\n print(\"Tienes $$\"+ \" \" + dolares + \" \" + \"Dólares\")\nelif opcion == 4:\n pesos = input(\"Cuántos $$ pesos Chilenos Tienes: \")\n pesos = float(pesos)\n valor_dolar = 722\n dolares = pesos / valor_dolar\n dolares = round(dolares, 2)\n dolares = str(dolares)\n print(\"Tienes $$\" + \" \" + dolares + \" \" + \"Dólares\")\nelse:\n print(\"Ingresa una opción correcta por favor\")\n","sub_path":"PrimerprogramaPy.py","file_name":"PrimerprogramaPy.py","file_ext":"py","file_size_in_byte":1367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"5527825","text":"# Standard Library Imports\nimport sys\nimport re\n\ntry:\n import urllib.parse as urlparse\nexcept ImportError:\n # noinspection PyUnresolvedReferences\n import urlparse\n\nPY3 = sys.version_info >= (3, 0)\nunicode_type = type(u\"\")\n\n\nclass CacheProperty(object):\n \"\"\"\n Converts a class method into a property and cache result after first use.\n\n When property is accessed for the first time, the result is computed and returned.\n The class property is then replaced with an instance attribute with the computed result.\n \"\"\"\n\n def __init__(self, func):\n self.__name__ = func.__name__\n self.__doc__ = func.__doc__\n self._func = func\n\n def __get__(self, instance, owner):\n if instance:\n attr = self._func(instance)\n setattr(instance, self.__name__, attr)\n return attr\n else:\n return self\n\n\ndef ensure_native_str(data, encoding=\"utf8\"):\n \"\"\"\n Ensures that given string is returned as a native str type, bytes on python2 or unicode on python3.\n\n :param data: String to convert if needed.\n :param encoding: The encoding to use when encoding.\n :returns: The given string as UTF-8.\n :rtype: str\n \"\"\"\n if isinstance(data, str):\n return data\n elif isinstance(data, unicode_type):\n # Only executes on python 2\n return data.encode(encoding)\n elif isinstance(data, bytes):\n # Only executes on python 3\n return data.decode(encoding)\n else:\n str(data)\n\n\ndef ensure_unicode(data, encoding=\"utf8\"):\n \"\"\"\n Ensures that given string is return as a unicode string.\n\n :param data: String to convert if needed.\n :param encoding: The encoding to use when decoding.\n :returns: The given string as unicode.\n :rtype: unicode\n \"\"\"\n if isinstance(data, bytes):\n return data.decode(encoding)\n else:\n return unicode_type(data)\n\n\ndef strip_tags(html):\n \"\"\"\n Strips out HTML tags and return plain text.\n\n :param str html: HTML with text to extract.\n :returns: Html with tags striped out\n :rtype: str\n\n :example:\n >>> strip_tags('
I linked to example.com')\n \"I linked to example.com\"\n \"\"\"\n # This will fail under python3 when html is of type bytes\n # This is ok sence you will have much bigger problems if you are still using bytes on python3\n return re.sub(\"<[^<]+?>\", \"\", html)\n\n\ndef urljoin_partial(base_url):\n \"\"\"\n Construct a full (absolute) URL by combining a base URL with another URL.\n\n This is useful when parsing HTML, as the majority of links would be relative links.\n\n Informally, this uses components of the base URL, in particular the addressing scheme,\n the network location and (part of) the path, to provide missing components in the relative URL.\n\n Returns a new \"partial\" object which when called, will pass ``base_url`` to :func:`urlparse.urljoin` along with the\n supplied relative URL.\n\n :param str base_url: The absolute URL to use as the base.\n :returns: A partial function that accepts a relative URL and returns a full absolute URL.\n\n :example:\n >>> url_constructor = urljoin_partial(\"https://google.ie/\")\n >>> url_constructor(\"/path/to/something\")\n \"https://google.ie/path/to/something\"\n >>> url_constructor(\"/gmail\")\n \"https://google.ie/gmail\"\n \"\"\"\n base_url = ensure_unicode(base_url)\n\n def wrapper(url):\n \"\"\"\n Construct a full (absolute) using saved base url.\n\n :param str url: The relative URL to combine with base.\n :return: Absolute url.\n :rtype: str\n \"\"\"\n return urlparse.urljoin(base_url, ensure_unicode(url))\n\n return wrapper\n\n\ndef parse_qsd(qs, keep_blank_values=False, strict_parsing=False):\n \"\"\"\n Parse a \"urlencoded\" query string, and return the data as a dictionary.\n\n Parse a query string given as a string or unicode argument (data of type application/x-www-form- urlencoded).\n Data is returned as a dictionary. The dictionary keys are the \"Unique\" query variable names and\n the values are \"Unicode\" values for each name.\n\n The optional argument ``keep_blank_values``, is a flag indicating whether blank values in percent-encoded queries\n should be treated as a blank string. A ``True`` value indicates that blanks should be retained as a blank string.\n The default ``False`` value indicates that blank values are to be ignored and treated as if they were not included.\n\n The optional argument ``strict_parsing``, is a flag indicating what to do with parsing errors. If ``False``\n (the default), errors are silently ignored. If ``True``, errors raise a \"ValueError\" exception.\n\n :param str qs: Percent-encoded \"query string\" to be parsed, or a URL with a \"query string\".\n :param bool keep_blank_values: ``True`` to keep blank values, else discard.\n :param bool strict_parsing: ``True`` to raise \"ValueError\" if there are parsing errors, else silently ignore.\n\n :return: Returns a dictionary of key/value pairs, with all keys and values as \"Unicode\".\n :rtype: dict\n\n :raises ValueError: If duplicate query field names exists or if there is a parsing error.\n\n :example:\n >>> parse_qsd(\"http://example.com/path?q=search&safe=no\")\n {u\"q\": u\"search\", u\"safe\": u\"no\"}\n >>> parse_qsd(u\"q=search&safe=no\")\n {u\"q\": u\"search\", u\"safe\": u\"no\"}\n \"\"\"\n params = {}\n qs = ensure_native_str(qs)\n parsed = urlparse.parse_qsl(qs.split(\"?\", 1)[-1], keep_blank_values, strict_parsing)\n if PY3:\n for key, value in parsed:\n if key not in params or not strict_parsing:\n params[key] = value\n else:\n # Only add keys that are not already added, multiple values are not supported\n raise ValueError(\"encountered duplicate param field name: '%s'\" % key)\n else:\n for bkey, value in parsed:\n ukey = bkey.decode(\"utf8\")\n if ukey not in params or not strict_parsing:\n params[ukey] = value.decode(\"utf8\")\n else:\n # Only add keys that are not already added, multiple values are not supported\n raise ValueError(\"encountered duplicate param field name: '%s'\" % bkey)\n\n # Return the params with all keys and values as unicode\n return params\n\n\ndef unicode_cmdargs(cmdarg):\n \"\"\"Convert a command line string to unicode.\"\"\"\n if isinstance(cmdarg, bytes):\n try:\n # There is a possibility that this will fail\n return cmdarg.decode(sys.getfilesystemencoding())\n except UnicodeDecodeError:\n try:\n # Attept decoding using utf8\n return cmdarg.decode(\"utf8\")\n except UnicodeDecodeError:\n # Fall back to latin-1\n return cmdarg.decode(\"latin-1\")\n # If this fails then we are fucked\n else:\n return cmdarg\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":6999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"87781436","text":"import json\nimport sys\nfrom pydub import AudioSegment\nfrom pydub.playback import play\n\nf = open('results/map.json')\nsync_result = json.load(f)\n\nsong = AudioSegment.from_wav(\"data/the_18th_letter.wav\")\nsecs = 1000\nchunks = []\nfor fragment in sync_result[\"fragments\"]:\n print(fragment)\n chunk = AudioSegment.empty()\n begin = fragment[\"begin\"]\n end = fragment[\"end\"]\n if begin == end:\n print(\"Jumping fragment because it's empty\")\n continue\n chunk = song[ float(begin) * secs: float(end) * secs]\n chunks.append({\n 'chunk': chunk,\n 'lines': fragment[\"lines\"]\n })\n print(fragment[\"lines\"])\n try:\n play(chunk)\n except Exception:\n print(\"Error playing audio chunk\")\n traceback = sys.exc_info()[2]\n print(sys.exc_info()[1])\n print(traceback.print_tb())\n\n\n\n","sub_path":"server/lib/audio-tools/player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"522159264","text":"import os\nimport re\nimport argparse\n\nparser =argparse.ArgumentParser(description= \"Deleting Unparsed Jsons\")\nparser.add_argument(\"--base_folder\" , default=\"/tmp/rawData_Labels_Test_RAW_DATA/labels\")\nargs = parser.parse_args()\nBASE_FOLDER = args.base_folder\n\nfor label in os.listdir(BASE_FOLDER):\n for group_folder in os.listdir(os.path.join(BASE_FOLDER,label)):\n for user in sorted(os.listdir(os.path.join(BASE_FOLDER,label,group_folder))):\n x=0\n for file in sorted(os.listdir(os.path.join(BASE_FOLDER,label,group_folder,user))):\n if file != \"Parsed jsons\":\n os.remove(os.path.join(BASE_FOLDER,label,group_folder,user,file))","sub_path":"Avisrur-git/concert_flow/Delete_Unparsed_Jsons.py","file_name":"Delete_Unparsed_Jsons.py","file_ext":"py","file_size_in_byte":690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"98722800","text":"__author__ = 'oun1982'\n'''\nf = open(\"myfile.txt\",\"r+\")\n\nprint(\"nmae of file :\",f.name)\nprint(\"Close or not :\",f.closed)\nprint(\"Opening mode :\",f.mode)\nprint(f.readlines())\n'''\nimport os\nimport linecache\nfPath = \"myfile.txt\"\nfor line in range(5):\n print(linecache.getline(fPath, line))\nlinecache.clearcache()\n\nwordTemp = []\nwordCount = 0\nfile = open(\"myfile.txt\", 'r+')\nfor line in file:\n for word in line.split():\n wordTemp.append(word)\n wordCount = wordCount + 1\nprint(wordTemp)\nprint(wordCount)\n\nprint(os.getcwd())\n\n","sub_path":"05.py","file_name":"05.py","file_ext":"py","file_size_in_byte":538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"274278845","text":"import numpy as np\nimport scripts.neuralnetwork as nn\nimport scripts.saveloaddata as svld\nfrom scripts.Data import Data\n\n\nTRAINING_SET_PATH = \"heart_disease/heart_train.csv\"\nTEST_SET_PATH = \"heart_disease/heart_test.csv\"\nDIMS_PATH = 'dims/hrt_dims.pkl'\nTHETA_PATH = 'thetas/hrt_theta_binary.pkl'\n\n\ndef train_heart_binary(dims, alpha=0.00045, iterations=1000, is_mini_batch=True, batch_count=16, lambd=0.00001, decay_rate=0):\n \"\"\" Trains the model on the heart disease binary data set.\n\n Preconditions:\n dims: list of int length >= 2\n alpha: float > 0\n iterations: int > 0\n is_mini_batch: bool\n batch_count: int > 0\n lambd: float >= 0\n decay_rate: >= 0\n\n Parameters:\n dims: The dimensions of the neural network\n alpha: The learning rate of the model\n iterations: The number of times to pass through the entire data set (epochs)\n is_mini_batch: Whether the model will be using mini-batches\n batch_count: The number of training samples in each batch\n lambd: The regularization parameter for negating overfitting\n decay_rate: The rate at which to reduce the learning rate each iteration\n\n Postconditions:\n theta: The learned parameters from the model\n \"\"\"\n\n # initializes the parameter dicts for the network and adams optimization\n theta, adams = nn.initialize_parameters(dims)\n\n # load the data sets\n X_train, df = svld.load_csv_sets(TRAINING_SET_PATH, (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12), \",\", 1)\n\n # get the labels using the loaded dataframe\n Y_train = np.array(df.target).reshape(1, len(df))\n\n # instantiate a Data class\n data = Data(X_train, Y_train)\n data.convert_labels_to_binary()\n\n # transpose the matrices in order to shuffle\n data.transpose()\n data.shuffle()\n\n # transpose them again in order to feed them into the neural network\n data.transpose()\n\n # preproccess the data\n data.standardize_input_data()\n data.normalize_input_data()\n\n # execute the training model\n theta = nn.training_model(dims, alpha, data.X, data.Y, iterations, theta, adams, lambd, is_mini_batch, batch_count, decay_rate)\n\n # test how it did\n print(\"\\nAfter evaluation on test set the model had:\")\n test_heart_binary(dims, theta)\n\n # ask if the user wishes to save the parameters\n svld.check_theta_save(dims, theta, THETA_PATH, DIMS_PATH)\n\n return theta\n\n\ndef test_heart_binary(dims=None, theta=None):\n \"\"\" Runs a neural network model on the heart disease test set\n\n Preconditions:\n dims: list of int length >= 2\n theta: dict\n\n Parameters:\n dims: The dimensions of the neural network model\n theta: The learned paramters of a neural network model\n\n Postconditions:\n Uses a model that has the given parameters and predicts on a test set.\n \"\"\"\n\n # if no theta is given load it\n if theta is None:\n theta = svld.load_pkl(THETA_PATH)\n\n # if no dimensions are given load it\n if dims is None:\n dims = svld.load_pkl(DIMS_PATH)\n\n # load the .csv file for the test set\n X_test, df = svld.load_csv_sets(TEST_SET_PATH, (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12), \",\", 1)\n\n # get the test labels from the pandas dataframe\n Y_test = np.array(df.target).reshape(1, len(df))\n\n # instantiate a Data class using the data\n data = Data(X_test, Y_test)\n data.convert_labels_to_binary()\n\n # transpose the matrices in order to shuffle\n data.transpose()\n data.shuffle()\n\n # transpose them again in order to feed them into the neural network\n data.transpose()\n\n # preproccess the data\n data.standardize_input_data()\n data.normalize_input_data()\n\n # predict on the test set\n nn.predict_binary(data.X, data.Y, dims, theta)\n","sub_path":"scripts/train_tests/hrt_dis_train_test.py","file_name":"hrt_dis_train_test.py","file_ext":"py","file_size_in_byte":3722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"565243121","text":"import os\n\nall_mds = [file for file in os.listdir('.')\n if file.endswith('md') \n and file != 'README.md'] \npaper_tag = 'Paper'\nread_paper_counts = 0\n# _io.TextIOWrapper, readline as a method to give line, generator backend\nreadme_file_obj = open('README.md') \nline = readme_file_obj.readline()\nprint(f'all record of markdown {len(all_mds)}')\nprint('checking all the markdown is in README.md or not...')\nwhile line:\n if line:\n for md in all_mds:\n if md in line:\n all_mds.remove(md)\n if paper_tag in line:\n read_paper_counts += 1\n line = readme_file_obj.readline()\n\nif all_mds:\n print(f'there are no record on README.md but exist {all_mds}')\nelse:\n print('-'*60)\n print('Done!')\n print(f'You have read {read_paper_counts} papers abstrsct, keep researching!')\n print('all clear, commit the repo =)')","sub_path":"link_checker.py","file_name":"link_checker.py","file_ext":"py","file_size_in_byte":888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"539839031","text":"#!/usr/bin/env python\n\nimport numpy as np\nimport sklearn.metrics\nfrom sklearn.preprocessing import OneHotEncoder\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.svm import SVC\nfrom ism_pkg.tools.balance_class_sampling import balance_class_sampling\n#import balance_class_sampling\n\n\n\nclass HSIC_IDS_optimizer():\n\tdef __init__(self, σ, stochastic=False, class_batch_size=200):\n\t\tself.stochastic = stochastic\n\t\tself.class_batch_size = class_batch_size\n\t\tself.σ = σ\n\t\tself.γ = 1/(2*σ*σ)\n\t\tself.βᦸ = []\n\t\tself.Xᦸ = []\n\t\tself.μᦸ = []\n\n\tdef compute_HSIC(self, K, Yₒ, normalize=True):\n\t\tȲₒ = Yₒ - np.mean(Yₒ, axis=0)\n\t\tΓ = Ȳₒ@Ȳₒ.T\n\t\tHᵪᵧ = np.sum(Γ*K)#/(n*n)\n\t\tif not normalize: return Hᵪᵧ\n\n\t\tHƘᵪ = K - np.mean(K, axis=0)\n\t\tKᵧ = Yₒ@Yₒ.T\n\t\tHKᵧ = Kᵧ - np.mean(Kᵧ, axis=0)\n\t\tHᵪ = np.linalg.norm(HƘᵪ)\t\t\t\t\t\t# equivalent to \tnp.sqrt(np.sum(KᵪH*KᵪH))\n\t\tHᵧ = np.linalg.norm(HKᵧ) \t\t\t\t\t\t# equivalent to \tnp.sqrt(np.sum(KᵧH*KᵧH))\n\t\tH = (Hᵪᵧ)/( Hᵪ * Hᵧ )\n\n\t\treturn H\n\n\n\tdef eig_solver(self, L, var_percentage=0.9, q=None):\t# will always pick the smallest eigenvectors\n\t\tΣ, Ꮴ = np.linalg.eigh(L)\n\t\tabsΣ = np.absolute(Σ)\n\t\t\n\t\tif q is None:\n\t\t\trank_sorted = np.cumsum(absΣ)/np.sum(absΣ)\n\t\t\trank = np.sum(rank_sorted < var_percentage) + 1\n\t\t\tnum_eig = rank\n\t\telse:\n\t\t\tnum_eig = int(q)\n\n\t\tU = Ꮴ[:, 0:num_eig]\n\t\tU_λ = Σ[0:num_eig]\n\n\t\t#print(U.T@L@U)\n\t\treturn [U, U_λ]\n\n\n\tdef fit(self, X, Y):\n\t\tif self.stochastic: self.stochastic_fit(X,Y)\n\t\telse: self.full_fit(X,Y)\n\n\tdef predict(self, xᵢ):\t\n\t\tŶⲧ = None\n\n\t\tif self.stochastic: \n\t\t\tbatches = zip( self.βᦸ, self.Xᦸ, self.μᦸ)\n\n\t\t\tfor β, X, μᵪ in batches:\n\t\t\t\tŶ = self.full_predict(xᵢ, β, X, μᵪ)\n\t\t\t\tŶₒ = OneHotEncoder(categories='auto', sparse=False).fit_transform(np.reshape(Ŷ,(len(Ŷ),1)))\n\t\t\t\tŶₒ = np.expand_dims(Ŷₒ, axis=0)\n\n\t\t\t\tif Ŷⲧ is None: Ŷⲧ = Ŷₒ\n\t\t\t\telse: Ŷⲧ = np.concatenate((Ŷⲧ, Ŷₒ), axis=0)\n\n\t\t\tŶ = np.argmax(np.sum(Ŷⲧ, axis=0), axis=1)\n\t\t\tŶ = LabelEncoder().fit_transform(Ŷ)\n\t\t\treturn Ŷ\n\t\telse: \n\t\t\tβ = self.βᦸ[0]\n\t\t\tX = self.Xᦸ[0]\n\t\t\tμᵪ = self.μᦸ[0]\n\n\t\t\treturn self.full_predict(xᵢ, β, X, μᵪ)\n\n\tdef full_predict(self, xᵢ, β, X, μᵪ):\n\t\txᵢ = np.atleast_2d(xᵢ)\n\t\tΦₓΦₓᵢᵀ = sklearn.metrics.pairwise.rbf_kernel(X, xᵢ, gamma=self.γ)\n\t\tƒₓ = ΦₓΦₓᵢᵀ.T@β\n\n\t\t#Ŷ = self.svm.predict(ƒₓ)\n\t\t#Ŷ = LabelEncoder().fit_transform(Ŷ)\n\t\t#return Ŷ\n\t\t\n\t\tpDis = sklearn.metrics.pairwise.pairwise_distances(ƒₓ, μᵪ.T)\n\t\tŶ = np.argmin(pDis, axis=1)\n\t\tŶ = LabelEncoder().fit_transform(Ŷ)\n\t\treturn Ŷ\n\n\n\tdef stochastic_fit(self, X, Y):\n\t\tself.BCSampling = ʆ = balance_class_sampling(X, Y, with_replacement=False)\n\n\t\twhile ʆ.epoch_count < 2:\n\t\t\t[Xᴮ, Yᴮ, Yₒout] = ʆ.sample(samples_per_class=self.class_batch_size)\n\t\t\tself.full_fit(Xᴮ, Yᴮ)\n\n\tdef get_weighted_kernel(self, X, β, γ): #ΦwwᵀΦᵀ = ΦΦᵀββᵀΦΦᵀ = KββᵀK\n\t\tƘ = sklearn.metrics.pairwise.rbf_kernel(X, gamma=γ)\n\t\treturn Ƙ@β@β.T@Ƙ\t\n\t\t\n\n\tdef full_fit(self, X, Y):\n\t\tγ = self.γ\n\t\t\n\t\t#self.c = len(np.unique(Y))\n\t\tself.Yₒ = Yₒ = OneHotEncoder(categories='auto', sparse=False).fit_transform(np.reshape(Y,(len(Y),1)))\n\t\tYₒᵃᵛᵍ = Yₒ/np.sum(Yₒ,axis=0)\n\t\tself.Ȳₒ = Ȳₒ = Yₒ - np.mean(Yₒ, axis=0)\n\n\t\tƘ = sklearn.metrics.pairwise.rbf_kernel(X, gamma=γ)\n\t\tƘȲₒ = Ƙ@Ȳₒ\n\t\tƘΓƘ = ƘȲₒ@ƘȲₒ.T\n\n\t\t[β, λ] = self.eig_solver(-ƘΓƘ)\t# must be negative since picking smallest eigenvectors\n\t\tself.Xout = β.T@Ƙ\n\t\tμᵪ = self.Xout@Yₒᵃᵛᵍ\t\t\t# kernel mean embedding\n\n\n\t\t##\tfit with SVM at the end\n\t\t#self.svm = SVC(gamma=γ)\n\t\t#self.svm.fit(self.Xout.T, np.squeeze(Y))\n\n\t\t#\tDebug code\n\t\tH_before = self.compute_HSIC(Ƙ, Yₒ, normalize=False)\n\t\tƘᵪ = self.get_weighted_kernel(X, β, γ)\n\t\tH_after = self.compute_HSIC(Ƙᵪ, Yₒ, normalize=False)\n\t\tprint('Before HSIC %.7f, After HSIC: %.7f: '%(H_before, H_after))\n\n\t\tself.βᦸ.append(β)\n\t\tself.Xᦸ.append(X)\n\t\tself.μᦸ.append(μᵪ) \n\nif __name__ == \"__main__\":\n\tX = np.array([[0.1,0.1],[0.2,0.1],[2.2,2],[1.9,2.1]])\n\tY = np.array([0,0,1,1])\n\tσ = np.median(sklearn.metrics.pairwise.pairwise_distances(X))\n\n\n\tǶ = HSIC_IDS_optimizer(σ)\n\tǶ.fit(X,Y)\n\tresult = Ƕ.predict(X[0:4,:])\n\tprint(result)\n","sub_path":"ism_pkg/tools/HSIC_IDS_optimizer.py","file_name":"HSIC_IDS_optimizer.py","file_ext":"py","file_size_in_byte":4356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"47151303","text":"import unittest\nimport day2defs\n\nclass check_palindrome(unittest.TestCase):\n def test_palin(self):\n str1=\"abba\"\n status=day2defs.palin(str1)\n self.assertEqual(status,\"Palindrome\")\n \n def test_matrix_mul(self):\n m1=[[2,2],\n [1,1]]\n m2=[[3,3],\n [1,1]]\n m3=[[0,0],\n [0,0]]\n st=day2defs.matrix_mul(m1,m2)\n self.assertEqual(st,[[8,8],[4,4]])\n\n def test_matrix_add(self):\n m1=[[2,2],\n [1,1]]\n m2=[[3,3],\n [1,1]]\n st=day2defs.matrix_add(m1,m2)\n self.assertEqual(st,[[5,5],[2,2]])\n\n def test_string(self):\n str10=\"string\"\n str20=day2defs.stringee(str10)\n self.assertEqual(str20,\"ng\")\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"Python/4-4.30/day2main.py","file_name":"day2main.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"594408564","text":"from knock52 import train\nfrom pprint import pprint\nimport numpy as np\nimport heapq\ndef knock57():\n lr, data, vectorizer = train()\n inverse_vectorizer_vocabulary_ = {v: k for k, v in vectorizer.vocabulary_.items()}\n for cnt, class_name in enumerate(lr.classes_):\n lr.coef_[cnt]\n print(class_name)\n for i in heapq.nlargest(10, lr.coef_[cnt]):\n index1 = np.where(lr.coef_[cnt] == i)\n print(inverse_vectorizer_vocabulary_[index1[0][0]],\":\",i)\n for i in heapq.nsmallest(10, lr.coef_[cnt]):\n index1 = np.where(lr.coef_[cnt] == i)\n print(inverse_vectorizer_vocabulary_[index1[0][0]],\":\",i)\n print()\n\nif __name__ == \"__main__\":\n knock57()","sub_path":"kazuma/chapter06/knock57.py","file_name":"knock57.py","file_ext":"py","file_size_in_byte":722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"617845076","text":"#!/usr/bin/env python\n\"\"\"\nClean up the output of MGL simulations to be usable. This script was\nnever finished as I found far too many inconsistencies in the MGL\noutput for it to be usable. This is just provided as a reference point\nin case someone wants to try this again in the future.\n\n\"\"\"\n\n# Copyright (C) 2013 Constantine Lignos\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n\nimport csv\nimport argparse\n\ndef apply_rule(form1, rule):\n \"\"\"Apply a rule to a form and return the result.\n >>> apply_rule(\"bit\", \"//0\")\n \"bit\"\n\n >>> apply_rule(\"bIld\", \"d/t/0\")\n \"bIlt\"\n\n >>> apply_rule(\"rYz\", \"Y/o/2\")\n \"roz\"\n\n >>> apply_rule(\"tEl\", \"El/old/0\")\n \"told\"\n \n \"\"\"\n # Parse rule\n left, right, idx = rule.split(\"/\")\n # No change\n if left == \"\" and right == \"\":\n return form1\n\n\ndef process(input_path, output_path):\n \"\"\"Read from input_path and write a cleaned up version to output_path.\"\"\"\n # Store each correct row by the form tuple, overwriting only if\n # the confidence is greater\n forms = {}\n with open(input_path, 'rU') as input_file:\n reader = csv.DictReader(input_file)\n for row in reader:\n form = int(row['form'])\n form1, form2 = (row['form1'], row['form2'])\n confidence = float(row['confidence'])\n pred = row['pred']\n # Did not get it right, disregard\n if pred != form2:\n continue\n # Check if we already have a higher stored confidence\n if (form in forms and forms[form]['confidence'] > confidence):\n continue\n forms[form] = row\n\n with open(output_path, 'wb') as output_file:\n writer = csv.DictWriter(output_file, reader.fieldnames)\n writer.writeheader()\n for _, row in sorted(forms.items()):\n writer.writerow(row)\n\n\ndef main():\n \"\"\"Parse arugments and call the main function.\"\"\"\n parser = argparse.ArgumentParser(description=__doc__)\n parser.add_argument('input', help='input CSV, derived from .sum file')\n parser.add_argument('prons', help='pronunciations')\n parser.add_argument('output', help='output CSV')\n args = parser.parse_args()\n process(args.input, args.output)\n\n\nif __name__ == \"__main__\":\n main()\n\n\n","sub_path":"process_mgl.py","file_name":"process_mgl.py","file_ext":"py","file_size_in_byte":2868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"318639012","text":"'''\nGiven an array of strings (all lowercase letters), \nthe task is to group them in such a way that all strings in a group are shifted versions of each other. \nTwo string S and T are called shifted if,\n S.length = T.length \n and\n S[i] = T[i] + K for \n 1 <= i <= S.length for a constant integer K\n\nInput : [\"acd\", \"dfg\", \"wyz\", \"yab\", \"mop\",\n \"bdfh\", \"a\", \"x\", \"moqs\"]\n\nOutput : a x\n acd dfg wyz yab mop\n bdfh moqs\nAll shifted strings are grouped together.\n'''\n\ndef group_shifted_strs(input):\n\n shift_dict = {}\n\n for i in range(len(input)):\n # pull current string\n merged_strs = \"\".join(input[i])\n # check if in string of that length is in dict else create list for us to store vals\n merged_vals = shift_dict.get(len(merged_strs), [])\n # since the current value is new append it \n merged_vals.append(input[i])\n # map it in the dict\n shift_dict[len(merged_strs)] = merged_vals\n return list(shift_dict.values())\n\nprint(group_shifted_strs([\"acd\", \"dfg\", \"wyz\", \"yab\", \"mop\",\n \"bdfh\", \"a\", \"x\", \"moqs\"]))\nprint(group_shifted_strs([\"abc\", \"bcd\", \"acef\", \"xyz\", \"az\", \"ba\", \"a\", \"z\"]))","sub_path":"python/group_shifted.py","file_name":"group_shifted.py","file_ext":"py","file_size_in_byte":1206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"562001048","text":"\"\"\"\r\n977.有序数组的平方\r\n给定一个按非递减顺序排序的整数数组 A,返回每个数字的平方组成的新数组,要求也按非递减顺序排序。\r\n\r\n \r\n\r\n示例 1:\r\n\r\n输入:[-4,-1,0,3,10]\r\n输出:[0,1,9,16,100]\r\n示例 2:\r\n\r\n输入:[-7,-3,2,3,11]\r\n输出:[4,9,9,49,121]\r\n \r\n\r\n提示:\r\n\r\n1 <= A.length <= 10000\r\n-10000 <= A[i] <= 10000\r\nA 已按非递减顺序排序。\r\n\r\n来源:力扣(LeetCode)\r\n链接:https://leetcode-cn.com/problems/squares-of-a-sorted-array\r\n著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。\r\n\"\"\"\r\nclass Solution:\r\n # 直接排序 55.53, 5.26\r\n def sortedSquares(self, A):\r\n A = [a ** 2 for a in A]\r\n return sorted(A)\r\n\r\n # 双指针 32,5.26\r\n def sortedSquares(self, A):\r\n l, r = 0, len(A) - 1\r\n result = [0 for i in range(r+1)]\r\n k = len(result) - 1\r\n while l <= r:\r\n if abs(A[l]) > abs(A[r]):\r\n result[k] = A[l] ** 2\r\n l += 1\r\n else:\r\n result[k] = A[r] ** 2\r\n r -= 1\r\n k -= 1\r\n return result\r\n\r\n\r\n\r\ns=Solution()\r\nprint(s.sortedSquares([-4,-1,0,3,10]))\r\nprint(s.sortedSquares([-7,-3,2,3,11]))","sub_path":"SquaresOfASortedArray.py","file_name":"SquaresOfASortedArray.py","file_ext":"py","file_size_in_byte":1276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"87703414","text":"from __future__ import absolute_import\n\nimport collections\nimport os\nimport re\nimport textwrap\nimport time\n\nfrom .compile import _is_32_bit, _is_64_bit\nfrom .storage import load_framework_info\n\n\nclass MergeNeededException(Exception):\n pass\n\n\nHEADER = textwrap.dedent(\n \"\"\"\\\n /*\n * This file is generated by objective.metadata\n *\n * Last update: %(timestamp)s\n */\n\n static void __attribute__((__used__)) use_protocols(void)\n {\n PyObject* p;\n\"\"\"\n)\n\nFOOTER = textwrap.dedent(\n \"\"\"\\\n }\n\"\"\"\n)\n\nFIND_VERSION = re.compile(r\"MacOSX(\\d+\\.\\d+)u?.sdk\")\n\n\ndef classify_archs(archs):\n if _is_32_bit(archs):\n return \"!defined(__LP64__)\"\n\n if _is_64_bit(archs):\n print([(a, _is_32_bit(a)) for a in archs])\n return \"defined(__LP64__)\"\n\n return None\n\n\ndef classify_versions(versions):\n min_version = min(versions)\n if min_version == \"10.6\":\n return None\n\n return \"PyObjC_BUILD_RELEASE >= %s\" % (\n \"%02d%02d\" % (tuple(map(int, min_version.split(\".\"))))\n )\n\n\ndef protocol_selector(found_info):\n versions_seen = {info[0] for info in found_info}\n archs_seen = {info[1] for info in found_info}\n\n selectors = []\n arch_selector = classify_archs(archs_seen)\n if arch_selector is not None:\n selectors.append(arch_selector)\n\n version_selector = classify_versions(versions_seen)\n if version_selector is not None:\n selectors.append(version_selector)\n\n if selectors:\n return \" && \".join(selectors)\n\n return None\n\n\ndef compile_protocol_file(output_fn, exceptions_fn, headerinfo_fns):\n \"\"\"\n Combine the data from header files scans and manual exceptions\n into a file than is usable for the metadata support in\n pyobjc 2.4 or later.\n \"\"\"\n # exceptions = load_framework_info(exceptions_fn)\n headerinfo = [load_framework_info(fn) for fn in headerinfo_fns]\n\n if not os.path.exists(os.path.dirname(output_fn)):\n os.makedirs(os.path.dirname(output_fn))\n\n with open(output_fn, \"w\") as fp:\n fp.write(HEADER % {\"timestamp\": time.ctime()})\n\n protocols = collections.defaultdict(list)\n\n for info in headerinfo:\n sdk = FIND_VERSION.search(info[\"sdk\"]).group(1)\n arch = info[\"arch\"]\n\n for name in info[\"definitions\"].get(\"formal_protocols\", ()):\n protocols[name].append((sdk, arch))\n\n grouped_names = collections.defaultdict(list)\n\n for name in protocols:\n selector = protocol_selector(protocols[name])\n grouped_names[selector].append(name)\n\n for selector in sorted(grouped_names):\n if selector is not None:\n fp.write(\"#if %s\\n\" % (selector,))\n for nm in sorted(grouped_names[selector]):\n fp.write(\n \" p = PyObjC_IdToPython(@protocol(%s)); Py_XDECREF(p);\\n\" % (nm,)\n )\n if selector is not None:\n fp.write(\"#endif /* %s */\\n\" % (selector,))\n\n fp.write(FOOTER)\n","sub_path":"objective/metadata/protocols.py","file_name":"protocols.py","file_ext":"py","file_size_in_byte":3030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"374511958","text":"#-*- coding: utf-8 -*-\n#@Time :2018/11/30 20:06\n#@Author :yangjuan\n#@Email :269573175@qq.com\n#@File :class_01.py\n\n# http类型的请求 requests模块\n\nimport requests\nurl = 'http://www.lemfix.com/topics/25'\n\n# 发送一个get类型的请求 返回一个消息实体\nres=requests.get(url)\nprint(res)\n\nres_2=requests.post(url,json={'key','value'})\nprint(res_2)","sub_path":"python_interface/python_1130/class_01.py","file_name":"class_01.py","file_ext":"py","file_size_in_byte":367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"10666574","text":"import random\n\n\ndef partition(seq, start, end):\n p = random.randint(start, end - 1)\n seq[p], seq[end - 1] = seq[end - 1], seq[p]\n pivot = seq[end - 1]\n\n lower_mid = j = start\n upper_mid = end - 1\n while j <= upper_mid:\n if seq[j] < pivot:\n seq[lower_mid], seq[j] = seq[j], seq[lower_mid]\n lower_mid += 1\n j += 1\n elif seq[j] > pivot:\n seq[upper_mid], seq[j] = seq[j], seq[upper_mid]\n upper_mid -= 1\n else:\n j += 1\n\n return lower_mid, upper_mid\n\n\ndef quicksort(seq, start, end):\n if start < end - 1:\n lower_mid, upper_mid = partition(seq, start, end)\n quicksort(seq, start, lower_mid)\n quicksort(seq, upper_mid + 1, end)\n return seq\n","sub_path":"lab5/Vasich/quicksort.py","file_name":"quicksort.py","file_ext":"py","file_size_in_byte":767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"19123564","text":"import binarysearchtree\nimport collections\nfrom binarysearchtree import Node\nimport itertools\n\n\nclass TreeDict(object):\n \n def __init__(self, args=None, **kwds): ##Default Constructor, creates new node and updates \n self.rootNode = Node()\n self.update(args, **kwds)\n\n def __getitem__(self, key): ##acts as the TreeDict[i] \n if key is None:\n raise KeyError\n else: \n try: ##lookup in binarysearchtreeclass\n return self.rootNode.lookup(key).value\n except ValueError:\n raise KeyError\n \n\n def __setitem__(self, key, value): ##used as the TreeDict[i]=blah \n if key is None:\n raise KeyError\n try:\n return self.rootNode.insert(key, value)\n except ValueError:\n print(\"Value Error\") \n \n \n def __contains__(self, key): ##if blah in Treedict \n if key is None:\n raise KeyError\n else:\n try:\n self.rootNode.lookup(key) ##lookup and return true\n return True\n except ValueError:\n print(\"Value Error\") \n return False\n \n\n def get(self, key, default=None): ##td.get \n if key is None:\n raise KeyError\n else: \n try:\n return self.rootNode.lookup(key).value\n except ValueError:\n return default\n \n\n def __delitem__(self, key): #\n if key is None:\n raise KeyError\n else:\n return self.rootNode.delete(key)\n \n\n \n def update(self, args, **kwds):\n if kwds: \n for key, value in kwds.items():\n self.rootNode.insert(key, value)\n elif isinstance(args, dict):\n currDict = args\n for key in currDict.keys():\n self.rootNode.insert(key,currDict[key])\n elif isinstance(args, TreeDict):\n self.rootNode = args.rootNode\n elif isinstance(args, collections.Iterable):\n for pair in args:\n key,value = pair[0], pair[1]\n self.rootNode.insert(key, value)\n else:\n return None\n \n\n def __len__(self): \n nodes= self.iterate(self.rootNode)\n if self.rootNode.key == None or self.rootNode.value == None:\n return 0\n \n count = 0\n for node in nodes:\n count = count+1\n return count\n \n def iterate(self, currNode):\n if currNode.left != None:\n yield from self.iterate(currNode.left)\n yield currNode.key, currNode.value\n if currNode.right != None:\n yield from self.iterate(currNode.right)\n \n def __iter__(self): \n for i, j in self.iterate(self.rootNode):\n yield i\n\n def items(self): \n for i in self.iterate(self.rootNode):\n yield i\n\n def values(self):\n for v in self.iterate(self.rootNode):\n yield v,k\n \n","sub_path":"TreeDict/treedict.py","file_name":"treedict.py","file_ext":"py","file_size_in_byte":3098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"557795079","text":"import os\r\nfrom sklearn.preprocessing import MinMaxScaler, LabelEncoder, scale\r\nimport numpy as np\r\nimport pandas as pd\r\nimport matplotlib\r\nmatplotlib.use('Tkagg')\r\nfrom matplotlib import pyplot as plt\r\nimport seaborn as sns\r\nfrom help.utils import reassign_cluster_with_ref\r\nfrom help.subroutines import *\r\n\r\n\r\ndef read_labels(ref, return_enc=False):\r\n ref = pd.read_csv(ref, sep='\\t', index_col=0, header=None)\r\n encode = LabelEncoder()\r\n ref = encode.fit_transform(ref.values.squeeze())\r\n classes = encode.classes_\r\n if return_enc:\r\n return ref, classes, encode\r\n else:\r\n return ref, classes\r\n\r\ndef filtering(raw_matrix):\r\n matrix = numpy.array([x/x.sum()*1000000 for x in raw_matrix])\r\n gini = lambda x : 0.5 * numpy.abs(numpy.subtract.outer(x, x)).mean() / numpy.mean(x)\r\n if raw_matrix.shape[0]<=10000:\r\n coef_gini = numpy.array([gini(x) for x in matrix.T])\r\n else:\r\n coef_gini = numpy.array([len(numpy.where(x>0)[0]) for x in matrix.T])\r\n means = matrix.mean(axis=0)\r\n mean_cutoff = (means.mean() - numpy.std(means))*2\r\n kk, bb = numpy.polyfit(numpy.log10(means), coef_gini, 1)\r\n yy = coef_gini + numpy.log10(means) * (-kk)\r\n index = numpy.where((yy>bb)&(means>mean_cutoff))[0]\r\n matrix_filtered = matrix[:, index]\r\n return matrix_filtered\r\n#\r\n#\r\ndef weighted_tsne(matrix, clusters):\r\n cell_types = list(set(clusters['cluster'].values))\r\n adjusted = copy.deepcopy(matrix.values)\r\n for ctype in cell_types:\r\n cluster_cells = numpy.where(clusters==ctype)[0]\r\n weight = adjusted[cluster_cells, :].mean(axis=0) * float(0.2)\r\n adjusted[cluster_cells, :] = numpy.array([x+weight for x in adjusted[cluster_cells, :]])\r\n if matrix.shape[0]<=10000:\r\n tsne_result = TSNE(n_components=2, random_state=int(0)).fit_transform(adjusted)\r\n return tsne_result\r\n\r\ndef build_accesson(ngroup=600, ncell=301, npc=40,pathin=\"\",pathout=\"\",dataname=\"\"):\r\n ngroups, ncell_cut = ngroup, ncell\r\n reads = pd.read_csv(os.path.join(pathin, 'data.txt'), sep='\\t', index_col=0)#读GSE时候用index_col=0\r\n cells = pd.read_csv(os.path.join(pathin,'filtered_cells.txt'), sep='\\t', index_col=0,\r\n engine='c', na_filter=False, low_memory=False)\r\n cells = cells.index.values\r\n peaks = ['peak'+str(x) for x in range(0, reads.shape[0])]\r\n npc = min(int(npc), reads.shape[0], reads.shape[1])\r\n pca_result = PCA(n_components=npc, svd_solver='full').fit_transform(reads)\r\n connectivity = kneighbors_graph(pca_result, n_neighbors=10, include_self=False)\r\n connectivity = 0.5*(connectivity + connectivity.T)\r\n ward_linkage = cluster.AgglomerativeClustering(n_clusters=ngroups, linkage='ward', connectivity=connectivity)\r\n y_predict = ward_linkage.fit_predict(pca_result)\r\n peak_labels_df = pd.DataFrame(y_predict, index=peaks, columns=['group'])\r\n peak_labels_df.to_csv(os.path.join(pathout,'Accesson_peaks_{}.csv'.format(dataname)), sep='\\t')\r\n groups = list(set(y_predict))\r\n reads = reads.values\r\n coAccess_matrix = np.array([reads[np.where(y_predict==x)[0],:].sum(axis=0) for x in groups])\r\n coAccess_matrix = coAccess_matrix.T\r\n coAccess_df = pd.DataFrame(coAccess_matrix, index=cells, columns=groups)\r\n coAccess_df.to_csv(os.path.join(pathout,'Accesson_reads_{}.csv'.format(dataname)),sep=',')\r\n return\r\n#\r\ndef cluster_plot(norm='zscore',dataname=\"\", clusternum=6,pathout=\"\",classname=None):\r\n reads_df = pd.read_csv(os.path.join(pathout,'Accesson_reads_{}.csv'.format(dataname)), sep=',', index_col=0,\r\n engine='c', na_filter=False, low_memory=False)\r\n normal = filtering(reads_df.values)\r\n if norm=='zscore':\r\n normal = scipy.stats.zscore(normal, axis=1)\r\n elif norm=='probability':\r\n normal = np.array([x/x.sum() for x in normal])\r\n else:\r\n print(\"Error: --norm should be zscore or probability\")\r\n matrix = pd.DataFrame(normal, index=reads_df.index, columns=['c_'+str(x+1) for x in numpy.arange(0,len(normal.T))])\r\n connect = kneighbors_graph(matrix, n_neighbors=20, include_self=False)\r\n connectivity = 0.5*(connect + connect.T)\r\n n_clust = clusternum\r\n clusters = knn_cluster(matrix, n_clust, connectivity)\r\n tsne_result = weighted_tsne(matrix, clusters)\r\n plot_cluster(clusters, n_clust, tsne_result, pathout,dataname,classname)\r\n\r\n c = clusters.values.T\r\n c = c[:][0]\r\n return c\r\n\r\n#\r\ndataname = \"Splenocyte\"\r\nncell = 3166\r\nclusternum = 12\r\n\r\npathin = \"E:/scATAC_impute/data_ATAC/{}/\".format(dataname)\r\npathout = \"E:/scATAC_impute/cluster/raw/\"\r\nlabel, classname = read_labels(os.path.join(pathin, \"labels.txt\"))\r\nraw = pd.read_csv(os.path.join(pathin,'data.txt'), sep='\\t', index_col=0)\r\nbuild_accesson(ncell=ncell, pathin=pathin,pathout=pathout,dataname=dataname,)\r\npred = cluster_plot(clusternum=clusternum,pathout=pathout,dataname=dataname,classname=classname)\r\npre = reassign_cluster_with_ref(pred, label)\r\npd.Series(pre, index=raw.columns).to_csv(os.path.join(pathout, 'label_{}.txt'.format(dataname)), sep='\\t', header=False)\r\n\r\nfrom sklearn.metrics import f1_score, normalized_mutual_info_score, adjusted_rand_score\r\na = adjusted_rand_score(label, pred)\r\nprint(a)\r\nb = normalized_mutual_info_score(label, pred)\r\nprint(b)\r\n\r\n","sub_path":"cluster.py","file_name":"cluster.py","file_ext":"py","file_size_in_byte":5302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"513155455","text":"import cv2\nimport time\nfrom datetime import datetime\n\n\ncameraNum = 0\nCAM_width = 640\nCAM_height = 480\n\ntime = 0\n\ncapture = cv2.VideoCapture(0)\ncapture.set(cv2.CAP_PROP_FRAME_WIDTH, CAM_width)\ncapture.set(cv2.CAP_PROP_FRAME_HEIGHT, CAM_height)\n\nmasking_state = False\ntracking_box = False\nonce = True\ntrack = cv2.TrackerCSRT_create()\nfirst_count = True\n\n\ndef roiWindow(img):\n global masking_state\n global tracking_box\n # ROI 구하기\n rect = cv2.selectROI(\"SelectWindow\", img, fromCenter=False, showCrosshair=True)\n cv2.destroyWindow(\"SelectWindow\")\n\n # Tracker 설정하기\n track.init(img, rect)\n tracking_box = True\n masking_state = False\n\n\ndef current2Dvelocity(box, currentTime, detaltrate=500):\n global first_count\n millis = 0\n if first_count:\n millis = currentTime\n return\n\n\ncurrent_milli_time = lambda: int(round(time.time() * 1000))\n\nwhile True:\n ret, frame = capture.read(cameraNum)\n if masking_state:\n cv2.destroyAllWindows()\n roiWindow(frame)\n\n if tracking_box:\n sucess, box = track.update(frame)\n\n left, top, w, h = [int(v) for v in box]\n\n cv2.rectangle(\n frame,\n pt1=(left, top),\n pt2=(left + w, top + h),\n color=(255, 255, 255),\n thickness=3,\n )\n\n cv2.imshow(\"Norm\", frame)\n\n \"\"\"\n if cv2.waitKey(1) == ord(\"q\"):\n break\n \"\"\"\n key = cv2.waitKey(1)\n if key == ord(\"a\"):\n print(\"a\")\n masking_state = True\n elif key == ord(\"q\"):\n print(\"q\")\n break\n\ncapture.release()\ncv2.destroyAllWindows()\n","sub_path":"camera_velocity.py","file_name":"camera_velocity.py","file_ext":"py","file_size_in_byte":1612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"282658313","text":"# Copyright (c) 2017 Renata Hodovan, Akos Kiss.\n#\n# Licensed under the BSD 3-Clause License\n# .\n# This file may not be copied, modified, or distributed except\n# according to those terms.\n\nfrom .install import __version__, antlr_jar_path, install\n\n\n__all__ = [\n '__version__',\n 'antlr_jar_path',\n 'install',\n]\n","sub_path":"antlerinator/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"502525622","text":"import os, sys, time, random, re, json, spacy\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom tqdm import tqdm\r\nfrom collections import Counter\r\nfrom spacy.tokenizer import Tokenizer\r\nfrom .. import datasets_utils\r\nfrom .. import register_dataset\r\nfrom . import basic_label_dataset\r\n\r\n@register_dataset('dbpedia')\r\nclass dbpedia(basic_label_dataset):\r\n def __init__(self, dataset_config):\r\n super().__init__(dataset_config)\r\n data_dir = 'datasets/datasets_multi/dbpedia_csv'\r\n self.encoding = 'utf-8'\r\n self.num_label = 14\r\n\r\n self.val_num = 60000\r\n self.tst_num = 70000\r\n\r\n self.trn_path = os.path.join(data_dir, 'train.csv')\r\n self.val_path = None\r\n self.tst_path = os.path.join(data_dir, 'test.csv')\r\n\r\n self.load_dataset(self.trn_path, self.val_path, self.tst_path)\r\n\r\n self.target_trn -= 1\r\n self.target_val -= 1\r\n self.target_tst -= 1\r\n\r\n assert self.num_label == len(set(self.target.tolist()))\r\n \r\n def load_file(self,\r\n filename, \r\n dictionary, \r\n unk,\r\n encoding,\r\n spliter = ' ', \r\n pre_eos = True, \r\n end_eos = True,\r\n verbose = True,\r\n lower = True,\r\n remove_punc = True,\r\n ):\r\n assert os.path.exists(filename), 'file [{}] does not exists.'.format(filename)\r\n source = []\r\n wizard = []\r\n target = []\r\n idx = 0\r\n csv_file = pd.read_csv(filename, header = None)\r\n labels = csv_file[0]\r\n titles = csv_file[1]\r\n texts = csv_file[2]\r\n\r\n pbar = tqdm(range(len(labels)), ascii = True)\r\n for idx in pbar:\r\n pbar.set_description(f\"Processing {filename.split('/')[-1]}\")\r\n words = datasets_utils.tokenize(titles[idx], spliter, pre_eos, end_eos, lower, remove_punc)\r\n index = [dictionary[1].get_index(word, True) for word in words]\r\n wizard.append(np.array(index))\r\n\r\n words = datasets_utils.tokenize(texts[idx], spliter, pre_eos, end_eos, lower, remove_punc)\r\n index = [dictionary[0].get_index(word, True) for word in words]\r\n source.append(np.array(index))\r\n\r\n target.append(int(labels[idx]))\r\n\r\n return source, wizard, target\r\n\r\n def build_dict(self, file_names, encoding):\r\n for file_name in file_names:\r\n if file_name is None: continue\r\n assert os.path.exists(file_name), 'File [{}] doesn\\'t exists.'.format(file_name)\r\n \r\n csv_data = pd.read_csv(file_name, header = None)\r\n titles = csv_data[1]\r\n texts = csv_data[2]\r\n\r\n counter_src = Counter()\r\n counter_tgt = Counter()\r\n tokens_src = 0\r\n tokens_tgt = 0\r\n pbar = tqdm(range(len(titles)), ascii = True)\r\n for idx in pbar:\r\n pbar.set_description(f\"Building dict from {file_name.split('/')[-1]}\")\r\n\r\n words = datasets_utils.tokenize(texts[idx], pre_eos = False, end_eos = False)\r\n tokens_src += len(words)\r\n counter_src.update(words)\r\n\r\n words = datasets_utils.tokenize(titles[idx], pre_eos = False, end_eos = False)\r\n tokens_tgt += len(words)\r\n counter_tgt.update(words)\r\n\r\n dict_src = datasets_utils.Dictionary()\r\n for wid, freq in counter_src.most_common(self.nvocab_src):\r\n if not wid in [dict_src.pad, dict_src.eos, dict_src.eoe, dict_src.unk]:\r\n dict_src.add_word(wid, freq)\r\n print(f'dict_src constructed, len = {len(dict_src) - dict_src.special} + {dict_src.special} = {len(dict_src)}')\r\n \r\n dict_tgt = datasets_utils.Dictionary()\r\n for wid, freq in counter_tgt.most_common(self.nvocab_tgt):\r\n if not wid in [dict_tgt.pad, dict_tgt.eos, dict_tgt.eoe, dict_tgt.unk]:\r\n dict_tgt.add_word(wid, freq)\r\n print(f'dict_tgt constructed, len = {len(dict_tgt) - dict_tgt.special} + {dict_tgt.special} = {len(dict_tgt)}')\r\n return dict_src, dict_tgt\r\n\r\n def load_dataset(self, file_trn, file_val = None, file_tst = None, shuffle = False):\r\n list_tmp = [file_trn]\r\n if file_val is not None: list_tmp.append(file_val)\r\n if file_tst is not None: list_tmp.append(file_tst)\r\n\r\n self.dict = self.build_dict(list_tmp, self.encoding)\r\n\r\n source_trn, wizard_trn, target_trn = self.load_file(file_trn, self.dict, False, self.encoding)\r\n source_tst, wizard_tst, target_tst = self.load_file(file_tst, self.dict, False, self.encoding)\r\n \r\n source_trn = np.array(source_trn, dtype = object)\r\n wizard_trn = np.array(wizard_trn, dtype = object)\r\n target_trn = np.array(target_trn )\r\n\r\n source_tst = np.array(source_tst, dtype = object)\r\n wizard_tst = np.array(wizard_tst, dtype = object)\r\n target_tst = np.array(target_tst )\r\n\r\n self.source_trn = source_trn\r\n self.wizard_trn = wizard_trn\r\n self.target_trn = target_trn\r\n\r\n self.source_val = np.concatenate([source_tst[5000 * i: 5000 * i + 1000] for i in range(14)])\r\n self.wizard_val = np.concatenate([wizard_tst[5000 * i: 5000 * i + 1000] for i in range(14)])\r\n self.target_val = np.concatenate([target_tst[5000 * i: 5000 * i + 1000] for i in range(14)])\r\n\r\n self.source_tst = np.concatenate([source_tst[5000 * i + 1000: 5000 * (i +1)] for i in range(14)])\r\n self.wizard_tst = np.concatenate([wizard_tst[5000 * i + 1000: 5000 * (i +1)] for i in range(14)])\r\n self.target_tst = np.concatenate([target_tst[5000 * i + 1000: 5000 * (i +1)] for i in range(14)])\r\n\r\n if self.pretrained is not None:\r\n embedding_matrix_src, missing_src = datasets_utils.get_embedding_matrix(self.embed_dim, self.dict[0], self.pretrained)\r\n embedding_matrix_tgt, missing_tgt = datasets_utils.get_embedding_matrix(self.embed_dim, self.dict[1], self.pretrained)\r\n else:\r\n embedding_matrix_src, missing_src = None, 0\r\n embedding_matrix_tgt, missing_tgt = None, 0\r\n self.embedding_matrix = (embedding_matrix_src, embedding_matrix_tgt)\r\n print(f'Train num = {len(self.target_trn)}, valid num = {len(self.target_val)}, test num = {len(self.target_tst)}')\r\n print(f'Dataset [{self.dataset_name}] has been built, missing = [{missing_src} and {missing_tgt}].')\r\n\r\n @classmethod\r\n def setup_dataset(cls):\r\n return cls\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"program/datasets/datasets_multi/_dbpedia.py","file_name":"_dbpedia.py","file_ext":"py","file_size_in_byte":6705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"236986562","text":"from db_shared import db\n\nclass Category(db.Model):\n _id = db.Column('id', db.Integer, primary_key=True)\n category_name = db.Column(db.String(200))\n expenses = db.relationship('Expenses', backref='category', lazy=True)\n\n def __init__(self, category_name):\n self.category_name = category_name\n#this class stores name, char, price and path to image\n#it is also connected to Category table\nclass Expenses(db.Model):\n _id = db.Column('id', db.Integer, primary_key=True)\n name = db.Column(db.String(120))\n #char defines if user gain some money or spend it\n #this column will hold + or - \n char = db.Column(db.String(10))\n price = db.Column(db.Float)\n path_to_img = db.Column(db.String(300))\n category_id = db.Column(db.Integer, db.ForeignKey('category.id'))\n\n def __init__(self,name,char,price,path_to_img, category_id):\n self.name = name\n self.char = char\n self.price = price\n self.path_to_img = path_to_img\n self.category_id = category_id","sub_path":"db_models.py","file_name":"db_models.py","file_ext":"py","file_size_in_byte":1016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"421204811","text":"# -*- coding: utf-8 -*-\n\"\"\"\nThis file is a Jouleclinical spider created on top of the ATSSpider\nscrapy crawl jouleclinical -a mining_job_id=999 -a iteration=1 -a extract=1 -a url=\"http://www.jouleclinical.com/asp/job-search-results.asp\"\n\nsample url:\n http://www.jouleclinical.com/asp/job-search-results.asp\n\"\"\"\nfrom urlparse import urljoin\nfrom re import compile\n\nfrom scrapy.http import Request\nfrom scrapy.selector import Selector\n\nfrom brightcorp.base.atsspiders import ATSSpider\nfrom brightcorp.items import BrightcorpItemLoader\nfrom brightcorp.processors import Prefix, HtmlFormatter, RemoveBadElements, ConvertDateString\n\n\nclass Jouleclinical(ATSSpider):\n\n name = 'jouleclinical'\n ref_re = compile(\"id=([^&]*)\")\n\n def start_requests(self):\n start_url = urljoin(\n self.start_urls[0], \"/asp/job-search-results.asp\"\n )\n yield Request(url=start_url, callback=self.parse)\n\n def parse(self, response):\n sel = Selector(response)\n job_count = sel.xpath(\n \"//p[contains(text(),'jobs found')]/b[1]/text()\"\n ).extract()\n if job_count:\n self.expected_job_count = job_count[0]\n\n jobs = sel.xpath(\n \"//tr[td/font[contains(text(),'Posted')]]\"\n )\n for job in jobs:\n job_link = job.xpath(\n \"td[1]//a/@href\"\n ).extract()\n if job_link:\n job_url = urljoin(response.url, job_link[0])\n job_id_res = self.ref_re.search(job_link[0])\n if job_id_res:\n jobid = job_id_res.group(1)\n dateails_url = urljoin(\n response.url, \"/asp/job-detail-main.asp?id=%s\" % jobid\n )\n meta = {\n 'title': job.xpath(\"td[1]//text()\").extract(),\n 'date': job.xpath(\"td[2]//text()\").extract(),\n 'url': job_url,\n 'jobid': jobid\n }\n yield Request(\n url=dateails_url, meta=meta,\n callback=self.parse_job_callback()\n )\n\n def parse_job(self, response):\n loader = BrightcorpItemLoader(response=response)\n loader.add_value('url', response.meta['url'])\n loader.add_value('title', response.meta['title'])\n loader.add_value(\n 'date', response.meta['date'],\n ConvertDateString(\"Posted %m/%d/%Y %I:%M:%S %p\")\n )\n loader.add_xpath(\n 'description', \"//body\",\n RemoveBadElements(['img', 'a', 'style', 'script']), HtmlFormatter()\n )\n\n loader.add_value(\n 'referencenumber', response.meta['jobid'],\n Prefix(\"%s-\" % self.name)\n )\n details_url = urljoin(\n response.url,\n \"/asp/job-detail-side.asp?id=%s\" % response.meta['jobid']\n )\n yield Request(url=details_url, meta={'loader': loader}, callback=self.parse_details)\n\n def parse_details(self, response):\n loader = response.meta['loader']\n sel = Selector(response)\n loader.add_value(\n 'location',\n sel.xpath(\n \"//span[contains(text(),'LOCATION')]/following-sibling::text()\"\n ).extract()\n )\n loader.add_value(\n 'jobtype',\n sel.xpath(\n \"//span[contains(text(),'JOB TYPE')]/following-sibling::text()\"\n ).extract()\n )\n yield loader.load_item()\n","sub_path":"brightcorp/brightcorp/spiders/jouleclinical.py","file_name":"jouleclinical.py","file_ext":"py","file_size_in_byte":3623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"249517211","text":"import numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nimport seaborn as sns\r\nimport gmaps\r\n\r\n'''\r\n Parking lots annotated in gmaps\r\n Author: Yifan Huang\r\n Edited and Modified by Xu Zhu in 3/15\r\n'''\r\n\r\ngmaps.configure(api_key='AIzaSyBCkXSNL58obNihjx6WUR5zqQUZYBcFP0E')\r\nlos_angeles_coordinates = (34.0522, -118.2437)\r\n\r\n\r\ndef clean_data(file_in):\r\n df=pd.read_csv(file_in,usecols=['X','Y','Zipcode','Lat','Lon','Type','Hours','HourlyCost','DailyCost','MonthlyCost','SpecialFeatures','Spaces'],low_memory=True)\r\n return df\r\n\r\ndef park():\r\n '''\r\n Annocate parking lots\r\n '''\r\n df=pd.read_csv('parking-citations-processed.csv',usecols=['Latitude_WGS', 'Longitude_WGS'],low_memory=True)\r\n dfmark=clean_data('City_Owned_Parking_Lots.csv')\r\n parking_locations = dfmark[['Y','X']].loc[:1e6]\r\n \r\n locationsh = df[['Latitude_WGS','Longitude_WGS']]\r\n locationsh=locationsh.groupby(['Latitude_WGS','Longitude_WGS'])\r\n freq1=df.groupby(['Latitude_WGS','Longitude_WGS']).size().reset_index(name='freq')\r\n locationsh=freq1[['Latitude_WGS','Longitude_WGS']]\r\n \r\n\r\n fig=gmaps.figure(center=los_angeles_coordinates, zoom_level=12)\r\n\r\n markers = gmaps.marker_layer(parking_locations)\r\n fig.add_layer(markers)\r\n fig.add_layer(gmaps.heatmap_layer(locationsh,weights=freq1['freq']))\r\n # fig.add_layer(gmaps.traffic_layer())\r\n return(fig)\r\n","sub_path":"parking.py","file_name":"parking.py","file_ext":"py","file_size_in_byte":1406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"495344592","text":"import argparse\nimport os\nimport math\nimport random\n\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n\n\nclass Paper:\n def __init__(self, id, abstract):\n self.id = id\n self.abstract = abstract\n self.feature_vector = None\n self.num_citations = 0\n self.is_used = False\n\n\n def set_label(self):\n if self.num_citations == 0:\n self.label = 0\n else:\n self.label = round(math.log10(self.num_citations)) + 1\n\n\ndef get_datasets(dataset=\"cit-HepTh\", shuffle=True, proportion=(0.7, 0.2)):\n \"\"\"指定数据集名称,获取指定比例的训练集、验证集和测试集\n 每个子集均为一个列表,列表中的每个元素对应于一个论文样本的特征向量和标签元组,即(feature_vector, label)\n\n Args:\n dataset (str, optional): 数据集名称,cit-HepTh或cit-HepPh(注意大小写). Defaults to \"cit-HepTh\".\n shuffle (bool, optional): 是否打乱数据集顺序. Defaults to True.\n proportion (tuple, optional): 训练集和验证集的比例. Defaults to (0.7, 0.2).\n\n Returns:\n tuple: 训练集、验证集、测试集\n \"\"\"\n # 特征提取\n paper_dict = extract_features()\n # 获取混合数据集\n datasets = get_paper_citation_network(paper_dict, dataset)\n\n # 打乱数据集顺序\n if shuffle:\n random.shuffle(datasets)\n \n # 划分训练集、验证集和测试集\n training_set = datasets[: int(proportion[0] * len(datasets))]\n validation_set = datasets[int(proportion[0] * len(datasets)): int((proportion[0] + proportion[1]) * len(datasets))]\n test_set = datasets[int((proportion[0] + proportion[1]) * len(datasets)): ]\n\n return training_set, validation_set, test_set\n\n\ndef extract_features():\n \"\"\"TF-IDF文本特征提取\n\n Returns:\n dict: 论文字典\n \"\"\"\n # 获取全部论文的元信息\n paper_dict = get_all_meta_info()\n # 论文字典ID列表\n id_list = list(paper_dict.keys())\n\n # 论文摘要文本语料库\n corpus = list()\n\n for id in id_list:\n paper = paper_dict[id]\n corpus.append(paper.abstract)\n \n # 提取TF-IDF文本特征矩阵\n vectorizer = TfidfVectorizer()\n feature_matrix = vectorizer.fit_transform(corpus).toarray()\n\n # 设置每个论文样本的特征向量\n for i in range(len(id_list)):\n paper = paper_dict[id_list[i]]\n paper.feature_vector = feature_matrix[i]\n \n return paper_dict\n\n\ndef get_all_meta_info():\n \"\"\"获取全部论文的元信息\n\n Returns:\n dict: 论文字典\n \"\"\"\n paper_dict = dict()\n\n dir = \"./dataset/cit-HepTh-abstracts/\"\n\n for year in range(1992, 2004):\n year_dir = os.path.join(dir, str(year))\n abs_filenames = os.listdir(year_dir)\n abs_filenames.sort()\n\n for abs_filename in abs_filenames:\n id = abs_filename[: -4]\n abs_path = os.path.join(year_dir, abs_filename)\n paper = get_paper_meta_info(id, abs_path)\n paper_dict[paper.id] = paper\n \n return paper_dict\n\n\ndef get_paper_meta_info(id, abs_path):\n \"\"\"获取一篇论文的元信息\n\n Args:\n id (str): 论文ID\n abs_path (str): 论文元信息文件路径\n\n Returns:\n Paper: 论文对象\n \"\"\"\n # 按行读取论文元信息文件\n with open(abs_path, 'r') as abs_file:\n abs = abs_file.readlines()\n abs = abs[2: -1]\n \n # 论文摘要起始位置\n abstract_start_index = abs.index(\"\\\\\\\\\\n\") + 1\n \n # 拼接论文摘要文本\n abstract = \"\".join(abs[abstract_start_index: ])\n abstract = abstract.replace(\"\\n\", \" \")\n \n return Paper(id, abstract)\n\n\ndef get_paper_citation_network(paper_dict, dataset):\n \"\"\"获取论文引用网络信息(真实节点和边)\n\n Args:\n paper_dict (dict): 论文字典\n dataset (str): 数据集名称,cit-HepTh或cit-HepPh(注意大小写)\n\n Returns:\n list: 混合数据集,每个元素由论文样本的特征向量和标签元组构成\n \"\"\"\n datasets = list()\n\n # 读取论文引用数据集的网络结构文件(包含节点和边信息)\n with open(\"./dataset/{}.txt\".format(dataset), 'r') as paper_citataion_network_txt:\n paper_citation_network = paper_citataion_network_txt.readlines()\n paper_citation_network = paper_citation_network[4: ]\n\n # 累计论文被引用量值\n for line in paper_citation_network:\n line = line[: -1]\n from_node_id, to_node_id = line.split('\\t')\n from_node_id = from_node_id.zfill(7)\n to_node_id = to_node_id.zfill(7)\n\n # 判断当前两个论文节点是否存在对应的元信息\n if from_node_id in paper_dict and to_node_id in paper_dict:\n from_paper = paper_dict[from_node_id]\n from_paper.is_used = True\n\n to_paper = paper_dict[to_node_id]\n to_paper.num_citations += 1\n to_paper.is_used = True\n \n # 构建混合数据集\n for key in paper_dict.keys():\n paper = paper_dict[key]\n if paper.is_used:\n paper.set_label()\n datasets.append((paper.feature_vector, paper.label))\n\n return datasets\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"\")\n parser.add_argument(\"-d\", \"--dataset\", type=str, default=\"cit-HepTh\", help=\"\")\n parser.add_argument(\"-s\", \"--shuffle\", type=bool, default=True, help=\"\")\n parser.add_argument(\"-p\", \"--proportion\", type=tuple, default=(0.7, 0.2), help=\"\")\n\n args = parser.parse_args()\n\n training_set, validation_set, test_set = get_datasets(dataset=args.dataset, shuffle=args.shuffle, proportion=args.proportion)\n","sub_path":"feature/feature_extraction.py","file_name":"feature_extraction.py","file_ext":"py","file_size_in_byte":5737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"478007146","text":"# This file creates a sample instance of a CSDS to run tests\n# and serves as a unit test of the CSDS API.\n\nfrom csds import CSDS, CSDSCollection\n\nsample_corpus = [\n (\"John said he likes beets.\", 5, 9, \"CB\", \"said\"),\n (\"John said he likes beets.\", 13, 18, \"NCB\", \"likes\"),\n (\"Mary sometimes says she likes beets.\", 15, 19, \"CB\", \"says\"),\n (\"Mary sometimes says she likes beets.\", 24, 29, \"NCB\", \"likes\"),\n (\"Maybe Mulligan said she likes beets.\", 15, 19, \"NCB\", \"said\"),\n (\"Maybe Mulligan said she likes beets.\", 24, 29, \"NCB\", \"likes\"),\n]\n\nsentence_id = 0\n\n\ndef make_cognitive_state(sample_tuple):\n global sentence_id\n csds = CSDS(*sample_tuple, 0, sentence_id)\n sentence_id += 1\n return csds\n\n\nif __name__ == \"__main__\":\n sample_csds_collection = CSDSCollection(\"No text corpus\")\n for sentence_id, sample in enumerate(sample_corpus):\n sample_csds_collection.add_labeled_instance(CSDS(*sample, 0, sentence_id))\n print(\"Created sample CSDS collection\")\n print(sample_csds_collection.get_info_short())\n print(sample_csds_collection.get_info_long())\n # Not something you would normally do--therefore not in the API:\n sample_csds_collection.labeled_instances.clear()\n new_samples = list(map(make_cognitive_state, sample_corpus))\n sample_csds_collection.add_list_of_labeled_instances(new_samples)\n print(sample_csds_collection.get_info_short())\n for sample in sample_csds_collection.get_next_instance():\n print(sample.get_marked_text())\n","sub_path":"CSDS/sample_csds.py","file_name":"sample_csds.py","file_ext":"py","file_size_in_byte":1509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"608551944","text":"\nimport matplotlib.pyplot as plt\nimport sys\nimport matplotlib\nimport numpy as np\nfrom utils1 import parseData,processData\n\ndef drawFig(df,yx):\n # Data for plotting\n fig, ax = plt.subplots()\n ls = []\n lab = []\n for name,group in df.groupby('time_budget'):\n print(group)\n df = group.groupby('sigma').mean()\n t = np.log2(df.index)\n s = df[yx]\n l, = ax.plot(t, s, marker='o')\n # to annotate\n #for ts in zip(t, s):\n # ax.annotate(\"(%s,%s)\" % ts, xy=ts, xytext=(-20, 10), textcoords='offset points')\n ls = np.append(ls,l,)\n lab = np.append(lab,name) \n\n le1 = ax.legend(ls, lab , loc='upper right')\n \n ax.set(xlabel='log2(sigma)', ylabel='second (s)',\n title='sigma ' + yx + ' curve')\n ax.grid()\n plt.gca().add_artist(le1)\n \n fig.savefig(\"test.png\")\n plt.show()\n\n\ndef main():\n df=parseData(sys.argv[1])\n #print(df)\n df=processData(df)\n #print(df)\n drawFig(df,'accuracy')\n #drawFig(df,'iter')\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"p12.py","file_name":"p12.py","file_ext":"py","file_size_in_byte":983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"319036663","text":"#!/usr/bin/env python3\n\nimport os\n\nimport TwitterKov\nfrom TwitterKov.experiments import Timer, getMemory\n\nfrom TwitterKov.ds.DictBigram import DictBigram\nfrom TwitterKov.ds.ListBigram import ListBigram\n\ndef generateMarkov(cl):\n\tchain = cl()\n\tfn = os.path.join(os.path.dirname(__file__), '../../data/train.dat')\n\twith open(fn) as f:\n\t\tfor tweet in TwitterKov.getTweets(f):\n\t\t\ttokens = TwitterKov.tokenizeTweet(tweet)\n\t\t\tchain.countTokens(tokens)\n\treturn chain\n\ndef score(chain):\n\tvals = [10**i for i in range(-9, 9)]\n\tfor i in vals:\n\t\tfn = os.path.join(os.path.dirname(__file__), '../../data/dev.dat')\n\t\twith open(fn) as f:\n\t\t\tchain.score(f, i)\n\n# Build ListBigram #\nwith Timer() as listBT:\n\tchain = generateMarkov(ListBigram)\n\nlistM = getMemory(chain)\n\n# Score ListBigram #\nwith Timer() as listST:\n\tscore(chain)\n\n# Build DictBigram #\nwith Timer() as dictBT:\n\tchain = generateMarkov(DictBigram)\n\ndictM = getMemory(chain)\n\n# Score DictBigram\nwith Timer() as dictST:\n\tchain = score(chain)\n\nalign = str(max(len(\"{:.2f}\".format(listM / (1024 ** 2))), len(\"{:.2f}\".format(dictM / (1024 ** 2)))))\nprint(\"=== Memory usage of model from train.dat ===\")\nprint((\"ListBigram: {:>\" + align + \".2f} MB\").format(listM / (1024 ** 2)))\nprint((\"DictBigram: {:>\" + align + \".2f} MB\").format(dictM / (1024 ** 2)))\nprint(\"Smaller by x{:.2f}\".format(listM / dictM))\nprint()\nalign = str(max(len(\"{:.2f}\".format(listBT.secs)), len(\"{:.2f}\".format(dictBT.secs))))\nprint(\"=== Building model from train.dat ===\")\nprint((\"ListBigram: {:>\" + align + \".2f} s\").format(listBT.secs))\nprint((\"DictBigram: {:>\" + align + \".2f} s\").format(dictBT.secs))\nprint(\"Speedup of x{:.2f}\".format(listBT.secs / dictBT.secs))\nprint()\nalign = str(max(len(\"{:.2f}\".format(listST.secs)), len(\"{:.2f}\".format(dictST.secs))))\nprint(\"=== Scoring model against dev.dat ===\")\nprint((\"ListBigram: {:>\" + align + \".2f} s\").format(listST.secs))\nprint((\"DictBigram: {:>\" + align + \".2f} s\").format(dictST.secs))\nprint(\"Speedup of x{:.2f}\".format(listST.secs / dictST.secs))","sub_path":"TwitterKov/experiments/list_vs_dict.py","file_name":"list_vs_dict.py","file_ext":"py","file_size_in_byte":2015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"78717583","text":"import serial\nimport time\n# import threading\nimport paho.mqtt.client as mqtt\n# import paho.mqtt.publish as publish\n\nfrom flask import Flask, render_template\nfrom flask_socketio import SocketIO, emit\nfrom threading import Thread\n\nbroker=\"mqtt.eclipse.org\"\n\n# The callback for when the client receives a CONNACK response from the server.\ndef on_connect(client, userdata, flags, rc):\n\tprint(\"Connected with result code \"+str(rc))\n\t# Subscribing in on_connect() means that if we lose the connection and\n\t# reconnect then subscriptions will be renewed.\n\tclient.subscribe(\"ixe/\")\n\ndef on_message(client, userdata, msg):\n\treceivedMessage = str(msg.payload.decode(\"utf-8\"))\n\tprint(\"received message = \"+receivedMessage)\n\tser.write(receivedMessage.encode())\n\nclient = mqtt.Client()\nclient.on_connect = on_connect\nclient.on_message = on_message\n\nclient.connect(broker, 1883, 60)\n\nclient.loop_start()\n\n# Arduino communication\nser = serial.Serial('/dev/ttyUSB0', 9600)\nser.flushInput()\n\ndef read_from_port(ser):\n\twhile True:\n\t\treading = ser.readline().decode().strip()\n\t\tprint(reading)\n\t\tclient.publish(\"ixe/\", reading)\n\t\tser.flushInput()\n\t\ttime.sleep(1)\n\nthread = Thread(target=read_from_port, args=[ser])\nthread.start()\n\n# Flask Webserver\napp = Flask(__name__)\napp.config['SECRET_KEY'] = 'secret!'\nsocketio = SocketIO(app)\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n@socketio.on('connect')\ndef test_connect():\n print('Client connected')\n emit('my response', {'data': 'Connected'})\n\n@socketio.on('disconnect')\ndef test_disconnect():\n print('Client disconnected')\n\ndef main():\n\ttry:\n\t\twhile True:\n\t\t\treading = ser.readline().decode().strip()\n\t\t\tprint(reading)\n\t\t\tclient.publish(\"there/\", reading)\n\t\t\tser.flushInput()\n\t\t\ttime.sleep(1)\n\texcept KeyboardInterrupt:\n\t\tser.close()\n\t\tclient.disconnect()\n\t\tclient.loop_stop()\n\t\tprint (\"done\")\n\n# Handle the LED messages\n@socketio.on('red')\ndef led_R():\n print(\"Turn the LED RED!\")\n ser.write(b'red') \n\n@socketio.on('green')\ndef led_G():\n print(\"Turn the LED GREEN!\")\n ser.write(b'green')\n\n@socketio.on('blue')\ndef led_B():\n print(\"Turn the LED BLUE!\")\n ser.write(b'blue')\n\n\nif __name__ == '__main__':\n\tapp.run(host='0.0.0.0', threaded=True)\n\tsocketio.run(app)\n\tmain()\n","sub_path":"Lab7/MyHelloFromHere/helloFromHere.py","file_name":"helloFromHere.py","file_ext":"py","file_size_in_byte":2254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"556358141","text":"from configparser import ConfigParser, ExtendedInterpolation\nimport pandas as pd\nimport yaml\n\n\nclass MonthlyReport():\n\n def __init__(self, data=None):\n self.__module_name__ = \"MonthlyReport\"\n self.__ctx__ = dict()\n self.__data__ = data\n\n print(self.__module_name__ + \"初始化……\")\n # 配置加载\n with open(self.__module_name__ + \"/\" + self.__module_name__ + \".yaml\", 'rb') as stream:\n try:\n ctx = yaml.safe_load(stream)\n for key in ctx.keys():\n self.__ctx__[key] = ctx[key]\n stream.close()\n except yaml.YAMLError as exc:\n print(exc)\n\n\n # 数据加载\n if data is None:\n data = pd.read_excel(\n self.__ctx__['data_source_path'],\n sheet_name=None,\n index_col=None\n )\n self.__ctx__['data'] = data\n\n # 处理链加载\n task_processors_names = self.__ctx__[\"task_chain\"]\n self.__ctx__[\"process_chain\"] = list()\n for name in task_processors_names:\n processor = __import__(self.__module_name__ + \".\" + name, fromlist=\"True\")\n cls = getattr(processor, name)\n self.__ctx__[\"process_chain\"].append(cls(self.__ctx__))\n\n self.__ctx__[\"data_processor\"] = self.__ctx__[\"process_chain\"][0]\n self.__ctx__[\"chart_processor\"] = self.__ctx__[\"process_chain\"][1]\n self.__ctx__[\"output_processor\"] = self.__ctx__[\"process_chain\"][2]\n\n print(self.__module_name__ + \"初始化完毕,开始执行\")\n\n def data_process(self):\n print(\"处理数据中\")\n self.__ctx__[\"data_processor\"].process()\n\n def chart_process(self):\n print(\"图表绘制中\")\n self.__ctx__[\"chart_processor\"].process()\n\n def output_process(self):\n print(\"最后输出中\")\n self.__ctx__[\"output_processor\"].process()\n\n def release(self):\n print(\"资源已释放\")\n\n\nif __name__ == 'main':\n print(\"hello from Monthly Report\")\n","sub_path":"MonthlyReport/MonthlyReport.py","file_name":"MonthlyReport.py","file_ext":"py","file_size_in_byte":2066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"573648828","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon May 28 16:38:04 2018\n\n@author: Yogendra\n\"\"\"\n\nimport nltk\nfrom nltk.tokenize import TweetTokenizer\nfrom nltk.probability import FreqDist\nfrom nltk.util import ngrams\nfrom nltk.corpus import stopwords, wordnet\nfrom nltk.stem import WordNetLemmatizer\n\nimport sklearn\nfrom sklearn import metrics\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.model_selection import train_test_split\n\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.naive_bayes import MultinomialNB\n\nimport re\nimport pandas as pd\nimport numpy as np\n\n\nwith open('C:\\\\Users\\\\IBM_ADMIN\\\\Downloads\\\\python_Lecs\\\\NLP_Movie_Review_Proj\\\\yelp_labelled.txt', 'r') as f:\n review_lines = f.readlines()\n \nprint(type(review_lines))\n\nprint(len(review_lines))\n\nfor one_line in review_lines[0:10]:\n print(one_line)\n\nreviews = []\nreview_labels = []\n\nfor line in review_lines: #Splitting reviews into text and labels\n line_list = line.split(\"\\t\")\n review = line_list[0]\n review = review.lower()\n reviews.append(review)\n label = line_list[1]\n label = int(label)\n review_labels.append(label)\n\nprint(len(reviews))\nprint(len(review_labels))\nprint(reviews[0])\nprint(review_labels[0])\n\n#Tokenize\n\n#Creating a single string of all the reviews\n\nreview_string = \" \".join(reviews)\nprint(review_string)\ntknzr = TweetTokenizer()\nreview_tokens = tknzr.tokenize(review_string)\nprint(len(review_tokens))\n\n#Removing punctuation\npunctuation = re.compile(r'[-.?!,\":;()|0-9]')\nreview_tokens2 = []\n\nfor token in review_tokens:\n word = punctuation.sub(\"\", token)\n if len(word)>0:\n review_tokens2.append(word)\n \nprint(len(review_tokens2))\n\n#Removing stopwords\n\nreview_tokens3 = []\nstp_words = set(stopwords.words('english'))\n\nfor token in review_tokens2: # remove stop words\n token = token.lower()\n if token not in stp_words:\n review_tokens3.append(token)\n \nprint(len(review_tokens3))\n\n#Finding Frequency Distribution\n\nfdist = FreqDist()\nfor word in review_tokens3:\n fdist[word]+=1\n \nprint(len(fdist))\n\nfdist_top20 = fdist.most_common(20) #top 20 tokens with highest frequency\n\n#Finding Parts of speech tags\n\npos_list = []\nfor token in review_tokens3: # List after stopwords and punctuation\n pos_list.append(nltk.pos_tag([token]))# The word should be inside [], else tagger will take it as string\n \nprint(len(pos_list))\n\nprint(pos_list[1])\n\npos_set = set()\n\nfor pos in pos_list: # Finding all different Part of Speech Tags\n pos_set.add(pos[0][1])\n \nprint(len(pos_set))\n\nprint(pos_set)\n\n#Finding Adjectives\npos_JJ = []\n\nfor each_POS in pos_list:\n if each_POS[0][1] in [\"JJ\",\"JJR\",\"JJS\"]:\n pos_JJ.append(each_POS[0][0])\n \nprint(len(pos_JJ))\n\nfdist_JJ = FreqDist()\nfor word in pos_JJ:\n fdist_JJ[word] += 1\n \nprint(len(fdist_JJ))\n\nfdist_JJ_top20 = fdist_JJ.most_common(20) #top 20 tokens with highest frequencies\n\nprint(fdist_JJ_top20)\n\n#Lemmatizing words\n\nword_lem = WordNetLemmatizer()\nlem_ADJ = []\nlem_ADV = []\nlem_VERB = []\n\nfor word in review_tokens3:\n word_pos =nltk.pos_tag([word])\n \n if word_pos[0][1] in [\"JJ\", \"JJR\", \"JJS\"]:\n lem_ADJ.append((word_pos[0][0], word_lem.lemmatize(word, wordnet.ADJ)))\n \n if word_pos[0][1] in [\"RB\",\"RBR\",\"RBS\"]:\n lem_ADV.append((word_pos[0][0], word_lem.lemmatize(word, wordnet.VERB)))\n \n if word_pos[0][1] in [\"VB\",\"VBD\",\"VBG\",\"VBN\",\"VBZ\"]:\n lem_VERB.append((word_pos[0][0], word_lem.lemmatize(word, wordnet.VERB)))\n\n\nprint(len(lem_ADJ)) \n\nprint(lem_ADJ[:10])\n\nprint(lem_ADV)\n\nprint(lem_ADV[:10])\n\nprint(lem_VERB)\n\nprint(lem_VERB[:10])\n\n# Checking most frequent n-grams\n\n#Segregating all positive and negative reviews\n\npositive_reviews = []\nnegative_reviews = []\n\nfor line in review_lines: # Splitting reviews into text and labels\n line_list = line.split(\"\\t\")\n \n label = line_list[1]\n label = int(label)\n \n if label==1:\n pos_review = line_list[0]\n pos_review = pos_review.lower()\n positive_reviews.append(pos_review)\n \n elif label==0:\n neg_review = line_list[0]\n neg_review = neg_review.lower()\n negative_reviews.append(neg_review)\n \nprint(len(positive_reviews))\nprint(len(negative_reviews))\n\n#Working on positive reviews\n\npos_review_string = \" \".join(positive_reviews)\n\npos_rev_tokens = nltk.word_tokenize(pos_review_string)\n\npos_rev_trigrams = list(nltk.trigrams(pos_rev_tokens))\n\nprint(len(pos_rev_trigrams))\n\nprint(pos_rev_trigrams[0])\n\nfdist_pos_rev = nltk.FreqDist(pos_rev_trigrams)\n\nprint(fdist_pos_rev.most_common(10))\n\n#Working on Negative Reviews\n \nneg_review_string = \" \".join(negative_reviews)\n\nneg_rev_tokens = nltk.word_tokenize(neg_review_string)\n\nneg_rev_trigrams = list(nltk.trigrams(neg_rev_tokens))\n\nprint(len(neg_rev_trigrams))\n\nprint(neg_rev_trigrams[0])\n\nfdist_neg_rev = nltk.FreqDist(neg_rev_trigrams)\n\nprint(fdist_neg_rev.most_common(10)) \n\n#Predicting reviews using machine learning\n\n#Creating features and labels\n\nreview_list = []\n\nfor line in review_lines: # Splitting reviews into text and labels\n line_list = line.split(\"\\t\")\n review = line_list[0]\n review = review.lower()\n review_list.append(review)\n \nprint(len(review_list))\n\nprint(review_list[1])\n\ntf_vect = TfidfVectorizer(min_df = 2, lowercase = True, stop_words = 'english')\n\nX_TFIDF = tf_vect.fit_transform(review_list)\n\nprint(type(X_TFIDF))\n\nprint(X_TFIDF.shape)\n\nX_TFIDF_names = tf_vect.get_feature_names()\n\nX_tf = pd.DataFrame(X_TFIDF.toarray(), columns = X_TFIDF_names)\n\nprint(X_tf.head())\n\ny = pd.Series(review_labels)\n\nprint(type(y))\n\nprint(y.shape)\n\nprint(y.head())\n\n#Train-test Split\n\nX_TF_train, X_TF_test, y_TF_train, y_TF_test = train_test_split(X_tf, y, test_size=0.2, random_state=5)\n\nprint(X_TF_train.shape)\nprint(X_TF_test.shape)\nprint(y_TF_train.shape)\nprint(y_TF_test.shape)\n \n#Using Multinomial Naive Bayes\nclf_TF = MultinomialNB()\nclf_TF.fit(X_TF_train, y_TF_train)\n\ny_TF_pred = clf_TF.predict(X_TF_test)\n\nprint(type(y_TF_pred))\n\nprint(y_TF_pred.shape)\n\nprint(metrics.accuracy_score(y_TF_test, y_TF_pred))\n\nscore_clf_TF = confusion_matrix(y_TF_test, y_TF_pred)\n\nprint(score_clf_TF)\n\nTP = score_clf_TF[0][0]\nFP = score_clf_TF[0][1]\nFN = score_clf_TF[1][0]\nTN = score_clf_TF[1][1]\n\nprint('True Positive: ',TP)\nprint('False Positive: ', FP)\nprint('False Negative: ', FN)\nprint('True Negative: ', TN)\n\nprint(\"Correctly Identified: \", TP+TN)\nprint(\"Wrongly Identified: \", FP+FN)\n\n#Checking Classifier on new Data\n\ndef find_sentiments (sentence):\n sent_list = [sentence]\n sent_vect = tf_vect.transform(sent_list)\n sent_pred = clf_TF.predict(sent_vect)\n print(\"Sentiment: \",sent_pred[0])\n return\n\nfind_sentiments(\"I liked the food a lot\")\nfind_sentiments(\"The food was very bad\")\nfind_sentiments(\"The place was good but the food was bad\") \n ","sub_path":"NLP_Customer_Review_Proj/NLP_Movie_Review_Proj/NLP_Movie_Review_Proj/NLP_Final_Proj.py","file_name":"NLP_Final_Proj.py","file_ext":"py","file_size_in_byte":6866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"559484633","text":"#!/usr/bin/env python3\nimport json, sys\nconnids, txids = {}, {}\nfor line in sys.stdin:\n ####print('> ', line)\n d = json.loads(line)\n if 'Connect' in d:\n k = d['Connect']['LocalAddress'] + d['Connect']['RemoteAddress']\n connids[k] = d['Connect']['ConnID']\n elif 'HTTPConnectionReady' in d:\n v = d['HTTPConnectionReady']['LocalAddress'] + d['HTTPConnectionReady']['RemoteAddress']\n txids[d['HTTPConnectionReady']['TransactionID']] = v\n for k in d:\n if k.startswith('HTTP'):\n v = txids[d[k]['TransactionID']]\n connid = connids[v]\n d[k]['ConnID'] = connid\n json.dump(d, sys.stdout, indent=4, sort_keys=True)\n sys.stdout.write(\"\\n\\n\")\n\n","sub_path":"testdata/filter.py","file_name":"filter.py","file_ext":"py","file_size_in_byte":720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"267816598","text":"#!/usr/bin/env python\nfrom ROOT import *\nfrom math import sqrt\nfrom collections import OrderedDict\nfrom array import array\n\ndef GetHist(f,hists,name): \n hists[name]=f.Get(name)\n\ndef FitSlices(h,fout=None,simple=True):\n name=h.GetName()\n nx=h.GetNbinsX()\n x =[]\n xe =[]\n mean =[] \n meane =[]\n width =[]\n widthe=[]\n for xi in range(1,nx+1):\n lo=h.GetXaxis().GetBinLowEdge(xi)\n hi=h.GetXaxis().GetBinUpEdge(xi)\n hslice=h.ProjectionY(\"{}_{}_{}\".format(name,int(lo),int(hi)),xi,xi,\"e\")\n if hslice.GetEntries()<1: continue\n x.append((lo+hi)/2) \n xe.append((hi-lo)/2)\n # fit\n if simple:\n mean.append(hslice.GetMean()) \n meane.append(hslice.GetMean()/sqrt(hslice.GetEntries()))\n width.append(hslice.GetRMS())\n widthe.append(0.)\n else:\n fit_lo = hslice.GetBinLowEdge(1)\n fit_hi = hslice.GetBinLowEdge(1+hslice.GetNbinsX())\n func = TF1(\"func\",\"gaus\",fit_lo,fit_hi)\n fit_result = hslice.Fit(func,\"QS\",\"\",fit_lo,fit_hi)\n mean.append(fit_result.Parameter(1)) \n meane.append(fit_result.ParError(1)) \n width.append(fit_result.Parameter(2))\n widthe.append(fit_result.ParError(2))\n if fout: \n fout.cd()\n hslice.Write()\n gmean = TGraphErrors(len(x),array('f',x),array('f',mean),array('f',xe),array('f',meane))\n gwidth = TGraphErrors(len(x),array('f',x),array('f',width),array('f',xe),array('f',widthe))\n gmean.SetName(\"g_{}_mean\".format(name))\n gwidth.SetName(\"g_{}_width\".format(name))\n return gmean,gwidth\n #return (mean,meane,width,widthe)\n\ndef plot(g,ytitle=\"response\",yrange=(0,1)):\n gStyle.SetOptStat(0)\n c = TCanvas(\"canv\",\"\",750,750)\n pad = TPad(\"pad\", \"pad\", .005, .01, .995, .995)\n pad.Draw()\n pad.cd()\n\n gPad.SetLeftMargin(0.17)\n gPad.SetRightMargin(0.05)\n gPad.SetBottomMargin(0.1)\n gPad.SetTopMargin(0.05)\n\n #draw this guy first\n b = TH1D(\"b\",\"\",1,0,g.GetX()[g.GetN()-1]+g.GetEXhigh()[g.GetN()-1])\n b.Draw()\n \n b.GetXaxis().SetTitle(\"p_{T}(Z) [GeV]\")\n b.GetXaxis().SetTitleOffset(1.2)\n b.GetYaxis().SetTitleOffset(1.5)\n b.GetYaxis().SetLabelSize(0.04)\n b.GetYaxis().SetTitleSize(0.04)\n b.GetYaxis().SetTitle(ytitle)\n b.GetYaxis().SetRangeUser(*yrange)\n b.Draw(\"axis\")\n\n g.Draw(\"same\")\n c.SaveAs(\"plots/{}.pdf\".format(g.GetName()))\n\ndef RunAll(infile, res_file, fit_file, name, ):\n h = f_in.Get(name)\n yrange = (h.GetYaxis().GetBinLowEdge(1),h.GetYaxis().GetBinLowEdge(1+h.GetNbinsY()))\n gpair = FitSlices(h,f_fits)\n res_file.cd()\n plot(gpair[0],\"response\",yrange)\n plot(gpair[1],\"resolution\",(0,100) if ('abs' in name) else (0,1))\n\ndef ArrayDivideErrs(n,ne,d,de):\n x=[]\n xe=[]\n for i in range(len(n)):\n if d[i]==0 or n[i]==0:\n x +=[0.]\n xe+=[0.]\n else:\n x+=[n[i]/d[i]]\n xe+=[(n[i]/d[i])*sqrt((ne[i]/n[i])**2+(de[i]/d[i])**2)]\n return x,xe\n\ndef RunFits(hz,hpara,hperp,name,fout=None,simple=True):\n #name=h.GetName()\n nx=hz.GetNbinsX()\n z =[]\n ze =[]\n zeup =[]\n zedn =[]\n para =[] \n parae =[]\n resPara =[]\n resParae=[]\n resPerp =[]\n resPerpe=[]\n\n for xi in range(1,nx+1):\n lo=hz.GetXaxis().GetBinLowEdge(xi)\n hi=hz.GetXaxis().GetBinUpEdge(xi)\n z_slice=hz.ProjectionY(\"{}_zpt_{}zpt{}\".format(hz.GetName(),int(lo),int(hi)),xi,xi,\"e\")\n para_slice=hpara.ProjectionY(\"{}_para_{}zpt{}\".format(hpara.GetName(),int(lo),int(hi)),xi,xi,\"e\")\n perp_slice=hperp.ProjectionY(\"{}_perp_{}zpt{}\".format(hperp.GetName(),int(lo),int(hi)),xi,xi,\"e\")\n #if hslice.GetEntries()<1: continue\n # fit\n if simple:\n z.append(z_slice.GetMean())\n ze.append(z_slice.GetRMS())\n zeup.append(hi-z_slice.GetMean()) # asym errors\n zedn.append(z_slice.GetMean()-lo) # asym errors\n para.append(para_slice.GetMean())\n parae.append(para_slice.GetRMS()/sqrt(para_slice.GetEntries()) if para_slice.GetEntries() else 0.)\n resPara.append(para_slice.GetRMS())\n resPerp.append(perp_slice.GetRMS())\n resParae.append(0.)\n resPerpe.append(0.)\n # else:\n # x.append((lo+hi)/2) \n # xe.append((hi-lo)/2)\n # fit_lo = hslice.GetBinLowEdge(1)\n # fit_hi = hslice.GetBinLowEdge(1+hslice.GetNbinsX())\n # func = TF1(\"func\",\"gaus\",fit_lo,fit_hi)\n # fit_result = hslice.Fit(func,\"QS\",\"\",fit_lo,fit_hi)\n # mean.append(fit_result.Parameter(1)) \n # meane.append(fit_result.ParError(1)) \n # width.append(fit_result.Parameter(2))\n # widthe.append(fit_result.ParError(2))\n if fout: \n fout.cd()\n para_slice.Write()\n perp_slice.Write()\n\n\n resp,respe = ArrayDivideErrs(para,parae,z,ze)\n\n g_resp = TGraphAsymmErrors(len(z),array('f',z),array('f',resp),\n array('f',zedn), array('f',zeup),\n array('f',respe),array('f',respe))\n g_resPara = TGraphAsymmErrors(len(z),array('f',z),array('f',resPara),\n array('f',zedn), array('f',zeup),\n array('f',resParae),array('f',resParae))\n g_resPerp = TGraphAsymmErrors(len(z),array('f',z),array('f',resPerp),\n array('f',zedn), array('f',zeup),\n array('f',resPerpe),array('f',resPerpe))\n g_resp.SetName(\"g_{}_resp\".format(name))\n g_resPara.SetName(\"g_{}_para_res\".format(name))\n g_resPerp.SetName(\"g_{}_perp_res\".format(name))\n\n return g_resp,g_resPara,g_resPerp\n \n # gmean = TGraphErrors(len(x),array('f',x),array('f',mean),array('f',xe),array('f',meane))\n # gwidth = TGraphErrors(len(x),array('f',x),array('f',width),array('f',xe),array('f',widthe))\n # gmean.SetName(\"g_{}_mean\".format(name))\n # gwidth.SetName(\"g_{}_width\".format(name))\n # return gmean,gwidth\n #return (mean,meane,width,widthe)\n\ndef RunAll2(infile, res_file, fit_file, name, ):\n hz = f_in.Get(\"ptz_2d\")\n hpara = f_in.Get(name+\"_para\")\n hperp = f_in.Get(name+\"_perp\")\n gs = RunFits(hz,hpara,hperp,name,fout=fit_file)\n #g_resp,g_resPara,g_resPerp = RunFits(hz,hpara,hperp,fout=fit_file)\n res_file.cd()\n plot(gs[0],\"response\",(0,2))\n plot(gs[1],\"para resolution\",(0,200))\n plot(gs[2],\"perp resolution\",(0,200))\n\n\nf_in = TFile(\"histograms.root\",\"read\")\nf_out = TFile(\"results.root\",\"recreate\")\nf_fits = TFile(\"fits.root\",\"recreate\")\n\n# run analysis\nRunAll2(f_in,f_out,f_fits,\"pf\")\nRunAll2(f_in,f_out,f_fits,\"puppi\")\nRunAll2(f_in,f_out,f_fits,\"gen\")\n\n# book2(hists,\"pf_para\" ,zpt_n,0,zpt_hi,para_n,para_lo,para_hi)\n# book2(hists,\"puppi_para\",zpt_n,0,zpt_hi,para_n,para_lo,para_hi)\n# book2(hists,\"gen_para\" ,zpt_n,0,zpt_hi,para_n,para_lo,para_hi)\n\n# RunAll(f_in,f_out,f_fits,\"pf_abs\" )\n# RunAll(f_in,f_out,f_fits,\"pf_ratio\" )\n# RunAll(f_in,f_out,f_fits,\"puppi_abs\" )\n# RunAll(f_in,f_out,f_fits,\"puppi_ratio\" )\n# RunAll(f_in,f_out,f_fits,\"pf_para_abs\" )\n# RunAll(f_in,f_out,f_fits,\"pf_perp_abs\" )\n# RunAll(f_in,f_out,f_fits,\"pf_para_ratio\" )\n# RunAll(f_in,f_out,f_fits,\"pf_perp_ratio\" )\n# RunAll(f_in,f_out,f_fits,\"puppi_para_abs\" )\n# RunAll(f_in,f_out,f_fits,\"puppi_perp_abs\" )\n# RunAll(f_in,f_out,f_fits,\"puppi_para_ratio\")\n# RunAll(f_in,f_out,f_fits,\"puppi_perp_ratio\")\n\nf_in.Close()\nf_fits.Close()\nf_out.Close()\n\nexit(0)\n#read histograms\nf_in = TFile(\"histograms.root\",\"read\")\nhists=OrderedDict()\nGetHist(f_in,hists,\"pf_abs\" )\nGetHist(f_in,hists,\"pf_ratio\" )\nGetHist(f_in,hists,\"puppi_abs\" )\nGetHist(f_in,hists,\"puppi_ratio\" )\nGetHist(f_in,hists,\"pf_para_abs\" ) #components\nGetHist(f_in,hists,\"pf_perp_abs\" )\nGetHist(f_in,hists,\"pf_para_ratio\" )\nGetHist(f_in,hists,\"pf_perp_ratio\" )\nGetHist(f_in,hists,\"puppi_para_abs\" )\nGetHist(f_in,hists,\"puppi_perp_abs\" )\nGetHist(f_in,hists,\"puppi_para_ratio\")\nGetHist(f_in,hists,\"puppi_perp_ratio\")\n\n# figure out sensible histogram ranges\nabs_range = (hists[\"pf_abs\"].GetYaxis().GetBinLowEdge(1),hists[\"pf_abs\"].GetYaxis().GetBinLowEdge(1+hists[\"pf_abs\"].GetNbinsY()))\nratio_range = (hists[\"pf_ratio\"].GetYaxis().GetBinLowEdge(1),hists[\"pf_ratio\"].GetYaxis().GetBinLowEdge(1+hists[\"pf_ratio\"].GetNbinsY()))\nf_fits = TFile(\"fits.root\",\"recreate\")\n\ngpairs=OrderedDict()\ngpairs[\"puppi_ratio\"] = FitSlices(hists[\"puppi_ratio\"],f_fits)\ngpairs[\"puppi_abs\"] = FitSlices(hists[\"puppi_abs\"],f_fits)\n\nf_out = TFile(\"results.root\",\"recreate\")\nfor p in gpairs:\n gpairs[p][0].Write()\n gpairs[p][1].Write()\n plot(gpairs[p][0],\"response\",ratio_range)\n plot(gpairs[p][1],\"resolution\",abs_range)\n\nf_in.Close()\nf_fits.Close()\nf_out.Close()\n\n\n","sub_path":"histfitter.py","file_name":"histfitter.py","file_ext":"py","file_size_in_byte":8961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"343356590","text":"#Objectivity_Distribution.py\r\nfrom textblob import TextBlob\r\nfrom matplotlib import pyplot\r\n\r\ndef ObjDist(fileList):\r\n text= []\r\n for i in fileList:\r\n book= open(i,\"r\")\r\n text.append(TextBlob(book.read()))\r\n book.close()\r\n \r\n for i in text:\r\n y= []\r\n sent_tot= 0\r\n for sentence in i.sentences:\r\n y.append(sentence.sentiment.subjectivity)\r\n sent_tot+= 1\r\n\r\n pyplot.xlabel(\"Sentence Progression\")\r\n pyplot.ylabel(\"Subjectivity\")\r\n pyplot.plot(range(sent_tot),y,\"bo\")\r\n pyplot.show()\r\n","sub_path":"Portfolio/novel/Objectivity_Distribution.py","file_name":"Objectivity_Distribution.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"408998287","text":"import numpy as np\nimport os\nfrom PIL import Image\nfrom matplotlib import pyplot as plt\nimport cv2\nTAG_FLOAT = 202021.25 # Magic number from source code\n\n\n#Becareful, script only test on binary mask\n#Therefore, when use this script, you should convert mask to binary\n#Example in last.\n\ndef read_flow(filename):\n \"\"\"\n Read a .flo file.\n Parameters\n ----------\n filename : str\n Filename to read flow from. Must have extension .flo.\n Returns\n -------\n flow : ndarray, shape (height, width, 2)\n U and V vector components of flow.\n \"\"\"\n ext = os.path.splitext(filename)[1]\n if ext != '.flo':\n quit('extension .flo expected')\n\n with open(filename, 'rb') as f:\n tag = np.fromfile(f, np.float32, count=1)[0]\n if tag != TAG_FLOAT:\n quit('invalid .flo file')\n width = np.fromfile(f, np.int32, 1)[0]\n height = np.fromfile(f, np.int32, 1)[0]\n\n data = np.fromfile(f, np.float32, count=2*width*height)\n flow = np.resize(data, (height, width, 2))\n\n return flow\n\n\ndef create_next_mask(mask, flow, obj_ids=[1]):\n '''\n Create mask from flow\n mask: (h, w) -> mask[x, y] = k -> have object k as pixel x, y\n flow: (h, w, 2)\n obj_ids: List of object id to move\n '''\n if isinstance(obj_ids, int):\n obj_ids = [obj_ids]\n print(flow.shape)\n new_mask = np.zeros_like(mask)\n for obj_id in obj_ids:\n mask_index = np.where(mask == obj_id)\n mask_index = np.array(mask_index).transpose()\n for ind in mask_index:\n new_ind = [0, 0]\n new_ind[0] = flow[ind[0], ind[1], 1] + ind[0]\n new_ind[1] = flow[ind[0], ind[1], 0] + ind[1]\n new_mask[int(new_ind[0]), int(new_ind[1])] = obj_id\n return new_mask\n\n\ndef get_bbox_from_mask(mask):\n '''\n Get bounding from mask\n Mask: Binary - only 0 or 1\n\n '''\n mask_index = np.where(mask > 0 )\n print(mask_index)\n left, right = min(mask_index[0]), max(mask_index[0])\n top, bottom = min(mask_index[1]), max(mask_index[1])\n\n height = bottom - top\n width = right - left\n return (float(top), float(left), float(height), float(width))\n\n\ndef dilate(mask, kernel_size, iterations):\n if isinstance(kernel_size, int):\n kernel_size = (kernel_size, kernel_size)\n\n kernel = np.ones(kernel_size)\n dilation = cv2.dilate(mask,kernel,iterations = 1)\n return dilation\n\ndef gaussian_blur(mask, kernel_size):\n if isinstance(kernel_size, int):\n kernel_size = (kernel_size, kernel_size)\n #kernel = cv2.getGaussianKernel(5, 0.1)\n #print(kernel)\n blur = cv2.GaussianBlur(mask, kernel_size, 0)\n print((np.floor(blur) == blur).sum() - (blur.shape[0] * blur.shape[1]))\n return blur\n\nif __name__ == '__main__':\n flow = read_flow('00000.flo')\n mask_pil = Image.open('00000.png')\n print(np.array(mask_pil).shape)\n old_mask = np.array(mask_pil)[:, :]\n print('Old mask')\n #plt.imshow(old_mask)\n #plt.show()\n new_mask = create_next_mask(old_mask, flow, obj_ids=[1, 2, 3])\n new_mask = np.array(new_mask, dtype=np.float64)\n new_mask_d = dilate(new_mask, 20, 1)\n #new_mask_g = new_mask_d\n new_mask_g = gaussian_blur(new_mask_d, 11)\n\n np_frame1 = np.array(Image.open('00001.jpg'), dtype=np.float64)\n\n for i in range(3):\n np_frame1[:, :, i] *= new_mask_g\n\n np_frame1 = np.array(np_frame1, dtype=np.int32)\n cv2.imwrite('00001.jpg', np_frame1[:, :, (2, 1, 0)])\n import json\n bbox = get_bbox_from_mask(new_mask_g)\n temp = [{'bbox':bbox, 'score':1.0}]\n json.dump(temp, open('00001.json', 'w'))","sub_path":"preprocessing/intermediate/flow_mask_gen.py","file_name":"flow_mask_gen.py","file_ext":"py","file_size_in_byte":3627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"160871393","text":"#!/usr/bin/env python3\n\"\"\"\nScript to run additional QC step in ENCODE rna-seq-pipeline\n\"\"\"\n\n__author__ = 'Otto Jolanki'\n__version__ = '0.1.0'\n__license__ = 'MIT'\n\nimport argparse\nimport json\nimport logging\nimport pysam\nfrom bisect import insort\nfrom collections import OrderedDict\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\nfilehandler = logging.FileHandler('rna_qc.log')\nfilehandler.setLevel(logging.DEBUG)\nconsolehandler = logging.StreamHandler()\nconsolehandler.setLevel(logging.INFO)\nformatter = logging.Formatter(\n '%(asctime)s | %(levelname)s | %(name)s: %(message)s')\nfilehandler.setFormatter(formatter)\nconsolehandler.setFormatter(formatter)\nlogger.addHandler(consolehandler)\nlogger.addHandler(filehandler)\n\n\nclass QCMetric(object):\n \"\"\"Container that holds the qc metric as OrderedDict (sorted by keys of\n the input dict) and the \"master\" key (name) of the said qc metric. Can be\n instantiated from a regular dict.\n \"\"\"\n\n def __init__(self, qc_metric_name, qc_metric_dict):\n if not isinstance(qc_metric_dict, dict):\n raise TypeError('QCMetric data must be a dict.')\n self._name = qc_metric_name\n self._content = OrderedDict(\n sorted(qc_metric_dict.items(), key=lambda x: x[0]))\n\n @property\n def content(self):\n return self._content\n\n @property\n def name(self):\n return self._name\n\n def __lt__(self, other):\n return self.name < other.name\n\n def __eq__(self, other):\n return self.name == other.name\n\n def __repr__(self):\n return 'QCMetric(%r, %r)' % (self.name, self.content)\n\n\nclass QCMetricRecord(object):\n \"\"\"Container that holds QCMetrics in sorted order.\n\n Attributes:\n metrics: list of metrics, kept sorted by the name of metrics\n \"\"\"\n\n def __init__(self, metrics=None):\n if metrics is None:\n self._metrics = []\n else:\n # names must be unique\n names = [metric.name for metric in metrics]\n assert len(names) == len(\n set(names)), 'Names of metrics have to be unique'\n metrics.sort()\n self._metrics = metrics\n\n @property\n def metrics(self):\n return self._metrics\n\n def add(self, qc_metric):\n \"\"\"Adds qc metric to the metrics, keeping it sorted by name.\n\n Args:\n qc_metric: QCMetric\n\n Returns: None\n\n Raises: AssertionError if a metric with same name is already in record\n \"\"\"\n\n assert qc_metric not in self._metrics, 'Metric with name {} already in record'.format(\n qc_metric.name)\n insort(self._metrics, qc_metric)\n\n def to_ordered_dict(self):\n \"\"\"Returns an OrderedDict with the contents.\n\n Returns: Ordered dict with structure as follows:\n - Ordered as the metrics is\n - Contents, assuming metrics = [qc1, qc2, qc3]:\n {\n qc1.name : qc1.content,\n qc2.name : qc2.content,\n qc3.name : qc3.content\n }\n \"\"\"\n result = OrderedDict()\n for metric in self.metrics:\n result.update({metric.name: metric.content})\n return result\n\n def __len__(self):\n \"\"\"\n Delegated to metrics.\n \"\"\"\n return len(self.metrics)\n\n def __iter__(self):\n \"\"\"\n Iterating QCMetricRecord is iterating over metrics.\n \"\"\"\n return iter(self.metrics)\n\n def __repr__(self):\n \"\"\"\n Like __iter__, __repr__ is delegated to metrics.\n \"\"\"\n return self.metrics.__repr__()\n\n\ndef read_dict_from_tsv(path_to_tsv):\n \"\"\"Reads tab separated file with two columns into a dict.\n\n Args:\n path_to_tsv: filepath that contains the tsv with two columns.\n\n Returns:\n result: dict with key value pairs so that the first item in a row is\n the key, and the second item is the value.\n\n Raises:\n AssertionError if a line in input does not have exactly two columns.\n \"\"\"\n\n result = {}\n with open(path_to_tsv, 'rt') as f:\n for line in f:\n line_split = line.split()\n try:\n assert len(line_split) == 2, 'Malformed line: {}'.format(line)\n except AssertionError:\n logger.exception('Malformed line %s', line)\n raise\n result.update({line_split[0]: line_split[1]})\n return result\n\n\ndef get_gene_type_counts(tr_to_gene_type_map, bampath):\n \"\"\"Counts reads by gene type from transcriptome alignment .bam file.\n\n Args:\n tr_to_gene_type_map: dict that maps transcript ids to gene types\n bampath: file path to transcriptome alignment .bam\n\n Returns:\n reads_by_gene_type: dict with counts of reads by gene type\n\n Raises:\n KeyError if transcript id (read.reference_name) that is in the .bam\n is not found in the tr_to_gene_type_map. The intended use of this\n function is to use the mapping generated from the same annotation\n that was used to build the bam, so this is an indication of mismatched\n inputs.\n \"\"\"\n bamfile = pysam.AlignmentFile(bampath, 'rb')\n reads_by_gene_type = {key: 0 for key in set(tr_to_gene_type_map.values())}\n reads_by_gene_type.update({'transcript_id_not_found': 0})\n for read in bamfile.fetch(until_eof=True):\n if read.is_secondary or read.is_unmapped or read.is_qcfail or read.is_duplicate:\n continue\n else:\n try:\n reference_name = read.reference_name\n gene_type = tr_to_gene_type_map[reference_name]\n reads_by_gene_type[gene_type] += 1\n except KeyError:\n logger.exception('Transcript ID %s not found in mapping!',\n read.reference_name)\n reads_by_gene_type['transcript_id_not_found'] += 1\n return reads_by_gene_type\n\n\ndef main(args):\n qc_record = QCMetricRecord()\n logger.info('Reading transcript id to gene type mapping from %s',\n args.tr_id_to_gene_type_tsv)\n tr_to_gene_type_map = read_dict_from_tsv(args.tr_id_to_gene_type_tsv)\n logger.info('Calculating gene type counts for bam %s', args.input_bam)\n gene_type_counts = get_gene_type_counts(tr_to_gene_type_map,\n args.input_bam)\n gene_type_counts = QCMetric('gene_type_count', gene_type_counts)\n qc_record.add(gene_type_counts)\n logger.info('Writing QC output into %s', args.output_filename)\n with open(args.output_filename, 'wt') as fp:\n json.dump(qc_record.to_ordered_dict(), fp)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\n '--input_bam', type=str, help='path to transcriptome bam')\n parser.add_argument(\n '--tr_id_to_gene_type_tsv',\n type=str,\n help='path to transcript id to gene type tsv')\n parser.add_argument('--output_filename', type=str)\n args = parser.parse_args()\n main(args)\n","sub_path":"src/rna_qc.py","file_name":"rna_qc.py","file_ext":"py","file_size_in_byte":7049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"284082942","text":"import copy\n\nimport rdomhelper.host0\nimport rdomhelper.server\nimport rdomhelper.ssh\nimport rdomhelper.undercloud\n\nimport pytest\n\n\nclass FakeSshClient(rdomhelper.ssh.SshClient):\n expectation = []\n\n def __init__(self, hostname, user, key_filename, via_ip):\n class Client(object):\n def close(self):\n pass\n self.hostname = hostname\n self._environment_filenames = []\n self._client = Client()\n self.description = 'not started yet'\n\n def load_private_key(self, f):\n pass\n\n def start(self):\n pass\n\n def run(self, cmd, **kwargs):\n kwargs['cmd'] = self._prepare_cmd(cmd, sudo=kwargs.get('sudo', False))\n assert FakeSshClient.expectation\n current_expection = FakeSshClient.expectation.pop(0)\n assert current_expection['func'] == 'run'\n\n # We do not make mandatory to declare in the expectation all the\n # parameters\n ignore_parameters = (\n 'sudo',\n 'retry',\n 'custom_log',\n 'success_status',\n 'error_callback',\n 'ignore_error')\n kwargs_to_compare = {}\n for k, v in kwargs.items():\n if k not in ignore_parameters:\n kwargs_to_compare[k] = v\n assert current_expection['args'] == kwargs_to_compare\n\n cmd_output, exit_status = current_expection.get('res', ('', 0))\n return self._evaluate_run_result(\n exit_status,\n cmd_output,\n kwargs.get('ignore_error'),\n kwargs.get('success_status', (0,)),\n kwargs.get('error_callback'))\n\n def create_file(self, path, content, mode='w'):\n kwargs = {}\n kwargs['path'] = path\n kwargs['content'] = content\n if mode != 'w':\n kwargs['mode'] = mode\n assert FakeSshClient.expectation\n current_expection = FakeSshClient.expectation.pop(0)\n assert current_expection['func'] == 'create_file'\n assert current_expection['args'] == kwargs\n\n\n@pytest.fixture(scope='function')\ndef fake_sshclient(monkeypatch, request):\n FakeSshClient.expectation = copy.deepcopy(request.param)\n monkeypatch.setattr('rdomhelper.ssh.SshClient', FakeSshClient)\n\n def fin():\n msg = 'Some expectations remain unevaluated: %s' % FakeSshClient.expectation\n assert not FakeSshClient.expectation, msg\n request.addfinalizer(fin)\n\n\n@pytest.fixture\ndef server_without_root_enabled(fake_sshclient):\n s = rdomhelper.server.Server(hostname='toto')\n return s\n\n\n@pytest.fixture\ndef server(server_without_root_enabled):\n s = rdomhelper.server.Server(hostname='toto')\n s._root_user_enabled = True\n ssh = FakeSshClient(None, None, None, None)\n s._ssh_pool.add_ssh_client('stack', ssh)\n s._ssh_pool.add_ssh_client('root', ssh)\n return s\n\n\n@pytest.fixture\ndef undercloud(fake_sshclient):\n s = rdomhelper.undercloud.Undercloud(hostname='toto')\n s._root_user_enabled = True\n ssh = FakeSshClient(None, None, None, None)\n s._ssh_pool.add_ssh_client('stack', ssh)\n s._ssh_pool.add_ssh_client('root', ssh)\n return s\n\n\n@pytest.fixture\ndef host0(fake_sshclient):\n s = rdomhelper.host0.Host0(hostname='toto')\n s._root_user_enabled = True\n ssh = FakeSshClient(None, None, None, None)\n s._ssh_pool.add_ssh_client('stack', ssh)\n s._ssh_pool.add_ssh_client('root', ssh)\n return s\n","sub_path":"rdomhelper/tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":3410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"15490246","text":"import pandas as pd\nimport os\nimport argparse\nimport numpy as np\nimport tqdm\n\nparser = argparse.ArgumentParser()\nparser.add_argument('-d', '--dataset', required=True, help='upx directory')\nparser.add_argument('-c', '--csv', required=True, help='upx label')\nparser.add_argument('-o', '--output', default='upx.csv', help='output name')\nargs = parser.parse_args()\n\nif not os.path.exists(args.dataset):\n\tparser.error(\"{} does not exists\".format(args.dataset))\nif not os.path.exists(args.csv):\n\tparser.error(\"{} does not exists\".format(args.csv))\n\nlabel = pd.read_csv(args.csv, names=['hash', 'y'])\nnames = []\ny = []\n\n#get directory names\nfor name in tqdm.tqdm(os.listdir(args.dataset)):\n\tpath = os.path.join(args.dataset, name)\n\tnames.append(path)\n\ty.append(label[label.hash==name].values[0][1])\t\n\nnp_names = np.array(names)\nnp_y = np.array(y)\n\ndata = pd.DataFrame({'hash': np_names, 'y': np_y})\ndata.to_csv(args.output, header=None, index=False)\n","sub_path":"utils/create_upxlist.py","file_name":"create_upxlist.py","file_ext":"py","file_size_in_byte":943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"322777877","text":"\"\"\"\n Following class is responsible for Image data extraction.\n Prior executing this class you will have to extract the CrisisMMD dataset on the same directory level\n as of this class.\n CrisisMMD dataset can be downloaded from : https://crisisnlp.qcri.org/data/crisismmd/CrisisMMD_v2.0.tar.gz\n\"\"\"\nimport os\nimport os.path\nimport pandas as pd\nimport shutil\nfrom shutil import copy\nimport numpy as np\nfrom PIL import Image as im\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img\n\n# CONSTANTS\nROOT = 'CrisisMMD_v2.0/'\nINFORMATIVE = 'Informative'\nNON_INFORMATIVE = 'Non-Informative/'\nTRAINING = 'Training_data/'\nTESTING = 'Testing_data/'\nTRAINING_INFORMATIVE = TRAINING + INFORMATIVE\nTRAINING_NON_INFORMATIVE = TRAINING + NON_INFORMATIVE\nTESTING_INFORMATIVE = TESTING + INFORMATIVE\nTESTING_NON_INFORMATIVE = TESTING + NON_INFORMATIVE\nFIRE = INFORMATIVE + '/Fire'\nFLOODS = INFORMATIVE + '/Floods'\nEARTH = INFORMATIVE + '/Earthquake'\nHURR = INFORMATIVE + '/Hurricane'\nDONT_KNOW = '/dont-know-cant-judge'\nLITTLE = '/little-or-no'\nMILD = '/mild'\nNAN = '/nan'\nSEVERE = '/severe'\nCATEGORIES_DICT = {\n 'Fire': FIRE,\n 'Earth-Q': EARTH,\n 'Floods': FLOODS,\n 'Hurricane': HURR\n}\nANNOTATIONS = {\n 'Fire': ['CrisisMMD_v2.0/annotations/california_wildfires_final_data.tsv'],\n 'Earth-Q': ['CrisisMMD_v2.0/annotations/iraq_iran_earthquake_final_data.tsv',\n 'CrisisMMD_v2.0/annotations/mexico_earthquake_final_data.tsv'],\n 'Floods': ['CrisisMMD_v2.0/annotations/srilanka_floods_final_data.tsv'],\n 'Hurricane': ['CrisisMMD_v2.0/annotations/hurricane_harvey_final_data.tsv',\n 'CrisisMMD_v2.0/annotations/hurricane_irma_final_data.tsv',\n 'CrisisMMD_v2.0/annotations/hurricane_maria_final_data.tsv']\n}\n\n\ndef info_sep(category, df_informative):\n \"\"\"\n Extracting the Informative Images to the specified category/class of the disaster severity\n :param category: category/class of disaster\n :param df_informative: Informative records.\n :return: None\n \"\"\"\n for index, row in df_informative.iterrows():\n src = ROOT + row['image_path']\n if row['image_damage'] == 'severe_damage':\n dest = CATEGORIES_DICT[category] + SEVERE\n copy(src, dest)\n elif row['image_damage'] == 'mild_damage':\n dest = CATEGORIES_DICT[category] + MILD\n copy(src, dest)\n elif row['image_damage'] == 'dont_know_or_cant_judge':\n dest = CATEGORIES_DICT[category] + DONT_KNOW\n copy(src, dest)\n elif row['image_damage'] == 'little_or_no_damage':\n dest = CATEGORIES_DICT[category] + LITTLE\n copy(src, dest)\n else:\n dest = CATEGORIES_DICT[category] + NAN\n copy(src, dest)\n\n\ndef augment_images(files):\n datagen = ImageDataGenerator(rotation_range=40,\n width_shift_range=0.2,\n height_shift_range=0.2,\n shear_range=0.2,\n zoom_range=0.2,\n horizontal_flip=True,\n fill_mode='nearest')\n for file in files:\n img_path = ROOT + file\n if os.path.exists(img_path):\n image = np.expand_dims(np.array(im.open(img_path), dtype='float32'), 0)\n save_to = TRAINING_NON_INFORMATIVE\n datagen.fit(image)\n for x, val in zip(datagen.flow(image, # image we chose\n save_to_dir=save_to, # this is where we figure out where to save\n save_prefix='aug',\n save_format='png'), range(1)):\n pass\n\n\ndef non_info_sep(df_noninfo):\n \"\"\"\n extract the Non-Informative Images\n :param df_noninfo: Non-Informative records\n :return: None\n \"\"\"\n for index, row in df_noninfo.iterrows():\n src = ROOT + row['image_path']\n copy(src, NON_INFORMATIVE)\n\n\ndef create_severity_dirs(category):\n \"\"\"\n Creating severity directories for the specified category\n :param category: category/class of disaster\n :return: None\n \"\"\"\n os.mkdir(category + DONT_KNOW)\n os.mkdir(category + LITTLE)\n os.mkdir(category + MILD)\n os.mkdir(category + SEVERE)\n os.mkdir(category + NAN)\n\n\ndef create_directory_structure():\n \"\"\"\n Creating File structure which will be required to store the extracted images.\n :return: None\n \"\"\"\n if os.path.exists(INFORMATIVE) and os.path.isdir(INFORMATIVE):\n shutil.rmtree(INFORMATIVE)\n if os.path.exists(NON_INFORMATIVE) and os.path.isdir(NON_INFORMATIVE):\n shutil.rmtree(NON_INFORMATIVE)\n if os.path.exists(TRAINING) and os.path.isdir(TRAINING):\n shutil.rmtree(TRAINING)\n if os.path.exists(TESTING) and os.path.isdir(TESTING):\n shutil.rmtree(TESTING)\n os.mkdir(INFORMATIVE)\n os.mkdir(NON_INFORMATIVE)\n os.mkdir(TRAINING)\n os.mkdir(TESTING)\n\n os.mkdir(TRAINING_INFORMATIVE)\n os.mkdir(TRAINING_NON_INFORMATIVE)\n os.mkdir(TESTING_INFORMATIVE)\n os.mkdir(TESTING_NON_INFORMATIVE)\n\n for key, value in CATEGORIES_DICT.items():\n os.mkdir(value)\n create_severity_dirs(value)\n\n\ndef extract_images():\n \"\"\"\n Extract images from the dataset. Further divide them into classes and severity\n :return: None\n \"\"\"\n for key, values in ANNOTATIONS.items():\n print(key, '->', values)\n for value in values:\n df = pd.read_csv(value, sep='\\t', error_bad_lines=False)\n # Considering only those images which have text of tweet and image in the tweet marked as Informative.\n df_informative = df.loc[(df['image_info'] == 'informative') & (df['text_info'] == 'informative')]\n # Separation of Non-Informative Images\n df_noninfo = df.loc[(df['image_info'] == 'not_informative') & (df['text_info'] == 'not_informative')]\n info_sep(category=key, df_informative=df_informative)\n non_info_sep(df_noninfo)\n\n\ndef get_Info_Non_Info_tweets(mainDataFrame, dataframe):\n \"\"\"\n Method which will accept a dataframe and return all the informative and Non informative tweet images\n :param mainDataFrame: Main Dataset\n :param dataframe: Queried Dataset\n :return:\n \"\"\"\n res = mainDataFrame[mainDataFrame['tweet_id'].isin(dataframe['tweet_id'])]\n info_res = res.loc[(res['text_info'] == 'informative') & (res['image_info'] == 'informative')]\n non_res = res.loc[(res['text_info'] == 'not_informative') & (res['image_info'] == 'not_informative')]\n return info_res['image_path'].tolist(), non_res['image_path'].tolist()\n\n\ndef copy_images(fnames, destination):\n \"\"\"\n Method to copy the images to destination\n :param fnames: list of file names to be copied\n :param destination: path to destination folder\n :return:\n \"\"\"\n Images_not_found = 0\n for path in fnames:\n src = ROOT + path\n if os.path.exists(src):\n copy(src, destination)\n else:\n Images_not_found = Images_not_found + 1\n print(Images_not_found, \" Images not found for \", destination)\n\n\ndef create_dataset():\n \"\"\"\n Method to split the dataset into training and testing w.r.t\n Informative and Non-Informative category.\n :return: None\n \"\"\"\n # TODO: Code cleaning and modularity\n train = 'final_tweets/train_df.csv'\n val = 'final_tweets/validate_df.csv'\n test = 'final_tweets/test_df.csv'\n merged = 'CrisisMMD_v2.0/Merged.csv'\n merged_df = pd.read_csv(merged)\n\n drop_cols = ['text_info_conf', 'tweet_text']\n keep_cols = ['tweet_id', 'image_info', 'text_info', 'image_path']\n merged_df = merged_df[keep_cols]\n train_df = pd.read_csv(train)\n val_df = pd.read_csv(val)\n test_df = pd.read_csv(test)\n train_df = train_df.drop(drop_cols, axis=1)\n val_df = val_df.drop(drop_cols, axis=1)\n test_df = test_df.drop(drop_cols, axis=1)\n\n train_info, train_non_info = get_Info_Non_Info_tweets(merged_df, train_df)\n test_info, test_non_info = get_Info_Non_Info_tweets(merged_df, test_df)\n val_info, val_non_info = get_Info_Non_Info_tweets(merged_df, val_df)\n\n print('**********Training*************')\n print('Informative:', len(train_info) + len(val_info))\n print('Non-Informative:', len(train_non_info) + len(val_non_info))\n print('**********Testing*************')\n print('Informative:', len(test_info))\n print('Non-Informative:', len(test_non_info))\n\n copy_images(train_info, TRAINING_INFORMATIVE)\n copy_images(train_non_info, TRAINING_NON_INFORMATIVE)\n copy_images(val_info, TRAINING_INFORMATIVE)\n copy_images(val_non_info, TRAINING_NON_INFORMATIVE)\n copy_images(test_info, TESTING_INFORMATIVE)\n copy_images(test_non_info, TESTING_NON_INFORMATIVE)\n\n l = train_non_info[:1500] + val_non_info\n print(\"len of aug : \", len(l))\n augment_images(l)\n\n\nif __name__ == '__main__':\n try:\n create_directory_structure()\n extract_images() # Uncomment only if you want to extract images at Granular level.\n create_dataset()\n except FileNotFoundError:\n print(\"Please check if the CrisisMMD dataset has been extracted in the same directory structure level\")\n except Exception as e:\n print(\"Exception Occured::\\n\", e)\n","sub_path":"data/Image-Extraction.py","file_name":"Image-Extraction.py","file_ext":"py","file_size_in_byte":9400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"98909653","text":"import gym\nimport numpy as np\n\nfrom gym_battlesnake.envs import BattlesnakeEnv\nfrom gym_battlesnake.envs.state import State\n\n\nclass FrameStack(gym.Wrapper):\n def __init__(self, env: BattlesnakeEnv, num_stacked_frames: int):\n super().__init__(env)\n self.num_stacked_frames = num_stacked_frames\n self.observation_space = gym.spaces.Box(\n low=0,\n high=255,\n shape=(num_stacked_frames, env.width, env.height),\n dtype=np.uint8,\n )\n\n def reset(self):\n self.unwrapped.state = State(\n width=self.unwrapped.width,\n height=self.unwrapped.height,\n num_snakes=self.unwrapped.num_snakes,\n num_fruits=self.unwrapped.num_fruits,\n stacked_frames=self.num_stacked_frames,\n )\n return self.unwrapped.state.observe()\n\n def step(self, action: int):\n return self.env.step(action)\n","sub_path":"gym_battlesnake/wrappers/frame_stack.py","file_name":"frame_stack.py","file_ext":"py","file_size_in_byte":922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"527776063","text":"import numpy\nfrom numba import jit\nfrom scipy.stats import norm\n\n############################################################\n############################################################\n# Modified script from here\n# Importo l'integratore per la distribuzione cumulativa\nfrom scipy.integrate import quad\n\nK = 10\n\n# Precalcola la distribuzione. Gli estremi vanno sempre da zero\n# fino al parametro calcolato sui fogli (vedo cosetto di cartoncino)\nMAX_LM = K\nX_LM = numpy.arange(0, MAX_LM, 0.01)\n\n\n# Costruisco la distribuzione cumulativa\ndef LMDist(x):\n return 1 / (K + numpy.e**(-K) - 1) * (1 - numpy.e**(-x))\n\n\ndef LMCumDist(u):\n return quad(LMDist, 0, u)[0]\n\n\n# Trasformo nella versione vettorizzata\nvectLMCumDist = numpy.vectorize(LMCumDist)\n\n# Calcolo sui valori tabulati\nLM_VALUES = vectLMCumDist(X_LM)\nLM_VALUES = numpy.append(LM_VALUES, 1)\n\n# Introduco le liste per indentificare cosa è magnitudine limite. Per info vedi il file corrispondente\n# In questa versione le magnitudini limite NON servono: per l'ordine vedi il vecchio script\n\nprint(\"K Value: {}\".format(K))\nprint(\"Using the new module\")\n\n# Original script starts here\ncache = True\n\n############################################################\n############################################################\n############ Propogate Probabilities functions ############\n############################################################\n############################################################\n\n# Parametri gaussiana, per tutto il resto. Infittisco un poco la\n# griglia, in questo momento mi pare troppo lassa\nN_SIGMA = 3\nX_GAUS = numpy.arange(-N_SIGMA, N_SIGMA, 0.01)\nGAUS = numpy.array(norm(0, 1).cdf(X_GAUS))\nGAUS = numpy.append(GAUS, 1)\n\n\n@jit(cache=cache, nopython=True)\ndef split_probability(value, delta, flag, threshold):\n \"\"\"\n Calculate split probability for a single object\n \"\"\"\n # flag != 0 -> upper limit (carries info for turnover)\n\n if numpy.isnan(value):\n return numpy.nan\n\n if int(round(flag)) == 0 and not numpy.isnan(delta) and delta != 0:\n normalized_threshold = (threshold - value) / delta\n if normalized_threshold <= -N_SIGMA:\n split_proba = 0\n elif normalized_threshold >= N_SIGMA:\n split_proba = 1\n else:\n x = numpy.searchsorted(\n a=X_GAUS,\n v=normalized_threshold,\n )\n split_proba = GAUS[x]\n elif int(round(flag)) != 0 and not numpy.isnan(delta) and delta != 0:\n normalized_threshold = (threshold - flag) / delta\n if normalized_threshold <= 0:\n split_proba = 0\n elif normalized_threshold >= MAX_LM:\n split_proba = 1\n else:\n x = numpy.searchsorted(\n a=X_LM,\n v=normalized_threshold,\n )\n split_proba = LM_VALUES[x]\n else:\n if (threshold - value) >= 0:\n split_proba = 1\n elif (threshold - value) < 0:\n split_proba = 0\n\n return 1 - split_proba\n\n\n@jit(cache=cache, nopython=True)\ndef split_probability_all(values, deltas, flags, threshold):\n \"\"\"\n Calculate split probabilities for all rows in values\n \"\"\"\n\n nof_objcts = values.shape[0]\n ps = [\n split_probability(values[i], deltas[i], flags[i], threshold)\n for i in range(nof_objcts)\n ]\n ps = numpy.array(ps)\n\n return ps\n\n\n@jit(cache=cache, nopython=True)\ndef return_class_probas(pnode, pY):\n \"\"\"\n The leaf probabilities for each class\n \"\"\"\n\n nof_objects = pY.shape[0]\n nof_classes = pY.shape[1]\n class_probas = numpy.zeros(nof_classes)\n\n for i in range(nof_objects):\n class_probas += pnode[i] * pY[i, :]\n\n # class_probas = class_probas/numpy.sum(pnode)\n class_probas = class_probas / len(pnode)\n # class_probas = pY\n\n return class_probas\n\n\n############################################################\n############################################################\n############################ MISC #########################\n############################################################\n############################################################\n\n\n@jit(cache=True, nopython=True)\ndef get_split_objects(pnode, p_split_right, p_split_left, is_max,\n n_objects_node, keep_proba):\n\n pnode_right = pnode * p_split_right\n pnode_left = pnode * p_split_left\n\n pnode_right_tot = numpy.nansum(pnode_right)\n pnode_left_tot = numpy.nansum(pnode_left)\n pnode_tot = pnode_right_tot + pnode_left_tot\n\n is_nan = numpy.isnan(p_split_right)\n\n p_split_right_batch = pnode_right_tot / pnode_tot\n p_split_right[is_nan] = p_split_right_batch\n pnode_right[is_nan] = pnode[is_nan] * p_split_right[is_nan]\n\n p_split_left_batch = pnode_left_tot / pnode_tot\n p_split_left[is_nan] = p_split_left_batch\n pnode_left[is_nan] = pnode[is_nan] * p_split_left[is_nan]\n\n best_right = [0]\n best_left = [0]\n\n is_max_right = [0]\n is_max_left = [0]\n\n for i in range(n_objects_node):\n # if is_nan[i]:\n # best_right.append(i)\n # best_left.append(i)\n # if (is_max[i] == 1):\n # if (p_split_right_batch > p_split_left_batch):\n # is_max_right.append(1)\n # is_max_left.append(0)\n # else:\n # is_max_right.append(0)\n # is_max_left.append(1)\n # else:\n if (p_split_right[i] >= 0.5 and is_max[i] == 1):\n best_right.append(i)\n is_max_right.append(1)\n elif pnode_right[i] > keep_proba:\n best_right.append(i)\n is_max_right.append(0)\n\n if (p_split_left[i] > 0.5 and is_max[i] == 1):\n best_left.append(i)\n is_max_left.append(1)\n elif pnode_left[i] > keep_proba:\n best_left.append(i)\n is_max_left.append(0)\n\n best_right = numpy.array(best_right)\n best_left = numpy.array(best_left)\n is_max_right = numpy.array(is_max_right)\n is_max_left = numpy.array(is_max_left)\n\n pnode_right, _ = pull_values(pnode_right, best_right[1:], best_left[1:])\n _, pnode_left = pull_values(pnode_left, best_right[1:], best_left[1:])\n\n return (\n pnode_right,\n pnode_left,\n best_right[1:],\n best_left[1:],\n is_max_right[1:],\n is_max_left[1:],\n p_split_right_batch,\n )\n\n\n#@jit(cache=True, nopython=True)\ndef choose_features(nof_features, max_features):\n \"\"\"\n function randomly selects the features that will be examined for each split\n \"\"\"\n features_indices = numpy.arange(nof_features)\n #numpy.random.seed()\n #features_chosen = numpy.random.choice(features_indices, size=max_features, replace = True)\n features_chosen = numpy.random.choice(features_indices,\n size=nof_features,\n replace=False)\n\n #print(features_chosen)\n return features_chosen\n\n\n@jit(cache=True, nopython=True)\ndef pull_values(A, right, left):\n \"\"\"\n Splits an array A to two\n according to lists of indicies\n given in right and left\n \"\"\"\n A_left = A[left]\n A_right = A[right]\n\n return A_right, A_left\n\n\ndef get_pY(pY_true, y_fake):\n \"\"\"\n Recieves a vector with the probability to be true (pY_true)\n returns a matrix with the probability to be in each class\n\n we put pY_true as the probability of the true class\n and (1-pY_true)/(nof_lables-1) for all other classes\n \"\"\"\n nof_objects = len(pY_true)\n\n all_labels = numpy.unique(y_fake)\n label_dict = {i: a for i, a in enumerate(all_labels)}\n nof_labels = len(all_labels)\n\n pY = numpy.zeros([nof_objects, nof_labels])\n\n for o in range(nof_objects):\n for c_idx, c in enumerate(all_labels):\n if y_fake[o] == c:\n pY[o, c_idx] = pY_true[o]\n else:\n pY[o, c_idx] = float(1 - pY_true[o]) / (nof_labels - 1)\n\n return pY, label_dict\n","sub_path":"PRF/misc_functions.py","file_name":"misc_functions.py","file_ext":"py","file_size_in_byte":8003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"129286023","text":"import re\nfrom bs4 import BeautifulSoup\nimport os\nimport pickle\nimport sys\n\ndirectory = \"./Data/Dataset/\"\nfiles = os.listdir(directory)\ndict_corpus = {}\n\nmonths = [\"January\",\"February\",\"March\",\"April\",\"May\",\"June\",\"July\",\"August\",\"September\",\"October\",\"November\",\"December\",\"\"]\n\n\ndef create_dictionary(filename):\n\n with open(filename,'r') as f:\n html_doc = f.read()\n soup = BeautifulSoup(html_doc,'html.parser')\n\n p_list = soup.find_all('p')\n date,idx = get_date(p_list)\n p_list = p_list[idx:]\n participants,idx = get_participants(p_list)\n p_list = p_list[idx:]\n presentation,idx = get_presentation_dictionary(p_list)\n p_list = p_list[idx:]\n questionnaire = get_questionnaire_dictionary(p_list)\n\n transcript = {\"Date\":date,\"Participants\":participants,\"Presentation\":presentation,\"Questionnaire\":questionnaire}\n return transcript\n\n\ndef get_date(p_list):\n regex = r\"\\s*\\d{1,2},{0,1}\\s*\\d{4}|\".join(months)[:-1]\n idx = 0\n for para in p_list:\n if para.text==\"Company Participants\":\n break\n idx+=1\n match = re.findall(regex,para.text)\n if len(match)!=0:\n break\n return match[0],idx\n\ndef get_participants(p_list):\n\n participants=[]\n count = 0\n idx = -1\n for para in p_list:\n if count==3: \n break\n idx+=1\n if para.strong!=None:\n count+=1\n continue\n name = para.text\n participants.append(name)\n \n return participants,idx\n\ndef get_presentation_dictionary(p_list):\n presentation = {}\n name = \"\"\n value = \"\"\n idx = -1\n for para in p_list:\n idx +=1\n if para.strong!=None:\n if name not in presentation.keys():\n presentation[name] = []\n presentation[name].append(value)\n if para.has_attr('id') and para['id']==\"question-answer-session\":\n break\n name = para.text\n value = \"\"\n continue\n value += para.text+\" \"\n\n presentation.pop(\"\")\n return presentation,idx\n\ndef get_questionnaire_dictionary(p_list):\n questionnaire = {}\n serial = 0\n name = \"\"\n statement = \"\"\n for para in p_list[1:]:\n if para.strong!=None:\n questionnaire[serial]={\"Speaker\":name,\"Remark\":statement}\n serial+=1\n name = para.text.split(\" - \")[-1]\n statement = \"\"\n continue\n statement += para.text+\" \"\n\n questionnaire[serial]={\"Speaker\":name,\"Remark\":statement}\n questionnaire.pop(0)\n return questionnaire\n\n\"\"\"def print_dictionary(transcript):\n print(\"Date: {}\".format(transcript['Date']))\n print(\"Participants: \",transcript[\"Participants\"])\n print(\"\\nPresentation\\n\")\n for presenter,statements in transcript[\"Presentation\"].items():\n print(\"{} :\".format(presenter))\n for statement in statements:\n print(statement)\n print(\"\\n\")\n print(\"\\nQuestion-Answer :{}\\n\".format(len(transcript[\"Questionnaire\"])))\n for key,value in transcript[\"Questionnaire\"].items():\n print(\"{} :\".format(value[\"Speaker\"]))\n print(value[\"Remark\"])\n print(\"\\n\")\"\"\"\n\ndef build_text(dict_transcript):\n\n text = \"\"\n text += \"Date\"+\" \"+dict_transcript[\"Date\"]+\" \\n\"\n text += \"Participants \\n\"\n for participant in dict_transcript[\"Participants\"]:\n text+=participant+\" \\n\"\n text += \"Presentation \\n\"\n for presenter,statements in dict_transcript[\"Presentation\"].items():\n text += presenter+\" \\n\"\n for statement in statements:\n text += statement+\" \\n\"\n text += \"Questionnaire\"+\" \\n\"\n for serial,statement in dict_transcript[\"Questionnaire\"].items():\n text += str(serial)+\" \"+statement[\"Speaker\"]+\" \\n\"\n text += statement[\"Remark\"]+\" \\n\"\n\n return text\n\n\n\nif(not os.path.isdir(\"./ECTText/\")):\n os.mkdir(\"./ECTText/\")\n\ncount = 0\nfor filename in files:\n try:\n transcript = create_dictionary(directory+filename)\n except Exception as e:\n #print(filename)\n #print(e)\n continue\n docId = int(filename.split(\".\")[0])\n dict_corpus[docId] = transcript\n text = build_text(transcript)\n with open(\"./ECTText/\"+str(docId)+\".txt\",\"w\") as f:\n f.write(text)\n sys.stdout.write(\"\\r{0}/{1} files processed...,{2}>\".format(count+1,len(files),\"=\"*(count//100)))\n sys.stdout.flush()\n count+=1\n\nwith open(\"ECTNestedDict.pkl\",\"wb\") as f:\n pickle.dump(dict_corpus,f)","sub_path":"assignment_2/build_corpus.py","file_name":"build_corpus.py","file_ext":"py","file_size_in_byte":4489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"134666184","text":"# -*- coding:utf-8 -*-\r\n'''\r\nfunction:\r\nsave model and reload model\r\n'''\r\nimport numpy as np\r\nnp.random.seed(1337)\r\n\r\nfrom keras.models import Sequential\r\nfrom keras.layers import Dense\r\nfrom keras.models import load_model\r\n\r\n# Create some data\r\n# X是一个行向量 200个元素\r\nx=np.linspace(-1,1,200)\r\nprint(x)\r\nnp.random.shuffle(x)\r\ny=0.5*x+np.random.normal(0,0.05,(200,))\r\nx_train,y_train=x[:160],y[:160]\r\nx_test,y_test=x[160:],y[160:]\r\nmodel=Sequential()\r\nmodel.add(Dense(output_dim=1,input_dim=1))\r\nmodel.compile(loss='mse',optimizer='sgd')\r\nfor step in range(300):\r\n cost=model.train_on_batch(x_train,y_train)\r\n\r\n# save\r\nprint('test before save:',model.predict(x_test[:2]))\r\nmodel.save('my_model.h5')\r\ndel model\r\n\r\n# load\r\nmodel=load_model('my_model.h5')\r\nprint('test after save:',model.predict(x_test[:2]))\r\n\r\n# save and reload the weights\r\nmodel.save_weights('my_model_weights.h5')\r\nmodel.load_weights('my_model_weights.h5')\r\n\r\n# Save and load fresh network without trained weights\r\nfrom keras.models import model_from_json\r\njson_string=model.to_json()\r\nmodel=model_from_json(json_string)","sub_path":"save_reload.py","file_name":"save_reload.py","file_ext":"py","file_size_in_byte":1105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"596631380","text":"\"\"\"\nMask R-CNN\nConfigurations and data loading code for the synthetic Objects dataset.\nThis is a duplicate of the code in the noteobook train_objects.ipynb for easy\nimport into other notebooks, such as inspect_model.ipynb.\n\nCopyright (c) 2017 Matterport, Inc.\nLicensed under the MIT License (see LICENSE for details)\nWritten by Waleed Abdulla\n\"\"\"\n\nimport os, sys\nimport numpy as np\nfrom pycocotools.coco import COCO\n\n# Root directory of the project\nROOT_DIR = os.path.abspath(\"../..\")\nif ROOT_DIR not in sys.path:\n sys.path.insert(0, ROOT_DIR)\n\nfrom instance_segmentation.objects_config import ObjectsConfig\n\nfrom coco import CocoDataset\n\n\nConfig = ObjectsConfig\n\nclass Dataset(CocoDataset):\n \"\"\"Generates the objects synthetic dataset. The dataset consists of simple\n objects (triangles, squares, circles) placed randomly on a blank surface.\n The images are generated on the fly. No file access required.\n \"\"\"\n def load(self, dataset_dir, subset, class_ids=None):\n \"\"\"Load a subset of the COCO dataset.\n dataset_dir: The root directory of the COCO dataset.\n subset: What to load (train, val, minival, val35k)\n class_ids: If provided, only loads images that have the given classes.\n class_map: TODO: Not implemented yet. Supports maping classes from\n different datasets to the same class ID.\n return_coco: If True, returns the COCO object.\n \"\"\"\n # Path\n image_dir = os.path.join(dataset_dir, \"train2014\" if subset == \"train\" else \"val2014\")\n\n # Create COCO object\n json_path_dict = {\n \"train\": \"annotations/instances_train2014.json\",\n \"val\": \"annotations/instances_val2014.json\",\n \"minival\": \"annotations/instances_minival2014.json\",\n \"val35k\": \"annotations/instances_valminusminival2014.json\",\n }\n coco = COCO(os.path.join(dataset_dir, json_path_dict[subset]))\n\n # Load all classes or a subset?\n if not class_ids:\n # All classes\n class_ids = sorted(coco.getCatIds())\n\n # All images or a subset?\n if class_ids:\n image_ids = []\n for id in class_ids:\n image_ids.extend(list(coco.getImgIds(catIds=[id])))\n # Remove duplicates\n image_ids = list(set(image_ids))\n else:\n # All images\n image_ids = list(coco.imgs.keys())\n\n # Add classes\n self.add_class(\"objects\", 1, \"object\")\n\n # Add images\n for i in image_ids:\n self.add_image(\n \"objects\",\n image_id=i,\n path=os.path.join(image_dir, coco.imgs[i]['file_name']),\n width=coco.imgs[i][\"width\"],\n height=coco.imgs[i][\"height\"],\n annotations=coco.loadAnns(coco.getAnnIds(imgIds=[i], iscrowd=False)))\n\n def load_mask(self, image_id):\n \"\"\"Load instance masks for the given image.\n\n Different datasets use different ways to store masks. This\n function converts the different mask format to one format\n in the form of a bitmap [height, width, instances].\n\n Returns:\n masks: A bool array of shape [height, width, instance count] with\n one mask per instance.\n class_ids: a 1D array of class IDs of the instance masks.\n \"\"\"\n image_info = self.image_info[image_id]\n instance_masks = []\n class_ids = []\n annotations = self.image_info[image_id][\"annotations\"]\n # Build mask of shape [height, width, instance_count] and list\n # of class IDs that correspond to each channel of the mask.\n for annotation in annotations:\n class_id = self.map_source_class_id(\"objects.1\")\n if class_id:\n m = self.annToMask(annotation, image_info[\"height\"],\n image_info[\"width\"])\n # Some objects are so small that they're less than 1 pixel area\n # and end up rounded out. Skip those objects.\n if m.max() < 1:\n continue\n instance_masks.append(m)\n class_ids.append(self.class_names.index(\"object\"))\n\n # Pack instance masks into an array\n if class_ids:\n mask = np.stack(instance_masks, axis=2)\n class_ids = np.array(class_ids, dtype=np.int32)\n return mask, class_ids\n else:\n # Call super class to return an empty mask\n return super(self.__class__).load_mask(image_id)\n","sub_path":"instance_segmentation/Coco/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":4562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"464617539","text":"# Backtracking\n\nmaze = [[\"S\", \".\", \".\",\".\"],\n [\".\",\"x\",\"x\",\".\"],\n [\".\",\".\",\".\",\"x\"],\n [\"x\",\"x\",\".\",\"E\"]]\n\n\ndef print_maze(maze):\n for row in maze:\n row_print = \"\"\n for value in row:\n row_print += value + \" \"\n print(row_print)\n\n\n\ndef solve_maze(maze):\n if len(maze) < 1:\n return None\n if len(maze[0]) < 1:\n return None\n \n return solve_maze_helper(maze, [], 0, 0)\n\n\ndef solve_maze_helper(maze, solution, pos_row, pos_col):\n # Get the Size of the maze both rows and columns\n num_row = len(maze)\n num_col = len(maze[0])\n\n # Base cases \n\n # Robot is already home \n if pos_row == num_row - 1 and pos_col == num_col -1:\n return solution\n \n # Is the robot out of bounds?\n if pos_row >= num_row or pos_col >= num_col:\n return None\n \n # Is robuddy on an obstacle?\n if maze[pos_row][pos_col] == 'x':\n return None\n\n # Recursive case\n\n #Try going right\n solution.append(\"r\")\n solution_going_right = solve_maze_helper(maze,solution,pos_row, pos_col +1)\n if solution_going_right is not None:\n return solution_going_right\n \n # Going Right Doesn't Work, Backtrack\n solution.pop()\n solution.append(\"d\")\n solution_going_down = solve_maze_helper(maze,solution,pos_row +1, pos_col)\n if solution_going_down is not None:\n return solution_going_down\n \n # No solution, impossible, Backtrack\n solution.pop()\n return None\n\nprint_maze(maze)\nprint(solve_maze(maze))","sub_path":"PythonPuzzleSolvers/RobotPuzzle/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"275674922","text":"class SignalAndTarget(object):\n \"\"\"\n Simple data container class.\n\n Parameters\n ----------\n X: 3darray or list of 2darrays\n The input signal per trial.\n y: 1darray or list\n Labels for each trial.\n \"\"\"\n\n def __init__(self, X, y):\n assert len(X) == len(y)\n self.X = X\n self.y = y\n\n","sub_path":"braindecode/datautil/signal_target.py","file_name":"signal_target.py","file_ext":"py","file_size_in_byte":338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"223017519","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\nimport json\nimport functools\nimport config\nfrom backend.utils.response import BaseResponse\n\n\ndef auth_login_redirect(func):\n\n def inner(self, *args, **kwargs):\n if not self.session['is_login']:\n self.redirect(config.LOGIN_URL)\n return\n func(self, *args, **kwargs)\n return inner\n\n\ndef auth_login_json(func):\n\n def inner(self, *args, **kwargs):\n if not self.session['is_login']:\n rep = BaseResponse()\n rep.summary = \"auth failed\"\n self.write(json.dumps(rep.__dict__))\n return\n func(self, *args, **kwargs)\n return inner\n","sub_path":"chouti/backend/utils/decrator.py","file_name":"decrator.py","file_ext":"py","file_size_in_byte":668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"511626800","text":"from pytest_bdd import given, when, then\nfrom model.contact import Contact\nimport random\nimport re\n\n\n@given('a contact list')\ndef contact_list(db):\n return db.get_contact_list()\n\n\n@given('a new contact with , ,
, , , and ')\ndef new_contact(firstname, lastname, address, home, mobile, work, email):\n return Contact(firstname=firstname, lastname=lastname, address=address, home=home, mobile=mobile, work=work, email=email)\n\n\n@when('I add the contact to the list')\ndef add_new_contact(app, new_contact):\n app.contact.Create(new_contact)\n\n\n@then('the new contact list is equal to the old contact list with the added contact')\ndef verify_contact_added(db, contact_list, new_contact):\n old_contacts = contact_list\n new_contacts = db.get_contact_list()\n old_contacts.append(new_contact)\n assert sorted(old_contacts, key=Contact.id_or_max) == sorted(new_contacts, key=Contact.id_or_max)\n\n\n@given('a non-empty contact list')\ndef non_empty_contact_list(app, db):\n if len(db.get_contact_list()) == 0:\n app.contact.Create(Contact(firstname='firstname'))\n return db.get_contact_list()\n\n\n@given('a random contact from the list')\ndef random_contact(non_empty_contact_list):\n return random.choice(non_empty_contact_list)\n\n\n@when('I delete the contact from the list')\ndef delete_contact(app, random_contact):\n app.contact.delete_contact_by_id(random_contact.id)\n\n\n@then('the new contact list is equal to the old contact list without the deleted contact')\ndef verify_ccontact_deleted(app, db, check_ui, non_empty_contact_list, random_contact):\n old_contacts = non_empty_contact_list\n new_contacts = db.get_contact_list()\n assert len(old_contacts) - 1 == len(new_contacts)\n old_contacts.remove(random_contact)\n assert old_contacts == new_contacts\n if check_ui:\n assert sorted(new_contacts, key=Contact.id_or_max) == sorted(app.contact.get_contact_list(),\n key=Contact.id_or_max)\n\n\n@given('a new contact with parameters')\ndef new_data():\n contact = Contact(firstname='test_firstname', lastname='test_lastname', address='test_address')\n return contact\n\n\n@when('I update the contact from the list')\ndef update_contact(app, new_data, random_contact):\n new_data.id = random_contact.id\n print('gfd')\n return app.contact.Update_contact_by_id(new_data, random_contact.id)\n\n\n@then('the new contact list is equal to the old contact list with the modify contact')\ndef verify_contact_modify(app, db, check_ui, non_empty_contact_list, random_contact, new_data):\n old_contacts = non_empty_contact_list\n new_contacts = db.get_contact_list()\n assert len(old_contacts) == len(new_contacts)\n old_contacts.remove(random_contact)\n old_contacts.append(new_data)\n assert sorted(old_contacts, key=Contact.id_or_max) == sorted(new_contacts, key=Contact.id_or_max)\n if check_ui:\n assert sorted(new_contacts, key=Contact.id_or_max) == sorted(app.contact.get_contact_list(),\n key=Contact.id_or_max)\n\n","sub_path":"bdd/contact_steps.py","file_name":"contact_steps.py","file_ext":"py","file_size_in_byte":3156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"482271761","text":"import torch\nfrom torch import nn\nimport torch.nn.functional as F\nfrom torchvision import transforms\nfrom PIL import Image\n\nclass Action(torch.nn.Module):\n \n class conv_block(torch.nn.Module):\n def __init__(self, channel_in, channel_out, stride=2, kernel_size=3, dilation=2):\n super().__init__()\n self.c1 = nn.Conv2d(channel_in, channel_out, kernel_size=kernel_size, dilation=dilation, stride=stride, padding=kernel_size//2)\n self.b1 = nn.BatchNorm2d(channel_out)\n self.c2 = nn.Conv2d(channel_out, channel_out, kernel_size=kernel_size, dilation=dilation, stride=1, padding=kernel_size//2)\n self.b2 = nn.BatchNorm2d(channel_out)\n \n self.downsample = None\n if channel_in != channel_out or stride != 1:\n self.downsample = nn.Conv2d(channel_in, channel_out, kernel_size=1, stride=stride, dilation=dilation)\n \n def forward(self, x):\n self.activation = F.relu(self.b2(self.c2(self.b1(self.c1(x))))) #consider adding relus between\n identity = x\n if self.downsample != None:\n identity = self.downsample(identity)\n return self.activation + identity\n \n class upconv_block(torch.nn.Module):\n \n def __init__(self, channel_in, channel_out, stride=2, kernel_size=3, dilation=2): \n super().__init__()\n self.upsample = nn.ConvTranspose2d(channel_in, channel_out, kernel_size=kernel_size, stride=stride, padding=kernel_size//2, dilation=dilation, output_padding=1)\n \n def forward(self, x, output_pad=False):\n return F.relu(self.upsample(x))\n \n def __init__(self, layers=[32,32,64,64,128,128], normalize=True, inference=True):\n super().__init__()\n\n \"\"\"\n Your code here\n \"\"\"\n self.normalize = normalize\n self.inference = inference\n self.mean = torch.tensor([8.9478, 8.9478, 8.9478,0,0,0], dtype=torch.float) #TODO: Remove the 1s later when not concat\n self.std = torch.tensor([47.0021, 42.1596, 39.2562,1,1,1], dtype=torch.float) #TODO: Remove the 1s later when not concat\n\n c = 6 #Testing the combined heatmap \n self.network = torch.nn.ModuleList()\n for l in layers:\n kernel_size = 7 if c == 3 or c == 6 else 3\n stride = 1 if c == 3 or c == 6 else 2\n self.network.append(self.conv_block(c, l, stride, kernel_size, 1))\n c = l\n \n self.upnetwork = torch.nn.ModuleList()\n self.upnetwork.append(self.upconv_block(c, layers[-2]))\n c = layers[-2]\n for l in reversed(layers[:-2]):\n self.upnetwork.append(self.upconv_block(c * 2, l, 2, 3, 1)) # x2 input because of skip\n c = l\n self.classifier = torch.nn.Linear(c, 3) \n \n\n def forward(self, x):\n \"\"\"\n Your code here\n Predict the aim point in image coordinate, given the supertuxkart image\n @img: (B,3,96,128)\n return (B,2)\n \"\"\"\n\n if self.inference and False: #Teesting removal\n x = x.squeeze()\n # print('forward',x.shape)\n if len(x.shape) == 4:\n images = []\n for i in x:\n img = transforms.functional.to_pil_image(i)\n x = transforms.functional.to_tensor(transforms.Resize((100,130))(img))\n images.append(x)\n x = torch.cat(images)\n # print(x.shape)\n else:\n img = transforms.functional.to_pil_image(x)\n x = transforms.functional.to_tensor(transforms.Resize((100,130))(img))\n # print('forward', x.shape)\n if self.normalize:\n x = (x - self.mean[None, :, None, None].to(x.device)) / self.std[None, :, None, None].to(x.device)\n \n ##Add preprocessing\n activations = []\n for i, layer in enumerate(self.network):\n z = layer(x)\n activations.append(z)\n x = z\n z = self.upnetwork[0](x)\n for i, layer in enumerate(self.upnetwork[1:]):\n x = torch.cat([z[:,:, :activations[-2-i].size(2), :activations[-2-i].size(3)], activations[-2-i]], dim=1)\n z = layer(x)\n\n return self.classifier(z.mean([2,3]))\n\ndef save_model(model, name='action'):\n from torch import save\n from os import path\n if isinstance(model, Action):\n return save(model.state_dict(), path.join(path.dirname(path.abspath(__file__)), '{}.th'.format(name)))\n raise ValueError(\"model type '%s' not supported!\"%str(type(model)))\n\n\ndef load_model(name='action'):\n from torch import load\n from os import path\n r = Action()\n r.load_state_dict(load(path.join(path.dirname(path.abspath(__file__)), '{}.th'.format(name)), map_location='cpu'))\n return r\n\nif __name__ == '__main__':\n model = Action()","sub_path":"final/agent_policy_gradient/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":4949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"308735249","text":"\n# coding: utf-8\n\n#

Fundamentals of Data Science voor ons

\n# \n#

Assignment 1

\n# \n# **GOAL** In this notebook we are going to cover the following practical aspects of data science:\n# \n# - Reading a csv file and loading it to a dataframe in python using pandas library\n# - Filtering out the required columns in the dataframe\n# - Summarising data based on the fields. Ex: Summing up all the rows corresponding to a certain entry in the dataset\n# - Plot shape of United States using the geographic data i.e. data with all the coordinates\n# - Scale and move the states using data of the coordinates\n# - Colour the states based on the average age of their population\n\n# To complete this assignment you need to have a running Anaconda installation with Python 2.7 on your device. Python package prerequisites include:\n# + **Python Data Analysis Library** [Pandas](https://pandas.pydata.org/pandas-docs/stable/install.html) \n# + **GDAL - Geospatial Data Abstraction Library ** [GDAL](http://www.gdal.org/index.html) \n# \n# \n\n# **Pandas** is a Python package providing fast, flexible, and expressive data structures designed to make working with “relational” or “labeled” data both easy and intuitive. It aims to be the fundamental high-level building block for doing practical, real world data analysis in Python. Additionally, it has the broader goal of becoming the most powerful and flexible open source data analysis / manipulation tool available in any language. It is already well on its way toward this goal.\n# \n# Pandas is well suited for many different kinds of data:\n# \n# - Tabular data with heterogeneously-typed columns, as in an SQL table or Excel spreadsheet\n# - Ordered and unordered (not necessarily fixed-frequency) time series data.\n# - Arbitrary matrix data (homogeneously typed or heterogeneous) with row and column labels\n# - Any other form of observational / statistical data sets. The data actually need not be labeled at all to be placed into a pandas data structure\n# \n# The two primary data structures of pandas, Series (1-dimensional) and DataFrame (2-dimensional), handle the vast majority of typical use cases in finance, statistics, social science, and many areas of engineering. \n\n# In[2]:\n\n# Import all the libraries required\nimport os\nimport json\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport pprint as pp\nimport matplotlib.cm as cm\nfrom matplotlib.colors import rgb2hex\nfrom descartes import PolygonPatch\nfrom shapely.geometry import Polygon, MultiPolygon\n\n\n#

A look at the data

\n# Throughout this assignment, the dataset that we would be using will be the US population statistics 2010-2016. It can be downloaded from https://www2.census.gov/programs-surveys/popest/datasets/2010-2016/state/asrh/.\n\n# As a first step, we will structure the data into a pandas DataFrame to simplify the data manipulation. We will start by loading the csv file of data into a DataFrame called population_data and we will then filter columns based on our use. *Take a look at the data and its fields*\n\n# In[3]:\n\npopulation_data = pd.read_csv('pop_data/sc-est2016-agesex-civ.csv')\n\n\n# In[4]:\n\npopulation_data.shape\n\n\n# The complete dataset has 13,572 rows and 15 columns. It can be verified by looking at the shape of your dataframe by population_data.shape. To select specific columns, create a list of column names and view the dataframe as:\n\n# In[5]:\n\n# Filtering the data by the columns ['NAME','SEX','AGE','POPEST2016_CIV']\npopulation_data[['NAME','SEX','AGE','POPEST2016_CIV']]\n\n\n# In[6]:\n\n# Filters out data for all sexes and all age group and store in a new dataframe 'population_data_all'\n# 0 staat voor man en vrouw samen (dus niet apart gespecificeerd)\npopulation_data_all = population_data[population_data['SEX']==0]\n# Haalt alle values eruit waarvan een geldige leeftijd bekend is.\npopulation_data_all = population_data_all[population_data_all['AGE']!=999]\n\n\n# In[7]:\n\n# Sum the population of each state for each year on the dataset 'population_data_all'\npopulation_data_all.groupby(by=['NAME'], as_index=False)[['POPEST2010_CIV','POPEST2011_CIV','POPEST2012_CIV',\n 'POPEST2013_CIV','POPEST2014_CIV','POPEST2015_CIV','POPEST2016_CIV']].sum()\n\n\n#

Installations

\n# GDAL - Geospatial Data Abstraction Library
\n# http://www.gdal.org/index.html\n# \n# For example,\n# ** On Linux Fedora:** \n#
    yum install libpng \n# yum install libtiff \n# sudo dnf install gdal gdal-devel
    \n# \n# ** In Ubuntu:**\n#
      sudo add-apt-repository ppa:ubuntugis/ppa && sudo apt-get update \n# sudo apt-get install gdal-bin \n# To verify after installation, try: $ ogrinfo
      \n# If the installation was successful, you will see something like this:\n# \n# + Usage: ogrinfo [--help-general] [-ro] [-q] [-where restricted_where]\n# [-spat xmin ymin xmax ymax] [-fid fid]\n# [-sql statement] [-al] [-so] [-fields={YES/NO}]\n# [-geom={YES/NO/SUMMARY}][--formats]\n# datasource_name [layer [layer ...]]\n#
      \n# \n# \n\n# **In Windows:**\n# Refer to https://sandbox.idre.ucla.edu/sandbox/tutorials/installing-gdal-for-windows\n\n#

      Get a US states shapefile

      \n# Sources\n# - ArcGIS shapefile of US 50 states + DC (https://www.arcgis.com/home/item.html?id=f7f805eb65eb4ab787a0a3e1116ca7e5)\n#
        \n# Recommended – convert to GeoJSON \n# ( ogr2ogr -f GeoJSON [name1].geojson [name2].shp - where, 'name1' is the name of the downloaded geojson file and 'name2' is the name you want to specify for the shape file)\n\n# In[11]:\n\n#S_DIR is the directory in which your converted name2.shp file is located \n#S_DIR = 'US_shape/' \nS_DIR = 'shapefiles/'\nBLUE = '#5599ff'\nBLACK = '#000000'\n\nwith open(os.path.join(S_DIR, 'states.geojson')) as rf: \n data = json.load(rf)\n\nfig = plt.figure() \nax = fig.gca()\n\n\n# In[12]:\n\nfor feature in data['features']:\n geometry = feature['geometry']\n if geometry['type'] == 'Polygon':\n poly = geometry\n ax.add_patch(PolygonPatch(poly, fc=BLACK, ec=BLUE, alpha=0.5, zorder=2))\n else:\n for polygon in geometry['coordinates'][0]:\n poly = Polygon(polygon)\n ax.add_patch(PolygonPatch(poly, fc=BLACK, ec=BLUE, alpha=0.5, zorder=2))\n\nax.axis('scaled')\nplt.axis('off')\nplt.show()\n\n\n# **TASKS** \n#

        Improve the map

        \n# - Try a different projection (example: US Census Bureau shapefile)\n# - Scale and move Alaska \n# - Increase the size of Hawaii\n# - Color the map based on the average age of each state for the year 2016 \n# - Example: for average age between 65-70 years color the states in maroon, for 60-65 years in red and so on\n# \n# \n# Something else: Matplotlib Basemap Toolkit
        \n# Even more: GeoPandas \n\n# In[13]:\n\ndef get_alpha(average_age, min_age, max_age):\n \"\"\"\n Get an alpha value based on the age range.\n Inputs: average_age, min_age, max_age\n Outputs: floating point number between 0 and 1\n \"\"\"\n bottom = min_age\n upper = max_age\n \n alpha = float(average_age-min_age)/float((max_age-min_age))\n \n return alpha\n\ndef alphatohex(alpha): \n \"\"\"\n Converts a number between 0 and 1 to a interpolate of red and blue\n Inputs: alpha value between 0 and 1\n Outputs: color code (string)\n \"\"\"\n c1 = (0,0,255)\n c2 = (0,255,0)\n if alpha >= 0.5:\n b = 255\n g = int(255-round(510*(alpha-0.5)))\n if alpha <= 0.5:\n g = 255\n b = int(round(510*(alpha)))\n rgb = (0,g,b)\n return \"#\"+\"\".join(map(chr, rgb)).encode('hex')\n\n\n# \n#

        Assignment

        \n# \n# This assignment should result in a report in the format as mentioned in blackboard. \n# \n#

        The deadline for the assignment is **13-09-2017 23:59PM CEST. **

        \n# \n\n# In[14]:\n\n# Reproject function\n# Geometry contains all the coordinates that determine the states outline. Coordinates are stored as pairs that \n# represent locations. Sets of locations form polygon outlines, between which lines are drawn.\n# Some states consist out of more than one polygon, which are stored as mulitpolygons consisting out of polygon sets\n\ndef projection(coordinates, extra_latitude, extra_longitude, shape):\n # States consisting out of one polygon\n if shape == \"Polygon\":\n for j in range(len(coordinates)):\n a = coordinates[j]\n for i in range(len(a)):\n c = a[i]\n c[1] = c[1] + extra_longitude\n c[0] = c[0] + extra_latitude\n coordinates[j][i] = c\n else:\n # States consisting out of multiple polygons\n for i in range(len(coordinates)):\n c = coordinates[i]\n c[1] = c[1] + extra_longitude\n c[0] = c[0] + extra_latitude\n coordinates[i] = c\n\ndef move_state(state_name, extra_lat, extra_long):\n if geometry['type'] == 'Polygon':\n # States consisting out of one polygon\n poly = geometry\n poly2 = poly.copy()\n coordinates = poly['coordinates']\n projected_coordinates = projection(coordinates,extra_lat, extra_long, shape=\"Polygon\")\n poly2['coordinates'] = projected_coordinates \n ax.add_patch(PolygonPatch(poly2, fc=RED, alpha=gradient, zorder=2))\n \n else:\n # States consisting out of multiple polygons\n for polygon in geometry['coordinates'][0]:\n coordinates = polygon\n projected_coordinates = projection(coordinates,extra_lat, extra_long, shape=\"Multipolygonon\")\n poly = Polygon(projected_coordinates)\n ax.add_patch(PolygonPatch(poly, fc=RED, alpha=gradient, zorder=2))\n\n\n# In[15]:\n\ndef scale(coordinates, coordinates2, scalefactor, shape):\n longcoords = []\n latcoords =[]\n \n if shape == \"Polygon\":\n # Find the minimum and maximum longitude and latitude of a state outline\n \n for j in range(len(coordinates)):\n a = coordinates[j]\n for i in range(len(a)):\n c = a[i]\n longcoords.append(c[1])\n latcoords.append(c[0])\n minlong = min(longcoords)\n maxlong = max(longcoords)\n minlat = min(latcoords)\n maxlat = max(latcoords)\n \n # Calculate new coordinate values based on states maximum and minimum long/latitude, causing proportional scaling\n # of every set of coordinates.\n # The -0.5 is implemented such that the middle stays in the same place. Coordinates above the states middle long/latitude\n # will extend in the opposite direction than the coordinates under this value.\n for j in range(len(coordinates)):\n a = coordinates[j]\n for i in range(len(a)):\n c = a[i]\n c[1] = c[1] + scalefactor * (float(c[1]-minlong)/float(maxlong-minlong)-0.5)\n c[0] = c[0] + scalefactor * (float(c[0]-minlat)/float(maxlat-minlat)-0.5)\n coordinates[j][i] = c\n else:\n # Find the minimum and maximum longitude and latitude of the combined outline of a state with multiple polygons\n for j in range(len(coordinates2)):\n a = coordinates2[j]\n for k in range(len(a)):\n b = a[k]\n for i in range(len(b)):\n c = b[i]\n longcoords.append(c[1])\n latcoords.append(c[0])\n minlong = min(longcoords)\n maxlong = max(longcoords)\n minlat = min(latcoords)\n maxlat = max(latcoords)\n \n # Calculate new coordinate values based on these maximum and minimum long/lat values.\n for i in range(i, len(coordinates)):\n c = coordinates[i]\n \n c[1] = c[1] + scalefactor * (float(c[1]-minlong)/float(maxlong-minlong)-0.5)\n c[0] = c[0] + scalefactor * (float(c[0]-minlat)/float(maxlat-minlat)-0.5)\n coordinates[i] = c\n \n return coordinates\n\n# Retrieve coordinates of given state, transform and plot on map\ndef scale_state(state_name):\n if geometry['type'] == 'Polygon':\n poly = geometry\n poly2 = poly.copy()\n coordinates = poly['coordinates']\n projected_coordinates = scale(coordinates,_, scalefactor, shape=\"Polygon\")\n poly2['coordinates'] = projected_coordinates \n ax.add_patch(PolygonPatch(poly2, fc=RED, alpha=gradient, zorder=2))\n \n else:\n for polygon in geometry['coordinates'][0]:\n coordinates = polygon\n coordinates2 = geometry['coordinates']\n projected_coordinates = scale(coordinates, coordinates2, scalefactor, shape=\"Multipolygonon\")\n poly = Polygon(projected_coordinates)\n ax.add_patch(PolygonPatch(poly, fc=RED, alpha=gradient, zorder=2))\n\n\n# In[16]:\n\n# Calculate average age of each state for the year 2016\npopulation_data_all['WEIGHT'] = population_data_all['AGE']*population_data_all['POPEST2016_CIV']\navgAge = population_data_all.groupby('NAME')['WEIGHT'].sum() / population_data_all.groupby('NAME')['POPEST2016_CIV'].sum()\n \n# Retrieve maximum and minimum average age\nmax_AvgAge = max(avgAge)\nmin_AvgAge = min(avgAge)\n\n\n# In[20]:\n\n# Set parameters \nS_DIR = 'shapefiles/' \nBLUE = '#5599ff'\nRED = '#F03911'\nBLACK = '#0B0B0B'\n\nextra_long = -20 # increase/decrease in longitude\nextra_lat = 20 # increase/decrease in latitude\nstate = 'Iowa' # State(s) that will be altered\nscalefactor = 100 # Increase of state size in degrees\n \n#-----------------------------------------------------------------# \n \nwith open(os.path.join(S_DIR, 'states.geojson')) as rf: \n data = json.load(rf)\n\nfig = plt.figure() \nax = fig.gca()\n \n \nfor feature in data['features']: # Retrieve each state (feature) from database\n geometry = feature['geometry'] # Retrieve geometry of state (dictionary with coordinates)\n properties = feature['properties']\n state_name = properties['STATE_NAME']\n avgAge_state = avgAge[state_name]\n alpha = get_alpha(avgAge_state,min_AvgAge, max_AvgAge) # Determine fill color based on states average age\n color = alphatohex(alpha)\n \n if state_name == state:\n #move_state(state, extra_lat, extra_long)\n #scale_state(state)\n pass\n else:\n if geometry['type'] == 'Polygon':\n # States consisting out of one polygon\n poly = geometry\n ax.add_patch(PolygonPatch(poly, fc=color, alpha=1, zorder=2))\n else:\n # States consisting out of multiple polygons\n for polygon in geometry['coordinates'][0]:\n poly = Polygon(polygon)\n ax.add_patch(PolygonPatch(poly, fc=color, alpha=1, zorder=2))\n \nax.axis('scaled')\nplt.axis('off')\nplt.show()\n\n","sub_path":"Week1/Week1.py","file_name":"Week1.py","file_ext":"py","file_size_in_byte":15125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"475179236","text":"from util import Stack, Graph\n\nancestors_data = [(1, 3), (2, 3), (3, 6), (5, 6), (5, 7), (4, 5), (4, 8), (8, 9), (11, 8), (10, 1)]\n\ndef earliest_ancestor(ancestors, starting_node):\n ancestor_tree = Graph()\n # Iterate through ancestors\n for (parent, child) in ancestors: \n # Add vertices to ancestor_tree\n ancestor_tree.add_vertex(parent)\n ancestor_tree.add_vertex(child)\n # print(\"ancestor tree\", ancestor_tree.vertices)\n \n for (parent, child) in ancestors:\n # Add edges\n ancestor_tree.add_edge(child, parent)\n # print(\"neighbors\", ancestor_tree.get_neighbors(5))\n # print(\"ancestor tree\", ancestor_tree.vertices)\n\n longest_path = 1 # Keep track of # ancestors; highest means most ancestors\n earliest_ancestor = 0 # Store last node (as an integer)\n for i in ancestor_tree.vertices:\n # print(\"i\", i) # Print vertices\n # Call dfs function from Graph class\n path = ancestor_tree.dfs(i, starting_node) # i is each vertex/node in graph\n # print(\"ancestor dfs\", ancestor_tree.dfs(starting_node, i))\n print('path', path)\n if path: # If there are items in list\n if len(path) > longest_path: # If list length is greater than longest path\n longest_path = len(path) # Set longest path equal to list length\n earliest_ancestor = i # Set earliest_ancestor equal to current node/vertex\n elif not path and longest_path == 1: # If path is 'None' and 'longest_path' is our default of 1 \n earliest_ancestor = -1\n \n print(\"earliest ancestor\", earliest_ancestor)\n return earliest_ancestor\n\nprint('earliest ancestor', earliest_ancestor(ancestors_data, 8))\n\n'''\nBFS Solution:\ndef earliest_ancestor(ancestors, starting_node):\n # Build graph\n graph = Graph()\n for pair in ancestors:\n graph.add_vertex(pair[0])\n graph.add_vertex(pair[1])\n # Build edges in reverse\n graph.add_edge(pair[1], pair[0])\n \n # Do a BFT (storing the path)\n q = Queue()\n q.enqueue([starting_node])\n max_path_len = 1\n earliest_ancestor = -1\n while q.size() > 0:\n path = q.dequeue()\n v = path[-1]\n\n # If the path is longer or equal and the value is smaller, or if the path is longer\n if (len(path) >= max_path_len and v < earliest_ancestor) or (len(path) > max_path_len):\n earliest_ancestor = v\n max_path_len = len(path)\n\n for neighbor in graph.vertices[v]:\n path_copy = list(path)\n path_copy.append(neighbor)\n q.enqueue(path_copy)\n\n return earliest_ancestor\n\n'''","sub_path":"projects/ancestor/ancestor.py","file_name":"ancestor.py","file_ext":"py","file_size_in_byte":2661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"428532426","text":"import numpy as np\n\nclass Card():\n def __init__(self, color, number, shape, shading):\n self.color = color\n self.number = number\n self.shape = shape\n self.shading = shading\n self.attr = {'color': color, 'number': number, 'shape': shape, 'shading': shading}\n def __str__(self):\n return '{}-{}-{}-{}'.format(self.color, self.number, self.shape, self.shading)\n\nclass Rule():\n def __init__(self, bin_num):\n self.bin_num = bin_num\n self.bins = []\n for bin in range(bin_num):\n self.bins.append(set([]))\n def add_card(self, card, bin):\n self.bins[bin].add(card)\n def bin_acc(self, card, test_card=None, test_bin=None):\n dist = []\n \n for bin in range(self.bin_num):\n #If already added, distance is 0\n if card in self.bins[bin] or card == test_card:\n dist.append(0.0)\n else:\n cur_dists = []\n incr = [1, 1, 1, 1]\n for bin_card in self.bins[bin]:\n card_dist = 0.0\n if not card.color == bin_card.color:\n card_dist += incr[0]\n if not card.number == bin_card.number:\n card_dist += incr[1]\n if not card.shape == bin_card.shape:\n card_dist += incr[2]\n if not card.shading == bin_card.shading:\n card_dist += incr[3]\n cur_dists.append(card_dist)\n if test_bin == bin:\n card_dist = 0\n if not card.color == test_card.color:\n card_dist += incr[0]\n if not card.number == test_card.number:\n card_dist += incr[1]\n if not card.shape == test_card.shape:\n card_dist += incr[2]\n if not card.shading == test_card.shading:\n card_dist += incr[3]\n cur_dists.append(card_dist)\n if len(cur_dists) > 0:\n dist.append(np.mean(cur_dists))\n else:\n dist.append(np.sum(incr))\n\n # already_added = False\n # for bin in range(self.bin_num):\n # if test_card in self.bins[bin]:\n # already_added = True\n\n # for bin in range(self.bin_num):\n # if already_added:\n # if card in self.bins[bin]:\n # dist.append(0)\n # else:\n # cur_dists = []\n # for bin_card in self.bins[bin]:\n # card_dist = 0\n # if not card.color == bin_card.color:\n # card_dist += 1\n # if not card.number == bin_card.number:\n # card_dist += 1\n # if not card.shape == bin_card.shape:\n # card_dist += 1\n # if not card.shading == bin_card.shading:\n # card_dist += 1\n # cur_dists.append(card_dist)\n # if len(cur_dists) > 0:\n # dist.append(np.mean(cur_dists))\n # else:\n # dist.append(0)\n # else:\n # if card in self.bins[bin] or test_card in self.bins[bin]:\n # dist.append(0)\n # else:\n # cur_dists = []\n # for bin_card in self.bins[bin]:\n # card_dist = 0\n # if not card.color == bin_card.color:\n # card_dist += 1\n # if not card.number == bin_card.number:\n # card_dist += 1\n # if not card.shape == bin_card.shape:\n # card_dist += 1\n # if not card.shading == bin_card.shading:\n # card_dist += 1\n # cur_dists.append(card_dist)\n # if test_bin==bin:\n # card_dist = 0\n # if not card.color == test_card.color:\n # card_dist += 1\n # if not card.number == test_card.number:\n # card_dist += 1\n # if not card.shape == test_card.shape:\n # card_dist += 1\n # if not card.shading == test_card.shading:\n # card_dist += 1\n # cur_dists.append(card_dist)\n # if len(cur_dists) > 0:\n # dist.append(np.mean(cur_dists))\n # else:\n # dist.append(0)\n # min_val = np.min(dist)\n # min_idx = np.where(dist == min_val)[0]\n\n # return min_idx[0]\n if np.sum(dist) == 0:\n dist = np.array([0.5, 0.5])\n else:\n dist = dist/np.sum(dist)\n acc = 1 - dist\n return acc\n\nclass Hypothesis():\n def __init__(self, bin_num, bins):\n self.bin_num = bin_num \n self.bin_rule = bins\n \n\n def sort_card(self, card):\n #For each bin\n bin_res = []\n for bin_ind, bin in enumerate(self.bin_rule):\n for row in bin: #one of these rows needs to be true\n flag = True\n for prop, val in row: #all of these need to be true\n if not card.attr[prop] in val:\n flag = False\n \n if flag:\n bin_res.append(True)\n break\n if len(bin_res) == bin_ind:\n bin_res.append(False)\n return bin_res\n\n def __str__(self):\n return str(self.bin_rule)\n\n \n ","sub_path":"card_order/archive/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":5971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"50600093","text":"# -*- encoding: utf-8 -*-\n'''\n@File : readCemsisExcel.py \n@Contact : rosonlee@mail.ustc.edu.cn\n@Modify Time @Author @Version @Description\n------------ ------- -------- -----------\n2019/10/28 20:13 rosonlee 1.0 None\n'''\nimport openpyxl, pprint\nprint('Opening workbooks')\nwb = openpyxl.load_workbook('censuspopdata.xlsx')\nsheet = wb['Population by Census Tract']\ncountyData = {}\n\nprint('Reading Rows....')\nfor row in range(2, sheet.max_row+ 1):\n state = sheet['B' + str(row)].value\n county = sheet['C' + str(row)].value\n pop = sheet['D' + str(row)].value\n\n countyData.setdefault(state, {})\n countyData[state].setdefault(county, {'tracts': 0, 'pop': 0})\n\n countyData[state][county]['tracts'] += 1\n countyData[state][county]['pop'] += int(pop)\nprint('Writing results...')\nresultFile = open('census2010.py', 'w')\nresultFile.write('allData = ' + pprint.pformat(countyData))\nresultFile.close()\nprint('Done.')","sub_path":"Pypart/XMl/readCemsisExcel.py","file_name":"readCemsisExcel.py","file_ext":"py","file_size_in_byte":969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"463638874","text":"# A node structure\nfrom collections import deque\n\n\nclass Node:\n # A utility function to create a new node\n def __init__(self, key):\n self.val = key\n self.left = None\n self.right = None\n\n @staticmethod\n def cousins_bt(root, x, y):\n if root is None:\n return False\n q = deque([root])\n while q:\n tmp = []\n for _ in range(len(q)):\n node = q.popleft()\n children = [node.left.val, node.right.val] if node.left is not None and node.right is not None else []\n if x in children and y in children:\n return False\n q.append(node.left) if node.left is not None else None\n q.append(node.right) if node.right is not None else None\n tmp.append(node.val)\n if x in tmp and y in tmp:\n return True\n return False\n\n\n# Driver Code\nif __name__ == '__main__':\n t_root = Node(1)\n t_root.left = Node(2)\n t_root.right = Node(3)\n t_root.left.left = Node(4)\n t_root.left.right = Node(5)\n\n print(\"cousins_bt\")\n\n print(t_root.cousins_bt(t_root, 4, 5))\n t_root = Node(1)\n t_root.left = Node(2)\n t_root.right = Node(3)\n t_root.left.left = Node(4)\n t_root.left.right = Node(5)\n\n print(\"cousins_bt\")\n\n print(t_root.cousins_bt(t_root, 4, 5))\n t_root = Node(1)\n t_root.left = Node(2)\n t_root.right = Node(3)\n t_root.left.right = Node(4)\n\n print(\"cousins_bt\")\n\n print(t_root.cousins_bt(t_root, 2, 5))\n","sub_path":"_Trees/bfs/leetcode/13_993.py","file_name":"13_993.py","file_ext":"py","file_size_in_byte":1550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"544228691","text":"#!/usr/bin/env python3\n\nimport sys, os\nimport glob\nimport tarfile\nimport subprocess\nimport shutil\nimport h5py\nimport numpy as np\nfrom distutils.util import strtobool\nfrom tempfile import mkdtemp\n\ndef main():\n tar_file = sys.argv[1]\n out_file = sys.argv[2]\n out_fmt = sys.argv[3]\n demux = strtobool( sys.argv[4] )\n disable_filt = strtobool( sys.argv[5] )\n threads = sys.argv[6]\n\n tempdir = mkdtemp()\n\n (flowcell, kit) = parse_meta(tar_file, tempdir)\n\n subprocess.call(\n [\"read_fast5_basecaller.py\",\n \"--input\", tempdir,\n \"--worker_threads\", threads,\n \"--save_path\", \"out_dir\",\n \"--flowcell\", flowcell,\n \"--kit\", kit,\n \"--recursive\",\n \"--files_per_batch_folder\", \"0\",\n \"--output_format\", out_fmt,\n \"--reads_per_fastq_batch\", \"999999999\" ] +\n [\"--barcoding\"] * demux +\n [\"--disable_filtering\"] * disable_filt )\n\n out_path = \"out_dir/workspace\"\n pass_path = os.path.join( out_path, \"pass\" )\n if os.path.exists( pass_path ):\n out_path = pass_path\n if demux:\n #check for demuxed albacore output and copy to Galaxy output\n final_dir = \"final\"\n if not os.path.exists(final_dir):\n os.makedirs(final_dir)\n dirs = glob.glob( os.path.join(out_path, \"*\") )\n for d in dirs:\n\n if out_fmt == 'fastq':\n bc = os.path.basename( os.path.normpath( d ) ) + \".fastq\"\n print(d)\n print(bc)\n out = os.path.join( final_dir, bc )\n files = glob.glob( os.path.join( d, \"*.fastq\") )\n if len(files) != 1:\n raise ValueError('No or multiple FASTQ output files found')\n found_file = files[0]\n shutil.copy(found_file, out)\n\n elif out_fmt == 'fast5':\n if (os.path.isfile(d)):\n if (d.endswith('.fast5')):\n bc = os.path.basename( os.path.normpath(d) ) + \".tar.gz\"\n files = [d]\n else:\n continue\n else:\n bc = os.path.basename( os.path.normpath( d ) ) + \".fast5.tar.gz\"\n files = glob.glob( os.path.join( d, \"**\", \"*.fast5\"), recursive=True)\n out = os.path.join( final_dir, bc )\n if len(files) < 1:\n raise ValueError('No FAST5 output files found')\n tar = tarfile.open(out, 'w:gz')\n tar.add( d )\n tar.close()\n\n else:\n raise ValueError('Bad output format specified')\n\n else:\n if out_fmt == 'fastq':\n #check for single albacore output and copy to Galaxy output\n files = glob.glob( os.path.join(out_path, \"*.fastq\") )\n if len(files) != 1:\n raise ValueError('No or multiple FASTQ output files found')\n found_file = files[0]\n shutil.copy(found_file, out_file)\n elif out_fmt == 'fast5':\n #check for single albacore output and copy to Galaxy output\n files = glob.glob( os.path.join(out_path,\"**\",\"*.fast5\"), recursive=True )\n if len(files) < 1:\n raise ValueError('No FAST5 output files found')\n tar = tarfile.open(out_file, 'w:gz')\n tar.add(out_path)\n tar.close()\n else:\n raise ValueError('Bad output format specified')\n\n try:\n shutil.rmtree(tempdir)\n except:\n print(\"Unable to remove temp directory:\", sys.exc_info()[0])\n raise\n\n\ndef parse_meta(fn, in_dir):\n\n try:\n # python's tarfile interface does not sanitize file paths within\n # tarballs, which can be a big security risk. GNU tar does sanitize by\n # default, so it's easier/safer here just to call the system tar\n subprocess.call([\n \"tar\",\n \"--warning=no-unknown-keyword\",\n \"-xf\",\n fn,\n \"-C\",\n in_dir])\n\n files = glob.glob(\n os.path.join(in_dir, \"**\", \"*.fast5\"),\n recursive=True\n )\n if len(files) < 1:\n raise ValueError('No FAST5 files found')\n test_file = files[0]\n\n f = h5py.File(test_file,\"r\")\n #TODO: clean up attribute checking\n try:\n flowcell = f[\"/UniqueGlobalKey/context_tags\"].attrs[\"flowcell\"].upper()\n except:\n try:\n flowcell = f[\"/UniqueGlobalKey/context_tags\"].attrs[\"flowcell_type\"].upper()\n except:\n raise ValueError('No attribute found for flowcell type')\n try:\n kit = f[\"/UniqueGlobalKey/context_tags\"].attrs[\"sequencing_kit\"].upper()\n except:\n raise ValueError('No attribute found for sequencing kit')\n \n except OSError as e:\n print(\"Unexpected error:\", e.strerror)\n raise\n\n except:\n print(\"Unexpected error:\", sys.exc_info()[0])\n raise\n\n return flowcell, kit\n\nif __name__ == \"__main__\" :\n main()\n","sub_path":"tools/albacore/albacore_1D.py","file_name":"albacore_1D.py","file_ext":"py","file_size_in_byte":5128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"297761153","text":"# -*- coding: utf-8 -*-\n\nfrom django.core.management import call_command\n\nimport norduniclient as nc\nfrom norduniclient.exceptions import UniqueNodeError, NodeNotFound\nimport norduniclient.models as ncmodels\n\nfrom apps.noclook.models import NodeHandle, NodeType, NodeHandleContext, User, Role, DEFAULT_ROLE_KEY\nfrom apps.noclook.management.commands.csvimport import Command as CSVCommand\nimport apps.noclook.vakt.rules as srirules\nimport apps.noclook.vakt.utils as sriutils\n\nfrom ..neo4j_base import NeoTestCase\nfrom .fileutils import write_string_to_disk\n\n__author__ = 'ffuentes'\n\nclass CsvImportTest(NeoTestCase):\n cmd_name = 'csvimport'\n\n organizations_str = \"\"\"\"organization_number\";\"account_name\";\"description\";\"phone\";\"website\";\"organization_id\";\"type\";\"parent_account\"\n1;\"Tazz\";;\"453-896-3068\";\"https://studiopress.com\";\"DRIVE\";\"University, College\";\n2;\"Wikizz\";;\"531-584-0224\";\"https://ihg.com\";\"DRIVE\";\"University, College\";\n3;\"Browsecat\";;\"971-875-7084\";\"http://skyrock.com\";\"ROAD\";\"University, College\";\"Tazz\"\n4;\"Dabfeed\";;\"855-843-6570\";\"http://merriam-webster.com\";\"LANE\";\"University, College\";\"Wikizz\"\n \"\"\"\n\n contacts_str = \"\"\"\"salutation\";\"first_name\";\"last_name\";\"title\";\"contact_role\";\"contact_type\";\"mailing_street\";\"mailing_city\";\"mailing_zip\";\"mailing_state\";\"mailing_country\";\"phone\";\"mobile\";\"fax\";\"email\";\"other_email\";\"PGP_fingerprint\";\"account_name\"\n\"Honorable\";\"Caesar\";\"Newby\";;\"Computer Systems Analyst III\";\"Person\";;;;;\"China\";\"897-979-7799\";\"501-503-1550\";;\"cnewby0@joomla.org\";\"cnewby1@joomla.org\";;\"Gabtune\"\n\"Mr\";\"Zilvia\";\"Linnard\";;\"Analog Circuit Design manager\";\"Person\";;;;;\"Indonesia\";\"205-934-3477\";\"473-256-5648\";;\"zlinnard1@wunderground.com\";;;\"Babblestorm\"\n\"Honorable\";\"Reamonn\";\"Scriviner\";;\"Tax Accountant\";\"Person\";;;;;\"China\";\"200-111-4607\";\"419-639-2648\";;\"rscriviner2@moonfruit.com\";;;\"Babbleblab\"\n\"Mrs\";\"Jessy\";\"Bainton\";;\"Software Consultant\";\"Person\";;;;;\"China\";\"877-832-9647\";\"138-608-6235\";;\"fbainton3@si.edu\";;;\"Mudo\"\n\"Rev\";\"Theresa\";\"Janosevic\";;\"Physical Therapy Assistant\";\"Person\";;;;;\"China\";\"568-690-1854\";\"118-569-1303\";;\"tjanosevic4@umich.edu\";;;\"Youspan\"\n\"Mrs\";\"David\";\"Janosevic\";;;\"Person\";;;;;\"United Kingdom\";\"568-690-1854\";\"118-569-1303\";;\"djanosevic4@afaa.co.uk\";;;\"AsFastAsAFAA\"\n \"\"\"\n\n secroles_str = \"\"\"\"Organisation\";\"Contact\";\"Role\"\n\"Chalmers\";\"CTH Abuse\";\"Abuse\"\n\"Chalmers\";\"CTH IRT\";\"IRT Gruppfunktion\"\n\"Chalmers\";\"Hans Nilsson\";\"Övrig incidentkontakt\"\n\"Chalmers\";\"Stefan Svensson\";\"Övrig incidentkontakt\"\n\"Chalmers\";\"Karl Larsson\";\"Primär incidentkontakt\"\n \"\"\"\n\n def setUp(self):\n super(CsvImportTest, self).setUp()\n # write organizations csv file to disk\n self.organizations_file = write_string_to_disk(self.organizations_str)\n\n # write contacts csv file to disk\n self.contacts_file = write_string_to_disk(self.contacts_str)\n\n # write contacts csv file to disk\n self.secroles_file = write_string_to_disk(self.secroles_str)\n\n # create noclook user\n User.objects.get_or_create(username=\"noclook\")[0]\n\n def tearDown(self):\n super(CsvImportTest, self).tearDown()\n # close organizations csv file\n self.organizations_file.close()\n\n # close contacts csv file\n self.contacts_file.close()\n\n # close contacts csv file\n self.secroles_file.close()\n\n def test_organizations_import(self):\n # call csvimport command (verbose 0)\n call_command(\n self.cmd_name,\n organizations=self.organizations_file,\n verbosity=0,\n )\n # check one of the organizations is present\n qs = NodeHandle.objects.filter(node_name='Browsecat')\n self.assertIsNotNone(qs)\n organization1 = qs.first()\n self.assertIsNotNone(organization1)\n self.assertIsInstance(organization1.get_node(), ncmodels.OrganizationModel)\n\n # check if one of them has a parent organization\n relations = organization1.get_node().get_relations()\n parent_relation = relations.get('Parent_of', None)\n self.assertIsNotNone(parent_relation)\n self.assertIsInstance(relations['Parent_of'][0]['node'], ncmodels.RelationModel)\n\n def test_contacts_import(self):\n # call csvimport command (verbose 0)\n call_command(\n self.cmd_name,\n contacts=self.contacts_file,\n verbosity=0,\n )\n # check one of the contacts is present\n full_name = '{} {}'.format('Caesar', 'Newby')\n qs = NodeHandle.objects.filter(node_name=full_name)\n self.assertIsNotNone(qs)\n contact1 = qs.first()\n self.assertIsNotNone(contact1)\n self.assertIsInstance(contact1.get_node(), ncmodels.ContactModel)\n\n # check if works for an organization\n qs = NodeHandle.objects.filter(node_name='Gabtune')\n self.assertIsNotNone(qs)\n organization1 = qs.first()\n self.assertIsNotNone(organization1)\n self.assertIsInstance(organization1.get_node(), ncmodels.OrganizationModel)\n\n # check if role is created\n role1 = ncmodels.RoleRelationship(nc.core.GraphDB.get_instance().manager)\n role1.load_from_nodes(contact1.handle_id, organization1.handle_id)\n self.assertIsNotNone(role1)\n self.assertEquals(role1.name, 'Computer Systems Analyst III')\n\n roleqs = Role.objects.filter(name=role1.name)\n self.assertIsNotNone(roleqs)\n self.assertIsNotNone(roleqs.first)\n\n # check for empty role and if it has the role employee\n qs = NodeHandle.objects.filter(node_name='David Janosevic')\n self.assertIsNotNone(qs)\n contact_employee = qs.first()\n self.assertIsNotNone(contact_employee)\n employee_role = Role.objects.get(slug=DEFAULT_ROLE_KEY)\n relations = contact_employee.get_node().get_outgoing_relations()\n self.assertEquals(employee_role.name, relations['Works_for'][0]['relationship']['name'])\n\n def test_fix_addresss(self):\n # call csvimport command (verbose 0) to import test contacts\n call_command(\n self.cmd_name,\n organizations=self.organizations_file,\n verbosity=0,\n )\n\n # check one of the contacts is present\n org_name = \"Tazz\"\n qs = NodeHandle.objects.filter(node_name=org_name)\n self.assertIsNotNone(qs)\n organization1 = qs.first()\n self.assertIsNotNone(organization1)\n self.assertIsInstance(organization1.get_node(), ncmodels.OrganizationModel)\n organization1_node = organization1.get_node()\n\n # check organization's website and phone\n phone1_test = '453-896-3068'\n has_phone1 = 'phone' in organization1_node.data\n self.assertTrue(has_phone1)\n self.assertEquals(organization1_node.data['phone'], phone1_test)\n\n website1_test = 'https://studiopress.com'\n has_website1 = 'website' in organization1_node.data\n self.assertTrue(has_website1)\n self.assertEquals(organization1_node.data['website'], website1_test)\n\n call_command(\n self.cmd_name,\n addressfix=True,\n verbosity=0,\n )\n\n # check the old fields are not present anymore\n qs = NodeHandle.objects.filter(node_name=org_name)\n self.assertIsNotNone(qs)\n organization1 = qs.first()\n self.assertIsNotNone(organization1)\n self.assertIsInstance(organization1.get_node(), ncmodels.OrganizationModel)\n organization1_node = organization1.get_node()\n\n has_phone = 'phone' in organization1_node.data\n self.assertFalse(has_phone)\n\n relations = organization1_node.get_outgoing_relations()\n relation_keys = list(relations.keys())\n has_address = 'Has_address' in relation_keys\n self.assertTrue(has_address)\n\n address_node = relations['Has_address'][0]['node']\n self.assertIsInstance(address_node, ncmodels.AddressModel)\n\n has_phone = 'phone' in address_node.data\n self.assertTrue(has_phone)\n\n # check address has the community context\n address_nh = NodeHandle.objects.get(handle_id=address_node.handle_id)\n com_ctx = sriutils.get_community_context()\n rule = srirules.BelongsContext(com_ctx)\n self.assertTrue(rule.satisfied(address_nh))\n\n def test_fix_emails_phones(self):\n # call csvimport command (verbose 0) to import test contacts\n call_command(\n self.cmd_name,\n contacts=self.contacts_file,\n verbosity=0,\n )\n\n # check one of the contacts is present\n full_name = '{} {}'.format('Caesar', 'Newby')\n qs = NodeHandle.objects.filter(node_name=full_name)\n self.assertIsNotNone(qs)\n contact1 = qs.first()\n self.assertIsNotNone(contact1)\n self.assertIsInstance(contact1.get_node(), ncmodels.ContactModel)\n contact_node = contact1.get_node()\n\n # check user emails in old fields\n email1_test = 'cnewby0@joomla.org'\n has_email1 = 'email' in contact_node.data\n self.assertTrue(has_email1)\n self.assertEquals(contact_node.data['email'], email1_test)\n\n email2_test = 'cnewby1@joomla.org'\n has_email2 = 'other_email' in contact_node.data\n self.assertTrue(has_email2)\n self.assertEquals(contact_node.data['other_email'], email2_test)\n\n # check user phones in old fields\n phone1_test = '897-979-7799'\n has_phone1 = 'phone' in contact_node.data\n self.assertTrue(has_phone1)\n self.assertEquals(contact_node.data['phone'], phone1_test)\n\n phone2_test = '501-503-1550'\n has_phone2 = 'mobile' in contact_node.data\n self.assertTrue(has_phone2)\n self.assertEquals(contact_node.data['mobile'], phone2_test)\n\n call_command(\n self.cmd_name,\n emailphones=True,\n verbosity=0,\n )\n\n # check the old fields are not present anymore\n qs = NodeHandle.objects.filter(node_name=full_name)\n self.assertIsNotNone(qs)\n contact1 = qs.first()\n self.assertIsNotNone(contact1)\n self.assertIsInstance(contact1.get_node(), ncmodels.ContactModel)\n contact_node = contact1.get_node()\n\n has_phone1 = 'phone' in contact_node.data\n self.assertTrue(not has_phone1)\n has_phone2 = 'mobile' in contact_node.data\n self.assertTrue(not has_phone2)\n has_email1 = 'email' in contact_node.data\n self.assertTrue(not has_email1)\n has_email2 = 'other_email' in contact_node.data\n self.assertTrue(not has_email2)\n\n relations = contact_node.get_outgoing_relations()\n relation_keys = list(relations.keys())\n has_phone = 'Has_phone' in relation_keys\n has_emails = 'Has_email' in relation_keys\n\n test_dict = {\n 'email': {\n 'work': email1_test,\n 'personal': email2_test,\n },\n 'phone': {\n 'work': phone1_test,\n 'personal': phone2_test,\n }\n }\n\n self.assertTrue(has_phone)\n self.assertTrue(has_emails)\n\n for phone_rel in relations['Has_phone']:\n phone_node = phone_rel['node']\n phone_type = phone_node.data['type']\n check_phone = test_dict['phone'][phone_type]\n self.assertEquals(check_phone, phone_node.data['name'])\n\n # check phone has the community context\n phone_nh = NodeHandle.objects.get(handle_id=phone_node.handle_id)\n com_ctx = sriutils.get_community_context()\n rule = srirules.BelongsContext(com_ctx)\n self.assertTrue(rule.satisfied(phone_nh))\n\n for email_rel in relations['Has_email']:\n email_node = email_rel['node']\n email_type = email_node.data['type']\n check_email = test_dict['email'][email_type]\n self.assertEquals(check_email, email_node.data['name'])\n\n # check phone has the community context\n email_nh = NodeHandle.objects.get(handle_id=email_node.handle_id)\n com_ctx = sriutils.get_community_context()\n rule = srirules.BelongsContext(com_ctx)\n self.assertTrue(rule.satisfied(email_nh))\n\n def test_secroles_import(self):\n # call csvimport command (verbose 0)\n call_command(\n self.cmd_name,\n secroles=self.secroles_file,\n verbosity=0,\n )\n\n # check if the organization is present\n qs = NodeHandle.objects.filter(node_name='Chalmers')\n self.assertIsNotNone(qs)\n organization1 = qs.first()\n self.assertIsNotNone(organization1)\n\n # check a contact is present\n qs = NodeHandle.objects.filter(node_name='Hans Nilsson')\n self.assertIsNotNone(qs)\n contact1 = qs.first()\n self.assertIsNotNone(contact1)\n\n # check if role is created\n role1 = ncmodels.RoleRelationship(nc.core.GraphDB.get_instance().manager)\n role1.load_from_nodes(contact1.handle_id, organization1.handle_id)\n self.assertIsNotNone(role1)\n self.assertEquals(role1.name, 'Övrig incidentkontakt')\n\n def test_organizations_import(self):\n # call csvimport command (verbose 0)\n call_command(\n self.cmd_name,\n organizations=self.organizations_file,\n verbosity=0,\n )\n\n call_command(\n self.cmd_name,\n addressfix=True,\n verbosity=0,\n )\n\n website_field = 'website'\n\n organization_type = NodeType.objects.get_or_create(type='Organization', slug='organization')[0] # organization\n all_organizations = NodeHandle.objects.filter(node_type=organization_type)\n\n for organization in all_organizations:\n # get the address and check that the website field is not present\n website_value = organization.get_node().data.get(website_field, None)\n self.assertIsNotNone(website_value)\n\n relations = organization.get_node().get_outgoing_relations()\n address_relations = relations.get('Has_address', None)\n orgnode = organization.get_node()\n\n self.assertIsNotNone(address_relations)\n\n # check and add it for test\n for rel in address_relations:\n address_end = rel['relationship'].end_node\n self.assertFalse(website_field in address_end._properties)\n handle_id = address_end._properties['handle_id']\n address_node = NodeHandle.objects.get(handle_id=handle_id).get_node()\n\n address_node.add_property(website_field, website_value)\n orgnode.remove_property(website_field)\n\n # fix it\n call_command(\n self.cmd_name,\n movewebsite=True,\n verbosity=0,\n )\n\n # check that it's good again\n all_organizations = NodeHandle.objects.filter(node_type=organization_type)\n\n for organization in all_organizations:\n # get the address and check that the website field is not present\n website_value = organization.get_node().data.get(website_field, None)\n self.assertIsNotNone(website_value)\n\n relations = organization.get_node().get_outgoing_relations()\n address_relations = relations.get('Has_address', None)\n orgnode = organization.get_node()\n\n self.assertIsNotNone(address_relations)\n\n # check the data is not present on the address\n for rel in address_relations:\n address_end = rel['relationship'].end_node\n self.assertFalse(website_field in address_end._properties)\n\n\n def test_orgid_fix(self):\n # call csvimport command (verbose 0)\n call_command(\n self.cmd_name,\n organizations=self.organizations_file,\n verbosity=0,\n )\n\n old_field1 = 'customer_id'\n new_field1 = 'organization_id'\n\n organization_type = NodeType.objects.get_or_create(type='Organization', slug='organization')[0] # organization\n all_organizations = NodeHandle.objects.filter(node_type=organization_type)\n\n for organization in all_organizations:\n orgnode = organization.get_node()\n org_id_val = orgnode.data.get(new_field1, None)\n self.assertIsNotNone(org_id_val)\n orgnode.remove_property(new_field1)\n orgnode.add_property(old_field1, org_id_val)\n\n # fix it\n call_command(\n self.cmd_name,\n reorgprops=True,\n verbosity=0,\n )\n\n # check that it's good again\n all_organizations = NodeHandle.objects.filter(node_type=organization_type)\n\n for organization in all_organizations:\n # get the address and check that the website field is not present\n org_id_val = organization.get_node().data.get(new_field1, None)\n self.assertIsNotNone(org_id_val)\n\n\n def test_fix_community_context(self):\n # call csvimport command (verbose 0) to import test organizations\n call_command(\n self.cmd_name,\n organizations=self.organizations_file,\n verbosity=0,\n )\n\n # and contacts\n call_command(\n self.cmd_name,\n contacts=self.contacts_file,\n verbosity=0,\n )\n\n # get types and contexts\n com_ctx = sriutils.get_community_context()\n\n csvcommand = CSVCommand()\n email_type = csvcommand.get_nodetype(type='Email', slug='email', hidden=True)\n phone_type = csvcommand.get_nodetype(type='Phone', slug='phone', hidden=True)\n address_type = csvcommand.get_nodetype(type='Address', slug='address', hidden=True)\n\n all_emails = NodeHandle.objects.filter(node_type=email_type)\n all_phones = NodeHandle.objects.filter(node_type=phone_type)\n all_address = NodeHandle.objects.filter(node_type=address_type)\n\n # delete context from all these nodes\n NodeHandleContext.objects.filter(\n context=com_ctx, nodehandle__in=all_emails).delete()\n NodeHandleContext.objects.filter(\n context=com_ctx, nodehandle__in=all_phones).delete()\n NodeHandleContext.objects.filter(\n context=com_ctx, nodehandle__in=all_emails).delete()\n\n # fix it\n call_command(\n self.cmd_name,\n contextfix=True,\n verbosity=0,\n )\n\n # check that every node have a context\n comm_emails_num = NodeHandleContext.objects.filter(\n context=com_ctx, nodehandle__in=all_emails).count()\n emails_num = all_emails.count()\n\n self.assertEqual(comm_emails_num, emails_num)\n\n comm_phones_num = NodeHandleContext.objects.filter(\n context=com_ctx, nodehandle__in=all_phones).count()\n phones_num = all_phones.count()\n\n self.assertEqual(comm_phones_num, phones_num)\n\n comm_address_num = NodeHandleContext.objects.filter(\n context=com_ctx, nodehandle__in=all_address).count()\n address_num = all_address.count()\n\n self.assertEqual(comm_address_num, address_num)\n\n def write_string_to_disk(self, string):\n # get random file\n tf = tempfile.NamedTemporaryFile(mode='w+')\n\n # write text\n tf.write(string)\n tf.flush()\n # return file descriptor\n return tf\n","sub_path":"src/niweb/apps/noclook/tests/management/test_csvimport.py","file_name":"test_csvimport.py","file_ext":"py","file_size_in_byte":19513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"161483567","text":"import numpy as np\nfrom formula.terms import Factor\nimport sympy\nfrom string import uppercase\nfrom StringIO import StringIO\nimport matplotlib.mlab as ML\nimport nose.tools as nt\n\nfrom os import remove\nfrom formula.terms import Term, Factor\nfrom formula.categorical import CategoricalFormula\nimport matplotlib.mlab as ML\nimport tempfile, rpy2.robjects\n\ndef random_letters(size, nlevels=6):\n return [uppercase[i] for i in np.random.random_integers(0,nlevels-1,size=size)]\n\ndef random_subset(subset, size):\n s = sorted(subset)\n return [s[i] for i in np.random.random_integers(0,len(s)-1,size=size)]\n\ndef random_recarray(size):\n initial = np.empty(size, dtype=np.dtype([('Y', np.float)]))\n initial['Y'] = np.random.standard_normal(size)\n numeric_vars = [np.random.standard_normal(size) for _ in range(10)]\n categorical_vars = [random_letters(size, l) for l in [3,4,7,6,4,5,8]]\n inter = ML.rec_append_fields(initial, ['n%s' % l for l in uppercase[:10]], numeric_vars)\n final = ML.rec_append_fields(inter, ['c%s' % l for l in uppercase[:len(categorical_vars)]], categorical_vars)\n return final, sympy.symbols(['n%s' % l for l in uppercase[:10]]), [Factor('c%s' % s, np.unique(l)) for s, l in zip(uppercase[:len(categorical_vars)],\n categorical_vars)]\n\ndef random_categorical_formula(size=500):\n nterms = np.random.poisson(5)\n X, n, c = random_recarray(size)\n d = {}\n for _ in range(nterms):\n expr = random_subset(n, np.random.binomial(len(n), 0.5))\n f = []\n for _ in range(np.random.poisson(2)):\n factors = random_subset(c, np.random.poisson(1))\n f.append(np.unique(factors))\n d[np.product(np.unique(expr))] = f\n return CategoricalFormula(d)\n\ndef random_from_factor(factor, size):\n return random_subset(factor.levels, size)\n\ndef random_from_terms_factors(terms, factors, size):\n dtype = np.dtype([(str(t), np.float) for t in terms] + [(f.name,'S30') for f in factors])\n data = np.empty(size, \n np.dtype([(str(terms[0]), np.float)]))\n data[str(terms[0])] = np.random.standard_normal(size)\n for t in terms[1:]:\n data = ML.rec_append_fields(data, str(t), \n np.random.standard_normal(size))\n for f in factors:\n data = ML.rec_append_fields(data, f.name, random_from_factor(f, size))\n return data\n\ndef random_from_categorical_formula(cf, size):\n exprs = []\n factors = []\n for key, value in cf.expr_factor_dict.items():\n if str(key) != '1':\n exprs += str(key).split(\"*\")\n for fs in value:\n factors += list(fs)\n return random_from_terms_factors(list(set(exprs)), list(set(factors)), size)\n\ndef simple():\n\n x = Term('x'); y = Term('y') ; z = Term('z')\n f = Factor('f', ['a','b','c'])\n g = Factor('g', ['aa','bb','cc'])\n h = Factor('h', ['a','b','c','d','e','f','g','h','i','j'])\n d = CategoricalFormula({x*y:((g,f),),x:([f],[g,f]),\n 1:([g],),\n z:([h],[h,g,f])})\n\n return d\n\ndef testR(d=simple(), size=500):\n\n X = random_from_categorical_formula(d, size)\n\n X = ML.rec_append_fields(X, 'response', np.random.standard_normal(size))\n fname = tempfile.mktemp()\n ML.rec2csv(X, fname)\n Rstr = '''\n data = read.table(\"%s\", sep=',', header=T)\n cur.lm = lm(response ~ %s, data)\n COEF = coef(cur.lm)\n ''' % (fname, d.Rstr)\n rpy2.robjects.r(Rstr)\n remove(fname)\n nR = list(np.array(rpy2.robjects.r(\"names(COEF)\")))\n\n nt.assert_true('(Intercept)' in nR)\n nR.remove(\"(Intercept)\")\n nF = [str(t).replace(\"_\",\"\").replace(\"*\",\":\") for t in d.formula.terms]\n \n nR = sorted([sorted(n.split(\":\")) for n in nR])\n\n nt.assert_true('1' in nF)\n nF.remove('1')\n\n nF = sorted([sorted(n.split(\":\")) for n in nF])\n nt.assert_equal(nR, nF)\n\n return d, X, nR, nF\n","sub_path":"tests/random_design.py","file_name":"random_design.py","file_ext":"py","file_size_in_byte":4013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"34862413","text":"import re\nfrom itertools import groupby\n\n\ndef encode(data):\n '''Run-length encode\n\n keyword arguments:\n data - data to be encoded\n\n returns a string\n\n '''\n enc = []\n\n for ch, num in groupby(data):\n enc.append(str(len(list(num))))\n enc.append(str(ch))\n \n for x in enc:\n if x == '1':\n enc.remove(x)\n\n enc = ''.join(enc)\n\n return enc\n \n\ndef decode(data):\n '''Run-length decode\n\n keyword arguments:\n data - data to be decoded\n\n returns a string\n\n '''\n return re.sub(r'(\\d+)(\\D)', lambda m: m.group(2) * int(m.group(1)), data)\n","sub_path":"python/run-length-encoding/run_length.py","file_name":"run_length.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"438810987","text":"\"\"\"This creates matlab like one liners that make it easy to visualize\ndata from the Python interpreter.\n\nRight now this provides the following useful functions.\n\n 1. surf(x, y, f) -- samples f along x, y and plots a surface.\n\n 2. view(arr) -- Views array as structured points.\n\n 3. viewi(arr) -- Views array as an image.\n\n 4. sampler(xa, ya, func) -- Samples func along array of ordered\n points (xa, ya).\n\nAuthor:\n Prabhu Ramachandran \n\nLicense:\n BSD -- http://www.opensource.org/licenses/bsd-license.html\n\"\"\"\n\nimport mayavi\nimport vtk\nimport Numeric\n\ntry:\n from vtk.util import vtkConstants\nexcept ImportError:\n class vtkConstants:\n pass\n vtkConstants.VTK_CHAR=2\n vtkConstants.VTK_UNSIGNED_CHAR = 3\n vtkConstants.VTK_SHORT = 4\n vtkConstants.VTK_UNSIGNED_SHORT = 5\n vtkConstants.VTK_INT = 6\n vtkConstants.VTK_UNSIGNED_INT = 7\n vtkConstants.VTK_LONG = 8\n vtkConstants.VTK_UNSIGNED_LONG = 9\n vtkConstants.VTK_FLOAT =10\n vtkConstants.VTK_DOUBLE =11\n\ndef array2vtk(z): \n \"\"\"Converts a Numeric Array to a VTK array object directly. The\n resulting array copies the data in the passed Numeric array. The\n array can therefore be deleted safely. This works for real arrays.\n\n XXX what should be done for complex arrays?\n \"\"\"\n \n arr_vtk = {'c':vtkConstants.VTK_UNSIGNED_CHAR,\n 'b':vtkConstants.VTK_UNSIGNED_CHAR,\n '1':vtkConstants.VTK_CHAR,\n 's':vtkConstants.VTK_SHORT,\n 'i':vtkConstants.VTK_INT,\n 'l':vtkConstants.VTK_LONG,\n 'f':vtkConstants.VTK_FLOAT,\n 'd':vtkConstants.VTK_DOUBLE,\n 'F':vtkConstants.VTK_FLOAT,\n 'D':vtkConstants.VTK_DOUBLE }\n\n # A dummy array used to create others.\n f = vtk.vtkFloatArray()\n # First create an array of the right type by using the typecode.\n tmp = f.CreateDataArray(arr_vtk[z.typecode()])\n tmp.SetReferenceCount(2) # Prevents memory leak.\n zf = Numeric.ravel(z)\n tmp.SetNumberOfTuples(len(zf))\n tmp.SetNumberOfComponents(1)\n tmp.SetVoidArray(zf, len(zf), 1)\n\n # Now create a new array that is a DeepCopy of tmp. This is\n # required because tmp does not copy the data from the NumPy array\n # and will point to garbage if the NumPy array is deleted.\n arr = f.CreateDataArray(arr_vtk[z.typecode()])\n arr.SetReferenceCount(2) # Prevents memory leak.\n arr.DeepCopy(tmp)\n\n return arr\n\n\ndef _create_structured_points_pyvtk(x, y, z):\n \n \"\"\"Creates a vtkStructuredPoints object given input data in the\n form of arrays. This uses pyvtk to do the job and generates a\n temporary file in the process.\n\n Input Arguments:\n x -- Array of x-coordinates. These should be regularly spaced.\n\n y -- Array of y-coordinates. These should be regularly spaced.\n\n z -- Array of z values for the x, y values given. The values\n should be computed such that the z values are computed as x\n varies fastest and y next.\n\n \"\"\"\n\n import pyvtk\n import tempfile, os\n \n nx = len(x)\n ny = len(y)\n nz = len(z)\n assert nx*ny == nz, \"len(x)*len(y) != len(z). \"\\\n \"You passed nx=%d, ny=%d, nz=%d\"%(nx, ny, nz)\n\n xmin, ymin = x[0], y[0]\n dx, dy= (x[1] - x[0]), (y[1] - y[0])\n\n # create a vtk data file\n sp = pyvtk.StructuredPoints ((nx, ny, 1), (xmin, ymin, 0), (dx, dy, 1))\n pd = pyvtk.PointData(pyvtk.Scalars(z, name='Scalars',\n lookup_table=\"default\"))\n d = pyvtk.VtkData(sp, pd, \"Surf data\")\n file_name = tempfile.mktemp(suffix='.vtk')\n d.tofile(file_name, format='ascii')\n\n # read the created file - yes this is circuitous but works for now.\n reader = vtk.vtkStructuredPointsReader()\n reader.SetFileName(file_name)\n reader.Update()\n # cleanup.\n os.remove(file_name)\n return reader.GetOutput()\n\n\ndef _create_structured_points_direct(x, y, z=None):\n \"\"\"Creates a vtkStructuredPoints object given input data in the\n form of Numeric arrays.\n\n Input Arguments:\n x -- Array of x-coordinates. These should be regularly spaced.\n\n y -- Array of y-coordinates. These should be regularly spaced.\n\n z -- Array of z values for the x, y values given. The values\n should be computed such that the z values are computed as x\n varies fastest and y next. If z is None then no scalars are\n associated with the structured points. Only the structured\n points data set is created.\n \"\"\"\n\n nx = len(x)\n ny = len(y)\n if z:\n nz = Numeric.size(z)\n assert nx*ny == nz, \"len(x)*len(y) != len(z)\"\\\n \"You passed nx=%d, ny=%d, nz=%d\"%(nx, ny, nz)\n\n xmin, ymin = x[0], y[0]\n dx, dy= (x[1] - x[0]), (y[1] - y[0])\n\n sp = vtk.vtkStructuredPoints()\n sp.SetDimensions(nx, ny, 1)\n sp.SetOrigin(xmin, ymin, 0)\n sp.SetSpacing(dx, dy, 1)\n if z:\n sc = array2vtk(z)\n sp.GetPointData().SetScalars(sc)\n return sp\n\n\ndef sampler(xa, ya, func,f_args=(),f_keyw=None):\n \"\"\"Samples a function at an array of ordered points (with equal\n spacing) and returns an array of scalars as per VTK's requirements\n for a structured points data set, i.e. x varying fastest and y\n varying next.\n \n Input Arguments:\n xa -- Array of x points.\n\n ya -- Array if y points.\n\n func -- function of x, and y to sample.\n\n f_args -- a tuple of additional positional arguments for func()\n (default is empty)\n\n f_keyw -- a dict of additional keyword arguments for func()\n (default is empty)\n \"\"\"\n if f_keyw is None:\n f_keyw = {}\n ret = func(xa[:,Numeric.NewAxis] +\n Numeric.zeros(len(ya), ya.typecode()),\n Numeric.transpose(ya[:,Numeric.NewAxis] +\n Numeric.zeros(len(xa), xa.typecode()) ),\n *f_args, **f_keyw\n )\n return Numeric.transpose(ret)\n\n\ndef _check_sanity(x, y, z):\n \"\"\"Checks the given arrays to see if they are suitable for\n surf.\"\"\"\n msg = \"Only ravelled or 2D arrays can be viewed! \"\\\n \"This array has shape %s\" % str(z.shape)\n assert len(z.shape) <= 2, msg\n \n if len( z.shape ) == 2:\n msg = \"len(x)*len(y) != len(z.flat). You passed \"\\\n \"nx=%d, ny=%d, shape of z=%s\"%(len(x), len(y), z.shape)\n assert z.shape[0]*z.shape[1] == len(x)*len(y), msg\n\n msg = \"length of y(%d) and x(%d) must match shape of z \"\\\n \"%s. (Maybe you need to swap x and y?)\"%(len(y), len(x),\n str(z.shape))\n assert z.shape == (len(y), len(x)), msg \n\n\ndef squeeze(a):\n \"Returns a with any ones from the shape of a removed\"\n a = Numeric.asarray(a)\n b = Numeric.asarray(a.shape)\n val = Numeric.reshape(a,\n tuple(Numeric.compress(Numeric.not_equal(b, 1), b)))\n return val\n\n\ndef surf(x, y, z, warp=1, scale=[1.0, 1.0, 1.0], viewer=None,\n f_args=(), f_keyw=None):\n \"\"\"Creates a surface given regularly spaced values of x, y and the\n corresponding z as arrays. Also works if z is a function.\n Currently works only for regular data - can be enhanced later.\n\n Input Arguments:\n x -- Array of x points (regularly spaced)\n\n y -- Array if y points (regularly spaced)\n\n z -- A 2D array for the x and y points with x varying fastest\n and y next. Also will work if z is a callable which supports\n x and y arrays as the arguments.\n\n warp -- If true, warp the data to show a 3D surface\n (default = 1). \n\n scale -- Scale the x, y and z axis as per passed values.\n Defaults to [1.0, 1.0, 1.0].\n\n viewer -- An optional viewer (defaults to None). If provided\n it will use this viewer instead of creating a new MayaVi\n window each time.\n\n f_args -- a tuple of additional positional arguments for func()\n (default is empty)\n\n f_keyw -- a dict of additional keyword arguments for func()\n (default is empty)\n \"\"\"\n\n if f_keyw is None:\n f_keyw = {}\n\n if callable(z):\n zval = Numeric.ravel(sampler(x, y, z, f_args=f_args, f_keyw=f_keyw))\n x, y = squeeze(x), squeeze(y)\n else:\n x, y = squeeze(x), squeeze(y)\n _check_sanity(x, y, z)\n zval = Numeric.ravel(z)\n assert len(zval) > 0, \"z is empty - nothing to plot!\"\n\n xs = x*scale[0]\n ys = y*scale[1]\n data = _create_structured_points_direct(xs, ys, zval)\n # do the mayavi stuff.\n if not viewer:\n v = mayavi.mayavi()\n else:\n v = viewer\n v.open_vtk_data(data)\n if warp:\n f = v.load_filter('WarpScalar', 0)\n f.fil.SetScaleFactor(scale[2])\n n = v.load_filter('PolyDataNormals', 0)\n n.fil.SetFeatureAngle(45)\n m = v.load_module('SurfaceMap', 0)\n if not viewer:\n a = v.load_module('Axes', 0)\n a.axes.SetCornerOffset(0.0)\n if (min(scale) != max(scale)) or (scale[0] != 1.0):\n a.axes.UseRangesOn()\n a.axes.SetRanges(x[0], x[-1], y[0], y[-1], min(zval), max(zval))\n o = v.load_module('Outline', 0)\n v.Render()\n return v\n\n\ndef view(arr, smooth=0, warp=0, scale=[1.0, 1.0, 1.0]):\n\n \"\"\"Allows one to view a 2D Numeric array. Note that the view will\n be set to the way we normally think of matrices with with 0, 0 at\n the top left of the screen.\n\n Input Arguments:\n arr -- Array to be viewed.\n \n smooth -- If true, view the array as VTK point data i.e. the\n matrix entries will be treated as scalar data at the integral\n values along the axes and between these points the colours will\n be interpolated providing a smooth appearance for the data. If\n set to false the data is viewed as cells with no interpolation\n and each cell of the matrix is viewed in a separate color with\n no interpolation. Note that if smooth is set to true you will\n be able to do more fancy things with the visualization (like\n contouring the data, warping it to get a 3d surface etc.) than\n when smooth is off. If warp is set to true then this option is\n set to true. (default=false)\n\n warp -- If true, warp the data to show a 3D surface (default =\n 0). If set the smooth option has no effect. Note that this is\n an expensive operation so use it sparingly for large arrays.\n\n scale -- Scale the x, y and z axis as per passed values.\n Defaults to [1.0, 1.0, 1.0].\n \"\"\"\n\n assert len(arr.shape) == 2, \"Only 2D arrays can be viewed!\"\n ny, nx = arr.shape\n if warp:\n smooth=1\n if not smooth:\n nx += 1\n ny += 1\n\n dx, dy, junk = Numeric.array(scale)*1.0\n xa = Numeric.arange(0, nx*scale[0] - 0.1*dx, dx, 'f')\n ya = Numeric.arange(0, ny*scale[1] - 0.1*dy, dy, 'f')\n \n if smooth:\n data = _create_structured_points_direct(xa, ya, arr)\n else:\n data = _create_structured_points_direct(xa, ya)\n sc = array2vtk(arr)\n data.GetCellData().SetScalars(sc)\n \n # do the mayavi stuff.\n v = mayavi.mayavi()\n v.open_vtk_data(data)\n if warp:\n f = v.load_filter('WarpScalar', 0)\n f.fil.SetScaleFactor(scale[2])\n n = v.load_filter('PolyDataNormals', 0)\n n.fil.SetFeatureAngle(45)\n m = v.load_module('SurfaceMap', 0)\n a = v.load_module('Axes', 0)\n a.axes.SetCornerOffset(0.0)\n a.axes.YAxisVisibilityOff()\n a.axes.UseRangesOn()\n arr_flat = Numeric.ravel(arr)\n a.axes.SetRanges(0, nx, 0, ny, min(arr_flat), max(arr_flat))\n o = v.load_module('Outline', 0)\n v.renwin.update_view(0, 0, -1, 0, -1, 0)\n v.Render()\n return v\n\n\ndef viewi(arr, smooth=0, lut='br', scale=[1.0, 1.0, 1.0]):\n \n \"\"\"Allows one to view a 2D Numeric array as an image. This works\n best for very large arrays (like 1024x1024 arrays). The\n implementation of this function is a bit of a hack and many of\n MayaVi's features cannot be used. For instance you cannot change\n the lookup table color and expect the color of the image to\n change.\n\n Note that the view will be set to the way we normally think of\n matrices with with 0, 0 at the top left of the screen.\n\n Input Arguments:\n arr -- Array to be viewed.\n \n smooth -- If true, perform interpolation on the image. If\n false do not perform interpolation. (default=0)\n\n lut -- Specifies the lookuptable to map the data with. This\n should be on of ['br', 'rb', 'bw', 'wb'] 'br' refers to\n blue-to-red, 'rb' to red-to-blue, 'bw' to black-to-white and\n 'wb' to white-black. (default='br')\n\n scale -- Scale the x, y and z axis as per passed values.\n Defaults to [1.0, 1.0, 1.0].\n \"\"\"\n\n valid_lut = {'br': 1, 'rb':2, 'bw':3, 'wb':4}\n \n assert len(arr.shape) == 2, \"Only 2D arrays can be viewed!\"\n assert lut in valid_lut.keys(), \\\n \"lut must be one of %s!\"%(valid_lut.keys())\n \n ny, nx = arr.shape\n dx, dy, junk = Numeric.array(scale)*1.0\n xa = Numeric.arange(0, nx*scale[0] - 0.1*dx, dx, 'f')\n ya = Numeric.arange(0, ny*scale[1] - 0.1*dy, dy, 'f')\n\n arr_flat = Numeric.ravel(arr)\n min_val = min(arr_flat)\n max_val = max(arr_flat)\n \n sp = _create_structured_points_direct(xa, ya)\n v = mayavi.mayavi()\n v.open_vtk_data(sp)\n\n mm = v.get_current_dvm().get_current_module_mgr()\n luth = mm.get_scalar_lut_handler()\n \n luth.lut_var.set(valid_lut[lut])\n luth.change_lut()\n\n l = luth.get_lut()\n l.SetRange(min_val, max_val)\n za = array2vtk(arr_flat)\n a = l.MapScalars(za, 0, 0)\n sp.GetPointData().SetScalars(a)\n sp.SetScalarTypeToUnsignedChar()\n sp.SetNumberOfScalarComponents(4)\n \n luth.legend_on.set(1)\n luth.legend_on_off() \n luth.set_data_range([min_val, max_val])\n luth.range_on_var.set(1)\n luth.set_range_on()\n \n ia = vtk.vtkImageActor()\n if smooth:\n ia.InterpolateOn()\n else:\n ia.InterpolateOff() \n ia.SetInput(sp)\n\n v.renwin.add_actors(ia)\n\n a = v.load_module('Axes', 0)\n a.axes.SetCornerOffset(0.0)\n a.axes.YAxisVisibilityOff()\n a.axes.UseRangesOn()\n a.axes.SetRanges(0, nx, 0, ny, min_val, max_val)\n o = v.load_module('Outline', 0)\n v.renwin.update_view(0, 0, -1, 0, -1, 0)\n t = v.renwin.tkwidget\n t.UpdateRenderer(0,0)\n t.Pan(0,-25)\n v.Render()\n return v\n\n\n\ndef main():\n \n \"\"\" A simple example. Note that the Tkinter lines are there only\n because this code will be run standalone. On the interpreter,\n simply invoking surf and view would do the job.\"\"\"\n \n import Tkinter\n r = Tkinter.Tk()\n r.withdraw()\n\n def f(x, y):\n return Numeric.sin(x*y)/(x*y)\n\n x = Numeric.arange(-7., 7.05, 0.1)\n y = Numeric.arange(-5., 5.05, 0.05)\n v = surf(x, y, f)\n\n import RandomArray\n z = RandomArray.random((50, 25))\n v1 = view(z)\n v2 = view(z, warp=1)\n z_large = RandomArray.random((1024, 512))\n v3 = viewi(z_large)\n\n # A hack for stopping Python when all windows are closed.\n v.master = r \n v1.master = r\n v2.master = r\n #v3.master = r\n \n r.mainloop()\n \n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Other Code/MayaVi-1.5/tools/imv.py","file_name":"imv.py","file_ext":"py","file_size_in_byte":15387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"435428118","text":"from functions import *\n\nif __name__ == \"__main__\":\n print('Running warmupexercise...\\n')\n print('5x5 Identity Matrix:\\n')\n warmupexercise()\n input('Press any key to continue')\n print('Plotting Data...\\n')\n data = pd.read_csv('ex1data1.txt', header=None)\n x = data.iloc[:, 0]\n y = data.iloc[:, 1]\n m = len(y)\n data.head()\n plotData(x, y)\n input('Press any key to continue')\n X = np.c_[np.ones((m, 1)), x]\n theta = np.zeros((2, 1))\n iterations = 1500\n alpha = 0.01\n print('\\nTesting the cost function...\\n')\n J = computeCost(X, y, theta)\n print('With theta = [0 ; 0]\\nCost computed = ', J)\n print('Expected cost value (approx) 32.07\\n')\n J = computeCost(X, y, [[-1], [2]])\n print('With theta = [-1 ; 2]\\n Cost computed = ', J)\n print('Expected cost value (approx) 54.24\\n')\n input('Press any key to continue')\n theta = gradientDescent(X, y, theta, alpha, iterations)\n print('Theta found by gradient descent:\\n')\n print(theta)\n print('Expected theta values (approx)\\n')\n print('-3.603\\n1.1664\\n')\n plt.plot([x], [y], 'rx', MarkerSize=7)\n plt.plot(X[:, 1], X.dot(theta), '-')\n # plt.legend('Training data', 'Linear regression')\n plt.xlabel('Population of City in 10,000s')\n plt.ylabel('Profit in $10,000s')\n plt.axis([4, 24, -5, 25])\n plt.show()\n predict1 = [1, 3.5]\n predict1 = np.dot(predict1, theta)\n print('For population = 35,000, we predict profit of ', (predict1*10000))\n predict2 = [1, 7]\n predict2 = np.dot(predict2, theta)\n print('For population = 70,000, we predict a profit of ', (predict2*10000))\n\n\n\n\n","sub_path":"single.py","file_name":"single.py","file_ext":"py","file_size_in_byte":1637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"231866653","text":"from util.config import ANEMONE_DATASET_STORE_PATH, ANEMONE_BERT_DATASET_FILE_NAME, ANEMONE_BERT_TRAIN_SET_FILE_NAME, ANEMONE_BERT_TEST_SET_FILE_NAME, ANEMONE_GENERAL_DATASET_FILE_NAME, EUREKA_REFINED_LABEL_STORE_PATH, JAVADOC_GLOBAL_NAME\nfrom util.concept_map.common import get_latest_concept_map\nfrom util.nel.common import get_api_name_from_entity_id\nfrom util.utils import get_html_text_except_code\nfrom bs4 import BeautifulSoup\nfrom tqdm import tqdm\n\nimport networkx as nx\nimport pickle\nimport re\nimport json\nimport random\nimport nltk\nimport os\n\n'''\n# 2021.4.14\n为新的ANEMONE准备数据集,主要做出以下改变\n1. 将context的sentence和prefix分开输入模型,模型自己可以决定利不利用prefix的信息\n2. entity的description不加入api的名字作为前缀,因为打算只做一个语境匹配模型\n'''\n\n\nCASE_THRESHOLD = 3\nMAX_LENGTH = 128\n\nconcept_map = get_latest_concept_map()\nNtype_attributes = nx.get_node_attributes(concept_map, 'Ntype')\nhref_attributes = nx.get_node_attributes(concept_map, 'local_href')\ndescription_attributes = nx.get_node_attributes(concept_map, 'description')\napi_entities = [\n node for node in concept_map if node in Ntype_attributes and node in href_attributes]\nnel_gt_entities = set()\nfor filename in os.listdir(EUREKA_REFINED_LABEL_STORE_PATH[JAVADOC_GLOBAL_NAME]):\n if filename.startswith('nel'):\n with open(os.path.join(EUREKA_REFINED_LABEL_STORE_PATH[JAVADOC_GLOBAL_NAME], filename), 'r', encoding='utf-8') as rf:\n entities = json.load(rf)\n for entity in entities:\n nel_gt_entities.add(entity)\n\nentity_gt_map = {} # 为了以entity为单位划分数据集(以得到更科学的precision),纪录每个entity的ground_truth, 用thread id_mention name的格式当key来特定是某个thread中的某个mention以防止mention重名\n\n\ndef get_memtion_key_in_entity_gt_map(thread_id, mention):\n return '_'.join([str(thread_id), mention])\n\n\ndef __process_post(context_thread: dict, post_html: str, mention: str, entity: str, label: int) -> list:\n '''\n 对一个单独的post处理生成数据项\n post_html: 问题或回答,html字符串\n '''\n global api_entities\n global description_attributes\n global nel_gt_entities\n global entity_gt_map\n global MAX_LENGTH\n ret = None\n if mention not in nel_gt_entities:\n return ret\n try:\n soup = BeautifulSoup(post_html, 'lxml')\n for pre in soup.find_all('pre'):\n pre.extract()\n if mention not in soup.text:\n return None\n sentences = nltk.sent_tokenize(soup.text)\n tags = ', '.join(context_thread['Tags'].strip(\n '<').strip('>').split('><'))\n title = context_thread['Title']\n prefix = tags + '. ' + title + '. '\n sentence_stack = []\n sentence = ''\n # 截取mention出现的一句话以及前面的若干句话加在一起作为sentence,保证整体句子长度不超过MAX_LENGTH\n for s in sentences:\n if mention in s:\n sentence = s # 2021.3.11 停止使用尽可能增加句子长度的做法,因为这样给模型带来了巨大的数据负担容易爆显存。。\n '''\n if mention in s:\n cur_length = len(nltk.word_tokenize(s))\n sentence = s\n if len(sentence_stack) == 0:\n break\n temp_s = sentence_stack.pop()\n while len(nltk.word_tokenize(temp_s)) + cur_length < MAX_LENGTH:\n sentence = temp_s + ' ' + sentence\n cur_length += len(nltk.word_tokenize(temp_s))\n if len(sentence_stack) == 0:\n break\n else:\n temp_s = sentence_stack.pop()\n break\n else:\n sentence_stack.append(s)\n '''\n if sentence == '':\n return None\n # sentence = prefix + ' ' + sentence\n # entity_desc = get_api_name_from_entity_id(entity) + ' description: ' + description_attributes[entity] # 原先的entity description是带api名字前缀的,后来决定用API名匹配+语境匹配的方式,ANEMONE只实现语境匹配,所以不加这个信息了\n entity_desc = description_attributes[entity]\n thread_id = context_thread['Id']\n ret = {\n 'prefix': prefix,\n 'sentence': sentence,\n 'mention': mention,\n 'entity_desc': entity_desc,\n 'entity': entity,\n 'label': label,\n 'thread_id': str(thread_id)\n }\n if label == 1:\n entity_gt_map[get_memtion_key_in_entity_gt_map(\n thread_id, mention)] = entity\n '''\n for sentence in sentences:\n if mention in sentence:\n ret.append({\n 'sentence': sentence,\n 'mention': mention,\n 'entity_desc': get_api_name_from_entity_id(entity) + ' description: ' + description_attributes[entity],\n 'label': label\n })\n '''\n except Exception as e:\n # print(e)\n return None\n return ret\n\n\ndef process_general_case(case: dict):\n '''\n 处理一个general的case变成BERT的训练集格式\n general的case长啥样见ANEMONE 1.1,1.2就不展示了\n '''\n ret = []\n context = case['context']\n posts = []\n posts.append(context['Body'])\n for answer in context['Answers']:\n posts.append(answer['Body'])\n for post in posts:\n data = __process_post(context,\n post, case['mention'], case['entity'], case['label'])\n if data is not None:\n ret.append(data)\n return ret\n\n\ndef __select_cases(cases: list, threshold: int) -> list:\n '''\n 对同一个mention,控制加入数据集的label为0的个数\n 在general的数据集中1一个label为1的有8个反例,感觉有点过多了不太能收敛\n 可以用这个函数调整label为0和1的数据的比例\n '''\n ret = [case for case in cases if case['label'] == 1]\n rest = [case for case in cases if case['label'] == 0]\n if threshold >= len(cases):\n return cases\n for i in range(threshold - 1):\n ret.append(rest[i])\n return ret\n\n\ndef generate_bert_dataset_from_general_dataset(general_dataset_file_path, target_doc=JAVADOC_GLOBAL_NAME):\n global CASE_THRESHOLD\n global entity_gt_map\n bert_dataset = []\n with open(general_dataset_file_path, \"r\", encoding=\"utf-8\") as rf, open(os.path.join(ANEMONE_DATASET_STORE_PATH[JAVADOC_GLOBAL_NAME], ANEMONE_BERT_DATASET_FILE_NAME), 'w', encoding=\"utf-8\") as wf, open(os.path.join(ANEMONE_DATASET_STORE_PATH[JAVADOC_GLOBAL_NAME], 'entity_gt_map.json'), 'w', encoding=\"utf-8\") as wf_gt:\n general_dataset = json.load(rf)\n cur_mention = ''\n temp_cases = []\n for case in tqdm(general_dataset):\n if case['mention'] == cur_mention:\n temp_cases.append(case)\n else:\n selected_cases = __select_cases(temp_cases, CASE_THRESHOLD)\n for c in selected_cases:\n bert_dataset.extend(\n process_general_case(c)\n )\n temp_cases = [case]\n cur_mention = case['mention']\n\n print(len(bert_dataset))\n wf.writelines([json.dumps(data, ensure_ascii=False) +\n '\\n' for data in bert_dataset])\n json.dump(entity_gt_map, wf_gt, ensure_ascii=False, indent=2)\n print(len(list(entity_gt_map.keys())))\n # json.dump(bert_dataset, wf, ensure_ascii=False, indent=2)\n with open(os.path.join(ANEMONE_DATASET_STORE_PATH[JAVADOC_GLOBAL_NAME], ANEMONE_BERT_TRAIN_SET_FILE_NAME), 'w', encoding=\"utf-8\") as wf_train, open(os.path.join(ANEMONE_DATASET_STORE_PATH[JAVADOC_GLOBAL_NAME], ANEMONE_BERT_TEST_SET_FILE_NAME), 'w', encoding=\"utf-8\") as wf_test:\n mentions = list(entity_gt_map.keys())\n random.shuffle(mentions)\n split_index = len(mentions) - len(mentions) // 10\n train_mentions = set(mentions[:split_index])\n test_mentions = set(mentions[split_index:])\n train_set = [\n case for case in bert_dataset if get_memtion_key_in_entity_gt_map(case['thread_id'], case['mention']) in train_mentions]\n test_set = [\n case for case in bert_dataset if get_memtion_key_in_entity_gt_map(case['thread_id'], case['mention']) in test_mentions]\n # random.shuffle(bert_dataset)\n # split_index = len(bert_dataset) - len(bert_dataset) // 10\n # train_set = bert_dataset[:split_index]\n # test_set = bert_dataset[split_index:]\n wf_train.writelines([json.dumps(data, ensure_ascii=False) +\n '\\n' for data in train_set])\n wf_test.writelines([json.dumps(data, ensure_ascii=False) +\n '\\n' for data in test_set])\n #json.dump(train_set, wf_train, indent=2, ensure_ascii=False)\n #json.dump(test_set, wf_test, indent=2, ensure_ascii=False)\n\n\nif __name__ == \"__main__\":\n generate_bert_dataset_from_general_dataset(os.path.join(\n ANEMONE_DATASET_STORE_PATH[JAVADOC_GLOBAL_NAME], ANEMONE_GENERAL_DATASET_FILE_NAME))\n","sub_path":"src/ANEMONE_1.35-prepare_BERT_NEL_dataset_refined_V2.py","file_name":"ANEMONE_1.35-prepare_BERT_NEL_dataset_refined_V2.py","file_ext":"py","file_size_in_byte":9358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"167404950","text":"import subprocess\n\n# 5. Выполнить пинг веб-ресурсов yandex.ru, youtube.com и преобразовать\n# результаты из байтовового в строковый тип на кириллице.\n\ndef ping_coding_UTF8(addr, requests):\n args = ['ping', addr, '-c', str(requests)]\n subproc_ping = subprocess.Popen(args, stdout=subprocess.PIPE)\n for line in subproc_ping.stdout:\n print(line.decode('utf-8'))\n\ndef main():\n request_counts = 4\n dest_addrs = ['yandex.ru', 'youtube.com',]\n for addr in dest_addrs:\n print('*' * 50, f'Пинг до {addr}', sep='\\n')\n ping_coding_UTF8(addr, requests=request_counts)\n\nif __name__ == '__main__':\n main()\n","sub_path":"lesson_1/homework_5.py","file_name":"homework_5.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"109634616","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations\n\n\ndef add_back_source_locales(apps, schema_editor):\n Locale = apps.get_model('base', 'Locale')\n Locale.objects.create(\n code='en',\n name='English',\n nplurals=2,\n plural_rule='(n != 1)',\n cldr_plurals='1,5'\n )\n Locale.objects.create(\n code='en-US',\n name='English',\n nplurals=2,\n plural_rule='(n != 1)',\n cldr_plurals='1,5'\n )\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('base', '0012_auto_20150804_0859'),\n ]\n\n operations = [\n migrations.RunPython(add_back_source_locales)\n ]\n","sub_path":"pontoon/base/migrations/0013_add_en_US.py","file_name":"0013_add_en_US.py","file_ext":"py","file_size_in_byte":703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"644964269","text":"# -*- coding: utf-8 -*-\n\nfrom __future__ import print_function\nfrom pprint import pprint\nimport re\nimport sys\nimport time\nimport boto3\nfrom botocore.exceptions import ClientError\n\n\nclass Task:\n def __init__(self,\n cluster='defaut', image='alpine', cmd='hostname',\n name=None, log_group=None, environment=[],\n region='ap-northeast-1',\n aws_access_key_id=None, aws_secret_access_key=None):\n if aws_access_key_id is not None and aws_secret_access_key is not None:\n self.ecs = boto3.client('ecs',\n region_name=region,\n aws_access_key_id=aws_access_key_id,\n aws_secret_access_key=aws_secret_access_key)\n self.logs = boto3.client('logs',\n region_name=region,\n aws_access_key_id=aws_access_key_id,\n aws_secret_access_key=aws_secret_access_key)\n else:\n self.ecs = boto3.client('ecs')\n self.logs = boto3.client('logs')\n self.name = name\n self.region = region\n self.cluster = cluster\n self.image = image\n self.cmd = cmd\n self.task_arn = None\n self.log_group = log_group\n self.memory = 300\n self.cpu = 0\n self.environment = environment\n\n def start(self, verbose=False):\n arn = self._get_task_definition_arn()\n if arn is None:\n arn = self._create_task_definition()\n if arn is None:\n return False\n\n containers = []\n command = []\n command.append('/bin/bash')\n command.append('-c')\n command.append(self.cmd)\n containers.append({\n 'name': self.task_name(),\n 'command': command\n })\n try:\n result = self.ecs.run_task(\n cluster=self.cluster,\n taskDefinition=arn,\n count=1,\n overrides={'containerOverrides': containers})\n if len(result['failures']) > 0:\n pprint(result['failures'])\n return False\n self.task_arn = result['tasks'][0]['taskArn']\n except self.ecs.exceptions.ClusterNotFoundException as e:\n print('cluster not found:', self.cluster, file=sys.stderr)\n return False\n\n if verbose:\n print('Task Details:', file=sys.stderr)\n print(('https://{region}.console.aws.amazon.com/ecs/home'\n '?region={region}#/clusters/{cluster}/tasks/{task}/details'\n ).format(\n region=self.region,\n cluster=self.cluster,\n task=self._task_id(self.task_arn)),\n file=sys.stderr)\n print('Task Logs:', file=sys.stderr)\n print(('https://{region}.console.aws.amazon.com/cloudwatch/home'\n '?region={region}#logEventViewer'\n ':group={group};stream={stream}').format(\n region=self.region,\n group=self._log_group(),\n stream=self._log_stream()),\n file=sys.stderr)\n return True\n\n def stop(self):\n self.ecs.stop_task(cluster=self.cluster, task=self.task_arn,\n reason='stop by ecs_task command')\n\n def is_finished(self):\n if self.task_arn is None:\n print('task_arn is None', file=sys.stderr)\n return True\n result = self.ecs.describe_tasks(cluster=self.cluster,\n tasks=[self.task_arn])\n if len(result['tasks']) == 0:\n print('missing task:', self.task_arn, file=sys.stderr)\n return False\n for task in result['tasks']:\n if task['lastStatus'] != 'STOPPED':\n return False\n return True\n\n def exit_code(self):\n if self.task_arn is None:\n print('task_arn is None', file=sys.stderr)\n return None\n result = self.ecs.describe_tasks(cluster=self.cluster,\n tasks=[self.task_arn])\n if len(result['tasks']) == 0:\n print('cannot find task', self.task_arn, file=sys.stderr)\n return None\n task = result['tasks'][0]\n if task['lastStatus'] != 'STOPPED':\n return None\n if 'stoppedReason' in task:\n if task['stoppedReason'] != 'Essential container in task exited':\n print(task['stoppedReason'], file=sys.stderr)\n for c in task['containers']:\n status = {'exitCode': 255}\n if 'exitCode' in c:\n status['exitCode'] = c['exitCode']\n if 'reason' in c:\n status['reason'] = re.sub(r'\\n+$', '', c['reason'])\n if len(result['failures']) > 0:\n status['failures'] = result['failures']\n return status\n return None\n\n def _task_id(self, arn):\n return re.sub(r'^[^/]+/', '', arn)\n\n def _log_stream(self):\n task_arn = self._task_id(self.task_arn)\n return '{prefix}/{taskDefinition}/{taskArn}'.format(\n prefix='ecs-task',\n taskDefinition=self.task_name(),\n taskArn=task_arn)\n\n def get_logs(self, start_at=0):\n log_stream = self._log_stream()\n streams = self.logs.describe_log_streams(\n logGroupName=self._log_group(),\n logStreamNamePrefix=log_stream)\n result = []\n for s in streams['logStreams']:\n events = {}\n events = self.logs.get_log_events(\n logGroupName=self._log_group(),\n logStreamName=s['logStreamName'],\n startTime=start_at+1)\n for e in events['events']:\n result.append({'message': e['message'],\n 'timestamp': e['timestamp']})\n return result\n\n def task_name(self):\n name = self.name\n if name is None:\n name = re.sub(r'[^a-zA-Z0-9_-]', '_', self.image)\n return \"rundeck-ecs-task-plugin-{name}\".format(name=name)\n\n def _get_task_definition_arn(self):\n arn = None\n try:\n result = self.ecs.describe_task_definition(\n taskDefinition=self.task_name())\n arn = result['taskDefinition']['taskDefinitionArn']\n except ClientError as e:\n msg = e.response['Error']['Message']\n if msg == 'Unable to describe task definition.':\n return None\n raise e\n return arn\n\n def _is_exists_log_group(self, name):\n arn = None\n groups = []\n try:\n result = self.logs.describe_log_groups(logGroupNamePrefix=name)\n groups = result['logGroups']\n except ClientError as e:\n return False\n return len(groups) > 0\n\n def _create_log_group(self, name):\n if self._is_exists_log_group(name):\n return True\n result = self.logs.create_log_group(logGroupName=name)\n return self._is_exists_log_group(name)\n\n def _log_group(self):\n if self.log_group is None:\n image = re.sub(r'[^a-zA-Z0-9_-]', '_', self.image)\n return '/rundeck/ecs/{cluster}/{image}/tasks'.format(\n cluster=self.cluster,\n image=image)\n return self.log_group\n\n def _create_task_definition(self):\n if not self._create_log_group(self._log_group()):\n max_retry = 60\n while not self._is_exists_log_group(self._log_group()):\n time.sleep(1)\n max_retry -= 1\n if max_retry <= 0:\n pprint('cannot create log group', file=sys.stderr)\n return None\n\n shaved_cmd = re.sub(r'[^a-zA-Z0-9/.-]', '_', self.cmd)\n stream_prefix = 'ecs-task'\n result = self.ecs.register_task_definition(\n family=self.task_name(),\n networkMode='bridge',\n containerDefinitions=[{\n 'cpu': self.cpu,\n 'name': self.task_name(),\n 'image': self.image,\n 'memory': self.memory,\n 'links': [],\n 'portMappings': [],\n 'volumesFrom': [],\n 'mountPoints': [],\n 'essential': True,\n 'environment': self.environment,\n 'logConfiguration': {\n 'logDriver': \"awslogs\",\n 'options': {\n 'awslogs-group': self._log_group(),\n 'awslogs-region': self.region,\n 'awslogs-stream-prefix': stream_prefix\n }\n }\n }],\n volumes=[],\n placementConstraints=[])\n return result['taskDefinition']['taskDefinitionArn']\n","sub_path":"contents/ecs.py","file_name":"ecs.py","file_ext":"py","file_size_in_byte":9139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"362478879","text":"import socket\nimport json\nimport cmath\nimport random\nfrom Crypto.Cipher import AES\n\nN = 32452867\n\n\ndef calc_exp(x):\n return cmath.exp(2j * cmath.pi * x / N)\n\n\nclientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nclientsocket.connect(('localhost', 8089))\n\nfirst_server_msg = clientsocket.recv(1024).decode('utf-8')\nprint(first_server_msg)\n\na = random.randint(0, 100) # private to client\nx_alice = calc_exp(a) # not secret\nclientsocket.send(bytes(json.dumps({\"alice_i\": x_alice.real, \"alice_j\": x_alice.imag}), \"UTF-8\"))\n\nd = json.loads(clientsocket.recv(1024).decode('utf-8'))\nx_bob = complex(d['bob_i'], d['bob_j'])\nprint(\"Read from Bob {}\".format(x_bob))\nx2 = x_bob ** a # alice's second computation\ncomputed_key = round((N * cmath.log(x2) / (2j * cmath.pi)).real)\nprint(\"\\033[1;31;40m Computed shared key: {}\".format(computed_key))\n\n# convert key to a 16 byte string\nextended_key = (str(computed_key) * (int(16 / len(str(computed_key))) + 1))[:16] # hack extension, not a secure key\ndec_suite = AES.new(extended_key, AES.MODE_ECB)\nenc = AES.new(extended_key, AES.MODE_ECB)\n\nwhile True:\n msg = input(\"Provide message for server:\\n\")\n msg = msg + ' ' * (16 - (len(msg) % 16))\n enc_msg = enc.encrypt(msg)\n assert (len(enc_msg) % 16 == 0)\n clientsocket.send(enc_msg)\n server_msg = clientsocket.recv(1024)\n if len(server_msg) > 0:\n dec_server_msg = dec_suite.decrypt(server_msg)\n print(\"Received from Bob: \\n\\tencrypted: {} \\n\\tdecrypted: {}\".format(server_msg, dec_server_msg))\n\n","sub_path":"dh_client.py","file_name":"dh_client.py","file_ext":"py","file_size_in_byte":1520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"284134358","text":"import pandas as pd\nimport matplotlib\ndata=pd.read_excel(\"presur.xlsx\",header=1)\nprint(data)\ndef average_of_los():\n \"\"\"average of all lo1,lo2,lo3,lo4,lo5,lo6 of all students in a list \"\"\"\n mylist=[]\n for i in range(1,7):\n mystring=\"LO\"+str(i)\n sum=data[mystring].mean()\n mylist.append(sum)\n return mylist\n\n#average_of_los()\n\ndef min_of_LO():\n \"\"\"minimum of all lo1,lo2,lo3,lo4,lo5,lo6 in a list\"\"\"\n mylist=[]\n for i in range(1,7):\n a=\"LO\"+str(i)\n min_lo=data[a].min()\n mylist.append(min_lo)\n return mylist\n\n# min_of_LO()\n\ndef max_of_LO():\n \"\"\"maximum of all lo1,lo2,lo3,lo4,lo5,lo6 in a list \"\"\"\n mylist=[]\n for i in range(1,7):\n a=\"LO\"+str(i)\n max_lo=data[a].max()\n mylist.append(max_lo)\n return mylist\n\n# max_of_LO()\n\ndef total_marks_of_student():\n \"\"\"Total marks of all students in a list\"\"\"\n mylist=[]\n for i in range(0,data.shape[0]):\n av=data.iloc[i,2:].sum()\n mylist.append(av) \n return mylist\n\n# total_marks_of_student()\n\n\ndef bottom_5_average():\n \"\"\"average of bottom 5 students of a all los in a list \"\"\"\n mylist=[]\n for i in range(1,7):\n string=\"LO\"+str(i)\n sort_data=data.sort_values(string)\n mea=data.iloc[0:5,i+1].mean()\n mylist.append(mea)\n return mylist\n\n\n# bottom_5_average()\n\n\ndef top_5_average():\n \"\"\"average of top 5 students of a all los in a list \"\"\"\n mylist=[]\n for i in range(1,7):\n string=\"LO\"+str(i)\n sort_data=data.sort_values(string,ascending=False)\n mea=data.iloc[0:5,i+1].mean()\n mylist.append(mea)\n return mylist\n\n\n#top_5_average()\n\n\ndef sum_of_marks():\n\n \"\"\" Total marks in all los of students in a list\"\"\"\n\n mylist=[]\n for i in range(0,data.shape[0]):\n s=data.iloc[i,2:].sum()\n mylist.append(s)\n return mylist\n\n\n# sum_of_marks()","sub_path":"3_Implementation/sdlc_project.py","file_name":"sdlc_project.py","file_ext":"py","file_size_in_byte":1900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"68735217","text":"import math\nimport logging\n\n# This class is only going to determine solar angles, solar radiation flux in rural area and emission from road\n# Solar radiation fluxes in urban area are calculated in the other class named \"SolarModel2\"\nclass SolarCalcs(object):\n \"\"\"\n SolarCalcs\n args:\n UCM # Urban Canopy - Building Energy Model object\n BEM # Building Energy Model object\n simTime # Simulation time bbject\n RSM # Rural Site & Vertical Diffusion Model Object\n forc # Forcing object\n parameter # Geo Param Object\n rural # Rural road Element object\n\n returns:\n rural\n UCM\n BEM\n \"\"\"\n\n def __init__(self,UCM,BEM,simTime,RSM,forc,parameter,rural):\n \"\"\" init solar calc inputs \"\"\"\n self.UCM = UCM\n self.BEM = BEM\n self.simTime = simTime\n self.RSM = RSM\n self.forc = forc\n self.parameter = parameter\n self.rural = rural\n\n # Logger will be disabled by default unless explicitly called in tests\n self.logger = logging.getLogger(__name__)\n\n def solarcalcs(self):\n \"\"\" Solar Calculation\n Mutates RSM, BEM, and UCM objects based on following parameters:\n UCM # Urban Canopy - Building Energy Model object\n BEM # Building Energy Model object\n simTime # Simulation time object\n RSM # Rural Site & Vertical Diffusion Model Object\n forc # Forcing object\n parameter # Geo Param Object\n rural # Rural road Element object\n\n Properties\n self.dir # Direct solar radiation [W m^-2]\n self.dif # Diffusive solar radiation [W m^-2]\n self.tanzen\n self.critOrient\n self.horSol\n self.Kw_term # Solar constant for wall [W m^-2]\n self.Kr_term # Solar constant for road [W m^-2]\n self.mr\n self.mw\n\n \"\"\"\n\n self.dir = self.forc.dir # Direct solar radiation [w m^-2]\n self.dif = self.forc.dif # Diffusive solar radiation [w m^-2]\n\n # Calculate fluxes during the day\n if self.dir + self.dif > 0.:\n\n self.logger.debug(\"{} Solar radiation > 0\".format(__name__))\n\n # Calculate solar angles\n self.solarangles()\n\n # Calculate direct horizontal radiation [W m^-2]\n self.horSol = max(math.cos(self.zenith)*self.dir, 0.0)\n '''\n # Fractional terms for wall & road\n self.Kw_term = min(abs(1./self.UCM.canAspect*(0.5-self.critOrient/math.pi) \\\n + 1/math.pi*self.tanzen*(1-math.cos(self.critOrient))),1.)\n self.Kr_term = min(abs(2.*self.critOrient/math.pi \\\n - (2/math.pi*self.UCM.canAspect*self.tanzen)*(1-math.cos(self.critOrient))), 1-2*self.UCM.canAspect*self.Kw_term)\n\n\n # Direct and diffuse solar radiation\n self.bldSol = self.horSol*self.Kw_term + self.UCM.wallConf*self.dif # Assume trees are shorter than buildings\n self.roadSol = self.horSol*self.Kr_term + self.UCM.roadConf*self.dif\n\n # Solar reflections. Add diffuse radiation from vegetation to alb_road if in season\n if self.simTime.month < self.parameter.vegStart or self.simTime.month > self.parameter.vegEnd:\n alb_road = self.UCM.road.albedo\n else:\n alb_road = self.UCM.road.albedo*(1.-self.UCM.road.vegCoverage) + self.parameter.vegAlbedo*self.UCM.road.vegCoverage\n\n # First set of reflections\n rr = alb_road * self.roadSol\n rw = self.UCM.alb_wall * self.bldSol\n\n # bounces\n fr = (1. - (1. - 2.*self.UCM.wallConf) * self.UCM.alb_wall + (1. - self.UCM.roadConf) \\\n * self.UCM.wallConf * alb_road * self.UCM.alb_wall)\n\n # (1.0-self.UCM.roadConf) road to wall view\n self.mr = (rr + (1.0-self.UCM.roadConf) * alb_road * (rw + self.UCM.wallConf * self.UCM.alb_wall * rr)) / fr\n self.mw = (rw + self.UCM.wallConf * self.UCM.alb_wall * rr) / fr\n\n # Receiving solar, including bounces (W m-2)\n self.UCM.road.solRec = self.roadSol + (1 - self.UCM.roadConf)*self.mw\n\n for j in xrange(len(self.BEM)):\n self.BEM[j].roof.solRec = self.horSol + self.dif\n self.BEM[j].wall.solRec = self.bldSol + (1 - 2*self.UCM.wallConf) * self.mw + self.UCM.wallConf * self.mr # ??????????\n '''\n self.rural.solRec = self.horSol + self.dif # Solar received by rural\n '''\n self.UCM.SolRecRoof = self.horSol + self.dif # Solar received by roof\n self.UCM.SolRecRoad = self.UCM.road.solRec # Solar received by road\n self.UCM.SolRecWall = self.bldSol+(1-2*self.UCM.wallConf)*self.UCM.road.albedo*self.roadSol # Solar received by wall\n \n # Vegetation heat (per m^2 of veg)\n self.UCM.treeSensHeat = (1-self.parameter.vegAlbedo)*(1-self.parameter.treeFLat)*self.UCM.SolRecRoad\n self.UCM.treeLatHeat = (1-self.parameter.vegAlbedo)*self.parameter.treeFLat*self.UCM.SolRecRoad\n '''\n\n\n else: # No Sun\n\n self.logger.debug(\"{} Solar radiation = 0\".format(__name__))\n '''\n self.UCM.road.solRec = 0.\n '''\n self.rural.solRec = 0.\n '''\n for j in xrange(len(self.BEM)):\n self.BEM[j].roof.solRec = 0.\n self.BEM[j].wall.solRec = 0.\n\n self.UCM.SolRecRoad = 0. # Solar received by road\n self.UCM.SolRecRoof = 0. # Solar received by roof\n self.UCM.SolRecWall = 0. # Solar received by wall\n \n self.UCM.treeSensHeat = 0.\n self.UCM.treeLatHeat = 0.\n '''\n\n return self.rural, self.UCM, self.BEM\n\n def solarangles (self):\n \"\"\"\n Calculation based on NOAA. Solves for zenith angle, tangent of zenithal angle,\n and critical canyon angle based on following parameters:\n canAspect # aspect Ratio of canyon\n simTime # simulation parameters\n RSM.lon # longitude (deg)\n RSM.lat # latitude (deg)\n RSM.GMT # GMT hour correction\n\n Properties\n self.ut # elapsed hours on current day\n self.ad # fractional year in radians\n self.eqtime\n self.decsol # solar declination angle\n self.zenith # Angle between normal to earth's surface and sun position\n self.tanzen # tangente of solar zenithal angle\n self.critOrient # critical canyon angle for which solar radiation reaches the road\n \"\"\"\n\n ln = self.RSM.lon\n\n month = self.simTime.month\n day = self.simTime.day\n secDay = self.simTime.secDay # Total elapsed seconds in simulation\n inobis = self.simTime.inobis # total days for first of month\n # i.e [0,31,59,90,120,151,181,212,243,273,304,334]\n canAspect = self.UCM.canAspect\n lon = self.RSM.lon\n lat = self.RSM.lat\n GMT = self.RSM.GMT\n\n self.ut = (24. + (int(secDay)/3600.%24.)) % 24. # Get elapsed hours on current day\n ibis = range(len(inobis))\n\n for JI in xrange(1,12):\n ibis[JI] = inobis[JI]+1\n\n date = day + inobis[month-1]-1 # Julian day of the year\n # divide circle by 365 days, multiply by elapsed days + hours\n self.ad = 2.0 * math.pi/365. * (date-1 + (self.ut-(12/24.))) # Fractional year (radians)\n\n self.eqtime = 229.18 * (0.000075+0.001868*math.cos(self.ad)-0.032077*math.sin(self.ad) - \\\n 0.01461*math.cos(2*self.ad)-0.040849*math.sin(2*self.ad))\n\n # Declination angle (angle of sun with equatorial plane)\n self.decsol = 0.006918-0.399912*math.cos(self.ad)+0.070257*math.sin(self.ad) \\\n -0.006758*math.cos(2.*self.ad)+0.000907*math.sin(2.*self.ad) \\\n -0.002697*math.cos(3.*self.ad)+0.00148 *math.sin(3.*self.ad)\n\n time_offset = self.eqtime - 4. * lon + 60 * GMT\n tst = secDay + time_offset * 60\n\n ha = (tst/4./60.-180.) * math.pi/180.\n zlat = lat * (math.pi/180.) # change angle units to radians\n self.radlat = zlat\n self.hh = ha\n # Calculate zenith solar angle\n self.zenith = math.acos(math.sin(zlat)*math.sin(self.decsol) + math.cos(zlat)*math.cos(self.decsol)*math.cos(ha))\n\n # tangente of solar zenithal angle\n if (abs(0.5*math.pi-self.zenith) < 1e-6):\n if(0.5*math.pi-self.zenith > 0.):\n self.tanzen = math.tan(0.5*math.pi-1e-6);\n\n if(0.5*math.pi-self.zenith <= 0.):\n self.tanzen = math.tan(0.5*math.pi+1e-6);\n\n elif (abs(self.zenith) < 1e-6):\n #TODO: Need to translate sign(1.,zenith) from matlab\n raise Exception(\"Error at zenith calc.\")\n #tanzen = sign(1.,zenith)*math.tan(1e-6);\n else:\n self.tanzen = math.tan(self.zenith)\n\n # critical canyon angle for which solar radiation reaches the road\n self.critOrient = math.asin(min(abs( 1./self.tanzen)/canAspect, 1. ))\n","sub_path":"UWG/solarcalcs.py","file_name":"solarcalcs.py","file_ext":"py","file_size_in_byte":9468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"350665909","text":"from random import choice, randint\nfrom firebase import firebase\nfrom player import Player\nfrom point_system import update_points, find_player\n\nfb = firebase.FirebaseApplication(\n 'https://discord-bot-db.firebaseio.com', None)\n\nenemies = [\n {\n 'name': 'Giant Gabagool',\n 'health': 93,\n },\n {\n 'name': 'Johnny Two Times',\n 'health': 22,\n },\n {\n 'name': 'John Deere Monky',\n 'health': 15\n },\n {\n 'name': 'DDOS Mundo',\n 'health': 66\n },\n {\n 'name': 'Bakugan',\n 'health': 30\n },\n {\n 'name': \"Waluigi's Legs\",\n 'health': 42\n },\n {\n 'name': 'Pineapple Bee Monster',\n 'health': 71,\n },\n {\n 'name': 'Big Clown',\n 'health': 48,\n },\n {\n 'name': 'Peanut Pete',\n 'health': 81\n },\n {\n 'name': 'Emotionally Unavailable Eddy',\n 'health': 99\n },\n {\n 'name': 'Big Bad Boy',\n 'health': 55\n },\n {\n 'name': 'Ultra Edison',\n 'health': 89\n },\n {\n 'name': 'Meatball Marinara',\n 'health': 64\n }\n]\n\n\ndef random_encounter() -> dict:\n encounter = choice(enemies)\n return encounter\n\n\ndef add_to_attacked(discord_id: str, boss=False, amount=None):\n if boss:\n boss = fb.get('/boss', None)\n if 'attacked' in boss:\n boss['attacked'][discord_id] = amount\n else:\n boss['attacked'] = {discord_id: amount}\n\n fb.patch(f'/boss/', boss)\n else:\n encounters = fb.get('/encounters', None)\n encounters_list = list(encounters.keys())\n encounter_key = encounters_list[0]\n encounter = encounters[encounter_key]\n if 'attacked' in encounter:\n encounter['attacked'][discord_id] = 0\n else:\n encounter['attacked'] = {discord_id: amount or 0}\n fb.patch(f'/encounters/{encounter_key}', encounter)\n\ndef combat_text(player, attacks, enemy, win=False, reward=0) -> str:\n weapon_text = ' (+10 from Nightmare Sword) ' if 'Nightmare Sword' in player['items'] else ''\n if win:\n if len(attacks) == 1:\n return f\"You rolled **{attacks[0]}**{weapon_text}and defeated **{enemy}**! You get **{reward}** points.\"\n elif len(attacks) == 2:\n first_attack, second_attack = attacks\n return f'''Your first attack of **{first_attack}**{weapon_text} failed, but using your _second sword_, you rolled **{second_attack}**{weapon_text}and defeated **{enemy}**! You get **{reward}** points.'''\n else:\n if len(attacks) == 1:\n return f\"You rolled **{attacks[0]}**{weapon_text}and lost to **{enemy}**. You get *nothing*.\"\n if len(attacks) == 2:\n first_attack, second_attack = attacks\n return f'''Your first attack of **{first_attack}**{weapon_text} failed, but your _second sword_ attack of **{second_attack}**{weapon_text}also failed to defeat **{enemy}**. Big Yikes.'''\n\ndef attack_enemy(discord_id: str) -> str:\n encounters = fb.get('/encounters', None)\n encounters_list = list(encounters.keys())\n # Check if there's an encounter\n if len(encounters_list) != 0:\n encounter = encounters[encounters_list[0]]\n\n # Check if this person has already attacked or if no one has attacked\n if 'attacked' not in encounter or discord_id not in encounter['attacked']:\n # Find player\n player = find_player(discord_id)\n\n # Roll attack\n attack = randint(1, 100)\n # Add 10 to attack if they have a sword\n attack += 10 if 'Nightmare Sword' in player['items'] else 0\n if attack > encounter['health']:\n # Calculate reward based on enemy health\n reward = get_reward(encounter['health'])\n # Find player and update points\n new_total = player['points'] + reward\n update_points(player, new_total)\n\n message = combat_text(player, [attack], encounter['name'], win=True, reward=reward)\n add_to_attacked(discord_id)\n return message\n else:\n # Try again if they have second sword\n if 'Second Sword' in player['items']:\n second_attack = randint(1, 100)\n second_attack += 10 if 'Nightmare Sword' in player['items'] else 0\n attacks = [attack, second_attack]\n\n if second_attack > encounter['health']:\n reward = get_reward(encounter['health'])\n new_total = player['points'] + reward\n update_points(player, new_total)\n message = combat_text(player, attacks, encounter['name'], win=True, reward=reward)\n add_to_attacked(discord_id)\n return message\n else:\n add_to_attacked(discord_id)\n message = combat_text(player, attacks, encounter['name'], win=False, reward=0)\n return message\n\n # user does not have any sword\n message = combat_text(player, [attack], encounter['name'], win=False, reward=0)\n add_to_attacked(discord_id)\n return message\n else:\n return f\"You've already attacked {encounters_list[0]}\"\n else:\n return \"There's no encounter right now!\"\n\n\ndef attack_boss(discord_id: str) -> str:\n boss = fb.get('/boss', None)\n # Check if there's a boss\n if boss:\n # Make sure user hasn't attacked\n if 'attacked' not in boss or discord_id not in boss['attacked']:\n player = Player(discord_id)\n # Generate normal attack\n attack = randint(1, 100)\n\n # Add modifiers\n if 'Nightmare Sword' in player.items:\n # Add 10 to attack\n attack += 10\n\n add_to_attacked(discord_id, boss=True, amount=attack)\n\n if 'attacked' in boss:\n attacks = boss['attacked']\n highest_attack = max(attacks.values())\n highest_attacker = max(attacks)\n\n return f'You attacked for **{attack}**! Current leader is <@{highest_attacker}> with **{highest_attack}**'\n else:\n return f'You attacked for **{attack}** and are the current leader!'\n else:\n return \"You've already attacked this boss!\"\n else:\n return \"There's no boss active right now!\"\n\ndef get_reward(health: int) -> int:\n base = health * 2\n modifier = choice(range(-20, 20))\n return base + modifier\n\n\nif __name__ == '__main__':\n # random_encounter()\n # attack('nothing')\n print(attack_enemy('200702104568987649'))\n # add_to_attacked('GreatBearShark', 50)\n # print(attack_boss('199772341679554561'))\n # boss = fb.get('/boss', None)\n # for player, attack in boss['attacked'].items():\n # print((player, attack))\n","sub_path":"combat_system.py","file_name":"combat_system.py","file_ext":"py","file_size_in_byte":7050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"76569595","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 countNodes(self, root):\n if not root:\n return 0\n \n left_height = right_height = 1\n p, q = root.left, root.right\n while p:\n p = p.left\n left_height += 1\n while q:\n q = q.right\n right_height += 1\n \n if left_height == right_height:\n return (1 << left_height) - 1\n else:\n return self.countNodes(root.left) + self.countNodes(root.right) + 1\n","sub_path":"python/Count Complete Tree Nodes.py","file_name":"Count Complete Tree Nodes.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"338810547","text":"from rest_framework.serializers import ModelSerializer\n\nfrom .models import GroupModel, UserGroupModel\n\n\nclass ShortGroupSerializer(ModelSerializer):\n class Meta:\n model = GroupModel\n fields = ['id', 'name']\n extra_kwargs = {'name': {'read_only': True}, 'id': {'read_only': True}}\n\n\nclass FullUserGroupSerializer(ModelSerializer):\n group = ShortGroupSerializer(read_only=True)\n\n class Meta:\n model = UserGroupModel\n fields = ['id', 'user', 'group']\n extra_kwargs = {'user': {'required': False}, 'id': {'read_only': True}}\n\n\nclass UserGroupSerializer(ModelSerializer):\n class Meta:\n model = UserGroupModel\n fields = ['id', 'user', 'group']\n\n\nclass GroupSerializer(ModelSerializer):\n users = UserGroupSerializer(many=True, required=False)\n\n class Meta:\n model = GroupModel\n fields = ['id', 'name', 'description', 'users']\n extra_kwargs = {'users': {'read_only': True}}\n\n\nclass ShortUserGroupSerializer(ModelSerializer):\n group = ShortGroupSerializer(many=True)\n\n class Meta:\n model = UserGroupModel\n fields = ['group']\n","sub_path":"backend/apps/group/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"627589878","text":"import pandas as pd\nfrom models.SIM import SIM\nimport utils\nfrom load_data import load_alldata\n\nuse_additional_data = True\nuse_ans = True\n\nmath_train = pd.read_json(r\"..\\Data\\dolphin-number_word_std\\number_word_std.dev.json\")\nif use_additional_data:\n additional_data = load_alldata()\n math_train = pd.concat([math_train[['text','ans','ans_simple','equations']],additional_data])\nmath_test = pd.read_json(r\"..\\Data\\dolphin-number_word_std\\number_word_std.test.json\")\n\nmodel = SIM()\nmodel.fit(math_train)\n\nprint(f'equation score on train: {model.equation_score(math_train)}')\nprint(f'equation score on test: {model.equation_score(math_test)}')\n\nprint(f'result score on train: {model.result_score(math_train,frac=0.1,verbose=False,use_ans=use_ans)}')\nprint(f'result score on test: {model.result_score(math_test,frac=1,verbose=True,use_ans=use_ans)}')\n\n#df.to_csv(r'..\\results\\error_analysis\\all_test_analysis.csv',index=False)\n","sub_path":"src/evaluation.py","file_name":"evaluation.py","file_ext":"py","file_size_in_byte":930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"225775388","text":"import sty\nimport _thread\n\n# Prints quaternions\ndef printQuaternions(q):\n print(q[0], q[1], q[2], q[3])\n\n# ---------------------------------------------------------------\n# IMU sensor\n# ---------------------------------------------------------------\n\n# Create the IMU sensor class\n# it takes some times to configure it\nimu = sty.Imu()\nprint('IMU sensor configured')\n\n# Create the filter class\nahrs = imu.Mahony(kp=1.5, ki=0.01)\n\n# Main application process\ndef app_proc():\n while True:\n # Update the filtered values (Mahony algorithm)\n printQuaternions(ahrs.update(imu.read()))\n\n# Start the application process\nif __name__ == \"__main__\":\n _thread.start_new_thread(app_proc, ())\n","sub_path":"imu/[04] - imu_mahony.py","file_name":"[04] - imu_mahony.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"117478913","text":"class LogicUnit:\n def __init__(self, type, *data):\n self.type = type\n if type == 'not':\n self.child = data[0]\n elif type == 'and' or type == 'or' or type == 'if' or type == 'iff':\n self.childA = data[0]\n self.childB = data[1]\n elif type == 'id':\n self.childA = data[0]\n self.childB = data[1]\n elif type == 'ex' or type == 'un':\n self.var = data[0]\n self.child = data[1]\n elif type == 'function':\n self.name = data[0]\n self.vars = data[1:]\n elif type == 'obj':\n self.name = data[0]\n else:\n raise Exception('Unknown type of LogicUnit: ' + type)\n self.parents = []\n self.children = []\n\n ops = {}\n\n def __str__(self):\n if self.type == 'not':\n return self.ops[self.type] + str(self.child)\n elif self.type == 'ex' or self.type == 'un':\n return '(' + self.ops[self.type] + str(self.var) + ')' + str(self.child)\n elif self.type == 'id':\n return str(self.childA) + self.ops[self.type] + str(self.childB)\n elif self.type == 'function':\n return str(self.name) + '(' + ', '.join([str(x) for x in self.vars]) + ')'\n elif self.type == 'obj':\n return self.name\n else:\n return '(' + str(self.childA) + self.ops[self.type] + str(self.childB) + ')'\n\n def __hash__(self):\n return str(self).__hash__()\n\n def not_len(self):\n x = self\n count = 0\n while x.type == 'not':\n count += 1\n x = x.child\n return count, x\n\n def __eq__(self, other):\n if self.type == other.type:\n if self.type == 'and' or self.type == 'or' or self.type == 'iff' or self.type == 'id':\n return (self.childA == other.childA and self.childB == other.childB) or \\\n (self.childA == other.childB and self.childB == other.childA)\n elif self.type == 'if':\n return self.childA == other.childA and self.childB == other.childB\n elif self.type == 'ex' or type == 'un':\n return self.var == other.var and self.child == other.child\n elif self.type == 'function':\n return self.name == other.name and len(self.vars) == len(other.vars) and\\\n all([x == y for x, y in zip(self.vars, other.vars)])\n elif self.type == 'not':\n a = self.not_len()\n b = other.not_len()\n return a[0] % 2 == b[0] % 2 and a[1] == b[1]\n elif self.type == 'obj':\n return self.name == other.name\n elif self.type == 'not':\n a = self.not_len()\n return a[0] % 2 == 0 and a[1] == other\n elif other.type == 'not':\n a = other.not_len()\n return a[0] % 2 == 0 and a[1] == self\n else:\n return False\n\n def substitute(self, other, subber):\n if self.type == 'not':\n ch = self.child.substitute(other, subber)\n if ch != self.child:\n return LogicUnit('not', ch)\n elif self.type == 'ex' or self.type == 'un':\n ch = self.child.substitute(other, subber)\n if ch != self.child:\n return LogicUnit(self.type, self.var, ch)\n elif self.type == 'function':\n children = [ch.substitute(other, subber) for ch in self.vars]\n if any([ch != sub for ch, sub in zip(self.vars, children)]):\n return LogicUnit(self.type, self.name, *children)\n elif self.type == 'obj':\n if self.name == other.name:\n return subber\n else:\n chA = self.childA.substitute(other, subber)\n chB = self.childB.substitute(other, subber)\n if chA != self.childA or chB != self.childB:\n return LogicUnit(self.type, chA, chB)\n return self\n\n def drop_var(self, subber):\n if self.type == 'ex' or self.type == 'un':\n return self.child.substitute(self.var, subber)\n return None\n\n def simplify_rule(self):\n if self.type == 'not':\n if self.child.type == 'not':\n return [self.child.child], 'DN'\n elif self.child.type == 'or':\n return [LogicUnit('not', self.child.childA), LogicUnit('not', self.child.childB)], 'NOR'\n elif self.child.type == 'if':\n return [self.child.childA, LogicUnit('not', self.child.childB)], 'NIF'\n elif self.child.type == 'iff':\n return [LogicUnit('not', LogicUnit('and', self.child.childA, self.child.childB)),\n LogicUnit('or', self.child.childA, self.child.childB)], 'NIFF'\n elif self.child.type == 'ex':\n return [LogicUnit('un', self.child.var, LogicUnit('not', self.child.child))], 'RS'\n elif self.child.type == 'un':\n return [LogicUnit('ex', self.child.var, LogicUnit('not', self.child.child))], 'RS'\n elif self.type == 'and':\n return [self.childA, self.childB], 'AND'\n elif self.type == 'iff':\n return [LogicUnit('if', self.childA, self.childB), LogicUnit('if', self.childB, self.childA)], 'IFF'\n return None, None\n\n def inference_rule(self, other):\n if self.type == 'if' and self.childA == other:\n return self.childB, 'MP'\n elif self.type == 'if' and LogicUnit('not', self.childB) == other:\n return LogicUnit('not', self.childA), 'MT'\n elif self.type == 'or' and LogicUnit('not', self.childA) == other:\n return self.childB, 'DS'\n elif self.type == 'or' and LogicUnit('not', self.childB) == other:\n return self.childA, 'DS'\n elif self.type == 'not' and self.child.type == 'and' and self.child.childA == other:\n return LogicUnit('not', self.child.childB), 'CS'\n elif self.type == 'not' and self.child.type == 'and' and self.child.childB == other:\n return LogicUnit('not', self.child.childA), 'CS'\n return None, None\n\n def substitute_equals(self, other):\n if self.type == 'id':\n A = other.substitute(self.childA, self.childB)\n B = other.substitute(self.childB, self.childA)\n if A != other and B != other:\n return A, B, 'SE'\n if A != other:\n return A, None, 'SE'\n if B != other:\n return B, None, 'SE'\n return None, None, None\n\n def auto_assume(self):\n if self.type == 'not' and self.child.type == 'and':\n return self.child.childA, self.child.childB\n elif self.type == 'or':\n return LogicUnit('not', self.childA), LogicUnit('not', self.childB)\n elif self.type == 'if':\n return self.childA, LogicUnit('not', self.childB)\n else:\n return None, None\n\n\nclass Logic:\n \"\"\"\n First order automatic logic prover\n \n Initialization:\n stmts = logical statements to be parsed\n l_, q_ = the symbols to be used for each logical operation while being parsed, and printed\n auto = whether the user or the program should create assumptions while proving\n new_var = function to be used for generating new varible strings when needed in proving, if not given then the user\n will be asked for new ones\n \n Functions: (to be accessed by the user)\n proof() = creates the proof\n print_proof()\n\n Grammar:\n l_not='¬', l_and='∧', l_or='∨', l_if='→', l_iff='↔', q_id='=', q_ex='∃', q_un='∀'\n\n \"\"\"\n def __init__(self, *stmts, l_not='¬', l_and='∧', l_or='∨', l_if='→', l_iff='↔', q_id='=', q_ex='∃', q_un='∀', auto=True, new_var=None):\n # setup syntax\n self.l_not = l_not\n self.l_and = l_and\n self.l_or = l_or\n self.l_if = l_if\n self.l_iff = l_iff\n self.ops = {l_and: 'and', l_or: 'or', l_if: 'if', l_iff: 'iff'}\n self.q_id = q_id\n self.q_ex = q_ex\n self.q_un = q_un\n self.qunta = {q_id: 'id', q_ex: 'ex', q_un: 'un'}\n LogicUnit.ops = {'not': l_not, 'and': l_and, 'or': l_or, 'if': l_if, 'iff': l_iff, 'id': q_id, 'ex': q_ex, 'un': q_un}\n # setup state\n self.stmts = stmts\n self.functions = set()\n self.objs = set()\n self.vars = set()\n # parsing details\n self.current = ''\n self.tok = ''\n # setup state for prooving\n self.logic = [self.parse(x) for x in self.stmts[:-1]]\n self.concl = self.parse(self.stmts[-1])\n self.contradiction = False\n self.contradiction_couple = []\n self.assuming = set(self.logic)\n self.available = set(self.logic)\n self.usable = set(self.logic)\n self.all = [(x, 'PREMISE') for x in self.logic]\n self.auto = auto\n self.new_var = new_var\n\n def parse_next(self):\n self.current = self.current[1:]\n if self.current:\n self.tok = self.current[0]\n else:\n self.tok = None\n\n def parse_eq(self, other):\n return self.tok == other\n\n def parse_match(self, other):\n if self.parse_eq(other):\n self.parse_next()\n else:\n raise Exception('Expected ' + other + ', but found ' + self.tok + 'in[' + self.current + ']')\n\n def parse_string(self):\n buf = ''\n while self.tok and self.tok in 'qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM0123456789':\n buf += self.tok\n self.parse_next()\n return LogicUnit('obj', buf)\n\n def parse(self, stmt):\n self.current = stmt\n self.tok = stmt[0]\n return self.parse_stmt()\n\n def parse_stmt(self):\n if self.parse_eq('('):\n self.parse_next()\n if self.parse_eq(self.q_ex) or self.parse_eq(self.q_un):\n qu = self.qunta[self.tok]\n self.parse_next()\n var = self.parse_string()\n self.vars.add(var)\n self.parse_match(')')\n return LogicUnit(qu, var, self.parse_stmt())\n a = self.parse_stmt()\n if self.tok not in self.ops:\n raise Exception('Expected logical connective')\n op = self.ops[self.tok]\n self.parse_next()\n b = self.parse_stmt()\n self.parse_match(')')\n return LogicUnit(op, a, b)\n elif self.parse_eq(self.l_not):\n self.parse_next()\n return LogicUnit('not', self.parse_stmt())\n else:\n a = self.parse_string()\n if self.parse_eq('('):\n self.functions.add(a)\n self.parse_next()\n v = self.parse_string()\n self.objs.add(v)\n var = [v]\n while self.parse_eq(','):\n self.parse_next()\n v = self.parse_string()\n self.objs.add(v)\n var.append(v)\n self.parse_match(')')\n return LogicUnit('function', a, *var)\n self.objs.add(a)\n if self.parse_eq(self.q_id):\n self.parse_next()\n b = self.parse_string()\n self.objs.add(b)\n return LogicUnit('id', a, b)\n return a\n\n def new_obj(self):\n if self.new_var:\n return self.new_var()\n print(\"Type new variable:\")\n add = LogicUnit('obj', input())\n self.objs.add(add)\n return add\n\n def add_stmt(self, stmt, rule):\n self.usable.add(stmt)\n self.assuming.add(stmt)\n self.available.add(stmt)\n self.all.append((stmt, rule))\n if LogicUnit('not', stmt) in self.available:\n self.contradiction_couple = [stmt, LogicUnit('not', stmt)]\n self.contradiction = True\n\n def assume(self, assumption):\n temp, self.assuming = self.assuming, set()\n non_used = self.usable.copy()\n self.add_stmt(assumption, 'ASM')\n return temp, non_used\n\n def unassume(self, assumption, temp, non_used):\n self.available -= self.assuming\n self.assuming = temp\n self.usable |= non_used\n unit = LogicUnit('not', assumption)\n unit.parents = [assumption] + self.contradiction_couple\n self.add_stmt(unit, 'ConD')\n\n def remove_assumption(self):\n self.all = self.all[:len(self.assuming)-1]\n self.usable -= self.assuming\n self.available -= self.assuming\n self.assuming = set()\n\n def get_parents(self):\n self.all.reverse()\n parental = {self.all[0][0]}\n for stmt, rule in self.all:\n if stmt in parental:\n for p in stmt.parents:\n parental.add(p)\n self.all.reverse()\n return parental\n\n def contradict_prove(self, assumption):\n while self.prove_loop():\n if self.contradiction:\n self.contradiction = False\n return True\n for log in self.available:\n for other in self.available:\n if LogicUnit('not', log) == other:\n self.contradiction_couple = [log, LogicUnit('not', log)]\n self.contradiction = False\n return True\n if self.auto:\n for log in self.usable:\n opA, opB = log.auto_assume()\n if opA:\n temp, non_used = self.assume(opA)\n if self.contradict_prove(opA):\n self.unassume(opA, temp, non_used)\n return self.contradict_prove(assumption)\n else:\n self.remove_assumption()\n self.add_stmt(opB, 'ASM')\n if self.contradict_prove(opB):\n self.unassume(opB, temp, non_used)\n return self.contradict_prove(assumption)\n else:\n self.remove_assumption()\n self.assuming = temp\n else:\n print(\"Out of options, either reject proof or make an assumption\")\n print(\"type: p(print out incomplete proof), y(will then be asked to type assumption), n(stop process)\")\n x = input()\n while x != 'n':\n if x == 'p':\n print(self.proof_str())\n elif x == 'y':\n print('type assumption to be made')\n assumption = input()\n stmt = self.parse(assumption)\n temp, non_used = self.assume(stmt)\n print(stmt)\n if self.contradict_prove(stmt):\n self.unassume(stmt, temp, non_used)\n return self.contradict_prove(assumption)\n return False\n else:\n print(\"unknown command\")\n x = input()\n return False\n\n def prove_loop(self):\n for log in self.usable:\n sim, rule = log.simplify_rule()\n if sim:\n log.children += sim\n self.usable.remove(log)\n for stmt in sim:\n stmt.parents = [log]\n self.add_stmt(stmt, rule)\n return True\n for other in self.available:\n inf, rule = log.inference_rule(other)\n if inf:\n log.children.append(inf)\n other.children.append(inf)\n inf.parents = [log, other]\n self.usable.remove(log)\n self.add_stmt(inf, rule)\n return True\n seA, seB, rule = log.substitute_equals(other)\n if seA and seA not in self.available:\n log.children.append(seA)\n seA.parents.append(log)\n self.add_stmt(seA, rule)\n if seB and seB not in self.available:\n log.children.append(seB)\n seB.parents.append(log)\n self.add_stmt(seB, rule)\n return True\n if seB and seB not in self.available:\n log.children.append(seB)\n seB.parents.append(log)\n self.add_stmt(seB, rule)\n return True\n if log.type == 'ex':\n new_var = self.new_obj()\n stmt = log.drop_var(new_var)\n log.children.append(stmt)\n stmt.parents.append(log)\n self.usable.remove(log)\n self.add_stmt(stmt, 'DE[' + new_var.name + '|' + log.var.name + ']')\n return True\n if log.type == 'un':\n for v in self.objs:\n stmt = log.drop_var(v)\n if stmt not in self.available:\n log.children.append(stmt)\n stmt.parents.append(log)\n self.add_stmt(stmt, 'DU[' + v.name + '|' + log.var.name + ']')\n return True\n for log in self.usable:\n if log.type == 'un':\n print(\"Create new var for: \" + str(log) + \"?\")\n print(\"Type: y(Yes) or n(No)\")\n if input() == 'y':\n new_var = self.new_obj()\n stmt = log.drop_var(new_var)\n log.children.append(stmt)\n stmt.parents.append(log)\n self.usable.remove(log)\n self.add_stmt(stmt, 'DU[' + new_var.name + '|' + log.var.name + ']')\n return True\n return False\n\n def proof(self):\n assumption = LogicUnit('not', self.concl)\n self.add_stmt(assumption, 'ASM')\n if self.contradict_prove(assumption):\n unit = LogicUnit('not', assumption)\n unit.parents = [assumption] + self.contradiction_couple\n self.add_stmt(unit, 'ConD')\n return True\n return False\n\n def proof_str(self):\n i = 0\n temp = self.get_parents()\n new_all = [x for x in self.all if x[0] in temp]\n units = [x[0] for x in new_all]\n proof_string = ''\n for stmt, rule in new_all:\n i += 1\n proof_string += \"{} {!s} {} {}\\n\".format(i, stmt, rule, ', '.join([str(units.index(x)+1) for x in stmt.parents]))\n return proof_string\n\n\ntest = Logic('(P↔¬(Q→P))', '(¬P→R)', '(¬P∧R)', auto=True)\ntest.proof()\nprint(test.proof_str())","sub_path":"fol.py","file_name":"fol.py","file_ext":"py","file_size_in_byte":18742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"592652560","text":"import scipy.stats as st\nimport sys\nimport itertools\nfrom collections import defaultdict\nfrom operator import itemgetter\nimport string\nimport random\nimport scipy.stats as stats\nfrom typing import Tuple, List\nfrom sklearn.cluster import AffinityPropagation\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nfrom sklearn.preprocessing import OrdinalEncoder\nfrom sklearn import datasets\n\n\n\n\ndef plot_feature_importance(importance, names, model_type, xlabel='SHAP values', title=' '):\n # Create arrays from feature importance and feature names\n feature_importance = np.array(importance)\n feature_names = np.array(names)\n\n # Create a DataFrame using a Dictionary\n data = {'feature_names': feature_names, 'feature_importance': feature_importance}\n fi_df = pd.DataFrame(data)\n\n # Sort the DataFrame in order decreasing feature importance\n fi_df.sort_values(by=['feature_importance'], ascending=False, inplace=True)\n\n # Define size of bar plot\n plt.figure(figsize=(10, 8))\n # Plot Searborn bar chart\n sns.barplot(x=fi_df['feature_importance'], y=fi_df['feature_names'])\n # Add chart labels\n plt.title(title)\n plt.xlabel(xlabel)\n plt.ylabel('FEATURE NAMES')\n\n\ndef plot_feature_importance_10(importance, names, model_type, xlabel='SHAP values', title=' '):\n # Create arrays from feature importance and feature names\n feature_importance = np.array(importance)\n feature_names = np.array(names)\n seaborn_colors = sns.color_palette(\"tab10\")\n colors = {names[i]: seaborn_colors[i] for i in range(len(names))}\n\n # Create a DataFrame using a Dictionary\n data = {'feature_names': feature_names, 'feature_importance': feature_importance}\n fi_df = pd.DataFrame(data)\n\n # Sort the DataFrame in order decreasing feature importance\n fi_df.sort_values(by=['feature_importance'], ascending=False, inplace=True)\n\n # Define size of bar plot\n plt.figure(figsize=(10, 8))\n sns.set(font_scale=1.5)\n # Plot Searborn bar chart\n sns.barplot(x=fi_df['feature_importance'], y=fi_df['feature_names'], palette=colors)\n # Add chart labels\n plt.title(title)\n plt.xlabel(xlabel)\n plt.ylabel('FEATURE NAMES')\n\n\ndef bar_plot(values_1, values_2, values_3, labels, variables_name, title):\n x = np.arange(len(variables_name)) # the label locations\n width = 0.2 # the width of the bars\n\n fig, ax = plt.subplots(dpi=250)\n rects1 = ax.bar(x - width / 2, values_1, width, label=labels[0])\n rects2 = ax.bar(x + width / 2, values_2, width, label=labels[1])\n rects3 = ax.bar(x + 1.5 * width, values_3, width, label=labels[2])\n\n # Add some text for labels, title and custom x-axis tick labels, etc.\n ax.set_ylabel('Shapley values')\n ax.set_title(title)\n ax.set_xticks(x)\n ax.set_xticklabels(variables_name)\n ax.legend()\n\n def autolabel(rects):\n \"\"\"Attach a text label above each bar in *rects*, displaying its height.\"\"\"\n for rect in rects:\n height = rect.get_height()\n ax.annotate('{}'.format(height),\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', color='black')\n\n autolabel(rects1)\n autolabel(rects2)\n autolabel(rects3)\n\n fig.tight_layout()\n\n plt.show()\n\n\ndef compute_fcluster_bydistance(data, dist_type='kendall'):\n d = data.shape[1]\n if dist_type == 'kendall':\n dist_matrix = np.zeros((d, d))\n for i in range(d):\n for j in range(d):\n tau, p_value = stats.kendalltau(data[:, i], data[:, j])\n dist_matrix[i, j] = tau\n elif dist_type == 'corr':\n dist_matrix = np.cov(data.T)\n else:\n raise ValueError(\"This type of distance is not implemented\")\n\n # print(dist_matrix)\n clustering = AffinityPropagation(random_state=5)\n coal_idx = clustering.fit_predict(np.abs(dist_matrix))\n coal = []\n for c in np.unique(coal_idx):\n t = np.argwhere(c == coal_idx)\n t = list(t.reshape(-1))\n coal.append(t)\n return coal\n\n\ndef ecart_model(model, X, y):\n y_predict = model.predict(X)\n error = (y_predict - y) ** 2\n print('mse = {} -- max = {} -- min = {} -- q0.95 = {} -- q0.25 {}'.format(np.mean(error),\n np.max(error),\n np.min(error),\n np.quantile(error, 0.95),\n np.quantile(error, 0.5)))\n return np.mean(error), np.quantile(error, 0.95), np.quantile(error, 0.25)\n\n\ndef get_given_data(x, idx, N):\n val = np.array([x[idx]])\n val = np.tile(val, N)\n return val\n\n\n# def gen_data_by_cat(x_in, cat_va, prob, N, S, S_bar):\n# # to do: make it real function of S, c_index, etc\n#\n# mixture_idx = np.random.choice(cat_va, size=N, replace=True, p=prob)\n#\n# rg = {key: sampleMVN(np.sum(mixture_idx == key), self.mean[key],\n# self.cov[key], S_bar, S, x_in[S]) for key in cat_va\n# if np.sum(mixture_idx == key) != 0}\n#\n# rg = np.concatenate([np.concatenate([rg[key], np.tile(self.dummy[key],\n# (np.sum(mixture_idx == key), 1))], axis=1) for key in\n# rg.keys()])\n#\n# rg_data = pd.DataFrame(rg, columns=[str(s) for s in S_bar] + [str(ca) for ca in self.cat_index])\n#\n# for val_id in S:\n# rg_data[str(val_id)] = get_given_data(val_id)\n#\n# rg_data = rg_data[sorted(rg_data.columns)]\n# return rg_data\n\n\ndef nb_row(row, up, low, S):\n return np.prod([(row[s] <= up[s]) * (row[s] > low[s]) for s in S])\n\n\ndef get_partition_tree(tree, leaf_id, part):\n a = tree.children_left.copy()\n b = tree.children_right.copy()\n f = tree.feature.copy()\n t = tree.threshold.copy()\n r_w = tree.weighted_n_node_samples.copy()\n r = tree.n_node_samples.copy()\n left = np.where(tree.children_left == leaf_id)[0]\n right = np.where(tree.children_right == leaf_id)[0]\n\n if (len(left) == 0) * (len(right) == 0):\n return (part)\n\n else:\n if len(right) != 0:\n right = int(right[0])\n\n part[f[right]] = np.concatenate((part[f[right]], np.array([[t[right], np.inf]])))\n return get_partition_tree(tree, right, part)\n else:\n left = int(left[0])\n part[f[left]] = np.concatenate((part[f[left]], np.array([[-np.inf, t[left]]])))\n return get_partition_tree(tree, left, part)\n\n\ndef get_final_partition(part):\n final_partition = {}\n for i, var_part in enumerate(part):\n final_partition[i] = [np.max(var_part[:, 0]), np.min(var_part[:, 1])]\n return final_partition\n\n\ndef leaves_proba(tree, leaf_id, data, S):\n partition_leaves = [np.array([[-np.inf, np.inf]]) for i in range(data.shape[1])]\n partition_leaves = get_partition_tree(tree, leaf_id, partition_leaves)\n partition_leaves = pd.DataFrame(get_final_partition(partition_leaves))[S]\n\n low = partition_leaves.iloc[0]\n up = partition_leaves.iloc[1]\n\n section_x = np.prod([(data[:, s] <= up[s]) * (data[:, s] >= low[s]) for s in S], axis=0)\n return np.sum(section_x)\n\n\ndef l1_norm(x, dim=1):\n return np.sum(np.abs(x), axis=1)\n\n\ndef rebuild_tree(parent_id, tree, data, y):\n tree.weighted_n_node_samples[parent_id] = len(data)\n tree.value[parent_id][0][0] = np.mean(y)\n\n if tree.children_right[parent_id] < 0:\n return 0\n else:\n right = tree.children_right[parent_id]\n left = tree.children_left[parent_id]\n\n left_cond = data[:, tree.feature[parent_id]] <= tree.threshold[parent_id]\n data_left = data[left_cond]\n y_left = y[left_cond]\n\n right_cond = data[:, tree.feature[parent_id]] > tree.threshold[parent_id]\n data_right = data[right_cond]\n y_right = y[right_cond]\n\n rebuild_tree(left, tree, data_left, y_left)\n rebuild_tree(right, tree, data_right, y_right)\n\ndef rebuild_acvtree(parent_id, tree, data, y):\n tree.node_sample_weight[parent_id] = data.shape[0]\n tree.values[parent_id] = np.mean(y, axis=0)\n\n if tree.children_right[parent_id] < 0:\n return 0\n else:\n right = tree.children_right[parent_id]\n left = tree.children_left[parent_id]\n\n left_cond = data[:, tree.features[parent_id]] <= tree.thresholds[parent_id]\n data_left = data[left_cond]\n y_left = y[left_cond]\n\n right_cond = data[:, tree.features[parent_id]] > tree.thresholds[parent_id]\n data_right = data[right_cond]\n y_right = y[right_cond]\n\n rebuild_acvtree(left, tree, data_left, y_left)\n rebuild_acvtree(right, tree, data_right, y_right)\n\n\ndef condMVN(mean, cov, set_bar, set, x):\n if set == []:\n return mean, cov\n else:\n mean_cond = mean[set_bar] + np.matmul(np.matmul(cov[set_bar][:, set],\n np.linalg.inv(cov[set][:, set])), x - mean[set])\n\n cov_cond = cov[set_bar][:, set_bar] - np.matmul(\n np.matmul(cov[set_bar][:, set], np.linalg.inv(cov[set][:, set])),\n cov[set][:, set_bar])\n\n return mean_cond, cov_cond\n\n\ndef marMVN(mean, cov, set_bar, set, x):\n if set == []:\n return mean, cov\n else:\n mean_cond = mean[set_bar]\n cov_cond = cov[set_bar][:, set_bar]\n return mean_cond, cov_cond\n\n\ndef sampleMVN(n, mean, cov, set_bar, set, x):\n mean_cond, cov_cond = condMVN(mean, cov, set_bar, set, x)\n sample = st.multivariate_normal(mean_cond, cov_cond).rvs(n)\n return np.reshape(sample, (n, len(set_bar)))\n\n\ndef sampleMarMVN(n, mean, cov, set_bar, set):\n mean_cond, cov_cond = marMVN(mean, cov, set_bar, set)\n sample = st.multivariate_normal(mean_cond, cov_cond).rvs(n)\n return np.reshape(sample, (n, len(set_bar)))\n\n\ndef chain_l(l):\n chain = []\n if type(l) == tuple:\n for it in l:\n if type(it) != list:\n chain.append(it)\n elif type(it) == list and len(it) > 1:\n chain = chain + it\n else:\n raise ValueError('problem...')\n else:\n chain = l\n return chain\n\n\ndef convert_list(l):\n if type(l) == list:\n return l\n else:\n return [l]\n\n\ndef convert_tuple(l):\n if type(l) == tuple:\n return l\n elif type(l) == list:\n return tuple(l)\n else:\n return (l,)\n\n\ndef linear_regression(coefs, x):\n return np.sum(coefs * x, axis=1)\n\n\ndef linear_regression_0(coefs, x):\n return np.sum(coefs * x)\n\n\n# utils for classifer data generation\n\n\ndef return_positive_semi_definite_matrix(n_dim: int) -> np.ndarray:\n \"\"\"Return positive semi-definite matrix.\n\n Args:\n n_dim (int): size of square matrix to return\n Returns:\n p (np.array): positive semi-definite array of shape (n_dim, n_dim)\n \"\"\"\n m = np.random.randn(n_dim, n_dim)\n p = np.dot(m, m.T)\n return p\n\n\ndef sigmoid(x: np.array) -> np.array:\n \"\"\"Return sigmoid(x) for some activations x.\n\n Args:\n x (np.array): input activations\n Returns:\n s (np.array): sigmoid(x)\n \"\"\"\n s = 1 / (1 + np.exp(-x))\n return s\n\n\ndef return_weak_features_and_targets(\n num_features: int,\n num_samples: int,\n mixing_factor: float,\n) -> Tuple[np.array, np.array, np.array, np.array]:\n \"\"\"Return weakly predictive features and a target variable.\n\n Create a multivariate Gaussian-distributed set of features and a\n response variable that is conditioned on a weighted sum of the features.\n\n Args:\n num_features (int): number of variables in Gaussian distribution\n num_samples (int): number of samples to take\n mixing_factor (float): squashes the weighted sum into the linear\n regime of a sigmoid. Smaller numbers squash closer to 0.5.\n Returns:\n X (np.array): weakly predictive continuous features\n (num_samples, num_features)\n Y (np.array): targets (num_samples,)\n \"\"\"\n\n cov = return_positive_semi_definite_matrix(num_features)\n X = np.random.multivariate_normal(mean=np.zeros(num_features), cov=cov, size=num_samples)\n\n weights = np.random.randn(num_features)\n y_probs = sigmoid(mixing_factor * np.dot(X, weights))\n y = np.random.binomial(1, p=y_probs)\n return X, y, cov, weights\n\n\ndef return_c_values(cardinality: int) -> Tuple[list, list]:\n \"\"\"Return categorical values for C+ and C-.\n\n Create string values to be used for the categorical variable c.\n We build two sets of values C+ and C-. All values from C+ end with\n \"A\" and all values from C- end with \"B\". The cardinality input\n determines len(c_pos) + len(c_neg).\n\n Args:\n cardinality (int): cardinality of c\n Returns:\n c_pos (list): categorical values from C+ sample\n c_neg (list): categorical values from C- sample\n \"\"\"\n suffixes = [\n \"{}{}\".format(i, j)\n for i in string.ascii_lowercase\n for j in string.ascii_lowercase]\n c_pos = [\"{}A\".format(s) for s in suffixes][:int(cardinality / 2)]\n c_neg = [\"{}B\".format(s) for s in suffixes][:int(cardinality / 2)]\n return c_pos, c_neg\n\n\ndef return_strong_features(\n y_vals: np.array,\n cardinality: int,\n z_pivot: int = 10\n) -> Tuple[np.array, np.array]:\n \"\"\"Return strongly predictive features.\n\n Given a target variable values `y_vals`, create a categorical variable\n c and continuous variable z such that y is perfectly predictable from\n c and z, with y = 1 iff c takes a value from C+ OR z > z_pivot.\n\n Args:\n y_vals (np.array): targets\n cardinality (int): cardinality of the categorical variable, c\n z_pivot (float): mean of z\n Returns:\n c (np.array): strongly predictive categorical variable\n z (np.array): strongly predictive continuous variable\n \"\"\"\n z = np.random.normal(loc=z_pivot, scale=5, size=2 * len(y_vals))\n z_pos, z_neg = z[z > z_pivot], z[z <= z_pivot]\n c_pos, c_neg = return_c_values(cardinality)\n c, z = list(), list()\n for y in y_vals:\n coin = np.random.binomial(1, 0.5)\n if y and coin:\n c.append(random.choice(c_pos + c_neg))\n z.append(random.choice(z_pos))\n elif y and not coin:\n c.append(random.choice(c_pos))\n z.append(random.choice(z_neg))\n else:\n c.append(random.choice(c_neg))\n z.append(random.choice(z_neg))\n return np.array(c), np.array(z)\n\n\ndef return_main_dataset(\n num_weak: int,\n num_samp: int,\n cardinality: int = 100,\n mixing_factor: float = 0.025,\n) -> Tuple[pd.DataFrame, np.array, np.array]:\n \"\"\"Generate training samples.\n\n Generate a dataset with features c and z that are perfectly predictive\n of y and additional features x_i that are weakly predictive of y and\n correlated with eachother.\n\n Args:\n num_weak (int): number of weakly predictive features x_i to create\n num_samp (int): number of sample to create\n cardinality (int): cardinality of the predictive categorical variable.\n half of these values will be correlated with y=1 and the other\n with y=0.\n mixing_factor (float): see `return_weak_features_and_targets`\n Returns:\n df (pd.DataFrame): dataframe with y, z, c, and x_i columns\n \"\"\"\n X, y, cov, weights = return_weak_features_and_targets(num_weak, num_samp, mixing_factor)\n c, z = return_strong_features(y, cardinality)\n xcol_names = ['x{}'.format(i) for i in range(num_weak)]\n df = pd.DataFrame(X, columns=xcol_names)\n df['y'] = y\n df['z'] = z\n df['c'] = c\n df['c'] = df['c'].astype('category')\n df = df[['y', 'c', 'z'] + xcol_names]\n return df, cov, weights\n\n\ndef encode_as_onehot(df_main: pd.DataFrame) -> pd.DataFrame:\n \"\"\"Replace string values for c with one-hot encoding.\"\"\"\n df_onehot = pd.get_dummies(df_main, 'c')\n df_onehot['y'] = df_main['y'].copy()\n return df_onehot\n\n\ndef encode_as_int(df_main: pd.DataFrame) -> pd.DataFrame:\n \"\"\"Replace string values for c with integer encoding.\"\"\"\n ord_enc = OrdinalEncoder(dtype=np.int)\n c_encoded = ord_enc.fit_transform(df_main[['c']])\n df_catnum = df_main.copy()\n df_catnum['c'] = c_encoded\n df_catnum['c'] = df_catnum['c'].astype('category')\n return df_catnum, ord_enc\n\n\ndef encode_as_magic_int(df_main: pd.DataFrame) -> pd.DataFrame:\n \"\"\"Replace string values for c with \"magic\" integer encoding.\n\n A magic encoding is one in which the sorted integer values keep all\n C+ values (values of c that end with \"A\") next to each other and all\n C- values (values of c that end with \"B\") next to eachother.\n \"\"\"\n values = sorted(df_main['c'].unique(), key=lambda x: x[-1])\n ord_enc = OrdinalEncoder(categories=[values], dtype=np.int)\n c_encoded = ord_enc.fit_transform(df_main[['c']])\n df_catnum = df_main.copy()\n df_catnum['c'] = c_encoded\n df_catnum['c'] = df_catnum['c'].astype('category')\n return df_catnum, ord_enc\n\n\ndef get_feature_names(df, include_c=True):\n names = [f for f in df.columns if not f.startswith('y')]\n if not include_c:\n names = [f for f in names if not f.startswith('c')]\n return names\n\n\ndef print_auc_mean_std(results):\n print(\" AUC: mean={:4.4f}, sd={:4.4f}\".format(\n np.mean(results['metric']), np.std(results['metric'])))\n\n\ndef print_sorted_mean_importances(results, n=5):\n data = defaultdict(list)\n imps = results['importances']\n for d in imps:\n for fname, imp in d.items():\n data[fname].append(imp)\n mu = {fname: np.mean(vals) for fname, vals in data.items()}\n mu = sorted(mu.items(), key=itemgetter(1), reverse=True)[:n]\n print(\" Importances:\")\n for fname, val in mu:\n print(\"{:>20}: {:0.03f}\".format(fname, val))\n\n\n# @jit(nopython=True)\ndef powerset(iterable):\n s = list(iterable)\n return itertools.chain.from_iterable(itertools.combinations(s, r) for r in range(len(s) + 1))\n\n\n# @jit(nopython=True)\ndef get_partition(leaf_id, part, node_id, children_left, children_right, feature, threshold):\n left = np.where(children_left == leaf_id)[0]\n right = np.where(children_right == leaf_id)[0]\n\n if (len(left) == 0) * (len(right) == 0):\n return part, node_id\n\n else:\n if len(right) != 0:\n right = int(right[0])\n node_id.append(feature[right])\n\n part[feature[right]] = np.concatenate((part[feature[right]], np.array([[threshold[right], np.inf]])))\n part[feature[right]] = np.array([[np.max(part[feature[right]][:, 0]), np.min(part[feature[right]][:, 1])]])\n return get_partition(right, part, node_id, children_left, children_right, feature, threshold)\n else:\n left = int(left[0])\n node_id.append(feature[left])\n\n part[feature[left]] = np.concatenate((part[feature[left]], np.array([[-np.inf, threshold[left]]])))\n part[feature[left]] = np.array([[np.max(part[feature[left]][:, 0]), np.min(part[feature[left]][:, 1])]])\n\n return get_partition(left, part, node_id, children_left, children_right, feature, threshold)\n\n\ndef explore_partition(i, x, children_left, children_right, features, thresholds, values,\n compatible_leaves, partition_leaves, partition_global, prob_global, s_global, S, S_bar, data,\n down_tx, up_tx, intv=False):\n\n if children_left[i] < 0:\n # tab[i] = 1\n compatible_leaves.append(i)\n partition_global[i] = partition_leaves\n partition_leaves = np.squeeze(np.array(partition_leaves))\n\n section_x = np.prod(\n [(data[:, s] <= partition_leaves[s, 1]) * (data[:, s] >= partition_leaves[s, 0]) for s in\n S], axis=0)\n\n section_x_bar = np.prod(\n [(data[:, s] <= partition_leaves[s, 1]) * (data[:, s] >= partition_leaves[s, 0]) for s in\n S_bar], axis=0)\n\n section_up = np.prod(\n [(data[:, s] <= partition_leaves[s, 1]) * (data[:, s] >= partition_leaves[s, 0]) for s in\n S], axis=0) * up_tx\n\n section_down = np.prod(\n [(data[:, s] <= partition_leaves[s, 1]) * (data[:, s] >= partition_leaves[s, 0]) for s in\n S], axis=0) * down_tx\n\n prob_all = section_x * section_x_bar\n prob_up = section_up * section_x_bar\n prob_down = section_down * section_x_bar\n\n s_all = section_x\n s_up = section_up\n s_down = section_down\n\n prob_global['all'].append(prob_all.reshape(1, -1))\n prob_global['up'].append(prob_up.reshape(1, -1))\n prob_global['down'].append(prob_down.reshape(1, -1))\n\n s_global['all'].append(s_all.reshape(1, -1))\n s_global['up'].append(s_up.reshape(1, -1))\n s_global['down'].append(s_down.reshape(1, -1))\n\n else:\n if features[i] in S:\n if x[features[i]] <= thresholds[i]:\n part_left = partition_leaves.copy()\n part_left[features[i]] = np.concatenate((part_left[features[i]], np.array([[-np.inf, thresholds[i]]])))\n part_left[features[i]] = np.array(\n [[np.max(part_left[features[i]][:, 0]), np.min(part_left[features[i]][:, 1])]])\n explore_partition(children_left[i], x, children_left, children_right, features, thresholds, values,\n compatible_leaves, part_left, partition_global, prob_global, s_global, S, S_bar, data,\n down_tx, up_tx, intv)\n else:\n part_right = partition_leaves.copy()\n part_right[features[i]] = np.concatenate((part_right[features[i]], np.array([[thresholds[i], np.inf]])))\n part_right[features[i]] = np.array(\n [[np.max(part_right[features[i]][:, 0]), np.min(part_right[features[i]][:, 1])]])\n explore_partition(children_right[i], x, children_left, children_right, features, thresholds, values,\n compatible_leaves, part_right, partition_global, prob_global, s_global, S, S_bar,\n data, down_tx, up_tx, intv)\n else:\n part_left = partition_leaves.copy()\n part_left[features[i]] = np.concatenate((part_left[features[i]], np.array([[-np.inf, thresholds[i]]])))\n part_left[features[i]] = np.array(\n [[np.max(part_left[features[i]][:, 0]), np.min(part_left[features[i]][:, 1])]])\n\n part_right = partition_leaves.copy()\n part_right[features[i]] = np.concatenate((part_right[features[i]], np.array([[thresholds[i], np.inf]])))\n part_right[features[i]] = np.array(\n [[np.max(part_right[features[i]][:, 0]), np.min(part_right[features[i]][:, 1])]])\n\n explore_partition(children_left[i], x, children_left, children_right, features, thresholds, values,\n compatible_leaves, part_left, partition_global, prob_global, s_global, S, S_bar, data\n ,down_tx, up_tx, intv)\n explore_partition(children_right[i], x, children_left, children_right, features, thresholds, values,\n compatible_leaves, part_right, partition_global, prob_global, s_global, S, S_bar, data\n ,down_tx, up_tx, intv)\n\n\ndef get_tree_partition(x, fx, tx, tree, S, data=None, is_reg=True):\n \"\"\"\n Compute the partition (L_m) of each compatible leaf of the condition X_s = x_S, then check for each\n observations in data in which leaves it falls.\n\n Args:\n x (array): observation\n fx (float): tree(x)\n tx (float): threshold of the classifier\n tree (DecisionTreeClassifier.tree_): model\n S (list): index of variables on which we want to compute the SDP\n algo (string): name of the estimators, recommended 'pluging'\n data (array): data used to compute the partion\n\n Returns:\n (array, array): binary array of shape (data_size, compatible_leaves), if [i, j] = 1 then observation i fall in\n leaf j.\n (array): return number of observations that fall in each leaf\n \"\"\"\n\n children_left = tree.children_left\n children_right = tree.children_right\n features = tree.features\n thresholds = tree.thresholds\n # r_w = tree.node_samples_weight\n index = range(x.shape[0])\n if is_reg:\n values = tree.values.reshape(-1) / tree.scaling\n y_pred = tree.predict(data)\n dist = (y_pred - fx) ** 2\n\n up_tx = np.array(dist > tx).reshape(-1)\n down_tx = np.array(dist <= tx).reshape(-1)\n else:\n values = tree.values / tree.scaling\n y_pred = tree.predict(data)\n\n if len(y_pred.shape) == 1:\n y_pred = np.array([1 - y_pred, y_pred]).T\n\n argmax_y_pred = np.argmax(y_pred, axis=1)\n\n up_tx = np.array(argmax_y_pred == int(fx)).reshape(-1)\n down_tx = np.array(argmax_y_pred != int(fx)).reshape(-1)\n\n S_bar = [i for i in index if i not in S]\n partition_leaves = [np.array([[-np.inf, np.inf]]) for i in range(data.shape[1])]\n partition_global = {i: [np.array([[-np.inf, np.inf]]) for i in range(data.shape[1])]\n for i in range(len(tree.features))}\n\n prob_global = {'all': [], 'up': [], 'down': []}\n s_global = {'all': [], 'up': [], 'down': []}\n\n part_final = {}\n compatible_leaves = []\n explore_partition(0, x, children_left, children_right, features, thresholds, values,\n compatible_leaves, partition_leaves, partition_global, prob_global, s_global, S, S_bar, data,\n down_tx, up_tx, intv=False)\n\n part_final['all'] = np.concatenate(prob_global['all'], axis=0)\n part_final['up'] = np.concatenate(prob_global['up'], axis=0)\n part_final['down'] = np.concatenate(prob_global['down'], axis=0)\n\n part_final['s_all'] = np.concatenate(s_global['all'], axis=0)\n part_final['s_up'] = np.concatenate(s_global['up'], axis=0)\n part_final['s_down'] = np.concatenate(s_global['down'], axis=0)\n\n return part_final, values[compatible_leaves]\n\n\n\nimport_errors = {}\ndef assert_import(package_name):\n global import_errors\n if package_name in import_errors:\n msg, e = import_errors[package_name]\n print(msg)\n raise e\n\n\ndef record_import_error(package_name, msg, e):\n global import_errors\n import_errors[package_name] = (msg, e)\n\n\ndef safe_isinstance(obj, class_path_str):\n \"\"\"\n Acts as a safe version of isinstance without having to explicitly\n import packages which may not exist in the users environment.\n\n Checks if obj is an instance of type specified by class_path_str.\n\n Parameters\n ----------\n obj: Any\n Some object you want to test against\n class_path_str: str or list\n A string or list of strings specifying full class paths\n Example: `sklearn.ensemble.RandomForestRegressor`\n\n Returns\n --------\n bool: True if isinstance is true and the package exists, False otherwise\n \"\"\"\n if isinstance(class_path_str, str):\n class_path_strs = [class_path_str]\n elif isinstance(class_path_str, list) or isinstance(class_path_str, tuple):\n class_path_strs = class_path_str\n else:\n class_path_strs = ['']\n\n # try each module path in order\n for class_path_str in class_path_strs:\n if \".\" not in class_path_str:\n raise ValueError(\"class_path_str must be a string or list of strings specifying a full \\\n module path to a class. Eg, 'sklearn.ensemble.RandomForestRegressor'\")\n\n # Splits on last occurence of \".\"\n module_name, class_name = class_path_str.rsplit(\".\", 1)\n\n # here we don't check further if the model is not imported, since we shouldn't have\n # an object of that types passed to us if the model the type is from has never been\n # imported. (and we don't want to import lots of new modules for no reason)\n if module_name not in sys.modules:\n continue\n\n module = sys.modules[module_name]\n\n # Get class\n _class = getattr(module, class_name, None)\n\n if _class is None:\n continue\n\n if isinstance(obj, _class):\n return True\n\n return False\n\n\ndef get_null_coalition(s_star, len_s_star):\n n_star = -np.ones(s_star.shape, dtype=np.long)\n index = list(range(s_star.shape[1]))\n\n for i in range(s_star.shape[0]):\n s_star_index = [s_star[i, j] for j in range(s_star.shape[1])]\n null_coalition = list(set(index) - set(s_star_index))\n n_star[i, len_s_star[i]:] = np.array(null_coalition)\n return s_star, n_star\n\n\ndef get_active_null_coalition_list(s_star, len_s_star):\n index = list(range(s_star.shape[1]))\n s_star_all = []\n n_star_all = []\n for i in range(s_star.shape[0]):\n s_star_all.append([s_star[i, j] for j in range(len_s_star[i])])\n n_star_all.append(list(set(index) - set(s_star_all[-1])))\n return s_star_all, n_star_all\n\nclass ModelW:\n def __init__(self, model, prediction='predict_proba'):\n self.model = model\n self.prediction = prediction\n\n def __call__(self, x):\n if self.prediction == 'predict_proba':\n if len(x.shape) == 1:\n return self.model.predict_proba(x.reshape(-1, 1))\n return self.model.predict_proba(x)\n elif self.prediction == 'predict_proba_one':\n if len(x.shape) == 1:\n return self.model.predict_proba(x.reshape(-1, 1))[:, 1]\n return self.model.predict_proba(x)[:, 1]\n else:\n if len(x.shape) == 1:\n return self.model.predict(x.reshape(-1, 1))\n return self.model.predict(x)\n\n def predict(self, x):\n return self.__call__(x)\n\ndef weighted_percentile(a, q, weights=None, sorter=None):\n \"\"\"\n Returns the weighted percentile of a at q given weights.\n Parameters\n ----------\n a: array-like, shape=(n_samples,)\n samples at which the quantile.\n q: int\n quantile.\n weights: array-like, shape=(n_samples,)\n weights[i] is the weight given to point a[i] while computing the\n quantile. If weights[i] is zero, a[i] is simply ignored during the\n percentile computation.\n sorter: array-like, shape=(n_samples,)\n If provided, assume that a[sorter] is sorted.\n Returns\n -------\n percentile: float\n Weighted percentile of a at q.\n References\n ----------\n 1. https://en.wikipedia.org/wiki/Percentile#The_Weighted_Percentile_method\n Notes\n -----\n Note that weighted_percentile(a, q) is not equivalent to\n np.percentile(a, q). This is because in np.percentile\n sorted(a)[i] is assumed to be at quantile 0.0, while here we assume\n sorted(a)[i] is given a weight of 1.0 / len(a), hence it is at the\n 1.0 / len(a)th quantile.\n \"\"\"\n if weights is None:\n weights = np.ones_like(a)\n if q > 100 or q < 0:\n raise ValueError(\"q should be in-between 0 and 100, \"\n \"got %d\" % q)\n\n a = np.asarray(a, dtype=np.float32)\n weights = np.asarray(weights, dtype=np.float32)\n if len(a) != len(weights):\n raise ValueError(\"a and weights should have the same length.\")\n\n if sorter is not None:\n a = a[sorter]\n weights = weights[sorter]\n\n nz = weights != 0\n a = a[nz]\n weights = weights[nz]\n\n if sorter is None:\n sorted_indices = np.argsort(a)\n sorted_a = a[sorted_indices]\n sorted_weights = weights[sorted_indices]\n else:\n sorted_a = a\n sorted_weights = weights\n\n # Step 1\n sorted_cum_weights = np.cumsum(sorted_weights)\n total = sorted_cum_weights[-1]\n\n # Step 2\n partial_sum = 100.0 / total * (sorted_cum_weights - sorted_weights / 2.0)\n start = np.searchsorted(partial_sum, q) - 1\n if start == len(sorted_cum_weights) - 1:\n return sorted_a[-1]\n if start == -1:\n return sorted_a[0]\n\n # Step 3.\n fraction = (q - partial_sum[start]) / (partial_sum[start + 1] - partial_sum[start])\n return sorted_a[start] + fraction * (sorted_a[start + 1] - sorted_a[start])\n\n\ndef find_nbor(rec_a, rec_b, S):\n axs = []\n dim = []\n for k in S:\n if rec_a[k, 0] == rec_b[k, 1]:\n axs.append(k)\n dim.append(0)\n elif rec_a[k, 1] == rec_b[k, 0]:\n axs.append(k)\n dim.append(1)\n return axs, dim\n\n\ndef extend_rec(rec_a, rec_b, S, axs, dim):\n a = 0\n for k in S:\n if k not in axs:\n if not rec_b[k, 0] <= rec_a[k, 0] and rec_b[k, 1] >= rec_a[k, 1]:\n a += 1\n if a == 0:\n for i, k in enumerate(axs):\n rec_a[k, dim[i]] = rec_b[k, dim[i]]\n return rec_a\n\n\ndef find_union(rec_a, list_ric, S):\n axs, dim = [], []\n for i, rec_b in enumerate(list_ric):\n axs, dim = find_nbor(rec_a, rec_b, S)\n if len(axs) != 0:\n break\n if len(axs) == 0 or len(list_ric) == 0:\n return rec_a\n else:\n del list_ric[i]\n rec_a = extend_rec(rec_a, rec_b, S, axs, dim)\n return find_union(rec_a, list_ric, S)\n\n\ndef extend_partition(rules, rules_data, sdp_all, pi, S):\n for i in range(rules.shape[0]):\n list_ric = [rules_data[i, j] for j in range(rules_data.shape[1]) if sdp_all[i, j] >= pi]\n find_union(rules[i], list_ric, S=S[i])\n\n\ndef generate_x(n, dim):\n \"\"\"Generate the features (x).\n\n Args:\n - n: the number of samples\n - dim: the number of features (feature dimensions)\n\n Returns:\n - x: (n x dim) data points sample from N(0, 1)\n \"\"\"\n x = np.random.randn(n, dim)\n return x\n\n\ndef generate_y(x, data_type, reg=False, coefs=None, logit_values=True):\n \"\"\"Generate corresponding label (y) given feature (x).\n\n Args:\n - x: features\n - data_type: synthetic data type (syn1 to syn6)\n\n Returns:\n - y: corresponding labels\n \"\"\"\n # number of samples\n n = x.shape[0]\n if reg:\n if data_type == 'syn7':\n logit1 = np.sum(coefs[0:2] * x[:, 0:2], axis=1)\n logit2 = np.sum(coefs[2:4] * x[:, 2:4], axis=1)\n idx1 = (x[:, 4] < 0) * 1\n idx2 = (x[:, 4] >= 0) * 1\n logit = logit1 * idx1 + logit2 * idx2\n return logit\n elif data_type == 'syn8':\n return np.sum(coefs[:3] * x[:, :3], axis=1)\n elif data_type == 'syn9':\n logit1 = np.sum(x[:, 2:6] ** 2, axis=1) - 4.0\n logit2 = -10 * np.sin(0.2 * x[:, 6]) + abs(x[:, 7]) + \\\n x[:, 8] + np.exp(-x[:, 9]) - 2.4\n\n idx1 = (x[:, 10] < 0) * 1\n idx2 = (x[:, 10] >= 0) * 1\n logit = logit1 * idx1 + logit2 * idx2\n return logit\n\n # Logit computation\n if data_type == 'syn1':\n logit = np.exp(x[:, 0] * x[:, 1])\n elif data_type == 'syn2':\n logit = np.exp(np.sum(x[:, 2:6] ** 2, axis=1) - 4.0)\n elif data_type == 'syn3':\n logit = np.exp(-10 * np.sin(0.2 * x[:, 6]) + abs(x[:, 7]) + \\\n x[:, 8] + np.exp(-x[:, 9]) - 2.4)\n elif data_type == 'syn4':\n logit1 = np.exp(x[:, 0] * x[:, 1])\n logit2 = np.exp(np.sum(x[:, 2:6] ** 2, axis=1) - 4.0)\n elif data_type == 'syn5':\n logit1 = np.exp(x[:, 0] * x[:, 1])\n logit2 = np.exp(-10 * np.sin(0.2 * x[:, 6]) + abs(x[:, 7]) + \\\n x[:, 8] + np.exp(-x[:, 9]) - 2.4)\n elif data_type == 'syn6':\n logit1 = np.exp(np.sum(x[:, 2:6] ** 2, axis=1) - 4.0)\n logit2 = np.exp(-10 * np.sin(0.2 * x[:, 6]) + abs(x[:, 7]) + \\\n x[:, 8] + np.exp(-x[:, 9]) - 2.4)\n\n # For syn4, syn5 and syn6 only\n if data_type in ['syn4', 'syn5', 'syn6']:\n # Based on X[:,10], combine two logits\n idx1 = (x[:, 10] < 0) * 1\n idx2 = (x[:, 10] >= 0) * 1\n logit = logit1 * idx1 + logit2 * idx2\n\n if not logit_values:\n # Compute P(Y=0|X)\n prob_0 = np.reshape((logit / (1 + logit)), [n, 1])\n\n # # Sampling process\n y = np.zeros([n, 2])\n y[:, 0] = np.reshape(np.random.binomial(1, prob_0), [n, ])\n y[:, 1] = 1 - y[:, 0]\n return y[:, 1]\n return logit / (1 + logit)\n\n\ndef generate_ground_truth(x, data_type):\n \"\"\"Generate ground truth feature importance corresponding to the data type\n and feature.\n\n Args:\n - x: features\n - data_type: synthetic data type (syn1 to syn6)\n\n Returns:\n - ground_truth: corresponding ground truth feature importance\n \"\"\"\n\n # Number of samples and features\n n, d = x.shape\n\n # Output initialization\n ground_truth = np.zeros([n, d])\n\n # For each data_type\n if data_type == 'syn1':\n ground_truth[:, :2] = 1\n elif data_type == 'syn2':\n ground_truth[:, 2:6] = 1\n elif data_type == 'syn3':\n ground_truth[:, 6:10] = 1\n\n # Index for syn4, syn5 and syn6\n if data_type in ['syn4', 'syn5', 'syn6', 'syn9']:\n idx1 = np.where(x[:, 10] < 0)[0]\n idx2 = np.where(x[:, 10] >= 0)[0]\n ground_truth[:, 10] = 1\n\n if data_type == 'syn4':\n ground_truth[idx1, :2] = 1\n ground_truth[idx2, 2:6] = 1\n elif data_type == 'syn5':\n ground_truth[idx1, :2] = 1\n ground_truth[idx2, 6:10] = 1\n elif data_type == 'syn6':\n ground_truth[idx1, 2:6] = 1\n ground_truth[idx2, 6:10] = 1\n elif data_type == 'syn7':\n idx1 = np.where(x[:, 4] < 0)[0]\n idx2 = np.where(x[:, 4] >= 0)[0]\n ground_truth[:, 4] = 1\n\n ground_truth[idx1, 0:2] = 1\n ground_truth[idx2, 2:4] = 1\n elif data_type == 'syn8':\n ground_truth[:, :3] = 1\n # ground_truth[idx2, 6:10] = 1\n elif data_type == 'syn9':\n ground_truth[idx1, :2] = 1\n ground_truth[idx2, 6:10] = 1\n\n return ground_truth\n\n\ndef generate_moons(x):\n moon_x, y = datasets.make_moons(n_samples=x.shape[0], noise=4 * 0.01)\n x = np.concatenate([moon_x, x], axis=1)\n for i in range(x.shape[0]):\n if x[i, 2] <= 0:\n if y[i] == 0:\n y[i] = 1\n else:\n y[i] = 0\n ground_truth = np.zeros(shape=x.shape)\n ground_truth[:, :3] = 1\n return x, y, ground_truth\n\n\ndef generate_dataset(mean, cov, n=10000, dim=11, data_type='syn1', seed=0, reg=False, coefs=None, logit_values=True):\n \"\"\"Generate dataset (x, y, ground_truth).\n\n Args:\n - n: the number of samples\n - dim: the number of dimensions\n - data_type: synthetic data type (syn1 to syn6)\n - seed: random seed\n\n Returns:\n - x: features\n - y: labels\n - ground_truth: ground truth feature importance\n \"\"\"\n\n # Seed\n np.random.seed(seed)\n\n # x generation\n data_gen = st.multivariate_normal(mean, cov)\n x = data_gen.rvs(n)\n if data_type == 'syn_moons':\n x, y, ground_truth = generate_moons(x)\n return x, y, ground_truth\n\n # x = generate_x(n, dim)\n # y generation\n y = generate_y(x, data_type, reg, coefs, logit_values)\n # ground truth generation\n ground_truth = generate_ground_truth(x, data_type)\n\n return x, y, ground_truth","sub_path":"acv_explainers/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":39487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"169457621","text":"#\n# @lc app=leetcode.cn id=17 lang=python3\n#\n# [17] 电话号码的字母组合\n#\n# https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number/description/\n#\n# algorithms\n# Medium (55.54%)\n# Likes: 1022\n# Dislikes: 0\n# Total Accepted: 197.9K\n# Total Submissions: 356.3K\n# Testcase Example: '\"23\"'\n#\n# 给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。\n# \n# 给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。\n# \n# \n# \n# 示例:\n# \n# 输入:\"23\"\n# 输出:[\"ad\", \"ae\", \"af\", \"bd\", \"be\", \"bf\", \"cd\", \"ce\", \"cf\"].\n# \n# \n# 说明:\n# 尽管上面的答案是按字典序排列的,但是你可以任意选择答案输出的顺序。\n# \n#\n# 思路:如何实现 len(digits)层 for循环嵌套\n# 2. *****回溯法*******\n# 1. 列表推导式!!!! --------- 确定层数的for循环:保存中间状态!!!!\n# @lc code=start\nclass Solution:\n #def letterCombinations(self, digits: str) -> List[str]:\n def letterCombinations(self, digits):\n if not digits: return []\n \n dial_dict = {'2':\"abc\", '3':\"def\", '4':\"ghi\", '5':\"jkl\", '6':\"mno\",\n '7':\"pqrs\",'8':\"tuv\",'9':\"wxyz\"}\n\n def method1():\n res = ['']\n new_res = []\n for digit in digits:\n for pre in res:\n for char in dial_dict[digit]:\n new_res.append(pre + char)\n res = new_res[:]\n new_res = []\n return res\n \n def method1_2():\n res = ['']\n for digit in digits:\n res = [ pre + char for pre in res for char in dial_dict[digit]]\n return res\n \n res = []\n combination = []\n n = len(digits)\n \n def backtrace(r):\n if r == n: res.append(''.join(combination))\n else: \n for char in dial_dict[digits[r]]:\n combination.append(char)\n backtrace(r+1)\n combination.pop(-1)\n\n backtrace(0)\n \n return res\n\n#s = Solution()\n#s.letterCombinations('23')\n\n# @lc code=end\n\n","sub_path":"17.电话号码的字母组合.py","file_name":"17.电话号码的字母组合.py","file_ext":"py","file_size_in_byte":2219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"551832362","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.9-x86_64/egg/pytransit/lpf/logposteriorfunction.py\n# Compiled at: 2020-03-16 19:34:28\n# Size of source mod 2**32: 9515 bytes\nimport seaborn as sb, pandas as pd, xarray as xa\nfrom pathlib import Path\nfrom time import strftime\nfrom typing import Union, Iterable\nfrom scipy.optimize import minimize\nfrom numpy import ndarray, atleast_2d, inf, isfinite, where, clip, diag, full\nfrom numpy.random import multivariate_normal\nfrom emcee import EnsembleSampler\nfrom matplotlib.pyplot import subplots, setp\nfrom tqdm.auto import tqdm\nfrom pytransit.utils.de import DiffEvol\nfrom pytransit.param import ParameterSet, UniformPrior as UP, NormalPrior as NP\n\nclass LogPosteriorFunction:\n _lpf_name = 'LogPosteriorFunction'\n\n def __init__(self, name: str, result_dir: Union[(Path, str)]='.'):\n \"\"\"The Log Posterior Function class.\n\n Parameters\n ----------\n name: str\n Name of the log posterior function instance.\n \"\"\"\n self.name = name\n self.result_dir = Path(result_dir if result_dir is not None else '.')\n self.ps = None\n self.de = None\n self.sampler = None\n self._local_minimization = None\n self._additional_log_priors = []\n self._old_de_fitness = None\n self._old_de_population = None\n\n def print_parameters(self, columns: int=2):\n columns = max(1, columns)\n for i, p in enumerate(self.ps):\n print((p.__repr__()), end=('\\n' if i % columns == columns - 1 else '\\t'))\n\n def _init_parameters(self):\n self.ps = ParameterSet()\n self.ps.freeze()\n\n def create_pv_population(self, npop=50):\n return self.ps.sample_from_prior(npop)\n\n def set_prior(self, parameter, prior, *nargs) -> None:\n if isinstance(parameter, str):\n descriptions = self.ps.descriptions\n names = self.ps.names\n if parameter in descriptions:\n parameter = descriptions.index(parameter)\n else:\n if parameter in names:\n parameter = names.index(parameter)\n else:\n params = ', '.join([f\"{ln} ({sn})\" for ln, sn in zip(self.ps.descriptions, self.ps.names)])\n raise ValueError(f'Parameter \"{parameter}\" not found from the parameter set: {params}')\n elif isinstance(prior, str):\n if prior.lower() in ('n', 'np', 'normal'):\n prior = NP(nargs[0], nargs[1])\n else:\n if prior.lower() in ('u', 'up', 'uniform'):\n prior = UP(nargs[0], nargs[1])\n else:\n raise ValueError(f'Unknown prior \"{prior}\". Allowed values are (N)ormal and (U)niform.')\n self.ps[parameter].prior = prior\n\n def lnprior(self, pv: ndarray) -> Union[(Iterable, float)]:\n \"\"\"Log prior density for a 1D or 2D array of model parameters.\n\n Parameters\n ----------\n pv: ndarray\n Either a 1D parameter vector or a 2D parameter array.\n\n Returns\n -------\n Log prior density for the given parameter vector(s).\n \"\"\"\n return self.ps.lnprior(pv) + self.additional_priors(pv)\n\n def additional_priors(self, pv):\n pv = atleast_2d(pv)\n return sum([f(pv) for f in self._additional_log_priors], 0)\n\n def lnlikelihood(self, pv):\n raise NotImplementedError\n\n def lnposterior(self, pv):\n lnp = self.lnprior(pv) + self.lnlikelihood(pv)\n return where(isfinite(lnp), lnp, -inf)\n\n def __call__(self, pv):\n return self.lnposterior(pv)\n\n def optimize_local(self, pv0=None, method='powell'):\n if pv0 is None:\n if self.de is not None:\n pv0 = self.de.minimum_location\n else:\n pv0 = self.ps.mean_pv\n res = minimize((lambda pv: -self.lnposterior(pv)), pv0, method=method)\n self._local_minimization = res\n\n def optimize_global(self, niter=200, npop=50, population=None, label='Global optimisation', leave=False, plot_convergence: bool=True, use_tqdm: bool=True, plot_parameters: tuple=(0, 2, 3, 4)):\n if self.de is None:\n self.de = DiffEvol((self.lnposterior), (clip(self.ps.bounds, -1, 1)), npop, maximize=True, vectorize=True)\n if population is None:\n self.de._population[:, :] = self.create_pv_population(npop)\n else:\n self.de._population[:, :] = population\n for _ in tqdm((self.de(niter)), total=niter, desc=label, leave=leave, disable=(not use_tqdm)):\n pass\n\n if plot_convergence:\n fig, axs = subplots(1, (1 + len(plot_parameters)), figsize=(13, 2), constrained_layout=True)\n rfit = self.de._fitness\n mfit = isfinite(rfit)\n if self._old_de_fitness is not None:\n m = isfinite(self._old_de_fitness)\n axs[0].hist((-self._old_de_fitness[m]), facecolor='midnightblue', bins=25, alpha=0.25)\n axs[0].hist((-rfit[mfit]), facecolor='midnightblue', bins=25)\n for i, ax in zip(plot_parameters, axs[1:]):\n if self._old_de_fitness is not None:\n m = isfinite(self._old_de_fitness)\n ax.plot((self._old_de_population[(m, i)]), (-self._old_de_fitness[m]), 'kx', alpha=0.25)\n ax.plot(self.de.population[(mfit, i)], -rfit[mfit], 'k.')\n ax.set_xlabel(self.ps.descriptions[i])\n\n setp(axs, yticks=[])\n setp((axs[1]), ylabel='Log posterior')\n setp((axs[0]), xlabel='Log posterior')\n sb.despine(fig, offset=5)\n self._old_de_population = self.de.population.copy()\n self._old_de_fitness = self.de._fitness.copy()\n\n def sample_mcmc(self, niter: int=500, thin: int=5, repeats: int=1, npop: int=None, population=None, label='MCMC sampling', reset=True, leave=True, save=False, use_tqdm: bool=True):\n if save:\n if self.result_dir is None:\n raise ValueError('The MCMC sampler is set to save the results, but the result directory is not set.')\n elif self.sampler is None:\n if population is not None:\n pop0 = population\n else:\n if hasattr(self, '_local_minimization') and self._local_minimization is not None:\n pop0 = multivariate_normal((self._local_minimization.x), (diag(full(len(self.ps), 1e-06))), size=npop)\n else:\n if self.de is not None:\n pop0 = self.de.population.copy()\n else:\n raise ValueError('Sample MCMC needs an initial population.')\n self.sampler = EnsembleSampler((pop0.shape[0]), (pop0.shape[1]), (self.lnposterior), vectorize=True)\n else:\n pop0 = self.sampler.chain[:, -1, :].copy()\n for i in tqdm((range(repeats)), desc=label, disable=(not use_tqdm), leave=leave):\n if not reset:\n if i > 0:\n self.sampler.reset()\n for _ in tqdm(self.sampler.sample(pop0, iterations=niter, thin=thin), total=niter, desc=('Run {:d}/{:d}'.format(i + 1, repeats)), leave=False, disable=(not use_tqdm)):\n pass\n\n if save:\n self.save(self.result_dir)\n pop0 = self.sampler.chain[:, -1, :].copy()\n\n def posterior_samples(self, burn: int=0, thin: int=1):\n fc = self.sampler.chain[:, burn::thin, :].reshape([-1, len(self.ps)])\n df = pd.DataFrame(fc, columns=(self.ps.names))\n return df\n\n def plot_mcmc_chains(self, pid: int=0, alpha: float=0.1, thin: int=1, ax=None):\n fig, ax = (None, ax) if ax is not None else subplots()\n ax.plot((self.sampler.chain[:, ::thin, pid].T), 'k', alpha=alpha)\n fig.tight_layout()\n return fig\n\n def save(self, save_path: Path='.'):\n save_path = Path(save_path)\n npar = len(self.ps)\n if self.de:\n de = xa.DataArray((self.de.population), dims=('pvector parameter'.split()), coords={'parameter': self.ps.names})\n else:\n de = None\n if self.sampler is not None:\n mc = xa.DataArray((self.sampler.chain), dims=('pvector step parameter'.split()), coords={'parameter': self.ps.names},\n attrs={'ndim':npar, 'npop':self.sampler.nwalkers})\n else:\n mc = None\n ds = xa.Dataset(data_vars={'de_population':de, 'mcmc_samples':mc}, attrs={'created':strftime('%Y-%m-%d %H:%M:%S'), \n 'name':self.name})\n ds.to_netcdf(save_path.joinpath(f\"{self.name}.nc\"))\n\n def __repr__(self):\n return f\"Target: {self.name}\\nLPF: {self._lpf_name}\"","sub_path":"pycfiles/PyTransit-2.0.0b1-py3.7/logposteriorfunction.cpython-37.py","file_name":"logposteriorfunction.cpython-37.py","file_ext":"py","file_size_in_byte":8914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"116185399","text":"\n# coding: utf-8\n\n# In[16]:\n\n\nimport sys\nimport os\nimport subprocess\nimport shutil\nimport tempfile\nimport uuid\nimport time\nimport itertools\nimport random\nimport pickle\nimport json\nimport copy\nimport argparse\nimport csv\nimport roots\n\n# import threading\n# from queue import Queue\nimport multiprocessing\nfrom multiprocessing import Process, Value, Pool, Lock, Manager\nfrom multiprocessing.managers import BaseManager, NamespaceProxy\nfrom ctypes import *\n\nfrom functools import partial\n\nclass NoDaemonProcess(multiprocessing.Process):\n # make 'daemon' attribute always return False\n def _get_daemon(self):\n return False\n def _set_daemon(self, value):\n pass\n daemon = property(_get_daemon, _set_daemon)\n\nclass MyPool(multiprocessing.pool.Pool):\n Process = NoDaemonProcess\n\n\n# In[17]:\n\n\nclass SeqManager(object):\n def __init__(self,signalSeq,graphemeSeq,costSeq,phnSeq,nssSeq,segSeq):\n self.signalSeq = signalSeq\n self.graphemeSeq = graphemeSeq\n self.costSeq = costSeq\n self.phnSeq = phnSeq\n self.nssSeq = nssSeq\n self.segSeq = segSeq\n\nclass ObjectiveEvalConf(object):\n def __init__(self, mode, rate, norm, normalizedtw):\n self.mode = mode\n self.rate = rate\n self.norm = norm\n self.normalizedtw = normalizedtw\n \nclass CorpusData(object):\n def __init__(self, rootsFile, seqManager, tmpDir, nbJobs, FLAG_debug, FLAG_keep):\n self.FLAG_debug = FLAG_debug\n self.FLAG_keep = FLAG_keep\n self.rootsFile = rootsFile\n self.seqManager = seqManager\n self.tmpDir = tmpDir\n self.nbJobs = nbJobs\n self.nbUtt = 0\n self.idToWav = []\n self.idToTxt = []\n self.idToCost = []\n self.idToJson = []\n self.idToTxTFile = []\n # self.idToDiphnSet = []\n corpus = roots.Corpus(rootsFile)\n self.nbUtt = corpus.count_utterances()\n tmpJsonDir = tempfile.mkdtemp(dir=self.tmpDir)\n for it in range(0, self.nbUtt):\n print(\" BuildFilesFor Utt %d ...\" % (it), end=\"\\r\")\n self.buildFilesForUtt(corpus, self.tmpDir, tmpJsonDir, it)\n\n # Note(JC): txt files will be removed\n feBuilder = FrontEndTTS(self.idToTxTFile, self.idToJson, self.FLAG_debug, self.FLAG_keep, self.tmpDir)\n # for i in range(len(self.idToTxTFile)):\n # feBuilder(i)\n pool = MyPool(self.nbJobs)\n pool.map(feBuilder, list(range(len(self.idToTxTFile))))\n pool.close()\n pool.join()\n\n corpus.destroy()\n\n def extractWav(self, utt, targetWav):\n\n samples = []\n\n # get values from segments\n segSeq = utt.get_sequence(self.seqManager.segSeq).as_segment_sequence()\n\n nbSeg = segSeq.count()\n for i in range(0, nbSeg):\n curSeg = segSeq.get_item(i).as_acoustic_Segment()\n # get associated signal segment\n relatedSigs = curSeg.get_related_items(self.seqManager.signalSeq)\n if relatedSigs.size() != 1:\n # TODO(JC): ERROR\n sys.stderr.write(\"Error in roots when trying to build signal\\n\")\n\n samples += relatedSigs[0].as_acoustic_SignalSegment().get_samples_from_time(curSeg.get_segment_start(),\n curSeg.get_segment_end())\n\n # Note(JC): Wav parameters should be consistant\n aSig = utt.get_sequence(self.seqManager.signalSeq).as_segment_sequence().get_item(0).as_acoustic_SignalSegment()\n targetAudio = roots.file_Audio(\"\", aSig.get_file_format())\n targetAudio.set_precision(aSig.get_precision())\n targetAudio.set_rate(aSig.get_rate())\n targetAudio.set_channels(aSig.get_channels())\n targetAudio.set_samples(samples)\n targetAudio.export_to_file(targetWav, 0, len(samples))\n\n def buildFilesForUtt(self, corpus, tmpDir, tmpJsonDir, uttIdx):\n utt = corpus.get_utterance(uttIdx)\n\n ## Get text\n textSeq = utt.get_sequence(self.seqManager.graphemeSeq)\n self.idToTxt.append(textSeq.to_string())\n\n ## Get wav path\n head, tail = os.path.split(self.rootsFile)\n wavPath = tempfile.NamedTemporaryFile(dir=tmpDir,\n prefix=str(uttIdx) + \"_\"+tail+\"_\",\n suffix=\".wav\",\n delete=False)\n wavPath.close()\n self.extractWav(utt, wavPath.name)\n self.idToWav.append(wavPath.name)\n\n ## Compute the cost\n # TODO(JC): use a function\n lengthSeq = utt.get_sequence(self.seqManager.costSeq)\n uttLength = lengthSeq.count()\n self.idToCost.append(uttLength)\n\n ### get the result of TTSFrontEnd in a json file\n uttrTxtFile = tempfile.NamedTemporaryFile(dir=tmpDir, delete=False)\n uttrTxtFile.write(bytes(textSeq.to_string(), 'UTF-8'))\n uttrTxtFile.close()\n\n self.idToJson.append(os.path.join(tmpJsonDir, str(uttIdx) + \".json\"))\n self.idToTxTFile.append(uttrTxtFile.name)\n utt.destroy()\n\n def getRootsFile(self):\n return self.rootsFile\n\n def getWav(self, uttId):\n return self.idToWav[uttId]\n\n def getTxt(self, uttId):\n return self.idToTxt[uttId]\n\n def getNbUtt(self):\n return self.nbUtt\n\n def _getCost(self, uttId):\n return self.idToCost[uttId]\n\n def getCost(self, uttSet):\n cost = 0\n for it in uttSet:\n cost = cost + self._getCost(it)\n return cost\n\n def saveSubCorpus(self, uttSet, path, tmpDir):\n ## Save id values\n idfile = tempfile.NamedTemporaryFile(dir=tmpDir, delete=False)\n for i in uttSet:\n idfile.write(bytes(\"%d\\n\" % i, 'UTF-8'))\n idfile.close()\n\n cmd = \"roots-extract -f %s %s %s\" % (idfile.name, self.rootsFile, path)\n if not self.FLAG_debug:\n cmd += \" > /dev/null 2>&1 \"\n if self.FLAG_debug:\n sys.stderr.write(\"\\n\" + cmd + \"\\n\") # DEBUG\n\n # subprocess.run(cmd, shell=True, check=True) # python >= 3.5\n subprocess.check_call(cmd, shell=True) # python < 3.5\n # os.system(cmd)\n\n if not self.FLAG_keep:\n os.unlink(idfile.name)\n\n return\n\n def getPreparedData(self, uttId):\n return self.idToJson[uttId]\n\n def removeJsonData(self, tmpJsonDir):\n shutil.rmtree(tmpJsonDir)\n print(' Json files generated by TTS Front End are removed ! ')\n return\n\nclass BestCandidateManager(BaseManager):\n pass\n\ndef sharedVoiceUnload(sharedVoice,FLAG_debug,FLAG_quiet):\n cmd = RepoDir+\"bin/manage_shared_corpus --shared-name \" + sharedVoice + \" --remove\"\n if FLAG_quiet:\n cmd += \" > /dev/null 2>&1 \"\n if FLAG_debug:\n sys.stderr.write(\"\\n\" + cmd + \"\\n\") # DEBUG\n # subprocess.run(cmd, shell=True, check=True) # python >= 3.5\n subprocess.check_call(cmd, shell=True) # python < 3.5\n # os.system(cmd)\n return\n##Load Shared Corpus Load\ndef sharedVoiceLoad(config, sharedVoice,FLAG_debug,FLAG_quiet):\n ## unload to avoid problems :\n sharedVoiceUnload(sharedVoice,FLAG_debug,FLAG_quiet)\n\n cmd = RepoDir+\"bin/manage_shared_corpus --max-unit-length 2 --shared-size 2000 --shared-name \" + sharedVoice + \" --config \" + config + \" --add-filter IS_LAST_SYL_OF_SENTENCE --add-filter IS_LAST_SYL_OF_BG --add-filter IS_IN_WORD_END --add-filter IS_SYLLABLE_DESCENDING --add-filter IS_SYLLABLE_RISING\"\n if FLAG_quiet:\n cmd += \" > /dev/null 2>&1 \"\n if FLAG_debug:\n sys.stderr.write(\"\\n\" + cmd + \"\\n\") # DEBUG\n # subprocess.run(cmd, shell=True, check=True) # python >= 3.5\n subprocess.check_call(cmd, shell=True) # python < 3.5\n # os.system(cmd)\n return\n\ndef createAndLoadSubVoice(voice, corpusFile, subCorpusFile, outVoiceDir,FLAG_debug,FLAG_quiet):\n\n # TODO (JC) : use sequence names from parameters\n cmdR2TTSC = RepoDir+\"bin/roots2ttscorpus --in-corpus \" + corpusFile + \" --out-directory \" + outVoiceDir + \" --filter-file \" + subCorpusFile + \" --reference-sequence=\\\"Segment Automatic\\\" --phoneme-sequence=\\\"Allophone Automatic\\\" \" + \" --NSS-sequence=\\\"NonSpeechSound Automatic\\\" --segment-sequence=\\\"Segment Automatic\\\" \" + \" --syllable-sequence=\\\"Syllable Automatic\\\" --word-sequence=\\\"Word Synapse\\\" \" + \" --POS-sequence=\\\"POS Synapse\\\" --signal-sequence=\\\"Signal\\\" --F0-sequence=\\\"F0\\\" \" + \" --spectral-sequence=\\\"MFCC\\\" --pitchmark-sequence=\\\"Pitchmark\\\" --normalize \"\n\n if not FLAG_debug:\n cmdR2TTSC += \" --verbose --info \"\n # elif FLAG_quiet:\n cmdR2TTSC = \"%s > /dev/null 2>&1 \" % cmdR2TTSC\n\n if FLAG_debug:\n sys.stderr.write(\"\\n\" + cmdR2TTSC + \"\\n\") # DEBUG\n # subprocess.run(cmdR2TTSC, shell=True, check=True) # python >= 3.5\n subprocess.check_call(cmdR2TTSC, shell=True) # python < 3.5\n # os.system(cmdR2TTSC)\n\n #Todo:feature_encoder_update_voice.py\n\n ## manage shared Corpus\n sharedVoice = voice + \"_voice\"\n config = os.path.join(outVoiceDir, \"corpus_config.json\")\n sharedVoiceLoad(config, sharedVoice,FLAG_debug,FLAG_quiet)\n return sharedVoice\n\ndef updateShVoice(tmpdirGIt,vuCorpus,cpd,FLAG_debug,FLAG_quiet,FLAG_keep):\n\n ## Save subCorpusFile\n subCorpusFile = os.path.join(tmpdirGIt, \"XXX.txt\")\n with open(subCorpusFile, mode=\"w\") as f:\n for i in vuCorpus:\n f.write(\"%d\\n\" % i)\n\n ## Build the voice\n voice = str(uuid.uuid4())\n tmpdirVoice = tempfile.mkdtemp(prefix=voice, dir=tmpdirGIt)\n shVoice = createAndLoadSubVoice(voice,cpd.getRootsFile(),subCorpusFile,tmpdirVoice,FLAG_debug,FLAG_quiet)\n\n ## Remove the temporary directory\n if not FLAG_keep:\n os.unlink(subCorpusFile)\n\n return shVoice\n\nclass FrontEndTTS(object):\n def __init__(self, idToTxtFile, idToJson, FLAG_debug, FLAG_keep, tmpdir):\n self.idToTxtFile = idToTxtFile\n self.idToJson = idToJson\n self.FLAG_debug = FLAG_debug\n self.FLAG_keep = FLAG_keep\n self.tmpdir = tmpdir\n\n def __call__(self, itt):\n\n print(\" FrontEndTTS Utterance %d ...\" % (itt), end=\"\\r\")\n cmdTTSFrontEnd = \"perl \" + RepoDir + \"script/spc/tts.pl \" +\\\n self.idToTxtFile[itt] + \" \" + self.idToJson[itt] +\\\n \" --alphabet=liaphon --espeak \" +\\\n \" --filters-target-cost --filters-target-cost-file \" +\\\n RepoDir + \"script/corprep/fromRoots/subkey_weights_fr_extended.json\" +\\\n \" --weight-tc=2.0 --no-filter --algorithm=Viterbi --heap-max=200\" +\\\n \" --length 2 --candidates-max=200 --stop=duration -t \" + str(self.tmpdir)\n\n if not self.FLAG_debug:\n cmdTTSFrontEnd = \"%s > /dev/null 2>&1\" % cmdTTSFrontEnd\n else:\n sys.stderr.write(\"\\n\" + cmdTTSFrontEnd + \"\\n\")\n try:\n subprocess.check_call(cmdTTSFrontEnd, shell=True)\n except subprocess.CalledProcessError:\n if not self.FLAG_debug:\n sys.stderr.write(\"\\n The TTSFrontEnd for %s is failed!\" % itt)\n\n if not self.FLAG_keep:\n os.unlink(self.idToTxtFile[itt])\n\nclass TTSCall(object):\n def __init__(self, cpd, shaVoice, ttsWavDir, uttToRemoveId, FLAG_debug):\n\n self.cpd = cpd\n self.shaVoice = shaVoice\n self.ttsWavDir = ttsWavDir\n self.uttToRemoveId = uttToRemoveId\n self.FLAG_debug = FLAG_debug\n\n def __call__(self, uttrId):\n\n uttPathTmpJsonTTS = self.cpd.getPreparedData(uttrId)\n\n tmpWavFilename = str(uttrId) + \".wav\"\n pathTmpwavTTS = os.path.join(self.ttsWavDir, tmpWavFilename)\n\n tmpdepFilename = \"Depdiph\" + str(uttrId) + \".txt\"\n pathTmpdepTTS = os.path.join(self.ttsWavDir, tmpdepFilename)\n\n tmpdepFilename = \"Score\" + str(uttrId) + \".csv\"\n pathTmpScoreTTS = os.path.join(self.ttsWavDir, tmpdepFilename)\n\n # print(\"uttrId:%s ,uttToRemoveId:%s\" %(uttrId,self.uttToRemoveId))\n banUtt = \"\"\n for i in self.uttToRemoveId:\n banUtt += \" --ban-utt=\" + str(i)\n # cmdTTSBackEnd = \"perl spc/tts.pl \"+uttPathTmpJsonTTS+\" \"+pathTmpwavTTS+\" --shared \"+shaVoice+\" --add-filter IS_LAST_SYL_OF_SENTENCE --add-filter IS_LAST_SYL_OF_BG --add-filter IS_IN_WORD_END --add-filter IS_SYLLABLE_DESCENDING --add-filter IS_SYLLABLE_RISING --length 2 --candidates-threshold 10 --alphabet=liaphon --nss-alphabet=liaphon --start=synthesis --ban-utt=\"+str(uttToRemoveId)+\" \"\n # cmdTTSBackEnd = \"perl \" + RepoDir + \"script/spc/tts.pl \" + uttPathTmpJsonTTS + \\\n # \" \" + pathTmpwavTTS + \" --shared \" + self.shaVoice + \\\n # \" --add-filter IS_LAST_SYL_OF_SENTENCE --add-filter IS_LAST_SYL_OF_BG\" + \\\n # \" --add-filter IS_IN_WORD_END --add-filter IS_SYLLABLE_DESCENDING\" + \\\n # \" --add-filter IS_SYLLABLE_RISING --length 2 --candidates-threshold 10\" + \\\n # \" --start=synthesis\" + banUtt + \" --utt-file=\" + str(pathTmpdepTTS) + \\\n # \" --n-diphone-min 0 --default-duration 477 --path-file \" + \\\n # pathTmpScoreTTS + \" --only-phase=0\" ## NOTE(JC): Expensive\n cmdTTSBackEnd = \"perl \" + RepoDir + \"script/spc/tts.pl \" + uttPathTmpJsonTTS +\\\n \" \" + pathTmpwavTTS + \" --shared \" + self.shaVoice + \\\n \" --alphabet=liaphon --espeak --ordering-sequence=\\\"Ordering Pause Pred\\\" \" +\\\n \" --filters-target-cost --filters-target-cost-file \" + RepoDir + \"script/corprep/fromRoots/subkey_weights_fr_extended.json\" +\\\n \" --weight-tc=2.0 --no-filter --algorithm=Viterbi --heap-max=200\" +\\\n \" --length 2 --candidates-max=200 \"\\\n \" --start=synthesis\" + banUtt + \" --utt-file=\" + str(pathTmpdepTTS) +\\\n \" --n-diphone-min 0 --path-file \" +\\\n pathTmpScoreTTS + \" --only-phase=-1 \"\n if not self.FLAG_debug:\n cmdTTSBackEnd = \"%s > /dev/null 2>&1\" % cmdTTSBackEnd\n else:\n # pass\n sys.stderr.write(\"\\n\" + cmdTTSBackEnd + \"\\n\")\n\n try:\n subprocess.check_call(cmdTTSBackEnd, shell=True)\n\n except subprocess.CalledProcessError:\n if self.FLAG_debug:\n sys.stderr.write(\"\\nThe wav generation for uttrId:\" + str(uttrId) + \"has been failed!\\n\")\n\n\n# In[19]:\n\n\nclass EvaluateCandidates(object):\n def __init__(self,\n cpdTest,\n blacklist,\n seqManager,\n cpd,\n tmpdir,\n shVoice,\n FLAG_debug,\n FLAG_keep,\n FLAG_quiet):\n\n\n self.cpdTest=cpdTest\n self.blacklist = blacklist\n self.seqManager = seqManager\n self.cpd = cpd\n self.tmpdir = tmpdir\n self.shVoice = shVoice\n self.FLAG_debug = FLAG_debug\n self.FLAG_keep = FLAG_keep\n self.FLAG_quiet = FLAG_quiet\n\n def __call__(self, uttid):\n\n if self.FLAG_debug:\n sys.stderr.write(\"** Work on utt %s **\\n\" % (uttid))\n\n ## Set tmp directories\n# tmpdirIt = tempfile.mkdtemp(prefix='utt_%s.' % uttId, dir=self.tmpdir)\n# tmpdirWav = tempfile.mkdtemp(dir=tmpdirIt)\n tmpdirWav =self.tmpdir\n # (breakID, uttdep, oeScore, oeScores) = apoTTS.ttsBackEnd(tmpvcCorpus, self.cpd, self.shVoice, tmpdirWav, utts2remove, uttdep,self.FLAG_debug,self.nbJobsOE)\n utts2remove = set()\n\n # handle bunchUttrsNbr : will make remove bunchUttrsNbr/2 utterances before and after\n\n tts = TTSCall(self.cpdTest, self.shVoice, tmpdirWav, utts2remove,\n self.FLAG_debug) # ttsPhase: (0: item creation, 1:unit selection, 2:signal generation) [-1:all]\n tts(uttid)\n\n if not os.path.exists(os.path.join(tmpdirWav, str(uttid) + \".wav\")):\n self.blacklist.append(uttid)\n if not self.FLAG_quiet:\n sys.stderr.write(\"\\t* Add utt in blacklist: %s \\n\" % (uttid))\n #break TODO: extend to number of uttid (when len(uttIdSet)>1)\n else:\n if self.FLAG_debug:\n sys.stderr.write(\"TTS %s in utterance Id set \\t [OK]\\n\" % uttid)\n # Update ScoreDependency.evalScore and ScoreDependency.diphoneUsage for uttid\n\n\n# In[20]:\n\n\ndef LoadResultDic(savePath):\n\n with open(savePath, 'r') as stFile:\n scoreTrack = json.load(stFile)\n vuCorpus = set()\n for utt in scoreTrack:\n i = int(utt)\n if scoreTrack[utt][\"Corpus\"] == \"V\" or scoreTrack[utt][\"Corpus\"] == \"VL\":\n vuCorpus.add(i)\n\n return vuCorpus\n\n\n# In[18]:\n## In\nrootsCorpus = \"/home/shamsi/Work/data/expe-audiobook-opt/roots/corpus_sub_0010.json\"\nrootsCorpusTest = \"/home/shamsi/Work/data/expe-audiobook-opt/roots/corpus_sub_0005r.json\"\n#@banba1: \"/run/shm/shamsi/RootsCorpus/\"\n# rootsCorpus = \"/run/shm/shamsi/RootsCorpus/roots/fullCorpusLess.json\"\n# rootsCorpusTest = \"/run/shm/shamsi/RootsCorpus/roots/corpus_sub_Test.json\"\ncontinueIt = 0\n\n## Roots Sequence names\ncostSequence = \"Segment Automatic\"\nsignalSequence = \"Signal\"\ngraphemeSequence = \"Grapheme Transcriber\"\nphonemeSequence = \"Allophone Automatic\"\nnssSequence = \"NonSpeechSound Automatic\"\nsegmentSequence = \"Segment Automatic\"\n\n# Objective eval config\nparametrisation = 'mgc'\nrate = 44100\nnorm = 2\nnormalizedtw = False\n\n# //\nprocessNbr = 4\n\n## Tmp files\ntmpdir = \"/home/shamsi/Work/data/expe-audiobook-opt/tmp\"\n#@banba1\n# tmpdir = \"/vrac/shamsi/tmp/expe-audiobook-opt/tmp\"\nFLAG_keep = False\n\n## Verbosity\nFLAG_debug = False\nFLAG_quiet = False\n\nMSIZE = 0\nESIZE = 0\nOrderList = \"\"\n\nRepoDir = \"/home/shamsi/Work/speech/\"\n#@banba1 = \"/vrac/shamsi/speech/\"\n#RepoDir = \"/vrac/shamsi/speech/\"\n\n\nsm = SeqManager(signalSequence,\n graphemeSequence,\n costSequence,\n phonemeSequence,\n nssSequence,\n segmentSequence)\n\noec = ObjectiveEvalConf(parametrisation,\n rate,\n norm,\n normalizedtw)\n\ncpd = CorpusData(rootsCorpus,\n sm,\n tmpdir,\n processNbr,\n FLAG_debug,\n FLAG_keep)\n\ncpdTest = CorpusData(rootsCorpusTest,\n sm,\n tmpdir,\n processNbr,\n FLAG_debug,\n FLAG_keep)\n\ncpdfullSize=cpd.getCost(set(range(0, cpd.getNbUtt())))\n\nCorpusSizelist=[1,0.85,0.75,0.60,0.5,0.40]\nscoreTrackTTSCost=\"/home/shamsi/Work/data/tmp/scoreTrack_TTSCost-/\"\nscoreTrackRandom=\"/home/shamsi/Work/data/tmp/scoreTrack_Random/\"\n#@banba1: \"/vrac/shamsi/tmp/scoreTeak2Synth/\"\n# scoreTrackTTSCost=\"/vrac/shamsi/tmp/scoreTeak2Synth/scoreTrack_TTSCost-/\"\n# scoreTrackRandom=\"/vrac/shamsi/tmp/scoreTeak2Synth/scoreTrack_Random/\"\n\n \nfor corpusSz in CorpusSizelist:\n it=1\n VuSize=1\n VuCorpusNxt=set()\n VuCorpus=set()\n while VuSize > corpusSz:\n VuCorpus=VuCorpusNxt\n VuCorpusNxt=LoadResultDic(os.path.join(scoreTrackRandom, \"It_\" + str(it) + \".json\"))\n VuSize=float(cpd.getCost(VuCorpusNxt))/cpdfullSize\n print(\"corpusSz:%s, VuSize:%s\" %(corpusSz,VuSize))\n it+=1\n print(\"^^^^^^^^^^^^\")\n diffVu=VuCorpus-VuCorpusNxt\n while len(diffVu)>0 and VuSize < corpusSz:\n VuCorpusNxt.add(diffVu.pop())\n VuSize = float(cpd.getCost(VuCorpusNxt)) / cpdfullSize\n print(\"VuSize:\" + str(VuSize))\n\n print(\"The final VuCorpus(len:%s):%s\" %(VuSize,VuCorpusNxt))\n \n tmpdirGIt = tempfile.mkdtemp(prefix='GreedyIteration%s.' % it,\n dir=tmpdir) # Added part for Parallelization\n shVoice = updateShVoice(tmpdirGIt, VuCorpusNxt, cpd, FLAG_debug, FLAG_quiet, FLAG_keep)\n manager = Manager()\n bcmanager = BestCandidateManager()\n bcmanager.start()\n blacklist = manager.list()\n UttsSet=set(range(0, cpdTest.getNbUtt()))\n us = EvaluateCandidates(cpdTest,\n blacklist,\n sm,\n cpd,\n tmpdirGIt,\n shVoice,\n FLAG_debug,\n FLAG_keep,\n FLAG_quiet)\n\n pool = MyPool(processNbr)\n pool.map(us,UttsSet)\n pool.close()\n pool.join()\n \n sharedVoiceUnload(shVoice, FLAG_debug, FLAG_quiet)\n \n ### Read the Score of Utterances ########\n ScoreDic={}\n if not os.path.exists(os.path.join(tmpdir, \"SentheticSignal_\"+str(corpusSz))):\n os.makedirs(os.path.join(tmpdir, \"SentheticSignal_\"+str(corpusSz)))\n for uttid in UttsSet:\n if os.path.exists(os.path.join(tmpdirGIt, str(uttid) + \".wav\")):\n shutil.move(os.path.join(tmpdirGIt, str(uttid) + \".wav\"), os.path.join(tmpdir, \"SentheticSignal_\"+str(corpusSz)+\"/\"+ str(uttid) + \".wav\"))\n score_eval = 0 # ScoreDependency.evalScore\n with open(str(os.path.join(tmpdirGIt, \"Score\" + str(uttid) + \".csv\"))) as csvfile:\n reader = csv.reader(csvfile, delimiter=';')\n uttsize = 0\n for row in reader:\n uttsize += 1\n if len(row) > 0 and str(row[0]) == \"[empty]\":\n # print(\"utt:\" + str(uttid) + \" ,\" + str(row[0]) + \":\" + str(row[13]))\n score_eval += float(row[13]) # #ScoreDependency.evalScore\n\n scoreNormalized = score_eval / uttsize\n if not FLAG_quiet:\n sys.stderr.write(\"\\t* Utt %s normalized(length) synthetic quality: %s \\n\" % (\n uttid, scoreNormalized))\n\n score_eval_UttSize = [score_eval , uttsize]\n ScoreDic[uttid]=score_eval_UttSize\n \n with open(os.path.join(tmpdir, \"SentheticSignal_\"+str(corpusSz))+\"/ObjScores.json\", 'w') as outfile:\n json.dump(ScoreDic, outfile)\n shutil.rmtree(tmpdirGIt)\n \n \n\n \n\n","sub_path":"Task08_NewTTSsetting/SynthesizeTestSection.py","file_name":"SynthesizeTestSection.py","file_ext":"py","file_size_in_byte":22382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"615106791","text":"import json\nimport sys\nimport itertools\nfrom datetime import datetime, timedelta\nimport heapq\nimport math\n\nmonths = {\n 'Jan': 1,\n 'Feb': 2,\n 'Mar': 3,\n 'Apr': 4,\n 'May': 5,\n 'Jun': 6,\n 'Jul': 7,\n 'Aug': 8,\n 'Sep': 9,\n 'Oct': 10,\n 'Nov': 11,\n 'Dec': 12\n}\n\nclass Tweet:\n def __init__(self, text):\n tweet_dict = json.loads(text)\n\n date = str(tweet_dict['created_at']).split(' ')\n # eg. Tue Mar 29 06:04:50 +0000 2016\n # *** Important: Under assumption that it is always +0000 timezone ***\n time = date[3].split(':')\n self.timestamp = datetime(int(date[5]), months[date[1]], int(date[2]), int(time[0]), int(time[1]), int(time[2]))\n self.hashtags = []\n for data in tweet_dict['entities']['hashtags']:\n self.hashtags.append(data['text'].lstrip('#'))\n\n def get_timestamp(self):\n return self.timestamp\n\n def get_hashtags(self):\n return self.hashtags\n\n def get_hashtag_combinations(self):\n return itertools.combinations(self.hashtags, 2)\n\nclass Graph:\n def __init__(self):\n self.graph = {}\n\n def add_double_edge(self, edge):\n self.graph.setdefault(edge[0], set())\n self.graph[edge[0]].add(edge[1])\n\n self.graph.setdefault(edge[1], set())\n self.graph[edge[1]].add(edge[0])\n\n def link_hashtags(self, tweet):\n for edge in tweet.get_hashtag_combinations():\n self.add_double_edge(edge)\n\n def remove_edge(self, edge):\n if edge[0] in self.graph[edge[1]]:\n self.graph[edge[1]].remove(edge[0])\n if edge[1] in self.graph[edge[0]]:\n self.graph[edge[0]].remove(edge[1])\n\n def unlink_hashtags(self, tweet):\n for edge in tweet.get_hashtag_combinations():\n self.remove_edge(edge)\n\n def average_degree(self):\n degree_sum = 0\n number_of_nodes = 0\n for node, edge_set in self.graph.iteritems():\n degree_sum += len(edge_set)\n if len(edge_set) > 0:\n number_of_nodes += 1\n if number_of_nodes == 0:\n return '%.2f' % 0.0\n else:\n # return float(degree_sum) / number_of_nodes # ok this doesn't work because of rounding issues\n # format into 3 places, then chop off that extra digit\n values = str('%.3f' % (float(degree_sum) / number_of_nodes)).split('.')\n return values[0] + '.' + values[1][:2]\n\n \nif __name__ == \"__main__\":\n with open(sys.argv[1]) as input_file, open(sys.argv[2], 'w') as output_file:\n window = []\n graph = Graph()\n tweet = Tweet(input_file.readline().strip())\n latest_time = tweet.get_timestamp()\n earliest_time = latest_time - timedelta(0, 60)\n graph.link_hashtags(tweet)\n output_file.write('{}\\n'.format(graph.average_degree()))\n\n for line_number, content in enumerate(input_file):\n try:\n tweet = Tweet(content)\n except Exception as e:\n # print e # throw out all 'limit' json objects (not tweets)\n continue\n\n if tweet.get_timestamp() > latest_time:\n latest_time = tweet.get_timestamp()\n earliest_time = latest_time - timedelta(0, 60)\n \n if tweet.get_timestamp() <= earliest_time:\n output_file.write('{}\\n'.format(graph.average_degree()))\n continue\n\n heapq.heappush(window, (tweet.get_timestamp(), tweet))\n\n graph.link_hashtags(tweet)\n while len(window) > 0 and window[0][0] < earliest_time:\n (time, old_tweet) = heapq.heappop(window)\n graph.unlink_hashtags(old_tweet)\n output_file.write('{}\\n'.format(graph.average_degree()))\n\n\n","sub_path":"src/average_degree.py","file_name":"average_degree.py","file_ext":"py","file_size_in_byte":3415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"560815569","text":"import pywt\nimport os\nimport numpy\nimport matplotlib.pylab as plt\n\nif __name__ == '__main__':\n dbFamily = ['db1', 'db2', 'db4']\n\n for wavlet in ['db4']:\n loadpath = 'E:\\\\LIDC\\\\LIDC-Nodules-Selected\\\\'\n savepath = 'E:\\\\LIDC\\\\LIDC-Nodule-Wavelet\\\\' + wavlet + '\\\\'\n pngPath = savepath + 'Png\\\\'\n csvPath = savepath + 'Csv\\\\'\n\n for indexA in os.listdir(loadpath):\n for indexB in os.listdir(loadpath + indexA):\n for indexC in ['Csv']:\n for indexD in os.listdir(os.path.join(loadpath, indexA, indexB, indexC)):\n print(indexA, indexB, indexC, indexD)\n if not os.path.exists(os.path.join(pngPath, indexA, indexB, indexD)):\n os.makedirs(os.path.join(pngPath, indexA, indexB, indexD))\n os.makedirs(os.path.join(csvPath, indexA, indexB, indexD))\n\n treatData = numpy.genfromtxt(os.path.join(loadpath, indexA, indexB, indexC, indexD), dtype=int,\n delimiter=',')\n cA, (cH, cV, cD) = pywt.dwt2(data=treatData, wavelet=wavlet)\n\n plt.figure(figsize=(numpy.shape(cA)[0] / 100, numpy.shape(cA)[1] / 100))\n plt.axis('off')\n plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)\n plt.imshow(cA, cmap='gray')\n plt.savefig(os.path.join(pngPath, indexA, indexB, indexD, 'cA.png'))\n plt.clf()\n plt.close()\n\n plt.figure(figsize=(numpy.shape(cH)[0] / 100, numpy.shape(cH)[1] / 100))\n plt.axis('off')\n plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)\n plt.imshow(cH, cmap='gray')\n plt.savefig(os.path.join(pngPath, indexA, indexB, indexD, 'cH.png'))\n plt.clf()\n plt.close()\n\n plt.figure(figsize=(numpy.shape(cV)[0] / 100, numpy.shape(cV)[1] / 100))\n plt.axis('off')\n plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)\n plt.imshow(cV, cmap='gray')\n plt.savefig(os.path.join(pngPath, indexA, indexB, indexD, 'cV.png'))\n plt.clf()\n plt.close()\n\n plt.figure(figsize=(numpy.shape(cD)[0] / 100, numpy.shape(cD)[1] / 100))\n plt.axis('off')\n plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)\n plt.imshow(cD, cmap='gray')\n plt.savefig(os.path.join(pngPath, indexA, indexB, indexD, 'cD.png'))\n plt.clf()\n plt.close()\n\n file = open(os.path.join(csvPath, indexA, indexB, indexD, 'cA.png'), 'w')\n for indexX in range(len(cA)):\n for indexY in range(len(cA[indexX])):\n if indexY != 0: file.write(',')\n file.write(str(cA[indexX][indexY]))\n file.write('\\n')\n file.close()\n\n file = open(os.path.join(csvPath, indexA, indexB, indexD, 'cH.png'), 'w')\n for indexX in range(len(cH)):\n for indexY in range(len(cH[indexX])):\n if indexY != 0: file.write(',')\n file.write(str(cH[indexX][indexY]))\n file.write('\\n')\n file.close()\n\n file = open(os.path.join(csvPath, indexA, indexB, indexD, 'cV.png'), 'w')\n for indexX in range(len(cV)):\n for indexY in range(len(cV[indexX])):\n if indexY != 0: file.write(',')\n file.write(str(cV[indexX][indexY]))\n file.write('\\n')\n file.close()\n\n file = open(os.path.join(csvPath, indexA, indexB, indexD, 'cD.png'), 'w')\n for indexX in range(len(cD)):\n for indexY in range(len(cD[indexX])):\n if indexY != 0: file.write(',')\n file.write(str(cD[indexX][indexY]))\n file.write('\\n')\n file.close()\n","sub_path":"LIDC_Project/Records/Fragment/WaveletTransform_Nodule.py","file_name":"WaveletTransform_Nodule.py","file_ext":"py","file_size_in_byte":4732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"136822162","text":"'''\nCreated on 5 feb. 2018\n\n@author: AYB\n'''\nimport traceback\nfrom time import sleep\n\ntry:\n import RPi.GPIO as GPIO\nexcept RuntimeError:\n print(\"Error importing RPi.GPIO! This is probably because you need superuser privileges. \"\n \"You can achieve this by using 'sudo' to run your script\")\nexcept Exception as ex:\n print(\"exception importing GPIO lib\")\n traceback.print_exc()\n \n \n\n\n\nclass Servo:\n \"\"\"\n Main class for controlling servos\n \n \n \"\"\"\n # UP/DOWN servo control pin\n _UD_ = 13\n # RIGHT/LEFT servo control pin\n _LR_ = 19\n \n FREQ = 50\n PWM_UD = None\n PWM_LR = None\n MAX_UP = 9.5 # 50 degree\n MAX_DOWN = 4.5 # 0 degree\n MAX_LEFT = 4.5 # 0 degree\n MAX_RIGHT = 9.5 # 50 degree\n NEUTRAL_Y = 7.5 # 30 degree\n NEUTRAL_X = 7.5 # 30 degree\n CURRENT_UD = 7.5\n CURRENT_LR = 7.5\n \n def __init__(self, UD_=13, LR_=19, use_board=False):\n \"\"\"\n Initialize function for servo class\n\n :param bool use_board: True if GPIO.BOARD numbering will be used\n \"\"\"\n try:\n \n if use_board:\n GPIO.setmode(GPIO.BOARD)\n print(\"PIN numbering: BOARD\")\n else:\n GPIO.setmode(GPIO.BCM)\n print(\"PIN numbering: BCM\")\n \n self._UD_ = UD_\n self._LR_ = LR_\n \n GPIO.setup(self._UD_, GPIO.OUT)\n GPIO.setup(self._LR_, GPIO.OUT)\n self.PWM_UD = GPIO.PWM(self._UD_, self.FREQ)\n self.PWM_LR = GPIO.PWM(self._LR_, self.FREQ)\n self.PWM_UD.start(self.CURRENT_UD)\n self.PWM_LR.start(self.CURRENT_LR)\n sleep(1)\n self.PWM_UD.stop()\n self.PWM_LR.stop()\n \n except Exception as ex:\n print(\"GPIO could not be set\")\n traceback.print_exc()\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n try:\n self.PWM_UD.stop()\n self.PWM_LR.stop()\n GPIO.cleanup()\n except RuntimeWarning:\n return True\n def stop(self):\n try:\n self.PWM_UD.stop()\n self.PWM_LR.stop()\n except Exception as ex:\n print(\"exception stopping the PWM\")\n traceback.print_exc()\n \n def clean_up(self):\n try:\n print(\"cleaning up pins\")\n self.PWM_UD.stop()\n self.PWM_LR.stop()\n GPIO.cleanup()\n \n except Exception as ex:\n print(\"exception cleaning up pins\")\n traceback.print_exc()\n \n def set_duty_cycle(self, pwm, cycle):\n try:\n \n pwm.ChangeDutyCycle(cycle)\n \n \n except Exception as ex:\n print(\"exception in set_duty_cycle\")\n \n def countAngle(self, angle):\n \"\"\"\n returns duty cycle from given angle\n \"\"\"\n return float(angle) / 10.0 + 4.5\n \n def move_UD(self, angle):\n self.PWM_UD.start(self.CURRENT_UD)\n pwm = self.countAngle(angle)\n if pwm >= self.MAX_DOWN and pwm <= self.MAX_UP:\n self.set_duty_cycle(self._UD_, pwm)\n self.CURRENT_UD = pwm\n else:\n self.set_duty_cycle(self._UD_, self.NEUTRAL_Y)\n self.CURRENT_UD = self.NEUTRAL_Y\n sleep(1)\n self.PWM_UD.stop()\n \n def move_LR(self, angle):\n self.PWM_LR.start(self.CURRENT_UD)\n pwm = self.countAngle(angle)\n if pwm >= self.MAX_LEFT and pwm <= self.MAX_RIGHT:\n self.set_duty_cycle(self._LR_, pwm)\n self.CURRENT_LR = pwm\n else:\n self.set_duty_cycle(self._LR_, self.NEUTRAL_X)\n self.CURRENT_LR = self.NEUTRAL_X\n sleep(1)\n self.PWM_LR.stop()\n def transit_U(self):\n self.PWM_UD.start(self.CURRENT_UD)\n pwm = self.CURRENT_UD + 0.5\n if pwm >= self.MAX_DOWN and pwm <= self.MAX_UP:\n self.set_duty_cycle(self._UD_, pwm)\n self.CURRENT_UD = pwm\n else:\n self.set_duty_cycle(self._UD_, self.NEUTRAL_Y)\n self.CURRENT_UD = self.NEUTRAL_Y\n sleep(1)\n self.PWM_UD.stop()\n def transit_D(self):\n self.PWM_UD.start(self.CURRENT_UD)\n pwm = self.CURRENT_UD - 0.5\n if pwm >= self.MAX_DOWN and pwm <= self.MAX_UP:\n self.set_duty_cycle(self._UD_, pwm)\n self.CURRENT_UD = pwm\n else:\n self.set_duty_cycle(self._UD_, self.NEUTRAL_Y)\n self.CURRENT_UD = self.NEUTRAL_Y\n sleep(1)\n self.PWM_UD.stop()\n def transit_R(self):\n self.PWM_LR.start(self.CURRENT_LR)\n pwm = self.CURRENT_LR + 0.5\n if pwm >= self.MAX_LEFT and pwm <= self.MAX_RIGHT:\n self.set_duty_cycle(self._LR_, pwm)\n self.CURRENT_LR = pwm\n else:\n self.set_duty_cycle(self._LR_, self.NEUTRAL_X)\n self.CURRENT_LR = self.NEUTRAL_X\n sleep(1)\n self.PWM_LR.stop()\n def transit_L(self):\n self.PWM_LR.start(self.CURRENT_LR)\n pwm = self.CURRENT_LR - 0.5\n if pwm >= self.MAX_LEFT and pwm <= self.MAX_RIGHT:\n self.set_duty_cycle(self._LR_, pwm)\n self.CURRENT_LR = pwm\n else:\n self.set_duty_cycle(self._LR_, self.NEUTRAL_X)\n self.CURRENT_LR = self.NEUTRAL_X\n sleep(1)\n self.PWM_LR.stop()\n \n \n def move_up(self, angle):\n #self.PWM_UD\n pass\n def move_down(self, angle):\n #self.PWM_UD\n pass\n def move_right(self, angle):\n #self.PWM_LR\n pass\n def move_left(self, angle):\n #self.PWM_LR\n pass\n \n def move_x(self, direction, angle):\n #self.PWM_LR\n pass\n \n def move_y(self, direction, angle):\n #self.PWM_UD\n pass\n \n \n \n \n \n \n \n \n\n ","sub_path":"servo.py","file_name":"servo.py","file_ext":"py","file_size_in_byte":5992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"208110535","text":"import linecache as lc\nimport numpy as np\nimport os \n\n#%%class\nclass Acquire_value():\n def __init__(self,file_path='./',atomic_num=3):\n \n self.file = file_path\n self.atomic_num = atomic_num\n \n def _get_line(self,file_tmp,rematch=None):\n \n counts = []\n with open (file_tmp,'r') as f:\n count = -1\n for line in f.readlines():\n count+=1\n if rematch in line:\n counts.append(count)\n return counts\n\n def get_energy(self):\n \n file_out = self.file + 'OUTCAR'\n \n tmp_line = self._get_line(file_out,rematch='TOTEN')\n toten = float(lc.getlines(file_out)[tmp_line[-1]].split()[4])\n return toten\n \n def get_fermi(self):\n \n file_out = self.file + 'OUTCAR'\n \n tmp_line = self._get_line(file_out,rematch='E-fermi')\n fermi = float(lc.getlines(file_out)[tmp_line[0]].split()[2])\n return fermi\n\n def get_Ne_p(self):\n\n file_pos = self.file + 'POSCAR'\n file_pot = self.file + 'POTCAR'\n tmp_pos = lc.getlines(file_pos)[6].split() \n tmp_lines = self._get_line(file_pot,rematch='ZVAL')\n nelect_p = 0\n for ii in range(len(tmp_lines)):\n tmp_zval = lc.getlines(file_pot)[tmp_lines[ii]].split()[5] \n nelect_p+=round(int(tmp_pos[ii])*float(tmp_zval))\n return nelect_p\n\n def get_Ne_d(self):\n \n file_out = self.file + 'OUTCAR'\n \n tmp_line = self._get_line(file_out,rematch='NELECT')\n nelect_d = lc.getlines(file_out)[tmp_line[0]].split()[2]\n return round(float(nelect_d))\n\n def get_image(self):\n \n file_image = self.file + 'image_cor/OUTCAR'\n \n tmp_line = self._get_line(file_image,rematch='Ewald')\n Ewald = lc.getlines(file_image)[tmp_line[0]].split()[4]\n return Ewald\n \n def get_PA(self):\n \n file_PA = self.file + 'OUTCAR'\n file_pos = self.file + 'POSCAR'\n \n tmp_atom_line = round(sum(map(int,lc.getlines(file_pos)[6].split()))/5)+3\n tmp_match_line = self._get_line(file_PA,rematch='electrostatic')\n \n for line in lc.getlines(file_PA)[tmp_match_line[0]:tmp_match_line[0]+tmp_atom_line]:\n if ' '+str(self.atomic_num )+' ' in line:\n if self.atomic_num %5==0:\n return line.split()[9]\n else:\n return line.split()[self.atomic_num %5*2-1]\n \n def get_gap(self):\n \n file_gap = self.file + 'EIGENVAL'\n \n nelect_vbm = int(lc.getlines(file_gap)[5].split()[0])//2\n nelect_cbm = nelect_vbm+1\n \n tmp_lines = self._get_line(file_gap,rematch=' '+str(nelect_vbm)+' ')\n Evbms = []\n for ii in tmp_lines:\n Evbms.append(lc.getlines(file_gap)[ii].split()[1])\n \n tmp_lines = self._get_line(file_gap,rematch=' '+str(nelect_cbm)+' ')\n Ecbms = []\n for ii in tmp_lines:\n Ecbms.append(lc.getlines(file_gap)[ii].split()[1])\n \n Ecbm, Evbm = min(map(float,Ecbms)), max(map(float,Evbms))\n return Ecbm, Evbm, Ecbm - Evbm\n \n def get_miu(self):\n file_value, file_out = self.file + 'value', self.file + 'out'\n with open (file_value,'r') as f:\n miu_i = {}\n for line in f.readlines():\n tmp = line.split()\n miu_i.update({tmp[0]:np.array([\n float(tmp[1])+float(tmp[2]),\n float(tmp[1])+float(tmp[3]),\n float(tmp[1])+float(tmp[4])\n ])})\n state_d = {}\n with open(file_out,'r') as f:\n for line in f.readlines():\n tmp = line.split()\n state_d.update({tmp[0]:float(tmp[1])})\n \n miu = np.zeros((3))\n for ele,state in state_d.items():\n miu +=miu_i[ele]*(-state_d[ele])\n \n return miu\n\n#%% main script\nfiles = ['N_Si','Vac_Si_defect','P_Si']\ndef main_Hf(files, atomic_num=None, epsilon=None):\n diff_d = {}\n\n for file in files:\n SC_energy = Acquire_value('scf/').get_energy()\n nelect_p = Acquire_value(file+'/').get_Ne_p()\n Ecbm, Evbm, gap = Acquire_value('scf/').get_gap()\n miu = Acquire_value(file+'/').get_miu()\n \n dirs = []\n for ii in os.listdir(file+'/'):\n if 'NELECT' in ii:\n dirs.append(ii)\n for path in dirs:\n nelect_d = Acquire_value(file+'/'+path+'/').get_Ne_d()\n charge_state = nelect_p - nelect_d\n D_energy = Acquire_value(file+'/'+path+'/scf/').get_energy()\n \n if atomic_num is None:\n V_delt = 0\n else:\n V_delt = Acquire_value(file+'/'+path+'/scf/', atomic_num=atomic_num).get_PA() -\\\n Acquire_value('scf/', atomic_num=atomic_num).get_PA()\n \n \n Ewald = Acquire_value('./').get_image()\n if epsilon is None:\n E_imagecor = 0\n else:\n E_imagecor = -2/3*charge_state**2*Ewald/epsilon\n \n \n Hf_vbm = D_energy + E_imagecor - SC_energy + miu + charge_state * (Evbm-0.5+V_delt)\n Hf_cbm = D_energy + E_imagecor - SC_energy + miu + charge_state * (Evbm+gap+0.5+V_delt)\n for ii in range(len(miu)):\n diff_d[file] = diff_d.get(file,[])\n diff_d[file].append([charge_state, D_energy, SC_energy, V_delt, E_imagecor, miu[ii], gap, Hf_vbm[ii], Hf_cbm[ii]])\n \n return diff_d\n \ndiff_d = main_Hf(files)","sub_path":"defect_cal.py","file_name":"defect_cal.py","file_ext":"py","file_size_in_byte":5808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"452629629","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# Created by yaochao on 2017/8/13\n\nimport jieba.analyse\nfrom jieba import analyse\n\nanalyse.set_stop_words('jishux/misc/stop_words_chinese.txt')\n\n\ndef get_description(content_text):\n if len(content_text) >= 100:\n description = content_text[0:100]\n else:\n description = content_text\n return description\n\n\ndef get_keywords(response, content_text):\n keywords = response.xpath('//meta[@name=\"keywords\"]/@content')\n if keywords:\n keywords = keywords.extract_first()\n if ',' in keywords:\n keywords = keywords.split(',')\n keywords = [keyword.strip() for keyword in keywords]\n keywords = list(set(keywords))\n if len(keywords) > 6:\n keywords = ','.join(keywords[0:6])\n else:\n keywords = ','.join(keywords)\n elif ',' in keywords:\n keywords = keywords.split(',')\n keywords = [keyword.strip() for keyword in keywords]\n keywords = list(set(keywords))\n if len(keywords) > 6:\n keywords = ','.join(keywords[0:6])\n else:\n keywords = ','.join(keywords)\n else:\n keywords = jieba.analyse.extract_tags(content_text, topK=6)\n keywords = ','.join(keywords)\n return keywords\n","sub_path":"jishux/misc/text_tools.py","file_name":"text_tools.py","file_ext":"py","file_size_in_byte":1340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"268644520","text":"# Copyright (c) 2013-2016, Freja Nordsiek\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n#\n# 1. Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n#\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 FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\"\"\" Module of functions to set and delete HDF5 attributes.\n\n\"\"\"\n\nimport sys\nimport copy\nimport string\nimport random\n\nimport numpy as np\nimport h5py\n\n\ndef next_unused_name_in_group(grp, length):\n \"\"\" Gives a name that isn't used in a Group.\n\n Generates a name of the desired length that is not a Dataset or\n Group in the given group. Note, if length is not large enough and\n `grp` is full enough, there may be no available names meaning that\n this function will hang.\n\n Parameters\n ----------\n grp : h5py.Group or h5py.File\n The HDF5 Group (or File if at '/') to generate an unused name\n in.\n length : int\n Number of characters the name should be.\n\n Returns\n -------\n str\n A name that isn't already an existing Dataset or Group in\n `grp`.\n\n \"\"\"\n ltrs = string.ascii_letters + string.digits\n existing_names = set(grp.keys())\n while True:\n name = ''.join([random.choice(ltrs) for i in range(0, length)])\n if name not in existing_names:\n return name\n\ndef convert_numpy_str_to_uint16(data):\n \"\"\" Converts a numpy.str_ to UTF-16 encoding in numpy.uint16 form.\n\n Convert a ``numpy.str`` or an array of them (they are UTF-32\n strings) to UTF-16 in the equivalent array of ``numpy.uint16``. The\n conversion will throw an exception if any characters cannot be\n converted to UTF-16. Strings are expanded along rows (across columns)\n so a 2x3x4 array of 10 element strings will get turned into a 2x30x4\n array of uint16's if every UTF-32 character converts easily to a\n UTF-16 singlet, as opposed to a UTF-16 doublet.\n\n Parameters\n ----------\n data : numpy.str_ or numpy.ndarray of numpy.str_\n The string or array of them to convert.\n\n Returns\n -------\n numpy.ndarray of numpy.uint16\n The result of the conversion.\n\n Raises\n ------\n UnicodeEncodeError\n If a UTF-32 character has no UTF-16 representation.\n\n See Also\n --------\n convert_numpy_str_to_uint32\n decode_to_numpy_str\n\n \"\"\"\n # An empty string should be an empty uint16\n if data.nbytes == 0:\n return np.uint16([])\n\n # If it is just a string instead of an array of them, then the\n # string can simply be converted and returned as a 1d array pretty\n # easily using ndarray's buffer option. The byte order mark, 2\n # bytes, needs to be removed.\n if not isinstance(data, np.ndarray):\n s = data.encode(encoding='UTF-16', errors='strict')\n return np.ndarray(shape=((len(s)-2)//2,), dtype='uint16',\n buffer=s[2:])\n\n # It is an array of strings. Each string in the array needs to be\n # converted. An object array is needed to hold all the converted\n # forms, as opposed to just constructing the final uint16 array,\n # because the converted forms could end up greatly differing lengths\n # depending on how many characters turn into doublets. The sizes of\n # each one need to be grabbed along the way to be able to construct\n # the final array. The easiest way to convert each string is to use\n # recursion.\n converted_strings = np.ndarray(shape=data.shape, dtype='object')\n sizes = np.zeros(shape=data.shape, dtype='int64')\n\n for index, x in np.ndenumerate(data):\n converted_strings[index] = convert_numpy_str_to_uint16(x)\n sizes[index] = np.prod(converted_strings[index].shape)\n\n # The shape of the new array is simply the shape of the old one with\n # the number of columns increased multiplicatively by the size of\n # the largest UTF-16 string so that everything will fit.\n length = np.max(sizes)\n shape = list(data.shape)\n shape[-1] *= length\n new_data = np.zeros(shape=tuple(shape), dtype='uint16')\n\n # Copy each string into new_data using clever indexing (using the\n # first part of index returns a 1d subarray that can be\n # addressed). Then, the conversion is done.\n for index, x in np.ndenumerate(converted_strings):\n new_data[index[:-1]][ \\\n (length*index[-1]):(length*index[-1]+sizes[index])] = x\n\n return new_data\n\ndef convert_numpy_str_to_uint32(data):\n \"\"\" Converts a numpy.str_ to its numpy.uint32 representation.\n\n Convert a ``numpy.str`` or an array of them (they are UTF-32\n strings) into the equivalent array of ``numpy.uint32`` that is byte\n for byte identical. Strings are expanded along rows (across columns)\n so a 2x3x4 array of 10 element strings will get turned into a 2x30x4\n array of uint32's.\n\n Parameters\n ----------\n data : numpy.str_ or numpy.ndarray of numpy.str_\n The string or array of them to convert.\n\n Returns\n -------\n numpy.ndarray of numpy.uint32\n The result of the conversion.\n\n See Also\n --------\n convert_numpy_str_to_uint16\n decode_to_numpy_str\n\n \"\"\"\n if data.nbytes == 0:\n # An empty string should be an empty uint32.\n return np.uint32([])\n else:\n # We need to calculate the new shape from the current shape,\n # which will have to be expanded along the rows to fit all the\n # characters (the dtype.itemsize gets the number of bytes in\n # each string, which is just 4 times the number of\n # characters. Then it is a mstter of getting a view of the\n # string (in flattened form so that it is contiguous) as uint32\n # and then reshaping it.\n shape = list(np.atleast_1d(data).shape)\n shape[-1] *= data.dtype.itemsize//4\n return data.flatten().view(np.uint32).reshape(tuple(shape))\n\ndef convert_to_str(data):\n \"\"\" Decodes data to the Python 3.x str (Python 2.x unicode) type.\n\n Decodes `data` to a Python 3.x ``str`` (Python 2.x ``unicode``). If\n it can't be decoded, it is returned as is. Unsigned integers, Python\n ``bytes``, and Numpy strings (``numpy.str_`` and\n ``numpy.bytes_``). Python 3.x ``bytes``, Python 2.x ``str``, and\n ``numpy.bytes_`` are assumed to be encoded in UTF-8.\n\n Parameters\n ----------\n data : some type\n Data decode into an ``str`` string.\n\n Returns\n -------\n str or data\n If `data` can be decoded into a ``str``, the decoded version is\n returned. Otherwise, `data` is returned unchanged.\n\n See Also\n --------\n convert_to_numpy_str\n convert_to_numpy_bytes\n\n \"\"\"\n # How the conversion is done depends on the exact underlying\n # type. Numpy types are handled separately. For uint types, it is\n # assumed to be stored as UTF-8, UTF-16, or UTF-32 depending on the\n # size when converting to an str. numpy.string_ is just like\n # converting a bytes. numpy.unicode has to be encoded into bytes\n # before it can be decoded back into an str. bytes is decoded\n # assuming it is in UTF-8. Otherwise, data has to be returned as is.\n\n if isinstance(data, (np.ndarray, np.uint8, np.uint16, np.uint32,\n np.bytes_, np.unicode_)):\n if data.dtype.name == 'uint8':\n return data.flatten().tostring().decode('UTF-8')\n elif data.dtype.name == 'uint16':\n return data.flatten().tostring().decode('UTF-16')\n elif data.dtype.name == 'uint32':\n return data.flatten().tostring().decode('UTF-32')\n elif data.dtype.char == 'S':\n return data.decode('UTF-8')\n else:\n if isinstance(data, np.ndarray):\n return data.flatten.tostring().decode('UTF-32')\n else:\n return data.encode('UTF-32').decode('UTF-32')\n\n if isinstance(data, bytes):\n return data.decode('UTF-8')\n else:\n return data\n\n\ndef convert_to_numpy_str(data, length=None):\n \"\"\" Decodes data to Numpy unicode string (str_).\n\n Decodes `data` to Numpy unicode string (UTF-32), which is\n ``numpy.str_``, or an array of them. If it can't be decoded, it is\n returned as is. Unsigned integers, Python string types (``str``,\n ``bytes``), and ``numpy.bytes_`` are supported. If it is an array of\n ``numpy.bytes_``, an array of those all converted to ``numpy.str_``\n is returned. Python 3.x ``bytes``, Python 2.x ``str``, and\n ``numpy.bytes_`` are assumed to be encoded in UTF-8.\n\n For an array of unsigned integers, it may be desirable to make an\n array with strings of some specified length as opposed to an array\n of the same size with each element being a one element string. This\n naturally arises when converting strings to unsigned integer types\n in the first place, so it needs to be reversible. The `length`\n parameter specifies how many to group together into a string\n (desired string length). For 1d arrays, this is along its only\n dimension. For higher dimensional arrays, it is done along each row\n (across columns). So, for a 3x10x5 input array of uints and a\n `length` of 5, the output array would be a 3x2x5 of 5 element\n strings.\n\n Parameters\n ----------\n data : some type\n Data decode into a Numpy unicode string.\n length : int or None, optional\n The number of consecutive elements (in the case of unsigned\n integer `data`) to compose each string in the output array from.\n ``None`` indicates the full amount for a 1d array or the number\n of columns (full length of row) for a higher dimension array.\n\n Returns\n -------\n numpy.str_ or numpy.ndarray of numpy.str_ or data\n If `data` can be decoded into a ``numpy.str_`` or a\n ``numpy.ndarray`` of them, the decoded version is returned.\n Otherwise, `data` is returned unchanged.\n\n See Also\n --------\n convert_to_str\n convert_to_numpy_bytes\n numpy.str_\n\n \"\"\"\n # The method of conversion depends on its type.\n if isinstance(data, np.unicode_) or (isinstance(data, np.ndarray) \\\n and data.dtype.char == 'U'):\n # It is already an np.str_ or array of them, so nothing needs to\n # be done.\n return data\n elif (sys.hexversion >= 0x03000000 and isinstance(data, str)) \\\n or (sys.hexversion < 0x03000000 \\\n and isinstance(data, unicode)):\n # Easily converted through constructor.\n return np.unicode_(data)\n elif isinstance(data, (bytes, bytearray, np.bytes_)):\n # All of them can be decoded and then passed through the\n # constructor.\n return np.unicode_(data.decode('UTF-8'))\n elif isinstance(data, (np.uint8, np.uint16)):\n # They are single UTF-8 or UTF-16 scalars, and are easily\n # converted to a UTF-8 string and then passed through the\n # constructor.\n return np.unicode_(convert_to_str(data))\n elif isinstance(data, np.uint32):\n # It is just the uint32 version of the character, so it just\n # needs to be have the dtype essentially changed by having its\n # bytes read into ndarray.\n return np.ndarray(shape=tuple(), dtype='U1',\n buffer=data.flatten().tostring())[()]\n elif isinstance(data, np.ndarray) and data.dtype.char == 'S':\n # We just need to convert it elementwise.\n new_data = np.zeros(shape=data.shape,\n dtype='U' + str(data.dtype.itemsize))\n for index, x in np.ndenumerate(data):\n new_data[index] = np.unicode_(x.decode('UTF-8'))\n return new_data\n elif isinstance(data, np.ndarray) \\\n and data.dtype.name in ('uint8', 'uint16', 'uint32'):\n # It is an ndarray of some uint type. How it is converted\n # depends on its shape. If its shape is just (), then it is just\n # a scalar wrapped in an array, which can be converted by\n # recursing the scalar value back into this function.\n shape = list(data.shape)\n if len(shape) == 0:\n return convert_to_numpy_str(data[()])\n\n # As there are more than one element, it gets a bit more\n # complicated. We need to take the subarrays of the specified\n # length along columns (1D arrays will be treated as row arrays\n # here), each of those converted to an str_ scalar (normal\n # string) and stuffed into a new array.\n #\n # If the length was not given, it needs to be set to full. Then\n # the shape of the new array needs to be calculated (divide the\n # appropriate dimension, which depends on the number of\n # dimentions).\n if len(shape) == 1:\n if length is None:\n length = shape[0]\n new_shape = (shape[0]//length,)\n else:\n if length is None:\n length = shape[-1]\n new_shape = copy.deepcopy(shape)\n new_shape[-1] //= length\n\n # The new array can be made as all zeros (nulls) with enough\n # padding to hold everything (dtype='UL' where 'L' is the\n # length). It will start out as a 1d array and be reshaped into\n # the proper shape later (makes indexing easier).\n new_data = np.zeros(shape=(np.prod(new_shape),),\n dtype='U'+str(length))\n\n # With data flattened into a 1d array, we just need to take\n # length sized chunks, convert them (if they are uint8 or 16,\n # then decode to str first, if they are uint32, put them as an\n # input buffer for an ndarray of type 'U').\n data = data.flatten()\n for i in range(0, new_data.shape[0]):\n chunk = data[(i*length):((i+1)*length)]\n if data.dtype.name == 'uint32':\n new_data[i] = np.ndarray(shape=tuple(),\n dtype=new_data.dtype,\n buffer=chunk.tostring())[()]\n else:\n new_data[i] = np.unicode_(convert_to_str(chunk))\n\n # Only thing is left is to reshape it.\n return new_data.reshape(tuple(new_shape))\n else:\n # Couldn't figure out what it is, so nothing can be done but\n # return it as is.\n return data\n\n\ndef convert_to_numpy_bytes(data, length=None):\n \"\"\" Decodes data to Numpy UTF-8 econded string (bytes_).\n\n Decodes `data` to a Numpy UTF-8 encoded string, which is\n ``numpy.bytes_``, or an array of them in which case it will be ASCII\n encoded instead. If it can't be decoded, it is returned as\n is. Unsigned integers, Python string types (``str``, ``bytes``), and\n ``numpy.str_`` (UTF-32) are supported.\n\n For an array of unsigned integers, it may be desirable to make an\n array with strings of some specified length as opposed to an array\n of the same size with each element being a one element string. This\n naturally arises when converting strings to unsigned integer types\n in the first place, so it needs to be reversible. The `length`\n parameter specifies how many to group together into a string\n (desired string length). For 1d arrays, this is along its only\n dimension. For higher dimensional arrays, it is done along each row\n (across columns). So, for a 3x10x5 input array of uints and a\n `length` of 5, the output array would be a 3x2x5 of 5 element\n strings.\n\n Parameters\n ----------\n data : some type\n Data decode into a Numpy UTF-8 encoded string/s.\n length : int or None, optional\n The number of consecutive elements (in the case of unsigned\n integer `data`) to compose each string in the output array from.\n ``None`` indicates the full amount for a 1d array or the number\n of columns (full length of row) for a higher dimension array.\n\n Returns\n -------\n numpy.bytes_ or numpy.ndarray of numpy.bytes_ or data\n If `data` can be decoded into a ``numpy.bytes_`` or a\n ``numpy.ndarray`` of them, the decoded version is returned.\n Otherwise, `data` is returned unchanged.\n\n See Also\n --------\n convert_to_str\n convert_to_numpy_str\n numpy.bytes_\n\n \"\"\"\n # The method of conversion depends on its type.\n if isinstance(data, np.bytes_) or (isinstance(data, np.ndarray) \\\n and data.dtype.char == 'S'):\n # It is already an np.bytes_ or array of them, so nothing needs\n # to be done.\n return data\n elif isinstance(data, (bytes, bytearray)):\n # Easily converted through constructor.\n return np.bytes_(data)\n elif (sys.hexversion >= 0x03000000 and isinstance(data, str)) \\\n or (sys.hexversion < 0x03000000 \\\n and isinstance(data, unicode)):\n return np.bytes_(data.encode('UTF-8'))\n elif isinstance(data, (np.uint16, np.uint32)):\n # They are single UTF-16 or UTF-32 scalars, and are easily\n # converted to a UTF-8 string and then passed through the\n # constructor.\n return np.bytes_(convert_to_str(data).encode('UTF-8'))\n elif isinstance(data, np.uint8):\n # It is just the uint8 version of the character, so it just\n # needs to be have the dtype essentially changed by having its\n # bytes read into ndarray.\n return np.ndarray(shape=tuple(), dtype='S1',\n buffer=data.flatten().tostring())[()]\n elif isinstance(data, np.ndarray) and data.dtype.char == 'U':\n # We just need to convert it elementwise.\n new_data = np.zeros(shape=data.shape,\n dtype='S' + str(data.dtype.itemsize))\n for index, x in np.ndenumerate(data):\n new_data[index] = np.bytes_(x.encode('UTF-8'))\n return new_data\n elif isinstance(data, np.ndarray) \\\n and data.dtype.name in ('uint8', 'uint16', 'uint32'):\n # It is an ndarray of some uint type. How it is converted\n # depends on its shape. If its shape is just (), then it is just\n # a scalar wrapped in an array, which can be converted by\n # recursing the scalar value back into this function.\n shape = list(data.shape)\n if len(shape) == 0:\n return convert_to_numpy_bytes(data[()])\n\n # As there are more than one element, it gets a bit more\n # complicated. We need to take the subarrays of the specified\n # length along columns (1D arrays will be treated as row arrays\n # here), each of those converted to an str_ scalar (normal\n # string) and stuffed into a new array.\n #\n # If the length was not given, it needs to be set to full. Then\n # the shape of the new array needs to be calculated (divide the\n # appropriate dimension, which depends on the number of\n # dimentions).\n if len(shape) == 1:\n if length is None:\n length2 = shape[0]\n new_shape = (shape[0],)\n else:\n length2 = length\n new_shape = (shape[0]//length2,)\n else:\n if length is None:\n length2 = shape[-1]\n else:\n length2 = length\n new_shape = copy.deepcopy(shape)\n new_shape[-1] //= length2\n\n # The new array can be made as all zeros (nulls) with enough\n # padding to hold everything (dtype='UL' where 'L' is the\n # length). It will start out as a 1d array and be reshaped into\n # the proper shape later (makes indexing easier).\n new_data = np.zeros(shape=(np.prod(new_shape),),\n dtype='S'+str(length2))\n\n # With data flattened into a 1d array, we just need to take\n # length sized chunks, convert them (if they are uint8 or 16,\n # then decode to str first, if they are uint32, put them as an\n # input buffer for an ndarray of type 'U').\n data = data.flatten()\n for i in range(0, new_data.shape[0]):\n chunk = data[(i*length2):((i+1)*length2)]\n if data.dtype.name == 'uint8':\n new_data[i] = np.ndarray(shape=tuple(),\n dtype=new_data.dtype,\n buffer=chunk.tostring())[()]\n else:\n new_data[i] = np.bytes_( \\\n convert_to_str(chunk).encode('UTF-8'))\n\n # Only thing is left is to reshape it.\n return new_data.reshape(tuple(new_shape))\n else:\n # Couldn't figure out what it is, so nothing can be done but\n # return it as is.\n return data\n\n\ndef decode_complex(data, complex_names=(None, None)):\n \"\"\" Decodes possibly complex data read from an HDF5 file.\n\n Decodes possibly complex datasets read from an HDF5 file. HDF5\n doesn't have a native complex type, so they are stored as\n H5T_COMPOUND types with fields such as 'r' and 'i' for the real and\n imaginary parts. As there is no standardization for field names, the\n field names have to be given explicitly, or the fieldnames in `data`\n analyzed for proper decoding to figure out the names. A variety of\n reasonably expected combinations of field names are checked and used\n if available to decode. If decoding is not possible, it is returned\n as is.\n\n Parameters\n ----------\n data : arraylike\n The data read from an HDF5 file, that might be complex, to\n decode into the proper Numpy complex type.\n complex_names : tuple of 2 str and/or Nones, optional\n ``tuple`` of the names to use (in order) for the real and\n imaginary fields. A ``None`` indicates that various common\n field names should be tried.\n\n Returns\n -------\n decoded data or data\n If `data` can be decoded into a complex type, the decoded\n complex version is returned. Otherwise, `data` is returned\n unchanged.\n\n See Also\n --------\n encode_complex\n\n Notes\n -----\n Currently looks for real field names of ``('r', 're', 'real')`` and\n imaginary field names of ``('i', 'im', 'imag', 'imaginary')``\n ignoring case.\n\n \"\"\"\n # Now, complex types are stored in HDF5 files as an H5T_COMPOUND type\n # with fields along the lines of ('r', 're', 'real') and ('i', 'im',\n # 'imag', 'imaginary') for the real and imaginary parts, which most\n # likely won't be properly extracted back into making a Python\n # complex type unless the proper h5py configuration is set. Since we\n # can't depend on it being set and adjusting it is hazardous (the\n # setting is global), it is best to just decode it manually. These\n # fields are obtained from the fields of its dtype. Obviously, if\n # there are no fields, then there is nothing to do.\n if data.dtype.fields is None:\n return data\n\n fields = list(data.dtype.fields)\n\n # If there aren't exactly two fields, then it can't be complex.\n if len(fields) != 2:\n return data\n\n # We need to grab the field names for the real and imaginary\n # parts. This will be done by seeing which list, if any, each field\n # is and setting variables to the proper name if it is in it (they\n # are initialized to None so that we know if one isn't found).\n\n real_fields = ['r', 're', 'real']\n imag_fields = ['i', 'im', 'imag', 'imaginary']\n\n cnames = list(complex_names)\n for s in fields:\n if s.lower() in real_fields:\n cnames[0] = s\n elif s.lower() in imag_fields:\n cnames[1] = s\n\n # If the real and imaginary fields were found, construct the complex\n # form from the fields. Now, in the case that one part is NaN but\n # the other is not, simply adding the real and complex parts\n # together will set both to NaN; so the ones where one and only one\n # component is NaN have to be set manually using the complex\n # function. Otherwise, return what we were given because it isn't in\n # the right form.\n if cnames[0] is not None and cnames[1] is not None:\n cdata = data[cnames[0]] + 1j*data[cnames[1]]\n for index in np.flatnonzero(np.isnan(data[cnames[0]]) \\\n ^ np.isnan(data[cnames[1]])):\n cdata.ravel()[index] = complex( \\\n data[cnames[0]].ravel()[index], \\\n data[cnames[1]].ravel()[index])\n return cdata\n else:\n return data\n\n\ndef encode_complex(data, complex_names):\n \"\"\" Encodes complex data to having arbitrary complex field names.\n\n Encodes complex `data` to have the real and imaginary field names\n given in `complex_numbers`. This is needed because the field names\n have to be set so that it can be written to an HDF5 file with the\n right field names (HDF5 doesn't have a native complex type, so\n H5T_COMPOUND have to be used).\n\n Parameters\n ----------\n data : arraylike\n The data to encode as a complex type with the desired real and\n imaginary part field names.\n complex_names : tuple of 2 str\n ``tuple`` of the names to use (in order) for the real and\n imaginary fields.\n\n Returns\n -------\n encoded data\n `data` encoded into having the specified field names for the\n real and imaginary parts.\n\n See Also\n --------\n decode_complex\n\n \"\"\"\n # Grab the dtype name, and convert it to the right non-complex type\n # if it isn't already one.\n dtype_name = data.dtype.name\n if dtype_name[0:7] == 'complex':\n dtype_name = 'float' + str(int(float(dtype_name[7:])/2))\n\n # Create the new version of the data with the right field names for\n # the real and complex parts. This is easy to do with putting the\n # right detype in the view function.\n dt = np.dtype([(complex_names[0], dtype_name),\n (complex_names[1], dtype_name)])\n return data.view(dt).copy()\n\n\ndef get_attribute(target, name):\n \"\"\" Gets an attribute from a Dataset or Group.\n\n Gets the value of an Attribute if it is present (get ``None`` if\n not).\n\n Parameters\n ----------\n target : Dataset or Group\n Dataset or Group to get the attribute of.\n name : str\n Name of the attribute to get.\n\n Returns\n -------\n The value of the attribute if it is present, or ``None`` if it\n isn't.\n\n \"\"\"\n if name not in target.attrs:\n return None\n else:\n return target.attrs[name]\n\n\ndef get_attribute_string(target, name):\n \"\"\" Gets a string attribute from a Dataset or Group.\n\n Gets the value of an Attribute that is a string if it is present\n (get ``None`` if it is not present or isn't a string type).\n\n Parameters\n ----------\n target : Dataset or Group\n Dataset or Group to get the string attribute of.\n name : str\n Name of the attribute to get.\n\n Returns\n -------\n str or None\n The ``str`` value of the attribute if it is present, or ``None``\n if it isn't or isn't a type that can be converted to ``str``\n\n \"\"\"\n value = get_attribute(target, name)\n if value is None:\n return value\n elif (sys.hexversion >= 0x03000000 and isinstance(value, str)) \\\n or (sys.hexversion < 0x03000000 \\\n and isinstance(value, unicode)):\n return value\n elif isinstance(value, bytes):\n return value.decode()\n elif isinstance(value, np.unicode_):\n return str(value)\n elif isinstance(value, np.bytes_):\n return value.decode()\n else:\n return None\n\n\ndef get_attribute_string_array(target, name):\n \"\"\" Gets a string array Attribute from a Dataset or Group.\n\n Gets the value of an Attribute that is a string array if it is\n present (get ``None`` if not).\n\n Parameters\n ----------\n target : Dataset or Group\n Dataset or Group to get the attribute of.\n name : str\n Name of the string array Attribute to get.\n\n Returns\n -------\n list of str or None\n The string array value of the Attribute if it is present, or\n ``None`` if it isn't.\n\n \"\"\"\n value = get_attribute(target, name)\n if value is None:\n return value\n return [convert_to_str(x) for x in value]\n\n\ndef set_attribute(target, name, value):\n \"\"\" Sets an attribute on a Dataset or Group.\n\n If the attribute `name` doesn't exist yet, it is created. If it\n already exists, it is overwritten if it differs from `value`.\n\n Parameters\n ----------\n target : Dataset or Group\n Dataset or Group to set the attribute of.\n name : str\n Name of the attribute to set.\n value : numpy type other than ``numpy.str_``\n Value to set the attribute to.\n\n \"\"\"\n if name not in target.attrs:\n target.attrs.create(name, value)\n elif target.attrs[name].dtype != value.dtype \\\n or target.attrs[name].shape != value.shape:\n target.attrs.create(name, value)\n elif np.any(target.attrs[name] != value):\n target.attrs.modify(name, value)\n\n\ndef set_attribute_string(target, name, value):\n \"\"\" Sets an attribute to a string on a Dataset or Group.\n\n If the attribute `name` doesn't exist yet, it is created. If it\n already exists, it is overwritten if it differs from `value`.\n\n Parameters\n ----------\n target : Dataset or Group\n Dataset or Group to set the string attribute of.\n name : str\n Name of the attribute to set.\n value : string\n Value to set the attribute to. Can be any sort of string type\n that will convert to a ``numpy.bytes_``\n\n \"\"\"\n set_attribute(target, name, np.bytes_(value))\n\n\ndef set_attribute_string_array(target, name, string_list):\n \"\"\" Sets an attribute to an array of string on a Dataset or Group.\n\n If the attribute `name` doesn't exist yet, it is created. If it\n already exists, it is overwritten with the list of string\n `string_list` (they will be vlen strings).\n\n Parameters\n ----------\n target : Dataset or Group\n Dataset or Group to set the string array attribute of.\n name : str\n Name of the attribute to set.\n string_list : list of str\n List of strings to set the attribute to. Strings must be ``str``\n\n \"\"\"\n s_list = [convert_to_str(s) for s in string_list]\n if sys.hexversion >= 0x03000000:\n target.attrs.create(name, s_list,\n dtype=h5py.special_dtype(vlen=str))\n else:\n target.attrs.create(name, s_list,\n dtype=h5py.special_dtype(vlen=unicode))\n\n\ndef del_attribute(target, name):\n \"\"\" Deletes an attribute on a Dataset or Group.\n\n If the attribute `name` exists, it is deleted.\n\n Parameters\n ----------\n target : Dataset or Group\n Dataset or Group to delete attribute of.\n name : str\n Name of the attribute to delete.\n\n \"\"\"\n if name in target.attrs:\n del target.attrs[name]\n","sub_path":"hdf5storage/utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":31879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"435164573","text":"\"\"\" 189. Rotate Array\nhttps://leetcode.com/problems/rotate-array/\n\nGiven an array, rotate the array to the right by k steps,\nwhere k is non-negative.\n\nExample 1:\nInput: nums = [1,2,3,4,5,6,7], k = 3\nOutput: [5,6,7,1,2,3,4]\nExplanation:\nrotate 1 steps to the right: [7,1,2,3,4,5,6]\nrotate 2 steps to the right: [6,7,1,2,3,4,5]\nrotate 3 steps to the right: [5,6,7,1,2,3,4]\n\nExample 2:\nInput: nums = [-1,-100,3,99], k = 2\nOutput: [3,99,-1,-100]\nExplanation:\nrotate 1 steps to the right: [99,-1,-100,3]\nrotate 2 steps to the right: [3,99,-1,-100]\n\nConstraints:\n1 <= nums.length <= 2 * 10^4\n-2^31 <= nums[i] <= 2^31 - 1\n0 <= k <= 10^5\n\"\"\"\n\n\nclass Solution:\n def reverse(self, nums: list[any], lo_idx: int, hi_idx: int):\n while lo_idx < hi_idx:\n nums[lo_idx], nums[hi_idx] = nums[hi_idx], nums[lo_idx]\n lo_idx += 1\n hi_idx -= 1\n\n def rotate(self, nums: list[any], k: int) -> None:\n base = len(nums)\n shift = k % base\n self.reverse(nums, 0, base - 1)\n self.reverse(nums, 0, shift - 1)\n self.reverse(nums, shift, base - 1)\n\n return\n\n# Had to look for a better solution\n# Runtime: 64 ms, faster than 55.11% of Python3 online submissions for Rotate Array.\n# Memory Usage: 15.7 MB, less than 33.02% of Python3 online submissions for Rotate Array.\n\nif __name__ == '__main__':\n my_solution = Solution()\n in_lst1 = [1,2,3,4,5,6,7]\n in_tgt = 3\n in_lst1 = [-1,-100,3,99]\n in_tgt = 2\n # in_lst1 = [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\"]\n # in_tgt = 4\n\n print(\"input: {}\".format(in_lst1))\n print(\"target: {}\".format(in_tgt))\n my_solution.rotate(in_lst1, in_tgt)\n print(\"result: {}\".format(in_lst1))\n","sub_path":"01/80-89/0189-rotate-array/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"176406472","text":"#!/usr/bin/python3\nimport os\nimport sys\nimport subprocess\n\ndef replication_check(context):\n context_for_check = context.replace('.', ',')\n command = ['samba-tool', 'drs', 'replicate', 'pdc1', 'pdc2', context_for_check]\n shell_command = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n decode = shell_command.stdout.decode('utf-8')\n #print(decode)\n if decode.find(\"was successful\") > -1:\n return 0\n else:\n return 1\n\nprint(replication_check(sys.argv[1]))\n","sub_path":"RepMon.1.3.py","file_name":"RepMon.1.3.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"574480228","text":"\nimport subprocess\nimport tempfile\nimport os\n\nclass OsExtException(BaseException):\n pass\n\ndef execute(cmd):\n \"\"\"\n Execute a OS command, throw an exception if the return code isn't 0, \n return all data written to stdout and stderr once execution finishes.\n \"\"\"\n \n fh = tempfile.NamedTemporaryFile(delete=False)\n return_code = subprocess.check_call(cmd, stderr=fh, stdout=fh, shell=False)\n filename = fh.name\n fh.close()\n \n fh = open(filename, 'r')\n std_all = fh.read()\n fh.close()\n \n tryno = 0\n done = False\n while(not done):\n try:\n os.unlink(filename)\n done = True\n except Exception as e:\n tryno += 1\n print(e)\n if tryno > 100000:\n raise e\n \n assert(not os.path.exists(filename))\n \n return std_all\n\ndef test_module():\n execute('dir')\n \n isFail = False\n try:\n execute('invalid_for_sure command')\n except OsExtException as e:\n isFail = True\n assert( isFail )\n \nif __name__ == '__main__':\n test_module()\n","sub_path":"osext.py","file_name":"osext.py","file_ext":"py","file_size_in_byte":1093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"24909430","text":"# INSTANCE AND CLASS VARIABLES\r\nclass Employee:\r\n no_of_leaves = 8 # Class name should start form capital for convention.\r\n pass\r\n\r\nharry = Employee()\r\nrohan = Employee()\r\n\r\nharry.name = \"Harry\"\r\nharry.salary = 445\r\nharry.role = \"Instruntor\"\r\n\r\nrohan.name = \"Rohan\"\r\nrohan.salary = 4554 # These are the own properties of the objects.\r\nrohan.role = (\"Student\")\r\nprint(rohan.name)\r\nprint(harry.salary)\r\nprint(harry.no_of_leaves) # This is same for all objects as it is a template.\r\nprint(rohan.no_of_leaves)\r\nprint(Employee.no_of_leaves)\r\nprint(Employee.__dict__) # This is the dictionary of the object.\r\nEmployee.no_of_leaves = 9 # This changes the properties of all the objects. The class variable cannot be changed using an object.\r\nrohan.no_of_leaves = 10 # This changes the properties of the specific object.\r\nprint(rohan.no_of_leaves)\r\nprint(Employee.__dict__) # The dictionary of the object is changed.\r\n # All the objects share the clas variable.\r\n","sub_path":"Code With Harry/Python Tuts/tut41 (Istance and Class Variable).py","file_name":"tut41 (Istance and Class Variable).py","file_ext":"py","file_size_in_byte":961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"585941448","text":"import re\n\nwith open(\"input.txt\") as input_file:\n program = input_file.read().splitlines()\n\nmask = ''\nmemory = {}\n\n\ndef apply_mask(dec_value):\n # Convert decimal value to binary string and pad left with zeros so length is 36\n # Then convert string to list since strings do not support setitem\n bin_string = list(bin(dec_value).replace(\"0b\", \"\").rjust(36, '0'))\n\n for i in range(0, len(mask)):\n if mask[i] != 'X':\n bin_string[i] = mask[i]\n\n dec_value = int(\"\".join(bin_string), 2)\n return dec_value\n\n\ndef parse(operation):\n operation = re.search(r\"mem\\[([0-9]+)] = ([0-9]+)\", operation)\n a = operation.group(1)\n v = apply_mask(int(operation.group(2)))\n return a, v\n\n\nfor line in program:\n if line.startswith(\"mask\"):\n mask = line.strip(\"mask = \")\n continue\n\n address, value = parse(line)\n # print(\"{}, {}\".format(address, value))\n memory[address] = value\n\ntotal = 0\nfor v in memory.values():\n total += v\n\nprint(total)\n","sub_path":"2020/14/puzzle_1.py","file_name":"puzzle_1.py","file_ext":"py","file_size_in_byte":997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"434612779","text":"from PyQt4 import QtGui, QtCore\nimport numpy as np\nimport cv2\nfrom image_loader_processor import *\n\n\nclass HistogramWidget(QtGui.QWidget):\n def __init__(self):\n super(HistogramWidget, self).__init__()\n\n self.img_proc = None\n\n self.averages = None\n self.ranges = None\n self.initUI()\n\n def initUI(self):\n self.setMinimumSize(300, 70)\n self.setMaximumHeight(70)\n\n def paintEvent(self, e):\n qp = QtGui.QPainter()\n qp.begin(self)\n self.drawWidget(qp)\n qp.end()\n\n def setImage(self, img_proc):\n assert(isinstance(img_proc, ImageLoaderProcessor))\n self.img_proc = img_proc\n self.update()\n\n def drawWidget(self, qp):\n #font = QtGui.QFont('Serif', 7, QtGui.QFont.Light)\n #qp.setFont(font)\n\n size = self.size()\n w = size.width()\n h = size.height()\n\n qp.setRenderHint(QtGui.QPainter.Antialiasing)\n\n qp.setPen(QtCore.Qt.NoPen)\n qp.setBrush(QtGui.QColor(50, 50, 50))\n qp.drawRect(0, 0, w, h)\n\n if self.img_proc is None:\n return\n\n hist = self.img_proc.get_histogram()[0]\n\n # Stretch histogram to fit widget\n trans = QtGui.QTransform()\n trans.scale(w / len(hist), -1)\n trans.translate(0, -h)\n qp.setTransform(trans)\n\n if self.img_proc is not None:\n qp.setPen(QtCore.Qt.NoPen)\n # qp.setPen(QtGui.QColor(230, 230, 230))\n qp.setBrush(QtGui.QColor(150, 150, 150))\n\n for idx in range(len(hist)):\n qp.drawRect(QtCore.QRectF(idx, 0, 1.1, hist[idx] * 50))\n\n","sub_path":"histogram_widget.py","file_name":"histogram_widget.py","file_ext":"py","file_size_in_byte":1636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"652753699","text":"import torch\nimport torch.nn as nn\nimport torch.nn.utils.rnn as rnn_utils\nimport torch.nn.functional as F\nimport torchvision.models as models\nfrom torch.nn.utils.rnn import PackedSequence\n\n'''\n# Image Embed (Resnet152) \n''' \n\n# COMMENTS\n\n# self.resnet_back is not used\n\n# num_classes = 1000 doesn't exist for our use case:\n# we don't have 1000 image classifications, just 1000 arbitrary classes\n# this particular fc isn't actually useful because we have \n# another fc layer nn.linear(image_ftrs + question_ftrs, 1024) in ConcatNet\n\nclass ImageEmbedding(nn.Module):\n def __init__(self, mode = 'train', freeze=True, with_attention=True): #1024 or 1000?\n super(ImageEmbedding, self).__init__()\n #get the first 0-7 layers ; delete the avgpool and fc layers\n self.with_attention = with_attention\n resnet = models.resnet152(pretrained=True)\n modules_front = list(resnet.children())[0:8] \n self.resnet_front = nn.Sequential(*modules_front)\n \n # freezing resnet_front\n if freeze:\n for param in self.resnet_front.parameters():\n param.requires_grad = False\n \n # get the avgpool and fc layers back\n self.resnet_back_pool = nn.AvgPool2d(kernel_size = 10, stride=1, padding=0) #1, 2048, 1, 1\n \n def forward(self, image):\n '''\n Outputs a 10x10x2048\n '''\n image = self.resnet_front(image)\n image = F.normalize(image, p=2, dim=1)\n if not self.with_attention:\n image = self.resnet_back_pool(image)\n image = image.view(-1, 2048)\n return image \n\n'''\n# Question Embed (LSTM) \n''' \nclass QnsEmbedding(nn.Module):\n def __init__(self, input_size = 300, question_ftrs = 1024, num_layers = 1, batch_first = True): #500 is word embedding size\n super(QnsEmbedding, self).__init__()\n self.tanh = nn.Tanh() #passed into tanh before feed into LSTM\n self.lstm = nn.LSTM(input_size = input_size, hidden_size = question_ftrs, num_layers = num_layers, batch_first = batch_first)\n self.num_layers = num_layers\n self.question_ftrs = question_ftrs\n self.cache = None\n \n def forward (self, inputs, cache=None):\n # refresh cache everytime forward is called\n if cache:\n self.cache = cache\n elif inputs.batch_sizes[0] != self.cache[0].size(1):\n self.init_cache(batch=inputs.batch_sizes[0])\n else:\n self.cache = [t*0 for t in self.cache]\n inputs_data = self.tanh(inputs.data) \n inputs = PackedSequence(inputs_data, inputs.batch_sizes)\n output, (hn, cn) = self.lstm(inputs, self.cache)\n return hn, cn\n \n def init_cache(self, batch=1, use_gpu = True):\n h0 = torch.zeros(self.num_layers, batch, self.question_ftrs)\n c0 = torch.zeros(self.num_layers, batch, self.question_ftrs)\n if use_gpu:\n h0, c0 = h0.cuda(), c0.cuda()\n self.cache = [h0, c0]\n return (h0, c0)\t\n\n'''\n# Attention Models \n''' \nclass Attention(nn.Module):\n def __init__ (self, image_ftrs=2048, question_ftrs=1024, k=512, glimpse=2, dropout=True, mode='train'):\n super(Attention, self).__init__()\n self.mode = mode\n self.image_ftrs = image_ftrs\n self.k_size = k\n self.question_ftrs = question_ftrs\n self.glimpse = glimpse\n self.conv_1 = nn.Conv2d(image_ftrs, k, 1) \n self.question_mid_fc = nn.Linear(question_ftrs, k)\n self.relu = nn.ReLU()\n self.conv_2 = nn.Conv2d(k, glimpse, 1)\n self.softmax = nn.Softmax(dim = 1)\n \n def forward (self, image_embed, questions_embed):\n '''\n image_embed = bx10x10x2048\n questions_embed = bx1x1024\n '''\n b, c, s1, s2 = image_embed.size()\n img_conv = self.conv_1(image_embed)\n \n # tiling\n qns_ft = self.question_mid_fc(questions_embed.view(b, self.question_ftrs))\n tiled_qns_ft = qns_ft.view(b, self.k_size, 1, 1).expand_as(img_conv)\n \n output = self.relu(img_conv + tiled_qns_ft)\n output = self.conv_2(output)\n output = self.softmax(output.view(b, -1)).view(b, self.glimpse, s1, s2)\n return output\n \n \n'''\n# concat two models - LSTM and RESNET152 \n''' \n\nclass ConcatNet(nn.Module):\n def __init__(self, vocab_size, word_emb_size = 300, emb_size = 1024, with_attention=True,\n glimpse=2, lstm_layers=1, output_size=3001, mode = 'train', freeze_resnet=True):\n super(ConcatNet, self).__init__()\n self.mode = mode\n self.freeze_resnet = freeze_resnet\n self.with_attention = with_attention\n self.glimpse = glimpse\n\n self.img_channel = ImageEmbedding(mode = mode, freeze=freeze_resnet, with_attention=with_attention)\n self.qns_channel = QnsEmbedding(word_emb_size, question_ftrs=emb_size, num_layers=lstm_layers, batch_first = True)\n if with_attention:\n self.atn_channel = Attention(question_ftrs=emb_size, glimpse=glimpse)\n \n self.word_emb_size = word_emb_size\n #vocab_size: size of dictionary embeddings, word_emb_size: size of each embedding vector\n self.word_embeddings = nn.Embedding(vocab_size, word_emb_size)\n if with_attention:\n inner_fc_inputsize = 2048 * self.glimpse + emb_size\n else:\n inner_fc_inputsize = 2048 + emb_size\n self.resolve_fc = nn.Sequential(nn.Dropout(0.5), nn.Linear(inner_fc_inputsize, 1024), \n nn.ReLU(), \n nn.Linear(1024, output_size), \n nn.Softmax(dim = 1))\n \n def forward(self, image, questions):\n image_embed = self.img_channel(image) # returns b x 10 x 10 x 2048\n emb_qns = self.word_embeddings(questions.data)\n embeds = PackedSequence(emb_qns, questions.batch_sizes)\n \n if not self.qns_channel.cache: # if cache is not inititated\n self.qns_channel.init_cache(batch=questions.batch_sizes[0])\n questions_embed, _ = self.qns_channel(embeds)\n questions_embed = questions_embed[-1]\n \n if self.with_attention:\n b, c, _, s = image_embed.size()\n img_attn = self.atn_channel(image_embed, questions_embed)\n # combining attention\n image_embed = image_embed.view(b, 1, c, -1).expand(b, self.glimpse, c, 100)\n img_attn = img_attn.view(b, self.glimpse, 1, -1).expand(b, self.glimpse, c, 100)\n image_final = (image_embed * img_attn).sum(dim=3).view(b, -1)\n else:\n image_final = image_embed\n \n added = torch.cat([image_final, questions_embed], dim=1)\n output = self.resolve_fc(added)\n return output\n \n def parameters(self):\n if self.freeze_resnet:\n all_params = list(self.qns_channel.parameters()) \\\n + list(self.resolve_fc.parameters()) \\\n + list(self.word_embeddings.parameters())\n if self.with_attention:\n all_params += list(self.atn_channel.parameters())\n return all_params\n else:\n return super(ConcatNet, self).parameters()\n \n \n","sub_path":"notebook/network_v6.py","file_name":"network_v6.py","file_ext":"py","file_size_in_byte":7300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"485330485","text":"import tensorflow as tf\n\n\"\"\"\nCTC损失函数: tensorflow 2.3.1 官方文档\ntf.nn.ctc_loss(labels, logits, label_length, logit_length, logits_time_major,blank_index)\n\nlabels: 真实标签,支持两种格式: 1.一维tensor,GPU/TPU训练时只能使用一维tensor, 2.稀疏tensor,推荐用于CPU训练,一维tensor也可用于CPU\n 1:一维tensor, shape为[batch_size, max_label_seq_length],长度为数据集中的最大标签长度,标签长度不够时用0在尾部填充\n 例如:有标签[2,5,3,7],[1,5],[2,8,9], 处理后为[ [2,5,3,7], [1,5,0,0], [2,8,9,0] ]\n 注意: 在 GPU/TPU 上计算CTC时 !必须! 使用一维tensor, CPU上训练时也可使用一维tensor\n \n 2:Sparse tensor稀疏张量, 例如:有标签[2,5,3,7],[1,5],[2,8,9], 处理后为: [indices, values, shape]\n indices=[(0,0),(0,1),(0,2),(0,3),(1,0),(1,1),(2,0),(2,1),(2,2)],\n values=[2,5,3,7,1,5,2,8,9],\n shape=(3,4), 3为行数,即标签的个数, 4为最大列数,即标签中的最大长度\n\nlogits: 网络预测值,有两种shape: \n 1:[frames, batch_size, num_labels] <--> [时序数, 批次大小, 类别数], logits_time_major为True时的shape\n \n 2:[batch_size, frames, num_labels] <--> [批次大小, 时序数, 类别数], logits_time_major为False时的shape\n\nlabel_length: 真实标签的长度序列,有两种格式: \n 1.一维tensor,shape为[batch_size],其值为真实标签的最大长度, 当labels为一维tensor时使用\n \n 2.None, 当labels为Sparse tensor时使用\n \nlogit_length: 预测值的长度序列, shape为[batch_size], 其值为logits中的时序数/frames\n\nlogits_time_major: (可选),默认为True, 其值为True时 logits 的shape为[时序数, 批次大小, 类别数]\n 其值为False时, shape为[批次大小, 时序数, 类别数]\n\nblank_index: (可选),默认为0, ctc中预测的空格在词库中的下标, 负数则从后往前计算词库的下标\n 例: 词库[a, 0, 1, b], blank_index为0时, 用a做ctc中的空格, blank_index为1时,用0做ctc中的空格, blank_index为正数时依此类推\n blank_index为-1时, 用b做ctc中的空格, blank_index为-2时, 用1做ctc中的空格, blank_index为负数时依此类推\n\nReturns: ctc loss, 一维tensor, shape为[batch_size], 值为负对数概率(negative log probabilities).\n\"\"\"\n\n\n# 自定义CTC Loss函数\nclass CTCLoss(tf.keras.losses.Loss):\n def __init__(self, logits_time_major=False, blank_index=-1, \n reduction=tf.keras.losses.Reduction.AUTO, name='ctc_loss'):\n super().__init__(reduction=reduction, name=name)\n self.logits_time_major = logits_time_major # 默认为False, 则logits/y_pred形状为 [批次大小, 时序数, 类别数]\n self.blank_index = blank_index # CTC中空格在词库中的位置, 默认值-1表示词库末尾\n\n def call(self, y_true, y_pred):\n y_true = tf.cast(y_true, tf.int32) # 将 y_true 中的值转换成int类型\n # 默认y_pred形状为[批次大小, 时序数, 类别数], logit_length的形状为[batch_size], 其值为时序数\n logit_length = tf.fill([tf.shape(y_pred)[0]], tf.shape(y_pred)[1]) # 返回用时序数填充shape为[批次大小]的一维张量\n loss = tf.nn.ctc_loss(\n labels=y_true, # y_true为稀疏张量\n logits=y_pred, # 网络预测值, 默认shape为 [批次大小, 时序数, 类别数]\n label_length=None, # y_true为稀疏张量时, label_length设为None\n logit_length=logit_length, # 形状为[batch_size], 其值为时序数\n logits_time_major=self.logits_time_major, # 默认为False\n blank_index=self.blank_index # 默认为-1\n )\n return tf.reduce_mean(loss)\n\n\n","sub_path":"TextLineRecognizer/CRNN/models/ctc_loss.py","file_name":"ctc_loss.py","file_ext":"py","file_size_in_byte":3964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"205116912","text":"# @Time : 2019/5/26 15:54\n# @Author : Xu Huipeng\n# @Blog : https://brycexxx.github.io/\n\nfrom typing import List\nfrom collections import Counter\n\n\nclass Solution:\n # 超时\n def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:\n res = []\n combination = []\n\n def is_repeat(comb: List[int]) -> bool:\n comb_counter = Counter(comb)\n for c in res:\n if Counter(c) == comb_counter: return True\n return False\n\n def recur(target: int):\n if target < 0: return\n if target == 0 and not is_repeat(combination):\n res.append(combination.copy())\n return\n for num in candidates:\n combination.append(num)\n recur(target - num)\n combination.pop()\n\n recur(target)\n return res\n\n def combinationSum1(self, candidates: List[int], target: int) -> List[List[int]]:\n candidates.sort()\n n = len(candidates)\n res = []\n\n def back_tracking(i: int, tmp_sum: int, tmp: List[int]) -> None:\n if tmp_sum > target or i == n:\n return\n if tmp_sum == target:\n res.append(tmp)\n return\n back_tracking(i, tmp_sum + candidates[i], tmp + [candidates[i]])\n back_tracking(i + 1, tmp_sum, tmp)\n\n back_tracking(0, 0, [])\n return res\n\n def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:\n candidates.sort()\n n = len(candidates)\n res = []\n\n def back_tracking(i: int, tmp_sum: int, tmp: List[int]) -> None:\n if tmp_sum > target or i == n:\n return\n if tmp_sum == target:\n res.append(tmp)\n return\n for j in range(i, n):\n if tmp_sum + candidates[j] > target:\n break\n back_tracking(j, tmp_sum + candidates[j], tmp + [candidates[j]])\n\n back_tracking(0, 0, [])\n return res\n\n\nif __name__ == '__main__':\n s = Solution()\n candidate = [2, 3, 6, 7, 4, 5]\n target = 9\n print(s.combinationSum1(candidate, target))\n print(s.combinationSum2(candidate, target))\n","sub_path":"combinationSum.py","file_name":"combinationSum.py","file_ext":"py","file_size_in_byte":2282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"59948645","text":"from gmaps import downloader\nimport os, gdal\nimport haversine as hs\nimport math\n\n\ndef split_image(input_filename, tile_size_x=1500, tile_size_y=1500, out_path='.', output_filename= 'tile_'):\n ds = gdal.Open(input_filename)\n band = ds.GetRasterBand(1)\n xsize = band.XSize\n ysize = band.YSize\n\n for i in range(0, xsize, tile_size_x):\n for j in range(0, ysize, tile_size_y):\n com_string = \"gdal_translate -of GTIFF -srcwin \" + str(i)+ \", \" + str(j) + \", \" + str(tile_size_x) + \", \" + str(tile_size_y) + \" \" + str(input_filename) + \" \" + str(out_path) + str(output_filename) + str(i) + \"_\" + str(j) + \".tif\"\n os.system(com_string)\n\n\nif __name__ == \"__main__\":\n marcianise_top_left = [41.05129674906493, 14.271082713309346]\n origin = marcianise_top_left\n square_edge = 4.5\n dest = hs.inverse_haversine((origin[0], origin[1]), square_edge*math.sqrt(2), hs.Direction.SOUTHEAST)\n\n downloader.main(origin[1], origin[0], dest[1], dest[0], 17, r'test.tif', server=\"Google\")\n os.system('convert test.tif -crop 1500x1500 test_%d.tif')\n","sub_path":"gmaps/splitimage.py","file_name":"splitimage.py","file_ext":"py","file_size_in_byte":1085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"99102099","text":"import os\r\nimport csv\r\n\r\ncsvpath = os.path.join(\"Resources\", \"election_data.csv\")\r\n\r\nlist_of_votes = []\r\ncomplete_list_of_candidates = {}\r\n\r\n\r\nwith open(csvpath) as csvfile:\r\n csvreader = csv.reader(csvfile, delimiter=',')\r\n next(csvreader)\r\n\r\n for row in csvreader:\r\n #total number of votes\r\n list_of_votes.append(row[2])\r\n \r\n candidate = row[2]\r\n if candidate in complete_list_of_candidates:\r\n complete_list_of_candidates[candidate] += 1\r\n else:\r\n complete_list_of_candidates[candidate] = 1\r\n \r\n def getList(dict):\r\n return dict.keys()\r\n\r\n #print the 4 names in a list, aka the count_of_candidates\r\n count_of_candidates = [key for key in complete_list_of_candidates]\r\n \r\n khan_count = (list_of_votes.count(\"Khan\"))\r\n correy_count = (list_of_votes.count(\"Correy\"))\r\n li_count = (list_of_votes.count(\"Li\"))\r\n otooley_count = (list_of_votes.count(\"O'Tooley\"))\r\n \r\n khan_avg = (khan_count)/len(list_of_votes)\r\n correy_avg = (correy_count)/len(list_of_votes)\r\n li_avg = (li_count)/len(list_of_votes)\r\n otooley_avg = (otooley_count)/len(list_of_votes)\r\n\r\n print(f'Election Results')\r\n print('----------------------------')\r\n print(f'Total Votes: {(len(list_of_votes))}')\r\n print('----------------------------')\r\n print(f'Khan: {(khan_avg):.0%} {(khan_count)}')\r\n print(f'Correy: {(correy_avg):.0%} {(correy_count)}')\r\n print(f'Li: {(li_avg):.0%} {(li_count)}')\r\n print(f'OTooley: {(otooley_avg):.0%} {(otooley_count)}')\r\n print('----------------------------')\r\n print(f'Winner: Khan')\r\n print('----------------------------')\r\n\r\n pypoll_hw = os.path.join(\"Resources\", \"pypoll_hw.csv\") \r\n\r\n with open(pypoll_hw, 'w') as csvfile:\r\n write_this = csv.writer(csvfile, delimiter=',')\r\n write_this.writerow(['Election Results'])\r\n write_this.writerow(['----------------------------'])\r\n write_this.writerow([(f'Total Votes: {(len(list_of_votes))}')])\r\n write_this.writerow(['----------------------------'])\r\n write_this.writerow([(f'Khan: {(khan_avg):.0%} {(khan_count)}')])\r\n write_this.writerow([(f'Correy: {(correy_avg):.0%} {(correy_count)}')])\r\n write_this.writerow([(f'Li: {(li_avg):.0%} {(li_count)}')])\r\n write_this.writerow([(f'OTooley: {(otooley_avg):.0%} {(otooley_count)}')])\r\n write_this.writerow(['----------------------------'])\r\n write_this.writerow([(f'Winner: Khan')])\r\n write_this.writerow(['----------------------------'])","sub_path":"PyPoll/PyPoll redo.py","file_name":"PyPoll redo.py","file_ext":"py","file_size_in_byte":2578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"594361983","text":"import sys\nimport math\nfrom numpy import NaN, Inf, arange, isscalar, asarray, array\nfrom datetime import datetime\n\ndef peakdet(v, delta=0.01, x = None):\n maxtab = []\n mintab = []\n \n if x is None:\n x = arange(len(v))\n \n v = asarray(v)\n \n if len(v) != len(x):\n sys.exit('Input vectors v and x must have same length')\n \n if not isscalar(delta):\n sys.exit('Input argument delta must be a scalar')\n \n if delta <= 0:\n sys.exit('Input argument delta must be positive')\n \n mn, mx = Inf, -Inf\n mnpos, mxpos = NaN, NaN\n \n lookformax = True\n \n for i in arange(len(v)):\n this = v[i]\n if this > mx:\n mx = this\n mxpos = x[i]\n if this < mn:\n mn = this\n mnpos = x[i]\n \n if lookformax:\n if this < mx-delta:\n maxtab.append((mxpos, mx))\n mn = this\n mnpos = x[i]\n lookformax = False\n else:\n if this > mn+delta:\n mintab.append((mnpos, mn))\n mx = this\n mxpos = x[i]\n lookformax = True\n \n return maxtab, mintab\n \ndef hasbreaker(l1, l2, limit, sampledlist, sensorz):\n\ti = 0\n\tp = l1[i]\n\tj = 0\n\tfound = False\n\tbindex = -1\n\tfor j in range(len(l2)):\t\t\t\t\t\n\t\twhile abs(p - l2[j]) > 1 and l2[j] < p:\n\t\t\tj+=1\n\t\t\tif j >= len(l2):\n\t\t\t\tbreak\n\t\tif j >= len(l2):\n\t\t\tbreak\n\t\twhile l2[j] < p:\n\t\t\tif abs(sampledlist[l2[j]]-sampledlist[p]) > limit:\n\t\t\t\tfound = True\n\t\t\t\tbindex = sensorz.index(sampledlist[p])\n\t\t\t\tbreak\n\t\t\tj+=1\n\t\t\tif j >= len(l2):\n\t\t\t\tbreak\n\t\tif found:\n\t\t\tbreak\n\t\ti+=1\n\t\tif i >= len(l1):\n\t\t\tbreak\n\t\tp = l1[i]\n\treturn bindex, found\n\t\ndef trailHasBreaker(l1, l2, limit, sampledlist):\n\ti = 0\n\tp = l1[i]\n\tj = 0\n\tfound = False\n\tfor j in range(len(l2)):\t\t\t\t\t\n\t\twhile abs(p - l2[j]) > 1 and l2[j] < p:\n\t\t\tj+=1\n\t\t\tif j >= len(l2):\n\t\t\t\tbreak\n\t\tif j >= len(l2):\n\t\t\tbreak\n\t\twhile l2[j] < p:\n\t\t\tif abs(sampledlist[l2[j]]-sampledlist[p]) > limit:\n\t\t\t\tfound = True\n\t\t\t\tbreak\n\t\t\tj+=1\n\t\t\tif j >= len(l2):\n\t\t\t\tbreak\n\t\tif found:\n\t\t\tbreak\n\t\ti+=1\n\t\tif i >= len(l1):\n\t\t\tbreak\n\t\tp = l1[i]\n\treturn found\n\ndef gettimediff(t1, t2):\n\tl1 = t1.split(':')\n\tl2 = t2.split(':')\n\t\n\th1, m1, s1 = int(l1[0]), int(l1[1]), int(l1[2])\n\th2, m2, s2 = int(l2[0]), int(l2[1]), int(l2[2])\n\t\n\ttime1 = datetime(2015,4,15,h1,m1,s1)\n\ttime2 = datetime(2015,4,15,h2,m2,s2)\n\t\n\tif time1 > time2:\n\t\treturn (time1-time2).seconds\n\telse:\n\t\treturn (time2-time1).seconds\n\t\t\ndef std_dev(x):\n\tmean=sum(x)/len(x)\n\ttotal=0\n\tfor i in x:\n\t\ttotal+=(i-mean)**2\n\tvar=total/len(x)\n\tstd=math.sqrt(var)\n\treturn std\n","sub_path":"smartloc/processor/detection_util.py","file_name":"detection_util.py","file_ext":"py","file_size_in_byte":2644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"267993841","text":"print(\"\\t\\t\\t Practice Problem 3.34\")\r\ndef pay(hourly,hours):\r\n print('hourly wage:',hourly,'hr')\r\n print('hourly pay:','10$')\r\n if hours >= 40:\r\n sal = 40*hourly \r\n O_time = sal + hourly *(hours - 40) * 1.5\r\n return O_time\r\n else:\r\n Not_Otime = hours * hourly\r\n return Not_Otime\r\n \r\nsalary = pay(10,35)\r\nprint(salary)\r\n\r\nsalary2 = pay(10,45)\r\nprint(salary2)\r\n","sub_path":"3.34.py","file_name":"3.34.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"470466768","text":"import os\nimport tempfile\nimport unittest\nfrom functools import partial\n\nimport table_compositor.html_writer as htmlw\nimport table_compositor.test.unit_test.table_compositor_fixtures as tcfx\n\n\ndef get_expected_output_folder(fname):\n base_path = os.path.join(\n os.path.dirname(__file__),\n '..', 'expected')\n os.makedirs(base_path, exist_ok=True)\n expected_fp = os.path.join(base_path, fname)\n return expected_fp\n\n\nclass TestHTMLWriterMeta(type):\n def __new__(cls, names, bases, attrs):\n def test_func_constructor(name, func_to_call, engine, *args):\n def _func(self):\n layout = func_to_call()\n # we drop the engine name from the test, since the expected file is the same for both engines\n fname = name.replace('_' + engine.__name__, '') + \".html\"\n actual_html_str = htmlw.HTMLWriter.to_html(layout, *args, border=1)\n expected_fp = get_expected_output_folder(fname)\n self.compare(expected_fp, actual_html_str)\n return _func\n\n scenarios = tcfx.get_scenarios()\n\n for s in scenarios:\n attrs[s.name] = test_func_constructor(s.name, partial(\n s.fixture_func,\n grid=s.grid,\n nested=s.nested,\n callback_func_cls=tcfx.HtmlCallBackFunc),\n s.engine_and_callback_funcs_cls[0],\n s.orientation)\n\n return type.__new__(cls, names, bases, attrs)\n\nclass TestUnit(unittest.TestCase, metaclass=TestHTMLWriterMeta):\n '''\n All test methods will be produced by the metaclass\n '''\n\n def compare(self, expected_fp, actual_html_str):\n\n with open(expected_fp) as f:\n expected_str = f.read()\n self.assertEqual(expected_str, actual_html_str)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"table_compositor/test/unit_test/test_table_compositor_html_writer.py","file_name":"test_table_compositor_html_writer.py","file_ext":"py","file_size_in_byte":1903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"629181317","text":"#!/usr/bin/python3\n\ndef to_set(seq):\n offset=0\n s=set()\n for w,t in seq:\n #s.add((offset,offset+len(w),t))\n s.add((offset,offset+len(w)))\n offset=offset+len(w)\n return s\nif __name__==\"__main__\":\n std,rst,cor=0,0,0\n for gold,result in zip(open('data/ctb_test.txt'),open('data/ctb_test_result.txt')):\n gold=gold.strip().split(' ')\n gold=[x.split('_') for x in gold]\n result=result.strip().split(' ')\n result=[x.split('/') for x in result]\n gold=to_set(gold)\n result=to_set(result)\n std+=len(gold)\n rst+=len(result)\n cor+=len(gold&result)\n print(std,rst,cor)\n p=cor/rst\n r=cor/std\n print(p,r,2*p*r/(p+r))\n","sub_path":" perminusminus/tagging/tagging_text_eval.py","file_name":"tagging_text_eval.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"231962631","text":"#\n# This script is designed to be called by the GHA workflow.\n#\n# It is designed to check that the PR text complies to our dev standards.\n#\n# The input is received via the environmet variables:\n# * PR_TITLE - title of the PR\n# * PR_BODY - the description of the PR\n#\n# To test it run\n#\n# $ export PR_TITLE='#1234 Test Title'\n# $ export PR_BODY='some lines\n# > Fixes #12345\n# > more lines'\n# $ python3 .github/scripts/check-pr-text.py\n#\nimport os\nimport re\nimport sys\n\npr_title = os.environ.get(\"PR_TITLE\", \"\")\npr_body = os.environ.get(\"PR_BODY\", \"\")\n\nprint(\"--- DEBUG ---\")\nprint(f\"Title: {pr_title}\")\nprint(f\"Body:\\n {pr_body}\")\nprint(\"-------------\")\n\n\ndef fail(message):\n print(message)\n print(\"Fix the title and then trigger a new push.\")\n print(\"A re-run for this job will not work.\")\n sys.exit(1)\n\n\nif not pr_title:\n fail(\"Title for the PR not found. \" \"Maybe missing PR_TITLE env var.\")\n\nif not pr_body:\n fail(\"Body for the PR not found. \" \"Maybe missing PR_BODY env var.\")\n\ntitle_search = re.search(r\"^(#\\d+) .+\", pr_title)\nif not title_search:\n fail(\n \"Title of PR has no issue ID reference. It must look like “#1234 Foo bar baz”.\"\n )\nelse:\n print(f\"PR title is complaint for {title_search[1]}. Good job.\")\n\n\nbody_search = re.search(r\".*Fixes (#\\d+).+\", pr_body)\nif not body_search:\n fail('Body of PR has no \"Fixes #12345\" issue ID reference.')\nelse:\n print(f\"PR description is complaint for {body_search[1]}. Good job.\")\n\n\nif title_search[1] != body_search[1]:\n fail(\"PR title and description have different IDs.\")\n\n# All good.\nsys.exit(0)\n","sub_path":".github/scripts/check-pr-text.py","file_name":"check-pr-text.py","file_ext":"py","file_size_in_byte":1597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"339519676","text":"import os\n\ndef rename_files():\n saved_path = os.getcwd()\n dir = \"/Users/waqasahmed/Documents/Udacity/full-stack-nanodegree/python-course/exercises/02/prank\"\n os.chdir(dir)\n file_list = os.listdir(dir)\n\n for file_name in file_list:\n os.rename(file_name, file_name.translate(None, \"0123456789\"))\n os.chdir(saved_path)\n \nrename_files()\n","sub_path":"python-course/exercises/02/rename_files.py","file_name":"rename_files.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"83840797","text":"\nfrom otter.experiment import run\nimport otter.gym as gym\n\nenv_params = {\n \"environment_name\": \"Reacher\",\n \"random_start\": True,\n \"random_target\": True,\n \"image\": True,\n \"image_dim\": 64,\n}\n\nenv = gym.from_config(env_params)\ndo = env.get_state_dim()\nds = 10\ndu = da = env.get_action_dim()\nhorizon = 50\n\nexperiment = dict(\n experiment_name='reacher-image',\n experiment_type='myexp',\n env=env_params,\n model=dict(\n do=do, du=du, ds=ds, da=da, horizon=horizon,\n state_encoder=None,\n state_decoder=None,\n action_encoder=None,\n action_decoder=None,\n prior= None,\n cost=dict(cost_type='quadratic')\n ),\n control = dict(\n num_epochs=1000,\n ),\n train=dict(\n num_epochs=1000,\n learning_rate=1e-3,\n model_learning_rate=2e-5 * horizon,\n beta_start=1e-4,\n beta_end=10.0,\n beta_rate=5e-5,\n beta_increase=0,\n batch_size=2,\n dump_every=100,\n summary_every=50,\n ),\n data=dict(\n num_rollouts=10,\n init_std=0.5,\n smooth_noise=False,\n ),\n dump_data=True,\n seed=0,\n out_dir='data/vae',\n horizon=100,\n\n rollouts_per_iter=20,\n num_iters=50,\n buffer_size=100,\n smooth_noise=False,\n num_videos=2,\n model_train={\n 'num_epochs': 0\n }\n)\nrun(experiment, remote=False, instance_type='m5.4xlarge',num_threads=1)\n\n\n","sub_path":"experiments/myexp/myexp_demo.py","file_name":"myexp_demo.py","file_ext":"py","file_size_in_byte":1417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"216127731","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.contrib import messages\nfrom django.core.urlresolvers import reverse\nfrom django.http import (\n HttpResponseBadRequest,\n HttpResponseForbidden,\n HttpResponseNotFound,\n HttpResponseRedirect\n)\nfrom django.views.generic import FormView, TemplateView, View\nfrom millionmilestogether.forms.friendship import FriendshipRequestForm\nfrom millionmilestogether.models import RegisteredUser, FriendRequest\nfrom millionmilestogether.views.generic import MMTAuthorizationMixin\n\n\nclass FriendListView(MMTAuthorizationMixin, TemplateView):\n template_name = \"millionmilestogether/friendship/index.html\"\n\n def get_context_data(self, **kwargs):\n ctx = super(FriendListView,\n self).get_context_data(**kwargs)\n user = self.request.user\n ctx['friend_requests'] = user.friendship_target.filter(\n confirmed=False\n )\n ctx['friends'] = user.get_friends().prefetch_related(\n 'child_set', 'child_set__guardians'\n )\n\n return ctx\nfriend_list = FriendListView.as_view()\n\n\nclass FriendshipRequestView(MMTAuthorizationMixin, FormView):\n form_class = FriendshipRequestForm\n template_name = \"millionmilestogether/friendship/request.html\"\n\n def get_context_data(self, **kwargs):\n ctx = super(FriendshipRequestView,\n self).get_context_data(**kwargs)\n\n # This is a bit of a hack for now\n expected = 'No one is registered with that email address.'\n\n if ctx['form'].errors.get('email', None) == [expected, ]:\n ctx['nonexistent_email'] = ctx['form'].data['email']\n\n return ctx\n\n def get_form(self, form_class):\n form = super(FriendshipRequestView, self).get_form(form_class)\n form.user = self.request.user\n return form\n\n def form_valid(self, form):\n email = form.cleaned_data['email']\n\n target = RegisteredUser.objects.get(email=email)\n self.request.user.initiate_friend_request(\n self.request,\n target\n )\n\n messages.success(\n self.request,\n 'Friend request to %s sent successfully.' % email\n )\n\n return HttpResponseRedirect(reverse('mmt-home'))\ninitiate_request = FriendshipRequestView.as_view()\n\n\nclass FriendshipAcceptView(View):\n def post(self, request, *args, **kwargs):\n if self.request.user.is_anonymous():\n return HttpResponseForbidden(\n \"You must be logged in to accept friend requests.\"\n )\n\n if 'id' not in self.request.POST:\n return HttpResponseBadRequest(\n \"You must provide a friend request to accept.\"\n )\n\n try:\n friend_request = FriendRequest.objects.get(\n pk=int(self.request.POST['id'])\n )\n except ValueError:\n return HttpResponseBadRequest(\n \"Friend request identifiers should be numeric.\"\n )\n except FriendRequest.DoesNotExist:\n return HttpResponseNotFound(\n \"Friend request not found.\"\n )\n\n if friend_request.target != self.request.user:\n return HttpResponseForbidden(\n \"You can only accept friend requests made to you.\"\n )\n\n FriendRequest.confirm(\n friend_request.initiator,\n friend_request.target\n )\n\n messages.success(\n self.request,\n 'Friend request from %s accepted.' % friend_request.initiator.email\n )\n\n return HttpResponseRedirect(reverse('mmt-home'))\naccept_request = FriendshipAcceptView.as_view()\n","sub_path":"millionmilestogether/views/friendship/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"403242938","text":"# -*- coding: utf-8 -*-\n'''\nDescription\n'''\n\nimport pytest\nfrom msg_lang.parser import (\n parse_comment, parse_message_start, parse_field, ParsingError,\n init_parse, parse)\nimport tempfile\n\n\ndef test_parse_line():\n src = '# comment'\n parsed = parse_comment(src)\n assert ['#', ' comment'] == parsed\n\n src = '# comment '\n parsed = parse_comment(src)\n assert ['#', ' comment '] == parsed\n\n src = 'M AddProduct'\n parsed = parse_message_start(src)\n assert ['M', 'AddProduct'] == parsed\n\n src = 'F id int'\n parsed = parse_field(src)\n assert ['F', 'id', 'int'] == parsed\n\n src = 'F name char[30]'\n parsed = parse_field(src)\n assert ['F', 'name', 'char', 30] == parsed\n\n src = 'F order_code int'\n parsed = parse_field(src)\n assert ['F', 'order_code', 'int'] == parsed\n\n src = 'F name long'\n with pytest.raises(ParsingError) as excinfo:\n parsed = parse_field(src)\n assert 'line 0: invalid field type: \\\"F name long\\\"' \\\n == str(excinfo.value)\n\n src = 'F name double[30]'\n with pytest.raises(ParsingError) as excinfo:\n parsed = parse_field(src)\n assert 'line 0: invalid field type: \\\"F name double[30]\\\"' \\\n == str(excinfo.value)\n\n src = 'F name char[a]'\n with pytest.raises(ParsingError) as excinfo:\n parsed = parse_field(src)\n assert 'line 0: array size must be number: \\\"F name char[a]\\\"' \\\n == str(excinfo.value)\n\n\ndef test_parse_file():\n with tempfile.NamedTemporaryFile(mode='w') as temp:\n temp.write(\n '''# add a product\n# to the 'on-order' list\n\nM AddProduct\nF id int\nF name char[30]\nF order_code int\nE''')\n temp.flush()\n\n init_parse(temp.name)\n ptree = parse()\n assert [['#', ' add a product'],\n ['#', \" to the 'on-order' list\"],\n [],\n ['M', 'AddProduct',\n ['F', 'id', 'int'],\n ['F', 'name', 'char', 30],\n ['F', 'order_code', 'int']]] == ptree\n","sub_path":"pragmatic/msg_lang/tests/test_parser.py","file_name":"test_parser.py","file_ext":"py","file_size_in_byte":2018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"209874986","text":"class Solution:\n def dfs(self, mem, matrix, i, j):\n if mem[i][j] != 0:\n return mem[i][j]\n \n steps = [[0, 1], [1, 0], [0, -1], [-1, 0]]\n \n for s in steps:\n ii = i + s[0]\n jj = j + s[1]\n \n if 0 <= ii < len(matrix) and 0 <= jj < len(matrix[0]) and matrix[ii][jj] > matrix[i][j]:\n mem[i][j] = max(mem[i][j], self.dfs(mem, matrix, ii, jj))\n \n mem[i][j] += 1\n # ans = max(mem[ii][jj])\n return mem[i][j]\n \n def longestIncreasingPath(self, matrix: List[List[int]]) -> int:\n if not matrix or not matrix[0]:\n return 0\n \n mem = [[0 for _ in range(len(matrix[0]))] for _ in range(len(matrix))]\n ans = 0\n for i in range(len(matrix)):\n for j in range(len(matrix[0])):\n mem[i][j] = self.dfs(mem, matrix, i, j)\n ans = max(mem[i][j], ans)\n \n return ans\n \n","sub_path":"submission/python/python/0329.py","file_name":"0329.py","file_ext":"py","file_size_in_byte":1000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"97764041","text":"import os\n\n\nclass Config:\n def __init__(self, path):\n self.path = os.path.abspath(os.path.relpath(path))\n self.config, self.keys = self.__readConfig()\n\n def __readConfig(self):\n config = {}\n keys = []\n with open(self.path, \"r\") as f:\n rawdata = f.read()\n data = rawdata.split(\"\\n\")\n data.remove(\"\")\n for line in data:\n temp = line.split(\":\")\n config[temp[0]] = temp[1]\n keys.append(temp[0])\n return (config, keys)\n\n def __saveConfig(self):\n data = \"\"\n for key in self.keys:\n data += key + \":\" + self.config[key] + \"\\n\"\n with open(self.path, \"w\") as f:\n f.write(data)\n return True\n\n def getConfig(self, key):\n if key in self.keys:\n return self.config[key]\n else:\n raise ValueError(\"Wanted config not available\")\n\n def setConfig(self, key, value):\n if key in self.keys:\n self.config[key] = str(value)\n else:\n raise ValueError(\"Impossible to change this config\")\n\n # functions for use in 'command line interface'\n\n def get(self, key=None):\n if key is not None:\n try:\n print(self.getConfig(key))\n except ValueError as e:\n print(\"ValueError:\", e)\n else:\n for i in self.keys:\n print(i + \": \" + self.config[i])\n\n def set(self, key, value):\n try:\n self.setConfig(key, value)\n print(key, \"is now\", value)\n except ValueError as e:\n print(\"ValueError:\", e)\n\n def header(self):\n head = \"Config:\\n\\n\"\n for i in self.keys:\n head += i + \": \" + self.config[i] + '\\n'\n head += \"\\nCommands:\\nset \\nget \\nsave\\n\" # Only temporary\n return head\n\n def save(self):\n self.__saveConfig()\n raise KeyboardInterrupt\n","sub_path":"game/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"155685002","text":"\"\"\"\n=====\nDecay\n=====\nThis example showcases:\n- using a generator to drive an animation,\n- changing axes limits during an animation.\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nimport datetime\nimport matplotlib.dates as ds\nimport time\nimport random\nimport wx\n\nfrom ui.temp_sql_record import TempQuerySQL_2\n\n\nclass GraphGen():\n\n def __init__(self,dates,lives,devices):\n \n self._GraphActivates = True\n self._LiveData = []\n\n db = TempQuerySQL_2()\n\n datas = db.GetDataSample(devicename=devices,recorddate=dates)\n if len(datas) == 0:\n wx.MessageBox('Data Grafik pada tanggal tersebut kosong', 'Warning',\n wx.OK | wx.ICON_WARNING)\n\n # try:\n #Live Update\n self._LiveUpdate = lives\n\n #New Var\n self.GR_UsedSensor = devices\n self.GR_Data_Before = datas\n self.GR_Data_Before_key = list(datas.keys())\n self.GR_Data_Before_key.sort()\n\n self.xdata, self.ydata = [], []\n \n # {\n # datetime.datetime string:\n # [datetime.datetime obj, value]\n # }\n\n #APLLY DATA EXIST\n for key in self.GR_Data_Before_key:\n items = self.GR_Data_Before[key]\n x = items[0]\n y = items[1]\n self.xdata.append(x)\n self.ydata.append(y)\n\n starts = self.GR_Data_Before[self.GR_Data_Before_key[0]][0]\n ends = self.GR_Data_Before[self.GR_Data_Before_key[-1]][0]\n\n valmin = self.GR_Data_Before[self.GR_Data_Before_key[0]][1]\n valmax = self.GR_Data_Before[self.GR_Data_Before_key[-1]][1]\n\n #FIGURE\n self.fig, self.ax = plt.subplots()\n self.date = dates\n self.x_axis_start = starts\n self.x_axis_end = ends\n self.y_axis_max = float(valmax) + (float(valmax) * (10/100))\n self.y_axis_min = float(valmin) - (float(valmax) * (10/100))\n\n #SERIES\n self.line, = self.ax.plot_date([], [],'-', lw=3, color='blue')\n self.ax.set_ylim(self.y_axis_min, self.y_axis_max)\n self.ax.set_xlim(self.x_axis_start, self.x_axis_end)\n self.ax.set_xlabel('Time Record')\n self.ax.set_ylabel('Value ' + str(self.GR_UsedSensor))\n self.ax.xaxis.set_major_formatter(ds.DateFormatter('%H:%M:%S'))\n self.fig.suptitle(str('Data ' + str(self.GR_UsedSensor) + ' On : ') + str(self.date), fontsize=14, fontweight='bold')\n self.fig.autofmt_xdate()\n self.ax.grid()\n\n figure = plt.gcf() # Get current figure\n toolbar = figure.canvas.toolbar # Get the toolbar handler\n toolbar.update()\n self.line.set_data(self.xdata, self.ydata)\n self.ax.grid()\n plt.rcParams['axes.facecolor'] = 'white'\n plt.rcParams['axes.edgecolor'] = 'white'\n plt.rcParams['axes.grid'] = True\n plt.rcParams['grid.alpha'] = 1\n plt.rcParams['grid.color'] = \"#cccccc\"\n plt.grid(True)\n plt.show()\n\n plt.clf()\n if self._LiveUpdate == True:\n self._LiveUpdate = False\n plt.close()\n time.sleep(1)\n self._GraphActivates = False\n return\n\n def GpGetdatetime(self):\n res = datetime.datetime.now()\n return (res)\n\n def GpGetdate(self):\n res = datetime.date.today()\n return (res)\n","sub_path":"old/ui/graph_generator.py","file_name":"graph_generator.py","file_ext":"py","file_size_in_byte":3387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"409853505","text":"from vgg16 import *\r\nfrom config import *\r\n\r\n\r\ndef loss(label, loggit):\r\n with tf.name_scope(\"loss_func\"):\r\n return label * tf.log(loggit)\r\n\r\nif __name__ == '__main__':\r\n layer_types = layer_types\r\n layer_params = layer_params\r\n learning_rate = 2e-3\r\n output_shape = [None, 20]\r\n model = VGG_16(layer_types, layer_params, output_shape)\r\n model.train_setting(loss=loss, optimzer=\"adam\", learning_rate=learning_rate)\r\n model.train()","sub_path":"CNN_Nets/VGG/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"201091291","text":"__author__ = 'mpletty'\nimport numpy as np\n\nfrom Node import Node\n\n\nclass NodeSingle(Node):\n \"\"\"\n takes probability from child containing the class\n with greatest weight\n \"\"\"\n\n def __init__(self, classifier_class, cluster_class, classes):\n super(NodeSingle, self).__init__(classifier_class, cluster_class, classes)\n\n def _evaluate(self, x, father_prediction, children_weight):\n nr_of_rows = x.shape[0]\n prediction = np.zeros((nr_of_rows, len(self.classes)))\n\n for i in range(nr_of_rows):\n weights = []\n for child_weight in children_weight:\n weights.append(child_weight[i])\n\n sorted_pairs = sorted(zip(weights, self.children), key=lambda pair: pair[0], reverse=True)\n\n done = set()\n for _, child in sorted_pairs:\n for j, clazz in enumerate(child.classes):\n if clazz in done:\n continue\n index = self.classes.index(clazz)\n prediction[i, index] = child.evaluate(x[i, :])[0, j]\n done.add(clazz)\n\n return prediction","sub_path":"hcoc/NodeSingle.py","file_name":"NodeSingle.py","file_ext":"py","file_size_in_byte":1145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"56218076","text":"from django.utils.translation import ugettext_lazy as _\nfrom django.db.models import Model, ForeignKey, TextField, PositiveIntegerField\n\n\nclass Text(Model):\n name = TextField(help_text=_('Input the name of the text.'))\n content = TextField(help_text=_('Input the entire text.'))\n\n def __str__(self):\n return self.name\n\n\nclass Segmentation(Model):\n text = ForeignKey(\n Text,\n related_name='segmentations',\n help_text=_('Please select the text to which this segmentation belongs.'),\n )\n\n def save(self, *args, **kwargs):\n '''Run parent save, then run populate() if this segmentation doesn't have at least one segment\n '''\n if self.segments.count() == 0: # If this segmentation has no segments...\n save = super(Segmentation, self).save(*args, **kwargs)\n self.segments.create(order=1, content=self.text.content) # ...then add a segment containing all the content of the parent text\n else:\n if ''.join([segment.content for segment in self.segments.all()]) != self.text.content:\n raise ValueError('Content of segments in segmentation %s does not match content of text' % str(self))\n return save # Test comment\n\n def __str__(self):\n return self.text.name\n\n\nclass Segment(Model):\n class Meta:\n unique_together = (\n ('segmentation', 'order')\n )\n ordering = ('order',)\n segmentation = ForeignKey(\n Segmentation,\n related_name='segments',\n help_text=_('Please select the segmentation to which this segment belongs.'),\n )\n content = TextField()\n order = PositiveIntegerField()\n\n def split_at(self, position):\n '''Split this segment at character , creating (and returning) a new Segment afterward\n New segment starts at (and includes) character at \n '''\n for segment in self.segmentation.segments.filter(order__gt=self.order).reverse():\n segment.order += 1\n segment.save()\n new_segment = self.segmentation.segments.create(content=self.content[position:], order=self.order+1)\n self.content = self.content[:position]\n self.save()\n return new_segment\n\n def merge(self):\n '''Merge this segment with the following segment. Delete following segment and \"pull\" down\n the order of all following segments.\n '''\n merged = self.segmentation.segments.get(order=self.order+1)\n self.content = self.content + merged.content\n # Merges each associated TranslationSegment with the TranslationSegment of the following Segment:\n for translation_segment in self.translations.all():\n try:\n merged_translation_segment = merged.translations.filter(\n translation=translation_segment.translation\n ).get()\n translation_segment.content += merged_translation_segment.content\n translation_segment.save()\n except TranslationSegment.DoesNotExist:\n pass\n merged.delete()\n self.save()\n \n def __str__(self):\n out = str(self.order) + ': '\n if len(self.content) < 10:\n out += self.content\n else:\n out += self.content[:9] + '...'\n return out\n\n\nclass Translation(Model):\n original = ForeignKey(\n Segmentation,\n related_name='translations',\n help_text=_('Select the segmentation to which this translation belongs.'),\n )\n name = TextField(help_text=_('Input translation of name.'))\n\n def __str__(self):\n return self.name\n\n\nclass TranslationSegment(Model):\n class Meta:\n unique_together = (\n ('translation', 'segment')\n )\n ordering = ('segment__order',)\n translation = ForeignKey(\n Translation,\n related_name='segments',\n help_text=_('Select the translation to which this translated segment belongs.'),\n )\n segment = ForeignKey(\n Segment,\n related_name='translations',\n help_text=_('Select the segment to which this translated segment corresponds.'),\n )\n content = TextField(help_text=_('Input the translation for the segment.'))\n\n def __str__(self):\n out = str(self.segment.order) + ': '\n if len(self.content) < 10:\n out += self.content\n else:\n out += self.content[:9] + '...'\n return out\n","sub_path":"Translations/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"144517856","text":"\nfrom selenium import webdriver\nfrom os import environ\n \npath = environ.get('PATH')\nenviron.putenv('PATH', path + ';C:/Program Files (x86)/Firefox')\n\nb = webdriver.Firefox()\nb.get('http://www.runoob.com/bootstrap/bootstrap-tutorial.html');\n\n# 根据 A 链接的文本精确定位 A 链接\nele = b.find_element_by_link_text('MySQL')\nele.click()\nb.back()\n\n# 根据 A 链接的部分文本模糊定位 A 链接\nele = b.find_element_by_partial_link_text('thon3')\nele.click()\nb.back()\n\n# 根据 CSS 选择器定位 DOM 元素\nele = b.find_element_by_css_selector('input[id=\"s\"]')\nele.clear()\nele.send_keys('java')\n\nb.quit()\n","sub_path":"org/zxd/selenium/elementlocator/locator2.py","file_name":"locator2.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"290070462","text":"# take q input for number of cases\r\n# for each q take input n\r\n# find the maximum number of distinct prime factors a number in range\r\n# 1 to n (inclusive) can have\r\n# Example: for n = 500\r\n# the maximum number of unique prime factors a number from 1 to 500 can have is 4\r\n\r\ndef primeCount(n):\r\n \r\n prime=[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]\r\n c,primorial=0,1\r\n for j in prime:\r\n primorial = primorial*j\r\n if primorial<=n:\r\n c+=1\r\n return c\r\n \r\n \r\nif __name__ == '__main__':\r\n\r\n q = int(input())\r\n\r\n for q_itr in range(q):\r\n n = int(input())\r\n\r\n result = primeCount(n)\r\n\r\n print(str(result) + '\\n')\r\n","sub_path":"Miscellaneous-Py/leonard's prime numbers.py","file_name":"leonard's prime numbers.py","file_ext":"py","file_size_in_byte":696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"42564963","text":"import random,sys,time\n\ndef random_data_generator (max_r):\n for i in range(max_r):\n yield random.randint(0, max_r)\n\ndef random_select(l,p):\n t = [] \n for i,v in enumerate(l):\n t=t+[v]*int(p[i]*100)\n return random.choice(t)\ndef findEnd(d,key):\n while(key in d):\n key=d[key]\n return key \n# given a dict and a key u which is a node finds randomly a node v such that there is a path from u to v \ndef choosePath(d,key):\n l = []\n while key in d:\n key=d[key]\n l.append(key)\n return random.choice(l)\n\ndef path(d,key):\n l = []\n while key in d:\n l.append(key)\n key=d[key]\n return l\n\ndef revPath(din,dout,key):\n l = []\n key=findEnd(dout,key)\n while key in din:\n l.append(key)\n oldkey=key\n key=din[key]\n din.pop(oldkey)\n dout.pop(key)\n l.append(key)\n for m,n in zip(l,l[1:]):\n dout[m]=n\n din[n]=m\n\nif __name__ == \"__main__\":\n operations = ['L','C','A','R','M','I']\n probability = [0.4,0.15,0.1,0.1,0.15,0.1] ## Respective probabilities with which to choose these \n tnum = 10000 ## Number of nodes \n maxweight = 100 ## Max weight to be used in link \n maxd = 20 ## Argument of multiadd\n testcases = 100000 ## Can be less than this number due to continue skips \n testfile = 'testcases.txt' ## Test case stored here \n edgein = {}\n edgeout = {}\n f = open(testfile,'w')\n f.write(str(tnum)+\"\\n\")\n for i in range(testcases): \n #assert(set(edgein.keys())==set(edgeout.values()))\n #assert(set(edgeout.keys())==set(edgein.values()))\n #assert(None not in edgein and None not in edgeout)\n op=random_select(operations,probability)\n d = random.randint(-maxd,maxd)\n if i%1000==0:\n print(\"Generating test\",i,\" with \"+op)\n if op=='L':\n node1 = random.randint(1,tnum-1)\n node2 = random.randint(1,tnum-1)\n if node1 == node2 or findEnd(edgein,node1)==findEnd(edgein,node2): \n continue\n weight = random.randint(0,maxweight-1)\n t1=findEnd(edgein,node1)\n temp1=findEnd(edgein,node2)\n if t1==temp1 :\n continue\n t2=findEnd(edgeout,node2)\n edgein[t1]=t2\n edgeout[t2]=t1\n f.write(\"L \"+str(node1) + \" \" +str(node2) + \" \" + str(weight)+\"\\n\")\n elif op=='C':\n if edgein=={}:\n continue\n node1=random.choice(list(edgein.keys()))\n node2=edgein[node1]\n edgein.pop(node1)\n edgeout.pop(node2)\n f.write(\"C \"+str(node1) + \" \" +str(node2)+\"\\n\")\n elif op=='A':\n if edgein=={}:\n continue\n node1=random.choice(list(edgein.keys()))\n node2 = choosePath(edgein,node1)\n d = random.randint(-maxd,maxd)\n f.write(\"A \"+str(node1) + \" \" +str(node2) + \" \" + str(d)+\"\\n\")\n elif op=='R':\n pass\n if edgein=={}:\n continue\n node1=random.choice(list(edgein.keys()))\n revPath(edgein,edgeout,node1)\n f.write(\"R \"+str(node1)+\"\\n\")\n elif op=='M':\n if edgein=={}:\n continue\n node1=random.choice(list(edgein.keys()))\n node2 = choosePath(edgein,node1)\n f.write(\"M \"+str(node1) + \" \" +str(node2)+\"\\n\")\n else :\n node1 = random.randint(1,tnum)\n node2 = random.randint(1,tnum)\n if node1 == node2:\n continue\n f.write(\"I \"+str(node1) + \" \" +str(node2)+\"\\n\")\n","sub_path":"P1/generateTests.py","file_name":"generateTests.py","file_ext":"py","file_size_in_byte":3772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"263044757","text":"\nimport re #引入正則表達式 (regular expression)是很方便的字串處理module。用來表達對字符串的一種過濾邏輯。\ndef stats_text_en(en): #定義一個函數\n #\\u4e00-\\u9fa5 \t漢字的unicode範圍\n #\\u0030-\\u0039 \t數字的unicode範圍\n #\\u0041-\\u005a \t大寫字母unicode範圍\n #\\u0061-\\u007a \t小寫字母unicode範圍\n #sub(pattern,repl,string) \t把字符串中的所有匹配表達式pattern中的地方替换成repl, 使用repl替換string中每一個匹配的子串後返回替換後的字符串。\n t1= re.sub(u\"([^\\u0041-\\u005a\\u0061-\\u007a])\",\" \",en) #把en中非英文字符轉換成“ ”\n text1 = t1.split() #把字符串分割\n d = {} #建一個空字典\n for i in text1: #循環一遍\n if i in d:\n d[i] += 1 #如果字典中沒有就顯示1,有的話就在原來的基礎上+1\n else:\n d[i] = 1\n\n a = sorted(d.items(),key=lambda x:x[1],reverse = True) #利用lambda函數進行values值的排序 (lambda 函數是一種快速定義單行的最小函數)\n return a\n\n\ndef stats_text_cn(cn): #定義一個統計中文漢字字頻的函數\n t2 = re.sub(u\"([^\\u4e00-\\u9fa5])\",\"\",cn) #將cn中非中文字符轉換成“”\n d = {} #建一個空字典\n for i in t2: #中文不需要分割,可以直接循環一遍!\n if i in d:\n d[i] +=1 #如果字典中沒有就顯示1,有的話就在原來的基礎上+1\n else:\n d[i] =1\n a = sorted(d.items(),key=lambda x:x[1],reverse = True) #利用lambda函數進行values值的排序\n return a\n\ndef stats_text(j): #定義合併輸出函數\n a = stats_text_cn(j) + stats_text_en(j) #將兩次統計結果合併(中文+英文)\n return a","sub_path":"exercises/1901090011/d07/mymodule/stats_word.py","file_name":"stats_word.py","file_ext":"py","file_size_in_byte":1772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"106037417","text":"from sys import argv, stderr\nfrom flask import Flask, request, redirect, make_response, url_for\nfrom flask import render_template\nfrom prof import Professor\nfrom profsDB import profsDB\nfrom CASClient import CASClient\nfrom updateDB import updateDB, createProf, deleteProf\nfrom profPreferencesDB import profPreferencesDB\nimport psycopg2\nfrom pathlib import Path\nfrom datetime import datetime\nfrom pytz import timezone\nfrom os import remove, path, environ\nimport io\nfrom PIL import Image\nimport csv\nfrom match import optimizePreferences\nfrom adminsDB import adminsDB\n\n\napp = Flask(__name__, template_folder='.')\n\nAPP_ROUTE = path.dirname(path.abspath(__file__))\n\n# Generated by os.urandom(16)\napp.secret_key = b'8\\x04h\\x0f\\x08U0\\xde\\x1a\\x92V\\xe3\\xd3\\x9b5\\xfa'\n\n#----------------------------------------------------------------------------------------------------#\n# Stripping HTML tags\n# From: https://stackoverflow.com/questions/753052/strip-html-from-strings-in-python\n#----------------------------------------------------------------------------------------------------#\n\nfrom io import StringIO\nfrom html.parser import HTMLParser\n\nclass MLStripper(HTMLParser):\n def __init__(self):\n super().__init__()\n self.reset()\n self.strict = False\n self.convert_charrefs= True\n self.text = StringIO()\n def handle_data(self, d):\n self.text.write(d)\n def get_data(self):\n return self.text.getvalue()\n\ndef strip_tags(html):\n s = MLStripper()\n s.feed(html)\n return s.get_data()\n\n#----------------------------------------------------------------------------------------------------#\n\ndef getProfs(search_criteria, input_arguments):\n profsDB_ = profsDB()\n error_statement = profsDB_.connect()\n profs = []\n if error_statement == '':\n connection = profsDB_.conn\n try:\n if len(input_arguments) != 0:\n profs = profsDB_.displayProfessorsByFilter(connection, search_criteria, input_arguments)\n else:\n profs = profsDB_.displayAllProfessors(connection)\n profs = profsDB_.return_profs_list(profs)\n except Exception as e:\n error_statement = str(e)\n profsDB_.disconnect()\n else:\n print(error_statement)\n\n return profs, error_statement\n\n@app.route('/')\n@app.route('/index')\ndef index():\n\n html = render_template('templates/index.html')\n response = make_response(html)\n return response\n\n@app.route('/search')\ndef search():\n\n username = CASClient().authenticate()\n\n html = render_template('templates/profs.html', username=username)\n response = make_response(html)\n return response\n\n@app.route('/about')\ndef about():\n\n html = render_template('templates/about.html')\n response = make_response(html)\n return response\n\n@app.route('/searchResults', methods=['GET'])\ndef searchResults(): \n\n username = CASClient().authenticate()\n\n search_criteria, input_arguments = getSearchCriteria()\n\n profs, error_statement = getProfs(search_criteria, input_arguments)\n\n html = ''\n if error_statement == '':\n\n if len(profs) == 0:\n html += '
        ' + \\\n \"No search results. Please try use different keywords.\" + \\\n '
        '\n\n i = 0\n for prof in profs:\n src = prof[11]\n\n # display image if in database\n if prof[12] != None:\n imageBytes = bytes(prof[12])\n image = Image.open(io.BytesIO(imageBytes))\n\n imageExtension = prof[13]\n\n netID = prof[0]\n filename = netID + '.' + imageExtension\n destination = \"/\".join([\"static/profImages/\", filename])\n image.save(destination)\n src = destination\n\n website = ''\n email = ''\n past_papers = ''\n if prof[4] != '':\n email = ''\n email += '' + strip_tags(prof[4]) + ''\n if prof[6] != '':\n website = ''\n past_papers = '
        Previous Papers Advised' \n\n\n html += '
        ' + \\\n '
        ' + \\\n '' + \\\n '
        ' + \\\n '
        ' + \\\n '

        ' + strip_tags(prof[1]) + ' ' + strip_tags(prof[2]) + '

        ' + \\\n '

        ' + strip_tags(prof[3]) + '

        ' + \\\n '

        ' + strip_tags(prof[8]) + '

        ' + \\\n '

        ' + strip_tags(prof[5]) + '

        ' + \\\n '

        ' + strip_tags(prof[7]) + '

        ' + \\\n email + \\\n website + \\\n '
        ' + \\\n '

        Add to advisor preferences

        ' + \\\n '
        ' +\\\n '' + \\\n '
        ' + \\\n '
        ' + \\\n '
        ' + \\\n '
        ' + \\\n '

        Bio:

        ' + \\\n '

        ' + strip_tags(prof[10]) + '

        ' + \\\n '
        ' + \\\n '
        ' + \\\n '

        Academic Interests:

        ' + \\\n '

        ' + strip_tags(prof[9]) + '

        ' + \\\n past_papers + \\\n '
        ' + \\\n '
        '\n i+=1\n else:\n html = error_statement\n print(error_statement, file=stderr)\n response = make_response(html)\n return response\n\ndef getSearchCriteria():\n input_arguments = []\n\n name = request.args.get('nameNetid')\n area = request.args.get('area')\n\n search_criteria = ''\n\n # search name/netid\n if name is None:\n name = ''\n name = name.strip()\n name = name.replace('%', r'\\%')\n names = name.split()\n\n if len(names)==1:\n search_criteria += '(first' + ' ILIKE ' + '%s' + ' OR '\n search_criteria += 'last' + ' ILIKE ' + '%s' + ' OR '\n search_criteria += 'netid' + ' ILIKE ' + '%s)' + ' AND '\n input_arguments.append('%'+names[0]+'%')\n input_arguments.append('%'+names[0]+'%')\n input_arguments.append('%'+names[0]+'%')\n elif len(names) > 1:\n search_criteria += '((first' + ' ILIKE ' + '%s' + ' OR '\n search_criteria += 'last' + ' ILIKE ' + '%s' + ') AND '\n search_criteria += '(first' + ' ILIKE ' + '%s' + ' OR '\n search_criteria += 'last' + ' ILIKE ' + '%s))' + ' AND '\n input_arguments.append('%'+names[0]+'%')\n input_arguments.append('%'+names[0]+'%')\n input_arguments.append('%'+names[1]+'%')\n input_arguments.append('%'+names[1]+'%')\n\n # search research area/ bio\n if area is None:\n area = ''\n area = area.strip()\n area = area.replace('%', r'\\%')\n areas = area.split(\",\")\n\n if len(areas) == 1:\n search_criteria += '(area' + ' ILIKE ' + '%s' + ' OR '\n input_arguments.append('%'+areas[0]+'%')\n search_criteria += 'bio' + ' ILIKE ' + '%s)' + ' AND '\n input_arguments.append('%'+areas[0]+'%')\n else:\n for i in range(len(areas)):\n search_criteria += '(area' + ' ILIKE ' + '%s' + ' OR '\n input_arguments.append('%'+areas[i]+'%')\n search_criteria += 'bio' + ' ILIKE ' + '%s)' + ' AND '\n input_arguments.append('%'+areas[i]+'%')\n\n if search_criteria != '' and search_criteria != None:\n search_criteria = search_criteria[:-5]\n return search_criteria, input_arguments\n\n\n#----------------------------------------------------------------------------------------------------#\n# Admin\n#----------------------------------------------------------------------------------------------------#\n\n\n@app.route('/admin', methods=[\"GET\"])\ndef admin():\n\n # check if user is an admin\n netID = CASClient().authenticate().rstrip('\\n')\n\n deniedAccess = ''\n\n adminsDB_ = adminsDB()\n error_statement = adminsDB_.connect()\n if error_statement != '':\n return 'Unable to connect to server. Please contact owner of the Application'\n\n conn = adminsDB_.conn \n cur = conn.cursor()\n cur.execute(\"SELECT * FROM admins WHERE netid=%s\", [netID])\n result = cur.fetchone()\n cur.close()\n adminsDB_.disconnect()\n\n if result == None:\n deniedAccess = 'deniedAccess'\n\n html = render_template('templates/admin.html', username=netID, deniedAccess=deniedAccess)\n response = make_response(html)\n return response\n\n\n@app.route('/profinfo', methods=[\"GET\"])\ndef profinfo():\n netID = request.args.get('netid')\n prof, error_statement = getProfs('netid ILIKE %s', [netID])\n html = ''\n\n if error_statement == '':\n if len(prof) == 0:\n html = '' \n else:\n prof = prof[0]\n\n src = prof[11]\n # display image if in database\n if prof[12] != None:\n imageBytes = bytes(prof[12])\n image = Image.open(io.BytesIO(imageBytes))\n\n imageExtension = prof[13]\n\n netID = prof[0]\n filename = netID + '.' + imageExtension\n destination = \"/\".join([\"static/profImages/\", filename])\n image.save(destination)\n src = destination\n\n html = \"
        \" + \\\n \"
        \" + \\\n \"
        \" + \\\n \"\" + \\\n \"
        \" + \\\n \"\" + \\\n \"
        \" + \\\n \"
        \" + \\\n \"
        \" + \\\n \"\" + \\\n \"
        \" + \\\n \"\" + \\\n \"
        \" + \\\n \"
        \" + \\\n \"
        \" + \\\n \"\" + \\\n \"
        \" + \\\n \"\" + \\\n \"
        \" + \\\n \"
        \" + \\\n \"
        \" + \\\n \"\" + \\\n \"
        \" + \\\n \"\" + \\\n \"
        \" + \\\n \"
        \" + \\\n \"
        \" + \\\n \"\" + \\\n \"
        \" + \\\n \"\" + \\\n \"
        \" + \\\n \"
        \" + \\\n \"
        \" + \\\n \"\" + \\\n \"
        \" + \\\n \"\" + \\\n \"
        \" + \\\n \"
        \" + \\\n \"
        \" + \\\n \"\" + \\\n \"
        \" + \\\n \"\" + \\\n \"
        \" + \\\n \"
        \" + \\\n \"
        \" + \\\n \"\" + \\\n \"
        \" + \\\n \"\" + \\\n \"
        \" + \\\n \"
        \" + \\\n \"
        \" + \\\n \"\" + \\\n \"
        \" + \\\n \"\" + \\\n \"
        \" + \\\n \"
        \" + \\\n \"
        \" + \\\n \"\" + \\\n \"
        \" + \\\n \"\" + \\\n \"
        \" + \\\n \"
        \" + \\\n \"
        \" + \\\n \"\" + \\\n \"
        \" + \\\n \"\" + \\\n \"
        \" + \\\n \"
        \" + \\\n \"
        \" + \\\n \"
        \" + \\\n \"\" + \\\n \"
        \" + \\\n \"

        *Small images (< 1MB) of dimensions 300x400 px work best.

        \" + \\\n \"\" + \\\n \"

        \" + \\\n \"\"\"
        \n \n \n \n
        \"\"\"\n else:\n print(error_statement, file=stderr)\n html = error_statement\n\n response = make_response(html)\n response.set_cookie('netid', netID)\n return response\n\ndef newProf(netid):\n prof = Professor(netid)\n prof.setTitle(request.args.get('title'))\n prof.setFirstName(request.args.get('firstname'))\n prof.setLastName(request.args.get('lastname'))\n prof.setEmail(request.args.get('email'))\n prof.setPhoneNumber(request.args.get('phone'))\n prof.setWebsite(request.args.get('website'))\n prof.setRooms(request.args.get('rooms'))\n prof.setDepartment(request.args.get('department'))\n prof.setResearchAreas(request.args.get('areas'))\n prof.setBio(request.args.get('bio'))\n imageExtension = request.args.get('image').split('.')[-1]\n imagePath = \"static\\profImages\\\\\" + netid + \".\" + imageExtension\n prof.setImagePath(imagePath)\n return prof\n\n@app.route('/displayprof', methods=[\"GET\"])\ndef displayprof():\n netID = request.cookies.get('netid')\n prof = newProf(netID)\n\n profsDB_ = profsDB()\n error_statement = profsDB_.connect()\n if error_statement != '':\n return error_statement\n conn = profsDB_.conn\n error_statement, returned = updateDB(conn, prof)\n if returned == False:\n error_statement = createProf(conn, prof)\n profsDB_.disconnect()\n if error_statement != '':\n print(error_statement)\n\n prof_, error_statement = getProfs('netid ILIKE %s', [netID])\n prof = prof_[0]\n if error_statement == '':\n\n src = prof[11]\n\n # display image if in database\n if prof[12] != None:\n imageBytes = bytes(prof[12])\n image = Image.open(io.BytesIO(imageBytes))\n\n imageExtension = prof[13]\n\n netID = prof[0]\n filename = netID + '.' + imageExtension\n destination = \"/\".join([\"static/profImages/\", filename])\n image.save(destination)\n src = destination\n\n html = \"

        This the updated information for \" + prof[1] + \" \" + prof[2] + \":


        \"\n html += \" \" + \\\n '' + \\\n \"\" + \\\n \"\" + \\\n \"\" + \\\n \"\" + \\\n \"\" + \\\n \"\" + \\\n \"\" + \\\n \"\" + \\\n \"\" + \\\n \"\" + \\\n \"\" + \\\n \"\" + \\\n \"\" + \\\n \"\" + \\\n \"\" + \\\n \"\" + \\\n \"\" + \\\n \"\" + \\\n \"\" + \\\n \"\" + \\\n \"\" + \\\n \"\" + \\\n \"\" + \\\n \"\" + \\\n \"\" + \\\n \"\" + \\\n \"\" + \\\n \"\" + \\\n \"\" + \\\n \"\" + \\\n \"\" + \\\n \"\" + \\\n \"\" + \\\n \"\" + \\\n \"\" + \\\n \"\" + \\\n \"\" + \\\n \"\" + \\\n \"\" + \\\n \"\" + \\\n \"\" + \\\n \"\" + \\\n \"\" + \\\n \"\" + \\\n \"\" + \\\n \"\" + \\\n \"\" + \\\n \"\" + \\\n \"\" +\\\n \"\" + \\\n \"
        NetID:\" + prof[0] + \"
        First Name:\" + prof[1] + \"
        Last Name:\" + prof[2] + \"
        Phone:\" + prof[5] + \"
        Email:\" + prof[4] + \"
        Title:\" + prof[3] + \"
        Website:\" + prof[6] + \"
        Rooms:\" + prof[7] + \"
        Department:\" + prof[8] + \"
        Areas:\" + prof[9]+ \"
        Bio:\" + prof[10] + \"
        Image File:\" + prof[11] + \"
        \" + \"\" + \"
        \" + \\\n \"\"\"
        \n \n
        \"\"\"\n else:\n print(error_statement, file=stderr)\n\n response = make_response(html)\n return response\n\n\n@app.route('/displayNewProf', methods=[\"GET\"])\ndef displayNewProf():\n netID = request.cookies.get('netid')\n\n prof = newProf(netID)\n\n profsDB_ = profsDB()\n try:\n profsDB_.connect()\n conn = profsDB_.conn\n error_statement, returned = updateDB(conn, prof)\n if returned == False:\n error_statement = createProf(conn, prof)\n except (Exception, psycopg2.DatabaseError) as error:\n error_statement = str(error)\n print(error_statement)\n finally:\n profsDB_.disconnect()\n\n prof_, error_statement = getProfs('netid ILIKE %s', [netID])\n prof = prof_[0]\n if error_statement == '':\n\n html = \"
        \" + \\\n \"
        \" + \\\n \"
        \" + \\\n \"\" + \\\n \"
        \" + \\\n \"\" + \\\n \"
        \" + \\\n \"
        \" + \\\n \"
        \" + \\\n \"\" + \\\n \"
        \" + \\\n \"\" + \\\n \"
        \" + \\\n \"
        \" + \\\n \"
        \" + \\\n \"\" + \\\n \"
        \" + \\\n \"\" + \\\n \"
        \" + \\\n \"
        \" + \\\n \"
        \" + \\\n \"\" + \\\n \"
        \" + \\\n \"\" + \\\n \"
        \" + \\\n \"
        \" + \\\n \"
        \" + \\\n \"\" + \\\n \"
        \" + \\\n \"\" + \\\n \"
        \" + \\\n \"
        \" + \\\n \"
        \" + \\\n \"\" + \\\n \"
        \" + \\\n \"\" + \\\n \"
        \" + \\\n \"
        \" + \\\n \"
        \" + \\\n \"\" + \\\n \"
        \" + \\\n \"\" + \\\n \"
        \" + \\\n \"
        \" + \\\n \"
        \" + \\\n \"\" + \\\n \"
        \" + \\\n \"\" + \\\n \"
        \" + \\\n \"
        \" + \\\n \"
        \" + \\\n \"\" + \\\n \"
        \" + \\\n \"\" + \\\n \"
        \" + \\\n \"
        \" + \\\n \"
        \" + \\\n \"\" + \\\n \"
        \" + \\\n \"\" + \\\n \"
        \" + \\\n \"
        \" + \\\n \"
        \" + \\\n \"\" + \\\n \"
        \" + \\\n \"\" + \\\n \"
        \" + \\\n \"
        \" + \\\n \"
        \" + \\\n \"
        \" + \\\n \"\" + \\\n \"
        \" + \\\n \"

        *Small images (< 1MB) of dimensions 300x400 px work best.

        \" + \\\n \"\" + \\\n \"

        \" + \\\n \"\"\"
        \n \n\n \n
        \"\"\"\n \n response = make_response(html)\n response.set_cookie('netid', netID)\n return response\n\n\n@app.route('/deleteprof', methods=[\"GET\"])\ndef deleteprof():\n netID = request.args.get('netid')\n\n profsDB_ = profsDB()\n error_statement = profsDB_.connect()\n if error_statement != '':\n return error_statement\n\n conn = profsDB_.conn\n error_statement = deleteProf(conn, netID)\n profsDB_.disconnect()\n if error_statement != '':\n print(error_statement)\n\n html = ''\n response = make_response(html)\n return response\n\n@app.route('/profPreferences', methods=[\"GET\"])\ndef profPreferences():\n\n username = CASClient().authenticate()\n\n first = request.args.get('first')\n if first == \"\":\n first = None\n second = request.args.get('second')\n third = request.args.get('third')\n fourth = request.args.get('fourth')\n\n profsDB_ = profsDB()\n error_statement = profsDB_.connect()\n profs = []\n if error_statement == '':\n connection = profsDB_.conn\n try:\n profs = profsDB_.displayAllProfessors(connection)\n profs = profsDB_.return_profs_list(profs)\n except Exception as e:\n error_statement = str(e)\n print(error_statement)\n\n profsDB_.disconnect()\n\n html = render_template('templates/profPreferences.html', \n first=first, second=second, third=third, fourth=fourth,\n profs=profs)\n else:\n html = error_statement\n response = make_response(html)\n return response\n\n@app.route('/submitPreferences', methods=[\"GET\"])\ndef submitPreferences():\n\n username = CASClient().authenticate().rstrip('\\n')\n\n advisor1 = request.args.get('Advisor1')\n if advisor1 == None:\n advisor1 = ''\n advisor2 = request.args.get('Advisor2')\n if advisor2 == None:\n advisor2 = ''\n advisor3 = request.args.get('Advisor3')\n if advisor3 == None:\n advisor3 = ''\n advisor4 = request.args.get('Advisor4')\n if advisor4 == None:\n advisor4 = ''\n\n advisor1Comments = request.args.get('Advisor1Comments')\n if advisor1Comments == None:\n advisor1Comments = ''\n advisor2Comments = request.args.get('Advisor2Comments')\n if advisor2Comments == None:\n advisor2Comments = ''\n advisor3Comments = request.args.get('Advisor3Comments')\n if advisor3Comments == None:\n advisor3Comments = ''\n advisor4Comments = request.args.get('Advisor4Comments')\n if advisor4Comments == None:\n advisor4Comments = ''\n\n courseSelection = request.args.get('courseSelection')\n\n fmt = '%Y-%m-%d %H:%M:%S %Z%z'\n eastern = timezone('America/New_York')\n loc_dt = datetime.now(eastern)\n submittedTime = loc_dt.strftime(fmt)\n if submittedTime == None:\n submittedTime = ''\n\n completedTime = submittedTime\n\n # insert data into 'preferences database'\n profPrefDB = profPreferencesDB()\n error_statement = profPrefDB.connect()\n if error_statement == '' :\n report = profPrefDB.createProfPreference([username, courseSelection,\n advisor1, advisor1Comments, advisor2, advisor2Comments, advisor3, \n advisor3Comments, advisor4, advisor4Comments, submittedTime, completedTime])\n profPrefDB.disconnect()\n else:\n print(error_statement, file=stderr)\n return error_statement\n\n response = make_response(report)\n return response\n\n@app.route('/getPreferences', methods=[\"GET\"])\ndef getPreferences():\n\n # username = CASClient().authenticate().rstrip('\\n')\n\n profPrefDB = profPreferencesDB()\n error_statement = profPrefDB.connect()\n\n report_preferences = []\n if error_statement == '' :\n report_preferences = profPrefDB.getProfPreference()\n report = report_preferences[0]\n preferences = report_preferences[1:]\n\n if report == \"Failed Download\":\n print(report, file=stderr)\n else:\n print(report)\n profPrefDB.disconnect()\n else:\n print(error_statement, file=stderr)\n return error_statement\n \n\n html = ''\n\n header = [\"Serial\",\"SID\",\"Submitted Time\",\"Completed Time\",\"Modified Time\",\"Draft\",\"UID\",\"Username\",\"Course Selection\",\"First Advisor Choice\",\"Topic or Comments\",\"Second Advisor Choice\",\"Topic or Comments\",\"Third Advisor Choice\",\"Topic or Comments\",\"Fourth Advisor Choice\",\"Topic or Comments\"]\n # spacing = [\"\"] * 17\n with open('preferences.csv', 'w', newline='') as csv_file:\n csv_writer = csv.writer(csv_file, delimiter=',')\n csv_writer.writerow(header)\n # csv_writer.writerow(spacing)\n for row in preferences:\n csv_writer.writerow(list(row))\n\n with open('preferences.csv', 'r', newline='') as csv_file:\n for row in csv_file:\n html += row\n\n remove('preferences.csv')\n\n response = make_response(html)\n return response\n\n@app.route('/getMatches', methods=[\"GET\"])\ndef getMatches():\n\n # username = CASClient().authenticate().rstrip('\\n')\n\n student_cap = 5\n pref_limit = 4\n report, prof_student_list, student_prof_list = optimizePreferences(student_cap, pref_limit)\n\n html = ''\n\n header = [\"Professor\"]\n for i in range(1, student_cap + 1):\n header.append(\"Student\" + str(i))\n # spacing = [\"\"] * 2\n with open('matches.csv', 'w', newline='') as csv_file:\n csv_writer = csv.writer(csv_file, delimiter=',')\n csv_writer.writerow([\"Student netids with an asterisk (*) indicate a non-ORFE advisor preference. Student netids with a dollar sign ($) indicate that a student was not paired with any of their preferences. See preferences.csv for more details.\"])\n csv_writer.writerow(header)\n # csv_writer.writerow(spacing)\n for prof in prof_student_list:\n prof_students = [prof]\n for student in prof_student_list[prof]:\n prof_students.append(student)\n csv_writer.writerow(prof_students)\n\n with open('matches.csv', 'r', newline='') as csv_file:\n for row in csv_file:\n html += row\n\n remove('matches.csv')\n\n response = make_response(html)\n return response\n\n@app.route('/upload', methods=[\"POST\"])\ndef upload():\n target = path.join(APP_ROUTE, 'static/profImages')\n netID = request.cookies.get('netid')\n \n file = request.files.getlist(\"file\")[0]\n fileExtension = file.filename.split('.')[-1]\n file_data = file.read()\n id_item = 254\n SaveImageToDatabase(netID, id_item, file_data, fileExtension)\n return ('', 204)\n\ndef SaveImageToDatabase(netID, id_item, FileImage, fileExtension):\n\n error_statement = ''\n\n stmt = \"\"\n stmt += \"UPDATE profs\"\n stmt += \" set image_actual=%s,\"\n stmt += \" image_extension=%s\"\n stmt += \" WHERE netid=%s\"\n\n try:\n adminsDB_ = adminsDB()\n adminsDB_.connect()\n conn = adminsDB_.conn\n cur = conn.cursor()\n cur.execute(stmt, [FileImage, fileExtension, netID])\n conn.commit()\n cur.close()\n except (Exception, psycopg2.DatabaseError) as error:\n error_statement = str(error)\n print(error_statement)\n finally:\n adminsDB_.disconnect()\n return error_statement\n\n@app.route('/getAdmins', methods=[\"GET\"])\ndef getAdmins():\n\n deniedAccess = ''\n\n adminsDB_ = adminsDB()\n error_statement = adminsDB_.connect()\n if error_statement != '':\n return error_statement\n conn = adminsDB_.conn\n cur = conn.cursor()\n cur.execute(\"SELECT netid FROM admins\")\n row = cur.fetchone()\n admins = \"\"\n while row is not None:\n admins += str(row[0]) + \",\"\n row = cur.fetchone()\n admins = admins[:-1]\n cur.close()\n adminsDB_.disconnect()\n return admins\n\n@app.route('/addNewAdmin', methods=[\"GET\"])\ndef addNewAdmin():\n netid = request.args.get('netid')\n\n error_statement = ''\n\n try:\n adminsDB_ = adminsDB()\n error_statement = adminsDB_.connect()\n conn = adminsDB_.conn\n cur = conn.cursor()\n stmt = \"INSERT INTO admins(netid) VALUES(%s)\"\n cur.execute(stmt, [netid])\n conn.commit()\n cur.close()\n adminsDB_.disconnect()\n except (Exception, psycopg2.DatabaseError) as error:\n error_statement = str(error)\n print(error_statement)\n finally:\n if conn is not None:\n conn.close()\n return error_statement\n\n\n@app.route('/removeAdmin', methods=[\"GET\"])\ndef removeAdmin():\n netid = request.args.get('netid')\n\n error_statement = ''\n try:\n adminsDB_ = adminsDB()\n error_statement = adminsDB_.connect()\n conn = adminsDB_.conn\n cur = conn.cursor()\n stmt = \"DELETE FROM admins WHERE netid=%s\"\n\n cur.execute(stmt, [netid])\n conn.commit()\n cur.close()\n adminsDB_.disconnect()\n except (Exception, psycopg2.DatabaseError) as error:\n error_statement = str(error)\n print(error_statement)\n finally:\n if conn is not None:\n conn.close()\n return error_statement\n\n\n\nif __name__ == '__main__':\n \n if (len(argv) != 2):\n print('Usage: ' + argv[0] + ' port', file=stderr)\n exit(1)\n\n try:\n port = int(argv[1])\n except:\n print(\"Port must be an integer\", file=stderr)\n exit(1) \n\n app.run(host='0.0.0.0', port=int(argv[1]), debug=True)\n","sub_path":"runserver.py","file_name":"runserver.py","file_ext":"py","file_size_in_byte":36730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"494411017","text":"# Author: henning.s.strandaa@gmail.com\n# Git: emasru\n\nimport matplotlib.pyplot as plt\n\n\ndef read():\n f = open(\"temperaturer.txt\", \"r\")\n\n date = []\n average = []\n normal = [] # Åpner filen og lager nye lister\n\n for row in f:\n data = row.split()\n date.append(str(data[0]))\n average.append(float(data[1]))\n normal.append(float(data[2])) # Skriver dataen inn i listen for hver rad, splittet med mellomrom\n\n f.close()\n data = [date, average, normal]\n return data # Lukker fila, og lager en ny liste som inneholder alle de andre listene, og returnerer denne\n\n\nfile_data = read()\nprint(\"Dato Gjennomsnittstemperatur Normaltemperatur\")\nfor x in range(len(file_data[0])):\n print(file_data[0][x], str(file_data[1][x]), str(file_data[2][x])) # Printer ut hver data, rekke for rekke\n\nfile_data_len = []\nfor x in range(len(file_data[0])):\n file_data_len.append(x) # Lager en liste med lengden til dataen, noe some trengs til plottingen\n\n# plt.bar(temperature_len, temperature[1], tick_label=temperature[0])\nax = plt.subplot(111)\nax.bar([x + 0.5 for x in file_data_len], file_data[1], color=\"r\", tick_label=file_data[0], label=\"Gjennomsnittstemperatur\")\nax.bar(file_data_len, file_data[2], color=\"g\", label=\"Normaltemperatur\")\nax.legend(loc='upper left')\nplt.show()\n\n\n","sub_path":"temperatures.py","file_name":"temperatures.py","file_ext":"py","file_size_in_byte":1326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"240411688","text":"\n\nfrom xai.brain.wordbase.nouns._vale import _VALE\n\n#calss header\nclass _VALES(_VALE, ):\n\tdef __init__(self,): \n\t\t_VALE.__init__(self)\n\t\tself.name = \"VALES\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"vale\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_vales.py","file_name":"_vales.py","file_ext":"py","file_size_in_byte":224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"365453657","text":"'''Basic CGRAPPA example using Shepp-Logan phantom.'''\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom phantominator import shepp_logan\n\nfrom pygrappa import cgrappa\n\nif __name__ == '__main__':\n\n # Generate fake sensitivity maps: mps\n N = 128\n ncoils = 4\n xx = np.linspace(0, 1, N)\n x, y = np.meshgrid(xx, xx)\n mps = np.zeros((N, N, ncoils))\n mps[..., 0] = x**2\n mps[..., 1] = 1 - x**2\n mps[..., 2] = y**2\n mps[..., 3] = 1 - y**2\n\n # generate 4 coil phantom\n ph = shepp_logan(N)\n imspace = ph[..., None]*mps\n imspace = imspace.astype('complex')\n imspace = imspace[:, :-4, :]\n ax = (0, 1)\n kspace = 1/np.sqrt(N**2)*np.fft.fftshift(np.fft.fft2(\n np.fft.ifftshift(imspace, axes=ax), axes=ax), axes=ax)\n\n # crop 20x20 window from the center of k-space for calibration\n pd = 10\n ctr = int(N/2)\n calib = kspace[ctr-pd:ctr+pd, ctr-pd:ctr+pd, :].copy()\n\n # calibrate a kernel\n kernel_size = (4, 4)\n\n # undersample by a factor of 2 in both x and y\n kspace[::2, 1::2, :] = 0\n kspace[1::2, ::2, :] = 0\n\n # reconstruct:\n res = cgrappa(\n kspace, calib, kernel_size, coil_axis=-1, lamda=0.01)\n\n # Take a look\n res = np.abs(np.sqrt(N**2)*np.fft.fftshift(np.fft.ifft2(\n np.fft.ifftshift(res, axes=ax), axes=ax), axes=ax))\n M, N = res.shape[:2]\n res0 = np.zeros((2*M, 2*N))\n kk = 0\n for idx in np.ndindex((2, 2)):\n ii, jj = idx[:]\n res0[ii*M:(ii+1)*M, jj*N:(jj+1)*N] = res[..., kk]\n kk += 1\n plt.imshow(res0, cmap='gray')\n plt.show()\n","sub_path":"pygrappa/examples/basic_cgrappa.py","file_name":"basic_cgrappa.py","file_ext":"py","file_size_in_byte":1576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"37482924","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jan 28 17:28:12 2019\n\n@author: Education\n\"\"\"\n\nimport random\n\nlist1 = ['grapes', 'orange', 'apple', 'papaya', 'tomato', 'Branjil', \n 'anjeer', 'banana', 'tomato', 'cabagge', 'penuts']\n\nName = random.choice(list1)\ny=list(\" \"*len(Name))\n\ntry:\n def Hangman():\n for i in range(6,-1,-1):\n playerguess=input(\"enter guess: \")\n if playerguess in Name:\n print(\"player wins\")\n x=Name.index(playerguess)\n y.insert(x,playerguess)\n else:\n print(\"player loss\") \n print(\"number of chances left:\",i )\n \n Hangman() \n choice=input(\"do u want play again yes or no: \")\n if(choice.upper()==\"YES\"):\n Hangman()\n else:\n print(\"Quit the Hangman\")\nexcept Exception as e:\n print(\"Exception:\",e)\n \nelse: \n for i in y:\n print(i,end=\" \") \n\nfinally:\n print(\"\\n Hangman Game\") ","sub_path":"hangman.py","file_name":"hangman.py","file_ext":"py","file_size_in_byte":870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"288427602","text":"import os\nimport shutil\nimport yaml\nimport yamlordereddictloader\n\nfrom typing import Dict\nfrom distutils.dir_util import copy_tree\nfrom demisto_sdk.common.tools import print_error, print_color, LOG_COLORS\nfrom demisto_sdk.common.constants import INTEGRATIONS_DIR, SCRIPTS_DIR, INCIDENT_FIELDS_DIR, INCIDENT_TYPES_DIR, \\\n INDICATOR_FIELDS_DIR, PLAYBOOKS_DIR, LAYOUTS_DIR, TEST_PLAYBOOKS_DIR, CLASSIFIERS_DIR, CONNECTIONS_DIR, \\\n DASHBOARDS_DIR, MISC_DIR, REPORTS_DIR, WIDGETS_DIR\n\n\nclass Initiator:\n \"\"\"Initiator creates a new pack/integration/script.\n\n Attributes:\n output_dir (str): The directory in which init will create the new pack/integration/script\n name (str): The name for the new pack/integration/script directory.\n id (str): The id for the created script/integration.\n integration (bool): Indicates whether to create an integration.\n script (bool): Indicates whether to create a script.\n full_output_path (str): The full path to the newly created pack/integration/script\n \"\"\"\n\n def __init__(self, output_dir: str, name: str = '', id: str = '', integration: bool = False, script: bool = False,\n pack: bool = False):\n self.output_dir = output_dir if output_dir else ''\n self.id = id\n\n self.is_integration = integration\n self.is_script = script\n self.is_pack = pack\n\n # if no flag given automatically create a pack.\n if not integration and not script and not pack:\n self.is_pack = True\n\n self.full_output_path = ''\n\n if name is not None and len(name) != 0:\n while ' ' in name:\n name = str(input(\"The directory and file name cannot have spaces in it, Enter a different name: \"))\n\n self.dir_name = name\n self.is_pack_creation = not all([self.is_script, self.is_integration])\n\n HELLO_WORLD_INTEGRATION = 'HelloWorld'\n HELLO_WORLD_SCRIPT = 'HelloWorldScript'\n DIR_LIST = [INTEGRATIONS_DIR, SCRIPTS_DIR, INCIDENT_FIELDS_DIR, INCIDENT_TYPES_DIR, INDICATOR_FIELDS_DIR,\n PLAYBOOKS_DIR, LAYOUTS_DIR, TEST_PLAYBOOKS_DIR, CLASSIFIERS_DIR, CONNECTIONS_DIR, DASHBOARDS_DIR,\n MISC_DIR, REPORTS_DIR, WIDGETS_DIR]\n\n def init(self):\n \"\"\"Starts the init command process.\n\n \"\"\"\n if self.is_integration:\n self.get_created_dir_name(created_object=\"integration\")\n self.get_object_id(created_object=\"integration\")\n return self.integration_init()\n\n elif self.is_script:\n self.get_created_dir_name(created_object=\"script\")\n self.get_object_id(created_object=\"script\")\n return self.script_init()\n\n elif self.is_pack:\n self.get_created_dir_name(created_object=\"pack\")\n return self.pack_init()\n\n def get_created_dir_name(self, created_object: str):\n \"\"\"Makes sure a name is given for the created object\n\n Args:\n created_object (str): the type of the created object (integration/script/pack)\n \"\"\"\n while not self.dir_name or len(self.dir_name) == 0:\n self.dir_name = str(input(f\"Please input the name of the initialized {created_object}: \"))\n while ' ' in self.dir_name:\n self.dir_name = str(input(\"The directory name cannot have spaces in it, Enter a different name: \"))\n\n def get_object_id(self, created_object: str):\n if not self.id:\n if self.is_pack_creation: # There was no option to enter the ID in this process.\n use_dir_name = str(input(f\"Do you want to use the directory name as an \"\n f\"ID for the {created_object}? Y/N\"))\n else:\n use_dir_name = str(input(f\"No ID given for the {created_object}'s yml file. \"\n f\"Do you want to use the directory name? Y/N \"))\n\n if use_dir_name and use_dir_name.lower() in ['y', 'yes']:\n self.id = self.dir_name\n else:\n while not self.id:\n self.id = str(input(f\"Please enter the id name for the {created_object}: \"))\n\n def pack_init(self) -> bool:\n \"\"\"Creates a pack directory tree.\n\n Returns:\n bool. Returns True if pack was created successfully and False otherwise\n \"\"\"\n # if an output directory given create the pack there\n if len(self.output_dir) > 0:\n self.full_output_path = os.path.join(self.output_dir, self.dir_name)\n\n # content-descriptor file indicates we are in \"content\" repository\n # thus we will create the pack under Packs directory\n elif os.path.isfile('content-descriptor.json'):\n self.full_output_path = os.path.join(\"Packs\", self.dir_name)\n\n # if non of the above conditions apply - create the pack in current directory\n else:\n self.full_output_path = self.dir_name\n\n if not self.create_new_directory():\n return False\n for directory in self.DIR_LIST:\n path = os.path.join(self.full_output_path, directory)\n os.mkdir(path=path)\n\n with open(os.path.join(self.full_output_path, 'CHANGELOG.md'), 'a') as fp:\n fp.write(\"## [Unreleased]\")\n\n fp = open(os.path.join(self.full_output_path, 'README.md'), 'a')\n fp.close()\n\n with open(os.path.join(self.full_output_path, 'metadata.json'), 'a') as fp:\n # TODO fill this once metadata.json script is ready\n fp.write('[]')\n\n fp = open(os.path.join(self.full_output_path, '.secrets-ignore'), 'a')\n fp.close()\n\n fp = open(os.path.join(self.full_output_path, '.pack-ignore'), 'a')\n fp.close()\n\n print_color(f\"Successfully created the pack {self.dir_name} in: {self.full_output_path}\", LOG_COLORS.GREEN)\n\n create_integration = str(input(\"\\nDo you want to create an integration in the pack? Y/N \")).lower()\n if create_integration in ['y', 'yes']:\n integration_init = Initiator(output_dir=os.path.join(self.full_output_path, 'Integrations'),\n integration=True)\n return integration_init.init()\n\n return True\n\n def integration_init(self) -> bool:\n \"\"\"Creates a new integration according to a template.\n\n Returns:\n bool. True if the integration was created successfully, False otherwise.\n \"\"\"\n # if output directory given create the integration there\n if len(self.output_dir) > 0:\n self.full_output_path = os.path.join(self.output_dir, self.dir_name)\n\n # will create the integration under the Integrations directory of the pack\n elif os.path.isdir(INTEGRATIONS_DIR):\n self.full_output_path = os.path.join('Integrations', self.dir_name)\n\n # if non of the conditions above apply - create the integration in the local directory\n else:\n self.full_output_path = self.dir_name\n\n if not self.create_new_directory():\n return False\n\n hello_world_path = os.path.normpath(os.path.join(__file__, \"..\", \"..\", 'common', 'templates',\n self.HELLO_WORLD_INTEGRATION))\n\n copy_tree(str(hello_world_path), self.full_output_path)\n if self.id != self.HELLO_WORLD_INTEGRATION:\n # note rename does not work on the yml file - that is done in the yml_reformatting function.\n self.rename(current_suffix=self.HELLO_WORLD_INTEGRATION)\n self.yml_reformatting(current_suffix=self.HELLO_WORLD_INTEGRATION)\n self.fix_test_file_import(name_to_change=self.HELLO_WORLD_INTEGRATION)\n\n print_color(f\"Finished creating integration: {self.full_output_path}.\", LOG_COLORS.GREEN)\n\n return True\n\n def script_init(self) -> bool:\n \"\"\"Creates a new script according to a template.\n\n Returns:\n bool. True if the script was created successfully, False otherwise.\n \"\"\"\n # if output directory given create the script there\n if len(self.output_dir) > 0:\n self.full_output_path = os.path.join(self.output_dir, self.dir_name)\n\n # will create the script under the Scripts directory of the pack\n elif os.path.isdir(SCRIPTS_DIR):\n self.full_output_path = os.path.join('Scripts', self.dir_name)\n\n # if non of the conditions above apply - create the integration in the local directory\n else:\n self.full_output_path = self.dir_name\n\n if not self.create_new_directory():\n return False\n\n hello_world_path = os.path.normpath(os.path.join(__file__, \"..\", \"..\", 'common', 'templates',\n self.HELLO_WORLD_SCRIPT))\n\n copy_tree(str(hello_world_path), self.full_output_path)\n if self.id != self.HELLO_WORLD_SCRIPT:\n # note rename does not work on the yml file - that is done in the yml_reformatting function.\n self.rename(current_suffix=self.HELLO_WORLD_SCRIPT)\n self.yml_reformatting(current_suffix=self.HELLO_WORLD_SCRIPT)\n self.fix_test_file_import(name_to_change=self.HELLO_WORLD_SCRIPT)\n\n print_color(f\"Finished creating script: {self.full_output_path}\", LOG_COLORS.GREEN)\n\n return True\n\n def yml_reformatting(self, current_suffix: str):\n \"\"\"Formats the given yml to fit the newly created integration/script\n\n Args:\n current_suffix (str): The yml file name (HelloWorld or HelloWorldScript)\n \"\"\"\n yml_dict = self.get_yml_data_as_dict(file_path=os.path.join(self.full_output_path, f\"{current_suffix}.yml\"))\n yml_dict[\"commonfields\"][\"id\"] = self.id\n yml_dict['name'] = self.id\n yml_dict[\"display\"] = self.id\n\n with open(os.path.join(self.full_output_path, f\"{self.dir_name}.yml\"), 'w') as f:\n yaml.dump(\n yml_dict,\n f,\n Dumper=yamlordereddictloader.SafeDumper,\n default_flow_style=False)\n\n os.remove(os.path.join(self.full_output_path, f\"{current_suffix}.yml\"))\n\n def rename(self, current_suffix: str):\n \"\"\"Renames the python, description, test and image file in the path to fit the newly created integration/script\n\n Args:\n current_suffix (str): The yml file name (HelloWorld or HelloWorldScript)\n \"\"\"\n os.rename(os.path.join(self.full_output_path, f\"{current_suffix}.py\"),\n os.path.join(self.full_output_path, f\"{self.dir_name}.py\"))\n os.rename(os.path.join(self.full_output_path, f\"{current_suffix}_description.md\"),\n os.path.join(self.full_output_path, f\"{self.dir_name}_description.md\"))\n os.rename(os.path.join(self.full_output_path, f\"{current_suffix}_test.py\"),\n os.path.join(self.full_output_path, f\"{self.dir_name}_test.py\"))\n if self.is_integration:\n os.rename(os.path.join(self.full_output_path, f\"{current_suffix}_image.png\"),\n os.path.join(self.full_output_path, f\"{self.dir_name}_image.png\"))\n\n def create_new_directory(self,) -> bool:\n \"\"\"Creates a new directory for the integration/script/pack.\n\n Returns:\n bool. True if directory was successfully created, False otherwise.\n \"\"\"\n try:\n os.mkdir(self.full_output_path)\n\n except FileExistsError:\n to_delete = str(input(f\"The directory {self.full_output_path} \"\n f\"already exists.\\nDo you want to overwrite it? Y/N \")).lower()\n while to_delete != 'y' and to_delete != 'n':\n to_delete = str(input(f\"Your response was invalid.\\nDo you want to delete it? Y/N \").lower())\n\n if to_delete in ['y', 'yes']:\n shutil.rmtree(path=self.full_output_path, ignore_errors=True)\n os.mkdir(self.full_output_path)\n\n else:\n print_error(f\"Pack not created in {self.full_output_path}\")\n return False\n\n return True\n\n def get_yml_data_as_dict(self, file_path: str) -> Dict:\n \"\"\"Converts YML file data to Dict.\n\n Args:\n file_path (str): The path to the .yml file\n\n Returns:\n Dict. Data from YML.\n \"\"\"\n with open(file_path) as f:\n return yaml.load(f, Loader=yamlordereddictloader.SafeLoader)\n\n def fix_test_file_import(self, name_to_change: str):\n \"\"\"Fixes the import statement in the _test.py file in the newly created initegration/script\n\n Args:\n name_to_change (str): The name of the former integration/script to replace in the import.\n \"\"\"\n with open(os.path.join(self.full_output_path, f\"{self.dir_name}_test.py\"), 'r') as fp:\n file_contents = fp.read()\n file_contents = file_contents.replace(name_to_change, self.dir_name)\n\n with open(os.path.join(self.full_output_path, f\"{self.dir_name}_test.py\"), 'w') as fp:\n fp.write(file_contents)\n","sub_path":"demisto_sdk/dev_tools/initiator.py","file_name":"initiator.py","file_ext":"py","file_size_in_byte":13187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"564723672","text":"# Feeds extension for Review Board.\nfrom django.conf import settings\nfrom django.conf.urls.defaults import patterns, include\nfrom django.http import HttpRequest\nfrom reviewboard.extensions.base import Extension\nfrom reviewboard.extensions.hooks import DashboardHook, URLHook\n\n\nclass MyDashboardHook(DashboardHook):\n\n def __getattribute__(self, name):\n \"\"\" Get Attribute from module\n \n At this point, Reviewboard extensions dont provide a way to get \n Request object during every page load. The Dashboard hook gets\n its entries when its loaded and uses it for all pages. This\n method uses a (ugly) hack to get the stacktrace from the current \n page and get the request object(and hence the user object) so I\n can do user specific things. This will change in the future when\n RB provides per-page hooks (as in NavigationBarHook)\n \"\"\"\n if name == 'entries':\n import sys\n f = sys._getframe()\n username = None\n while f:\n request = f.f_locals.get('request')\n if isinstance(request, HttpRequest):\n username = request.user.username\n break\n f = f.f_back\n\n site_root = settings.SITE_ROOT\n entries = [\n {\n 'label': 'My Feeds',\n 'url': '#',\n 'subitems': [\n {\n 'label': 'RSS',\n 'url': \"%sfeeds/feed/%s\" % (site_root, username)\n },\n {\n 'label': 'Atom 1',\n 'url': \"%sfeeds/feed/%s?type=atom\" % (site_root,\n username)\n }\n ]\n },\n {\n 'label': 'All Review Feeds',\n 'url': \"%sfeeds/r/\" % (site_root,)\n }\n ]\n return entries\n else:\n return DashboardHook.__getattribute__(self, name)\n\n\nclass RSSExtension(Extension):\n is_configurable = False\n\n def __init__(self, *args, **kwargs):\n super(RSSExtension, self).__init__(*args, **kwargs)\n\n self.url_hook = URLHook(self, patterns('',\n (r'^feeds/', include('rbrssfeeds.urls'))))\n self.dashboard_hook = MyDashboardHook(self)\n","sub_path":"rbrssfeeds/rbrssfeeds/extension.py","file_name":"extension.py","file_ext":"py","file_size_in_byte":2511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"302444866","text":"import cairo\nimport rsvg\n\nimg = cairo.ImageSurface(cairo.FORMAT_ARGB32, 640, 480)\n\nctx = cairo.Context(img)\n\nhandler = rsvg.Handle('test.svg')\n# or, for in memory SVG data:\n# handler = rsvg.Handle(None, str())\n\nhandler.render_cairo(ctx)\nimg.write_to_png(\"svg.png\")\n","sub_path":"svg2png.py","file_name":"svg2png.py","file_ext":"py","file_size_in_byte":275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"167129725","text":"import cv2\r\nimg = cv2.imread(r'D:\\cvtest\\wuhu.jpg')\r\ngray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\r\nface_cascade=cv2.CascadeClassifier(r'D:\\cvtest\\haarcascade_frontalface_default.xml')\r\nfaces=face_cascade.detectMultiScale(gray,scaleFactor=1.05,minNeighbors=15)\r\neye_cascade=cv2.CascadeClassifier(r'D:\\cvtest\\xml\\xml\\haarcascade_eye.xml')\r\neyes=eye_cascade.detectMultiScale(gray,scaleFactor=1.05,minNeighbors=15)\r\neye_glass_cascade=cv2.CascadeClassifier(r'D:\\cvtest\\xml\\xml\\haarcascade_eye_tree_eyeglasses.xml')\r\neyes_glass=eye_cascade.detectMultiScale(gray,scaleFactor=1.05,minNeighbors=15)\r\nfor (x,y,w,h) in faces:\r\n img=cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),3)\r\nfor (x,y,w,h) in eyes:\r\n img=cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),3)\r\n# for (x,y,w,h) in eyes_glass:\r\n# img=cv2.rectangle(img,(x,y),(x+w,y+h),(0,0,255),3)\r\nresized=cv2.resize(img,(512,800))\r\ncv2.imshow('wow',resized)\r\nk=cv2.waitKey(0)\r\nif k==27:\r\n cv2.destroyWindow('wow')\r\nif k==115:\r\n cv2.imwrite(r'D:\\cvtest\\wuhu_hhh.jpg',img)\r\n cv2.destroyWindow('wow')","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"52268504","text":"import json\nimport warnings\nfrom collections import namedtuple\nfrom typing import Any, Dict, List\n\nimport pytest\n\nfrom aws_lambda_powertools import Metrics, single_metric\nfrom aws_lambda_powertools.metrics import (\n MetricUnit,\n MetricUnitError,\n MetricValueError,\n SchemaValidationError,\n UniqueNamespaceError,\n)\nfrom aws_lambda_powertools.metrics.base import MetricManager\n\n\n@pytest.fixture(scope=\"function\", autouse=True)\ndef reset_metric_set():\n metrics = Metrics()\n metrics.clear_metrics()\n yield\n\n\n@pytest.fixture\ndef metric() -> Dict[str, str]:\n return {\"name\": \"single_metric\", \"unit\": MetricUnit.Count, \"value\": 1}\n\n\n@pytest.fixture\ndef metrics() -> List[Dict[str, str]]:\n return [\n {\"name\": \"metric_one\", \"unit\": MetricUnit.Count, \"value\": 1},\n {\"name\": \"metric_two\", \"unit\": MetricUnit.Count, \"value\": 1},\n ]\n\n\n@pytest.fixture\ndef dimension() -> Dict[str, str]:\n return {\"name\": \"test_dimension\", \"value\": \"test\"}\n\n\n@pytest.fixture\ndef dimensions() -> List[Dict[str, str]]:\n return [\n {\"name\": \"test_dimension\", \"value\": \"test\"},\n {\"name\": \"test_dimension_2\", \"value\": \"test\"},\n ]\n\n\n@pytest.fixture\ndef non_str_dimensions() -> List[Dict[str, Any]]:\n return [\n {\"name\": \"test_dimension\", \"value\": True},\n {\"name\": \"test_dimension_2\", \"value\": 3},\n ]\n\n\n@pytest.fixture\ndef namespace() -> Dict[str, str]:\n return {\"name\": \"test_namespace\"}\n\n\n@pytest.fixture\ndef a_hundred_metrics() -> List[Dict[str, str]]:\n metrics = []\n for i in range(100):\n metrics.append({\"name\": f\"metric_{i}\", \"unit\": \"Count\", \"value\": 1})\n\n return metrics\n\n\ndef serialize_metrics(metrics: List[Dict], dimensions: List[Dict], namespace: Dict) -> Dict:\n \"\"\" Helper function to build EMF object from a list of metrics, dimensions \"\"\"\n my_metrics = MetricManager()\n for dimension in dimensions:\n my_metrics.add_dimension(**dimension)\n\n my_metrics.add_namespace(**namespace)\n for metric in metrics:\n my_metrics.add_metric(**metric)\n\n if len(metrics) != 100:\n return my_metrics.serialize_metric_set()\n\n\ndef serialize_single_metric(metric: Dict, dimension: Dict, namespace: Dict) -> Dict:\n \"\"\" Helper function to build EMF object from a given metric, dimension and namespace \"\"\"\n my_metrics = MetricManager()\n my_metrics.add_metric(**metric)\n my_metrics.add_dimension(**dimension)\n my_metrics.add_namespace(**namespace)\n return my_metrics.serialize_metric_set()\n\n\ndef remove_timestamp(metrics: List):\n \"\"\" Helper function to remove Timestamp key from EMF objects as they're built at serialization \"\"\"\n for metric in metrics:\n del metric[\"_aws\"][\"Timestamp\"]\n\n\ndef test_single_metric_one_metric_only(capsys, metric, dimension, namespace):\n # GIVEN we attempt to add more than one metric\n # WHEN using single_metric context manager\n with single_metric(**metric) as my_metric:\n my_metric.add_metric(name=\"second_metric\", unit=\"Count\", value=1)\n my_metric.add_metric(name=\"third_metric\", unit=\"Seconds\", value=1)\n my_metric.add_dimension(**dimension)\n my_metric.add_namespace(**namespace)\n\n output = json.loads(capsys.readouterr().out.strip())\n expected = serialize_single_metric(metric=metric, dimension=dimension, namespace=namespace)\n\n remove_timestamp(metrics=[output, expected]) # Timestamp will always be different\n\n # THEN we should only have the first metric added\n assert expected[\"_aws\"] == output[\"_aws\"]\n\n\ndef test_multiple_namespaces_exception(metric, dimension, namespace):\n # GIVEN we attempt to add multiple namespaces\n namespace_a = {\"name\": \"OtherNamespace\"}\n namespace_b = {\"name\": \"AnotherNamespace\"}\n\n # WHEN an EMF object can only have one\n # THEN we should raise UniqueNamespaceError exception\n with pytest.raises(UniqueNamespaceError):\n with single_metric(**metric) as my_metric:\n my_metric.add_dimension(**dimension)\n my_metric.add_namespace(**namespace)\n my_metric.add_namespace(**namespace_a)\n my_metric.add_namespace(**namespace_b)\n\n\ndef test_log_metrics(capsys, metrics, dimensions, namespace):\n # GIVEN Metrics is initialized\n my_metrics = Metrics()\n my_metrics.add_namespace(**namespace)\n for metric in metrics:\n my_metrics.add_metric(**metric)\n for dimension in dimensions:\n my_metrics.add_dimension(**dimension)\n\n # WHEN we utilize log_metrics to serialize\n # and flush all metrics at the end of a function execution\n @my_metrics.log_metrics\n def lambda_handler(evt, ctx):\n return True\n\n lambda_handler({}, {})\n\n output = json.loads(capsys.readouterr().out.strip())\n expected = serialize_metrics(metrics=metrics, dimensions=dimensions, namespace=namespace)\n\n remove_timestamp(metrics=[output, expected]) # Timestamp will always be different\n\n # THEN we should have no exceptions\n # and a valid EMF object should've been flushed correctly\n assert expected[\"_aws\"] == output[\"_aws\"]\n for dimension in dimensions:\n assert dimension[\"name\"] in output\n\n\ndef test_namespace_env_var(monkeypatch, capsys, metric, dimension, namespace):\n # GIVEN we use POWERTOOLS_METRICS_NAMESPACE\n monkeypatch.setenv(\"POWERTOOLS_METRICS_NAMESPACE\", namespace[\"name\"])\n\n # WHEN creating a metric but don't explicitly\n # add a namespace\n with single_metric(**metric) as my_metrics:\n my_metrics.add_dimension(**dimension)\n monkeypatch.delenv(\"POWERTOOLS_METRICS_NAMESPACE\")\n\n output = json.loads(capsys.readouterr().out.strip())\n expected = serialize_single_metric(metric=metric, dimension=dimension, namespace=namespace)\n\n remove_timestamp(metrics=[output, expected]) # Timestamp will always be different\n\n # THEN we should add a namespace implicitly\n # with the value of POWERTOOLS_METRICS_NAMESPACE env var\n assert expected[\"_aws\"] == output[\"_aws\"]\n\n\ndef test_service_env_var(monkeypatch, capsys, metric, namespace):\n # GIVEN we use POWERTOOLS_SERVICE_NAME\n monkeypatch.setenv(\"POWERTOOLS_SERVICE_NAME\", \"test_service\")\n my_metrics = Metrics(namespace=namespace[\"name\"])\n\n # WHEN creating a metric but don't explicitly\n # add a dimension\n @my_metrics.log_metrics\n def lambda_handler(evt, context):\n my_metrics.add_metric(**metric)\n return True\n\n lambda_handler({}, {})\n\n monkeypatch.delenv(\"POWERTOOLS_SERVICE_NAME\")\n\n output = json.loads(capsys.readouterr().out.strip())\n expected_dimension = {\"name\": \"service\", \"value\": \"test_service\"}\n expected = serialize_single_metric(metric=metric, dimension=expected_dimension, namespace=namespace)\n\n remove_timestamp(metrics=[output, expected]) # Timestamp will always be different\n\n # THEN metrics should be logged using the implicitly created \"service\" dimension\n assert expected == output\n\n\ndef test_metrics_spillover(monkeypatch, capsys, metric, dimension, namespace, a_hundred_metrics):\n # GIVEN Metrics is initialized and we have over a hundred metrics to add\n my_metrics = Metrics()\n my_metrics.add_dimension(**dimension)\n my_metrics.add_namespace(**namespace)\n\n # WHEN we add more than 100 metrics\n for _metric in a_hundred_metrics:\n my_metrics.add_metric(**_metric)\n\n # THEN it should serialize and flush all metrics at the 100th\n # and clear all metrics and dimensions from memory\n output = json.loads(capsys.readouterr().out.strip())\n spillover_metrics = output[\"_aws\"][\"CloudWatchMetrics\"][0][\"Metrics\"]\n assert my_metrics.metric_set == {}\n assert len(spillover_metrics) == 100\n\n # GIVEN we add the 101th metric\n # WHEN we already had a Metric class instance\n # with an existing dimension set from the previous 100th metric batch\n my_metrics.add_metric(**metric)\n\n # THEN serializing the 101th metric should\n # create a new EMF object with a single metric in it (101th)\n # and contain have the same dimension we previously added\n serialized_101th_metric = my_metrics.serialize_metric_set()\n expected_101th_metric = serialize_single_metric(metric=metric, dimension=dimension, namespace=namespace)\n remove_timestamp(metrics=[serialized_101th_metric, expected_101th_metric])\n\n assert serialized_101th_metric[\"_aws\"] == expected_101th_metric[\"_aws\"]\n\n\ndef test_log_metrics_should_invoke_function(metric, dimension, namespace):\n # GIVEN Metrics is initialized\n my_metrics = Metrics()\n\n # WHEN log_metrics is used to serialize metrics\n @my_metrics.log_metrics\n def lambda_handler(evt, context):\n my_metrics.add_namespace(**namespace)\n my_metrics.add_metric(**metric)\n my_metrics.add_dimension(**dimension)\n return True\n\n # THEN log_metrics should invoke the function it decorates\n # and return no error if we have a metric, namespace, and a dimension\n lambda_handler({}, {})\n\n\ndef test_incorrect_metric_unit(metric, dimension, namespace):\n # GIVEN we pass a metric unit not supported by CloudWatch\n metric[\"unit\"] = \"incorrect_unit\"\n\n # WHEN we attempt to add a new metric\n # THEN it should fail validation and raise MetricUnitError\n with pytest.raises(MetricUnitError):\n with single_metric(**metric) as my_metric:\n my_metric.add_dimension(**dimension)\n my_metric.add_namespace(**namespace)\n\n\ndef test_schema_no_namespace(metric, dimension):\n # GIVEN we add any metric or dimension\n # but no namespace\n\n # WHEN we attempt to serialize a valid EMF object\n # THEN it should fail validation and raise SchemaValidationError\n with pytest.raises(SchemaValidationError):\n with single_metric(**metric) as my_metric:\n my_metric.add_dimension(**dimension)\n\n\ndef test_schema_incorrect_value(metric, dimension, namespace):\n # GIVEN we pass an incorrect metric value (non-number/float)\n metric[\"value\"] = \"some_value\"\n\n # WHEN we attempt to serialize a valid EMF object\n # THEN it should fail validation and raise SchemaValidationError\n with pytest.raises(MetricValueError):\n with single_metric(**metric) as my_metric:\n my_metric.add_dimension(**dimension)\n my_metric.add_namespace(**namespace)\n\n\ndef test_schema_no_metrics(dimensions, namespace):\n # GIVEN Metrics is initialized\n my_metrics = Metrics()\n my_metrics.add_namespace(**namespace)\n\n # WHEN no metrics have been added\n # but a namespace and dimensions only\n for dimension in dimensions:\n my_metrics.add_dimension(**dimension)\n\n # THEN it should fail validation and raise SchemaValidationError\n with pytest.raises(SchemaValidationError):\n my_metrics.serialize_metric_set()\n\n\ndef test_exceed_number_of_dimensions(metric, namespace):\n # GIVEN we we have more dimensions than CloudWatch supports\n dimensions = []\n for i in range(11):\n dimensions.append({\"name\": f\"test_{i}\", \"value\": \"test\"})\n\n # WHEN we attempt to serialize them into a valid EMF object\n # THEN it should fail validation and raise SchemaValidationError\n with pytest.raises(SchemaValidationError):\n with single_metric(**metric) as my_metric:\n my_metric.add_namespace(**namespace)\n for dimension in dimensions:\n my_metric.add_dimension(**dimension)\n\n\ndef test_log_metrics_during_exception(capsys, metric, dimension, namespace):\n # GIVEN Metrics is initialized\n my_metrics = Metrics()\n\n my_metrics.add_metric(**metric)\n my_metrics.add_dimension(**dimension)\n my_metrics.add_namespace(**namespace)\n\n # WHEN log_metrics is used to serialize metrics\n # but an error has been raised during handler execution\n @my_metrics.log_metrics\n def lambda_handler(evt, context):\n raise ValueError(\"Bubble up\")\n\n with pytest.raises(ValueError):\n lambda_handler({}, {})\n\n output = json.loads(capsys.readouterr().out.strip())\n expected = serialize_single_metric(metric=metric, dimension=dimension, namespace=namespace)\n\n remove_timestamp(metrics=[output, expected]) # Timestamp will always be different\n # THEN we should log metrics and propagate the exception up\n assert expected[\"_aws\"] == output[\"_aws\"]\n\n\ndef test_log_no_metrics_error_propagation(capsys, metric, dimension, namespace):\n # GIVEN Metrics is initialized\n my_metrics = Metrics()\n\n @my_metrics.log_metrics(raise_on_empty_metrics=True)\n def lambda_handler(evt, context):\n # WHEN log_metrics is used with raise_on_empty_metrics param and has no metrics\n # and the function decorated also raised an exception\n raise ValueError(\"Bubble up\")\n\n # THEN the raised exception should be\n with pytest.raises(SchemaValidationError):\n lambda_handler({}, {})\n\n\ndef test_all_possible_metric_units(metric, dimension, namespace):\n\n # GIVEN we add a metric for each metric unit supported by CloudWatch\n # where metric unit as MetricUnit key e.g. \"Seconds\", \"BytesPerSecond\"\n for unit in MetricUnit:\n metric[\"unit\"] = unit.name\n # WHEN we iterate over all available metric unit keys from MetricUnit enum\n # THEN we raise no MetricUnitError nor SchemaValidationError\n with single_metric(**metric) as my_metric:\n my_metric.add_dimension(**dimension)\n my_metric.add_namespace(**namespace)\n\n # WHEN we iterate over all available metric unit keys from MetricUnit enum\n all_metric_units = [unit.value for unit in MetricUnit]\n\n # metric unit as MetricUnit value e.g. \"Seconds\", \"Bytes/Second\"\n for unit in all_metric_units:\n metric[\"unit\"] = unit\n # THEN we raise no MetricUnitError nor SchemaValidationError\n with single_metric(**metric) as my_metric:\n my_metric.add_dimension(**dimension)\n my_metric.add_namespace(**namespace)\n\n\ndef test_metrics_reuse_metric_set(metric, dimension, namespace):\n # GIVEN Metrics is initialized\n my_metrics = Metrics()\n my_metrics.add_metric(**metric)\n\n # WHEN Metrics is initialized one more time\n my_metrics_2 = Metrics()\n\n # THEN Both class instances should have the same metric set\n assert my_metrics_2.metric_set == my_metrics.metric_set\n\n\ndef test_log_metrics_clear_metrics_after_invocation(metric, dimension, namespace):\n # GIVEN Metrics is initialized\n my_metrics = Metrics()\n\n my_metrics.add_metric(**metric)\n my_metrics.add_dimension(**dimension)\n my_metrics.add_namespace(**namespace)\n\n # WHEN log_metrics is used to flush metrics from memory\n @my_metrics.log_metrics\n def lambda_handler(evt, context):\n return True\n\n lambda_handler({}, {})\n\n # THEN metric set should be empty after function has been run\n assert my_metrics.metric_set == {}\n\n\ndef test_log_metrics_non_string_dimension_values(capsys, metrics, non_str_dimensions, namespace):\n # GIVEN Metrics is initialized and dimensions with non-string values are added\n my_metrics = Metrics()\n my_metrics.add_namespace(**namespace)\n for metric in metrics:\n my_metrics.add_metric(**metric)\n for dimension in non_str_dimensions:\n my_metrics.add_dimension(**dimension)\n\n # WHEN we utilize log_metrics to serialize\n # and flush all metrics at the end of a function execution\n @my_metrics.log_metrics\n def lambda_handler(evt, ctx):\n return True\n\n lambda_handler({}, {})\n output = json.loads(capsys.readouterr().out.strip())\n\n # THEN we should have no exceptions\n # and dimension values hould be serialized as strings\n for dimension in non_str_dimensions:\n assert isinstance(output[dimension[\"name\"]], str)\n\n\ndef test_add_namespace_warns_for_deprecation(capsys, metrics, dimensions, namespace):\n # GIVEN Metrics is initialized\n my_metrics = Metrics()\n with pytest.deprecated_call():\n my_metrics.add_namespace(**namespace)\n\n\ndef test_log_metrics_with_explicit_namespace(capsys, metrics, dimensions, namespace):\n # GIVEN Metrics is initialized with service specified\n my_metrics = Metrics(service=\"test_service\", namespace=namespace[\"name\"])\n for metric in metrics:\n my_metrics.add_metric(**metric)\n for dimension in dimensions:\n my_metrics.add_dimension(**dimension)\n\n # WHEN we utilize log_metrics to serialize\n # and flush all metrics at the end of a function execution\n @my_metrics.log_metrics\n def lambda_handler(evt, ctx):\n return True\n\n lambda_handler({}, {})\n\n output = json.loads(capsys.readouterr().out.strip())\n\n dimensions.append({\"name\": \"service\", \"value\": \"test_service\"})\n expected = serialize_metrics(metrics=metrics, dimensions=dimensions, namespace=namespace)\n\n remove_timestamp(metrics=[output, expected]) # Timestamp will always be different\n\n # THEN we should have no exceptions and the namespace should be set to the name provided in the\n # service passed to Metrics constructor\n assert expected == output\n\n\ndef test_log_metrics_with_implicit_dimensions(capsys, metrics):\n # GIVEN Metrics is initialized with service specified\n my_metrics = Metrics(service=\"test_service\", namespace=\"test_application\")\n for metric in metrics:\n my_metrics.add_metric(**metric)\n\n # WHEN we utilize log_metrics to serialize and don't explicitly add any dimensions\n @my_metrics.log_metrics\n def lambda_handler(evt, ctx):\n return True\n\n lambda_handler({}, {})\n\n output = json.loads(capsys.readouterr().out.strip())\n\n expected_dimensions = [{\"name\": \"service\", \"value\": \"test_service\"}]\n expected = serialize_metrics(\n metrics=metrics, dimensions=expected_dimensions, namespace={\"name\": \"test_application\"}\n )\n\n remove_timestamp(metrics=[output, expected]) # Timestamp will always be different\n\n # THEN we should have no exceptions and the dimensions should be set to the name provided in the\n # service passed to Metrics constructor\n assert expected == output\n\n\ndef test_log_metrics_with_renamed_service(capsys, metrics, metric):\n # GIVEN Metrics is initialized with service specified\n my_metrics = Metrics(service=\"test_service\", namespace=\"test_application\")\n for metric in metrics:\n my_metrics.add_metric(**metric)\n\n @my_metrics.log_metrics\n def lambda_handler(evt, ctx):\n # WHEN we manually call add_dimension to change the value of the service dimension\n my_metrics.add_dimension(name=\"service\", value=\"another_test_service\")\n my_metrics.add_metric(**metric)\n return True\n\n lambda_handler({}, {})\n\n output = json.loads(capsys.readouterr().out.strip())\n lambda_handler({}, {})\n second_output = json.loads(capsys.readouterr().out.strip())\n\n remove_timestamp(metrics=[output]) # Timestamp will always be different\n\n # THEN we should have no exceptions and the dimensions should be set to the name provided in the\n # add_dimension call\n assert output[\"service\"] == \"another_test_service\"\n assert second_output[\"service\"] == \"another_test_service\"\n\n\ndef test_log_metrics_with_namespace_overridden(capsys, metrics, dimensions):\n # GIVEN Metrics is initialized with namespace specified\n my_metrics = Metrics(namespace=\"test_service\")\n for metric in metrics:\n my_metrics.add_metric(**metric)\n for dimension in dimensions:\n my_metrics.add_dimension(**dimension)\n\n # WHEN we try to call add_namespace\n # THEN we should raise UniqueNamespaceError exception\n @my_metrics.log_metrics\n def lambda_handler(evt, ctx):\n my_metrics.add_namespace(name=\"new_namespace\")\n return True\n\n with pytest.raises(UniqueNamespaceError):\n lambda_handler({}, {})\n\n with pytest.raises(UniqueNamespaceError):\n my_metrics.add_namespace(name=\"another_new_namespace\")\n\n\ndef test_single_metric_with_service(capsys, metric, dimension):\n # GIVEN we pass namespace parameter to single_metric\n\n # WHEN creating a metric\n with single_metric(**metric, namespace=\"test_service\") as my_metrics:\n my_metrics.add_dimension(**dimension)\n\n output = json.loads(capsys.readouterr().out.strip())\n expected = serialize_single_metric(metric=metric, dimension=dimension, namespace={\"name\": \"test_service\"})\n\n remove_timestamp(metrics=[output, expected]) # Timestamp will always be different\n\n # THEN namespace should match value passed as service\n assert expected[\"_aws\"] == output[\"_aws\"]\n\n\ndef test_namespace_var_precedence(monkeypatch, capsys, metric, dimension, namespace):\n # GIVEN we use POWERTOOLS_METRICS_NAMESPACE\n monkeypatch.setenv(\"POWERTOOLS_METRICS_NAMESPACE\", namespace[\"name\"])\n\n # WHEN creating a metric and explicitly set a namespace\n with single_metric(**metric, namespace=namespace[\"name\"]) as my_metrics:\n my_metrics.add_dimension(**dimension)\n monkeypatch.delenv(\"POWERTOOLS_METRICS_NAMESPACE\")\n\n output = json.loads(capsys.readouterr().out.strip())\n expected = serialize_single_metric(metric=metric, dimension=dimension, namespace=namespace)\n\n remove_timestamp(metrics=[output, expected]) # Timestamp will always be different\n\n # THEN namespace should match the explicitly passed variable and not the env var\n assert expected[\"_aws\"] == output[\"_aws\"]\n\n\ndef test_emit_cold_start_metric(capsys, namespace):\n # GIVEN Metrics is initialized\n my_metrics = Metrics()\n my_metrics.add_namespace(**namespace)\n\n # WHEN log_metrics is used with capture_cold_start_metric\n @my_metrics.log_metrics(capture_cold_start_metric=True)\n def lambda_handler(evt, context):\n return True\n\n LambdaContext = namedtuple(\"LambdaContext\", \"function_name\")\n lambda_handler({}, LambdaContext(\"example_fn\"))\n\n output = json.loads(capsys.readouterr().out.strip())\n\n # THEN ColdStart metric and function_name dimension should be logged\n assert output[\"ColdStart\"] == 1\n assert output[\"function_name\"] == \"example_fn\"\n\n\ndef test_emit_cold_start_metric_only_once(capsys, namespace, dimension, metric):\n # GIVEN Metrics is initialized\n my_metrics = Metrics()\n my_metrics.add_namespace(**namespace)\n\n # WHEN log_metrics is used with capture_cold_start_metric\n # and handler is called more than once\n @my_metrics.log_metrics(capture_cold_start_metric=True)\n def lambda_handler(evt, context):\n my_metrics.add_metric(**metric)\n my_metrics.add_dimension(**dimension)\n\n LambdaContext = namedtuple(\"LambdaContext\", \"function_name\")\n lambda_handler({}, LambdaContext(\"example_fn\"))\n capsys.readouterr().out.strip()\n\n # THEN ColdStart metric and function_name dimension should be logged\n # only once\n lambda_handler({}, LambdaContext(\"example_fn\"))\n\n output = json.loads(capsys.readouterr().out.strip())\n\n assert \"ColdStart\" not in output\n\n assert \"function_name\" not in output\n\n\ndef test_log_metrics_decorator_no_metrics(dimensions, namespace):\n # GIVEN Metrics is initialized\n my_metrics = Metrics(namespace=namespace[\"name\"], service=\"test_service\")\n\n # WHEN using the log_metrics decorator and no metrics have been added\n @my_metrics.log_metrics\n def lambda_handler(evt, context):\n pass\n\n # THEN it should raise a warning instead of throwing an exception\n with warnings.catch_warnings(record=True) as w:\n lambda_handler({}, {})\n assert len(w) == 1\n assert str(w[-1].message) == \"No metrics to publish, skipping\"\n\n\ndef test_log_metrics_with_implicit_dimensions_called_twice(capsys, metrics):\n # GIVEN Metrics is initialized with service specified\n my_metrics = Metrics(service=\"test_service\", namespace=\"test_application\")\n\n # WHEN we utilize log_metrics to serialize and don't explicitly add any dimensions,\n # and the lambda function is called more than once\n @my_metrics.log_metrics\n def lambda_handler(evt, ctx):\n for metric in metrics:\n my_metrics.add_metric(**metric)\n return True\n\n lambda_handler({}, {})\n output = json.loads(capsys.readouterr().out.strip())\n\n lambda_handler({}, {})\n second_output = json.loads(capsys.readouterr().out.strip())\n\n expected_dimensions = [{\"name\": \"service\", \"value\": \"test_service\"}]\n expected = serialize_metrics(\n metrics=metrics, dimensions=expected_dimensions, namespace={\"name\": \"test_application\"}\n )\n\n remove_timestamp(metrics=[output, expected, second_output]) # Timestamp will always be different\n\n # THEN we should have no exceptions and the dimensions should be set to the name provided in the\n # service passed to Metrics constructor\n assert output[\"service\"] == \"test_service\"\n assert second_output[\"service\"] == \"test_service\"\n\n for metric_record in output[\"_aws\"][\"CloudWatchMetrics\"]:\n assert [\"service\"] in metric_record[\"Dimensions\"]\n\n for metric_record in second_output[\"_aws\"][\"CloudWatchMetrics\"]:\n assert [\"service\"] in metric_record[\"Dimensions\"]\n","sub_path":"tests/functional/test_metrics.py","file_name":"test_metrics.py","file_ext":"py","file_size_in_byte":24925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"232765594","text":"from SDDS_file import SDDS_file\nimport polynomial_correction\n\nDEBUG = True\n\ndef _read_in_sdds_file(sdds_file_path):\n sdds_file = SDDS_file(sdds_file_path)\n sdds_file.read_in()\n return sdds_file\n\ndef _output_new_data(corrected_bpm_data, sdds_file, new_sdds_file_path):\n '''Old sdds_file is used to get the header and meta information for the new_sdds_file.'''\n new_sdds_file = SDDS_file(new_sdds_file_path)\n new_sdds_file.file_header = sdds_file.file_header\n new_sdds_file.bpm_positions = sdds_file.bpm_positions\n new_sdds_file.bpm_data = corrected_bpm_data\n new_sdds_file.write_out()\n\ndef _test_print(data):\n bpm = 'BPM.33R3.B2'\n start_turn = 100\n if DEBUG:\n for i in range(3):\n print('%s (turn %d): (%.5f, %.5f)' % (bpm, start_turn+i, data['X'][bpm][start_turn+i], data['Y'][bpm][start_turn+i]))\n\ndef _to_bpm_data(data, year):\n for plane in data:\n for bpm in data[plane]:\n for i in range(len(data[plane][bpm])):\n bpm_type = bpm.split('.')[0]\n \n coefficients = polynomial_correction.get_coefficients_of_bpm_type(bpm_type, polynomial_correction.old_coefficients[year])\n\n if coefficients:\n data[plane][bpm][i] = polynomial_correction.revert_correction_polynomial(data[plane][bpm][i], coefficients)\n else:\n print('Warning: No coefficients for bpm type: \"%s\" found! Skipping...' % bpm_type)\n return data\n\ndef from_ideal_to_bpm_data(sdds_file_path, new_sdds_file_path, year=2012):\n '''Year is needed in order to find the right coefficients for the non linear correction.'''\n if DEBUG: print('Reading in: %s' % sdds_file_path)\n sdds_file = _read_in_sdds_file(sdds_file_path)\n data = sdds_file.get_bpm_data()\n \n if DEBUG: print('Got data. Applying reverse correction...')\n _test_print(data)\n\n data = _to_bpm_data(data, year)\n print('Now we have raw BPM data.')\n\n _test_print(data)\n if DEBUG: print('Writing out new data to: %s' % new_sdds_file_path)\n\n _output_new_data(data, sdds_file, new_sdds_file_path)\n print('Done!')\n\nif __name__ == '__main__':\n '''We get model data and transform it into raw bpm data by undoing the correction.'''\n sdds_file_path = '/afs/cern.ch/user/r/rwestenb/workarea/11_12_injectionMD/modelB2inj_correctedoptics/analysis/simulated_data/model.sdds'\n new_sdds_file_path = '/afs/cern.ch/user/r/rwestenb/workarea/11_12_injectionMD/modelB2inj_correctedoptics/analysis/bpm_data/model.bpm_data.sdds'\n\n from_ideal_to_bpm_data(sdds_file_path, new_sdds_file_path, year=2012)","sub_path":"Analyses/BPMnonLinearities/from_ideal_to_bpm_data.py","file_name":"from_ideal_to_bpm_data.py","file_ext":"py","file_size_in_byte":2626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"548626781","text":"import csv\nfrom collections import Counter\n\nDIR = \"../JavaPreprocesamiento/\"\nTEXT = \"market.csv\"\nFINAL = \"market.txt\"\nIRREGULAR = \"IrregularVerbs.csv\"\nCOLS = 10 # Numero de columnas de el archivo de texto\nVOCABULARY = 200 # Numero de palabras a mantener\n\nDEBUG = True\n\n# Simbolos o palabras que no se van a considerar\nSIGNS = [\" œ \",\" £ \",\"\\\"\",\" ‘ \",\" ’ \", \" of \", \" the \",\" an \",\" a \",\",\",\".\",\";\",\":\",\"...\",\"?\",\"!\",\"¡\",\"(\",\")\",\"[\",\"]\",\"—\",\"-\",\"_\",\"/\",\"'\\'\",\"*\",\"$\",\"@\",\"0\",\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"·\",\"#\",\"|\",\"º\",\"ª\",\"~\",\"%\",\"€\",\"&\",\"¬\",\"=\",\"^\",\"+\",\"š\",\"ç\",\"<\",\">\",\"•\",\"”\",\"“\",\"—\", \"“\", \"”\", \"•\"]\nRULES = [ (\"won't\",\"will not\"), (\"shan't\", \"shall not\"), (\"can't\", \"cannot\") # Negaciones problematicas\n ]\n# Tipicas contracciones, no serian ambiguas porque van con un pronombre\n# (la sustitucion es mas compleja en varios casos cuando no van con pronombre)\nPRONOUNS = [\"i\",\"you\",\"he\",\"she\",\"it\",\"we\",\"they\"]\nCONTRACTIONS = [(\"m\",\"am\"),(\"re\",\"are\"),(\"s\",\"is\"),(\"ve\",\"have\"),(\"ll\",\"will\"),(\"d\",\"had\")] # Ultimo caso dudoso 'had' o 'would'\nRULES.extend([(p+\"'\"+c,y) for p in PRONOUNS for (c,y) in CONTRACTIONS])\nif(DEBUG):\n print(RULES)\n print(\"\\n\")\n\n# Comprobar al final de cada palabra\nPOSTFIX = [ (\"n't\",\" not\"), (\"nŽt\", \" not\"), (\"n`t\",\" not\"), # Negaciones generales\n (\"ies\",\"y\"), (\"s\",\"\"), (\"es\",\"\"), (\"zzes\",\"z\"), (\"ves\",\"f\"), # Plural a singular\n ]\n\n\ndef readData(name):\n \"\"\" Lectura de archivo csv \n Devuelve matriz con los datos y cabecera\n \"\"\"\n data = []\n with open(name, 'r') as f:\n reader = csv.reader(f)\n for row in reader:\n data.append(row)\n return data\n\ndef writeData(name, data):\n \"\"\" Escribe en archivo name los\n datos 'data'\"\"\"\n with open(name, 'w') as f:\n f.write(data)\n\ndef preProcess(data,irregular):\n \"\"\" Procesa una cadena de caracteres\n \"\"\"\n data = [x for row in data for x in row]\n data = \" \".join(data[10:])\n data = data.lower() # Trabajar con minusculas\n for (x,y) in RULES: # \n data = data.replace(x,y)\n for sign in SIGNS: # Elimina simbolos\n data = data.replace(sign, \" \")\n for verb in irregular: # Pasar formas verbales irregulares a infinitivo\n for form in verb[1:]:\n if form != \"\":\n data = data.replace(form,verb[0])\n return data\n\ndef tokenize(data):\n sp = [ d for d in data.split(\" \") if d != \"\"] # Tokeniza el texto\n count = [ a for (a,_) in Counter(sp).most_common(VOCABULARY-1) ] # Solo queremos palabras mas comunes\n di = { a : count.index(a) for a in count } # Diccionario con la codificacion\n return \" \".join(sp),[ di[x] for x in sp if x in di], di \n\n \n\n\ndata = readData(DIR+TEXT)\nirregular_verbs = readData(DIR+IRREGULAR)\n\ndata = preProcess(data, irregular_verbs)\ndata,tokens, dic = tokenize(data)\nwriteData(FINAL,data)\n\nprint(dic)\n","sub_path":"src/preprocesado.py","file_name":"preprocesado.py","file_ext":"py","file_size_in_byte":2897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"307450678","text":"from triangles import LoadShaders\n\nfrom OpenGL.GL import *\nfrom OpenGL.GL import shaders\nfrom OpenGL.GLU import *\nfrom OpenGL.GLUT import *\n\nimport numpy as np\nimport math\nimport ctypes\n\nimport sys\n\nvertex_positions = [\n\t[-1, -1, 0, 1],\n\t[1, -1, 0, 1],\n\t[-1, 1, 0, 1],\n\t[-1, -1, 0, 1],\n]\n\nvertex_positions = np.matrix(vertex_positions, dtype=\"f\")\n\nvertex_indices = [\n\t0, 1, 2,\n]\n\nvertex_indices = np.array(vertex_indices, dtype=\"ushort\")\n\nvertex_colors = [\n\t[1, 1, 1, 1],\n\t[1, 1, 0, 1],\n\t[1, 0, 1, 1],\n\t[0, 1, 1, 1],\n]\n\nvertex_colors = np.matrix(vertex_colors, dtype=\"f\")\n\nshaderInfo = [\n\t(GL_VERTEX_SHADER, './shaders/restart.vert'),\n\t(GL_FRAGMENT_SHADER, './shaders/restart.frag'),\n]\n\nvao = None\nebo = None\nvbo = None\n\nrender_prog = None\n\nrender_model_matrix_loc = None\nrender_projection_matrix_loc = None\n\naspect = 0\n\ndef frustum(left, right, bottom, top, n, f):\n\tm = [\n\t\t[(2.0 * n) / (right - left), 0.0, 0.0, 0.0],\n\t\t[0.0, (2.0 * n) / (top - bottom), 0.0, 0.0],\n\t\t[(right + left)/(right - left), (top + bottom)/(top - bottom), -(f+n)/(f-n), -1.0],\n\t\t[0.0, 0.0, -(2.0 * f * n)/(f-n), 0.0],\n\t]\n\tm = np.matrix(m, dtype=\"f\")\n\treturn m\n\t\n\ndef translation(vector):\n\tm = [\n\t\t[1, 0, 0, 0],\n\t\t[0, 1, 0, 0],\n\t\t[0, 0, 1, 0],\n\t\t[vector[0], vector[1], vector[2], 1],\n\t]\n\t\n\tm = np.matrix(m, dtype=\"f\")\n\treturn m\n\n\ndef init():\n\tglobal render_prog\n\n\tglobal vao\n\tglobal ebo\n\tglobal vbo\n\n\tglobal render_model_matrix_loc\n\tglobal render_projection_matrix_loc\n\n\trender_prog = LoadShaders(shaderInfo)\n\tglUseProgram(render_prog)\n\n\trender_model_matrix_loc = glGetUniformLocation(render_prog, \"model_matrix\")\n\trender_projection_matrix_loc = glGetUniformLocation(render_prog, \"projection_matrix\")\n\n\tvao = glGenVertexArrays(1)\n\tglBindVertexArray(vao)\n\n\tebo = glGenBuffers(1)\n\tglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo)\n\tglBufferData(GL_ELEMENT_ARRAY_BUFFER, vertex_indices, GL_STATIC_DRAW)\n\n\tvbo = glGenBuffers(1)\n\tglBindBuffer(GL_ARRAY_BUFFER, vbo)\n\n\tglBufferData(GL_ARRAY_BUFFER, vertex_positions.nbytes + vertex_colors.nbytes, None, GL_STATIC_DRAW)\n\tglBufferSubData(GL_ARRAY_BUFFER, 0, vertex_positions.nbytes, vertex_positions)\n\tglBufferSubData(GL_ARRAY_BUFFER, vertex_positions.nbytes, vertex_colors.nbytes, vertex_colors)\n\n\tglEnableVertexAttribArray(0)\n\tglEnableVertexAttribArray(1)\n\tglVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, None)\n\tglVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 0, ctypes.c_void_p(vertex_positions.nbytes))\n\n\ndef display():\n\tglobal vao\n\tglobal render_prog\n\t\n\tglClearColor(0, 0, 0, 1)\n\tglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)\n\n\tprojection_matrix = frustum(-1.0, 1.0, -aspect, aspect, 1.0, 500.0)\n\n\tglUniformMatrix4fv(render_projection_matrix_loc, 1, GL_FALSE, projection_matrix)\n\n\tglBindVertexArray(vao)\n\t\n\tglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo)\n\tglEnableVertexAttribArray(0)\n\n\t# DrawArrays\n\tmodel_matrix = translation(np.array([-3.0, 0.0, -5.0], dtype=\"f\"));\n\tglUniformMatrix4fv(render_model_matrix_loc, 1, GL_FALSE, model_matrix);\n\tglDrawArrays(GL_TRIANGLES, 0, 3);\n\t\n\t# DrawElements\n\tmodel_matrix = translation(np.array([-1.0, 0.0, -5.0], dtype=\"f\"));\n\tglUniformMatrix4fv(render_model_matrix_loc, 1, GL_FALSE, model_matrix);\n\tglDrawElements(GL_TRIANGLES, 3, GL_UNSIGNED_SHORT, None);\n\t\n\t# DrawElementsBaseVertex\n\tmodel_matrix = translation(np.array([1.0, 0.0, -5.0], dtype=\"f\"));\n\tglUniformMatrix4fv(render_model_matrix_loc, 1, GL_FALSE, model_matrix);\n\tglDrawElementsBaseVertex(GL_TRIANGLES, 3, GL_UNSIGNED_SHORT, None, 1);\n\n\tmodel_matrix = translation(np.array([3.0, 0.0, -5.0], dtype=\"f\"));\n\tglUniformMatrix4fv(render_model_matrix_loc, 1, GL_FALSE, model_matrix);\n\tglDrawArraysInstanced(GL_TRIANGLES, 0, 3, 1);\t\n\n\tglutSwapBuffers()\n\ndef reshape(w, h):\n\tglobal aspect \n\taspect= float(h)/float(w)\n\tglViewport(0, 0, w, h)\n\n\nif __name__ == '__main__':\n\n\tglutInit(sys.argv)\n\tglutInitDisplayMode(GLUT_RGB)\n\tglutInitWindowSize(512, 512)\n\tglutInitContextVersion(3, 3)\n\tglutInitContextProfile(GLUT_CORE_PROFILE)\n\tglutCreateWindow(sys.argv[0])\n\n\tinit()\n\t\n\tglutDisplayFunc(display)\n\tglutReshapeFunc(reshape)\n\tglutMainLoop()\n","sub_path":"computer_graphics_with_opengl/python/drawingTypes.py","file_name":"drawingTypes.py","file_ext":"py","file_size_in_byte":4045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"395171520","text":"\nclass QuickSort:\n def __init__(self):\n self.array = [34, 21, 90, 1, 5, 19, 30, 45]\n\n def quick_sort(self, low, high):\n if low < high:\n i = self.do_partition(low, high)\n self.quick_sort(low, i)\n self.quick_sort(i + 1, high)\n\n def do_partition(self, low, high):\n i = low - 1\n pivot = self.array[high - 1]\n for j in range(low, high):\n if self.array[j] <= pivot:\n i = i + 1\n self.array[i], self.array[j] = self.array[j], self.array[i]\n return i\n\n\nif __name__ == '__main__':\n q = QuickSort()\n low = 0\n high = len(q.array)\n q.quick_sort(low, high)\n print (q.array)","sub_path":"QuickSort.py","file_name":"QuickSort.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"68912014","text":"\n#from src.models.data_utils import *\nfrom src.models.model_utils import *\nfrom src.models.train_model import *\nfrom src.models.perf_utils import *\nimport math\nimport numpy as np\nfrom matplotlib import pyplot as plt\nplt.switch_backend('agg')\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\nimport tensorflow as tf\nv0 = tf.__version__[0]\nif v0 == '2':\n # For tensorflow 2, keras is included in tf\n from tensorflow.keras.models import *\nelif v0 == '1':\n #For tensorflow 1.2.0\n from keras.models import *\nnp.random.seed(17)\nfrom matplotlib import pyplot as plt\nimport numpy as np\nimport pickle\n\nplt.switch_backend('TKAgg')\n\nlisteOutputs = ['fls','DS','PT','FBUOY']\ncolors = ['navy', 'darkred', 'black', 'darkgreen']\nlinestyles = ['-', '--', '-.', ':']\noutputsLatex = {'fls':'\\\\acrshort{fls}', 'DS':'\\\\acrshort{ds}', 'PT':'\\\\acrshort{pts}', 'FBUOY':'\\\\acrshort{fbuoy}'}\nlisteFeatures = ['3Dfeatures_HS_noOP','2Dfeatures','3Dfeatures_HS','2Dfeatures']\nnOuts = 4\n\nidxTest = np.load('reports/corpora/DictaSign/recognitionUnique/predictions/recognitionUniqueDictaSign_DS_159336941.npz')['idxTest']\nidxTestClasse = np.sort(idxTest)\nprint(idxTestClasse)\nnbVid = idxTestClasse.size\n\nnbFrames = np.zeros(nbVid)\nannotation_raw = np.load('data/processed/DictaSign/annotations.npz', encoding='latin1', allow_pickle=True)['dataBrut_DS']\n\nidxDebFin = {'debut': np.zeros(nbVid), 'fin':np.zeros(nbVid)}\n\nnamesTest = []\nnamesAll = np.load('data/processed/DictaSign/list_videos.npy')\nfor i in range(nbVid):\n namesTest.append(namesAll[idxTestClasse[i]])\n nbFrames[i] = annotation_raw[idxTestClasse[i]].shape[0]\nprint(namesTest)\n\nresults_videos = {}\nfor i in range(nbVid):\n results_videos[namesTest[i]] = {}\n for iOut in range(nOuts):\n out = listeOutputs[iOut]\n results_videos[namesTest[i]][out] = {}\n results_videos[namesTest[i]][out]['true'] = np.zeros(int(nbFrames[i]))\n results_videos[namesTest[i]][out]['pred'] = np.zeros(int(nbFrames[i]))\n\n\n\nsavePredictions='reports/corpora/DictaSign/recognitionUnique/predictions/'\nsaveGlobalResults='reports/corpora/DictaSign/recognitionUnique/global/globalUnique.dat'\ndataGlobal=pickle.load(open(saveGlobalResults,'rb'))\n\nfor iOut in range(nOuts):\n out = listeOutputs[iOut]\n print(out)\n dataGlobal[out].keys()\n for k in dataGlobal[out].keys():\n if dataGlobal[out][k]['comment'] == 'plot thesis v2':\n if dataGlobal[out][k]['params']['inputType'] == listeFeatures[iOut]:\n print(k)\n print(dataGlobal[out][k]['params']['inputType'])\n K = k\n saveBestName='recognitionUniqueDictaSign_'+out+'_'+str(K)\n\n predict = np.load(savePredictions+saveBestName+'.npz')\n true=predict['true']\n pred=predict['pred']\n idxTest=predict['idxTest']\n\n T = true.shape[0]\n\n idxDebFin = {'debut': np.zeros(nbVid), 'fin':np.zeros(nbVid)}\n\n idxDebTmp = 0\n for i in range(nbVid):\n nbFramesVid = annotation_raw[idxTest[i]].shape[0]\n finTmp = np.min([T, idxDebTmp+nbFramesVid])\n results_videos[namesAll[idxTest[i]]][out]['true'][0:finTmp-idxDebTmp] = true[idxDebTmp:finTmp,1]\n results_videos[namesAll[idxTest[i]]][out]['pred'][0:finTmp-idxDebTmp] = pred[idxDebTmp:finTmp,1]\n idxDebTmp += nbFramesVid\n\n\n #plt.figure()\n #plt.plot(np.arange(T), true[:,1])\n #plt.plot(np.arange(T), pred[:,1])\n #plt.show()\n\n\nimport tikzplotlib\nfrom os.path import expanduser\nhome = expanduser(\"~\")\nplotList = range(nbVid)#[8]\nfor j in plotList:\n for iOut in range(nOuts):\n out = listeOutputs[iOut]\n plt.figure()\n plt.title(namesAll[idxTestClasse[j]])\n plt.yticks([0,0.5,1])\n plt.xlabel(\"$t$\")\n plt.plot(results_videos[namesAll[idxTestClasse[j]]][out]['true'], color=colors[iOut])\n tikzplotlib.save(home+'/thesis/testSequences/'+namesAll[idxTestClasse[j]]+'_'+out+'_true.tex')\n plt.close()\n plt.figure()\n plt.title(namesAll[idxTestClasse[j]])\n plt.yticks([0,0.5,1])\n plt.xlabel(\"$t$\")\n plt.plot(results_videos[namesAll[idxTestClasse[j]]][out]['pred'], color=colors[iOut], linestyle=linestyles[iOut])\n tikzplotlib.save(home+'/thesis/testSequences/'+namesAll[idxTestClasse[j]]+'_'+out+'_pred_v2.tex')\n plt.close()\n \n \n\n\nfor j in plotList:\n plt.figure()\n plt.title(namesAll[idxTestClasse[j]])\n for iOut in range(nOuts):\n out = listeOutputs[iOut]\n plt.plot(results_videos[namesAll[idxTestClasse[j]]][out]['true'], color=colors[iOut])\n plt.plot(results_videos[namesAll[idxTestClasse[j]]][out]['pred'], color=colors[iOut], linestyle=linestyles[iOut])\n plt.yticks([0,0.5,1])\n plt.xlabel(\"$t$\")\n #tikzplotlib.save(home+'/thesis/testSequences/'+namesAll[idxTestClasse[j]]+'_v2.tex')\n plt.show()\n\noutType='PT'\nidxClasse = 0\nplt.figure()\nt = np.arange(7340, 7375)\nplt.plot(t, results_videos[namesAll[idxTestClasse[idxClasse]]][outType]['true'][t], label='Annotation')\nplt.plot(t, results_videos[namesAll[idxTestClasse[idxClasse]]][outType]['pred'][t], '--', label='Prediction')\nplt.xlim((t[0],t[-1]+1))\nplt.ylim((0,1))\nplt.yticks([0,0.5,1])\nplt.xlabel(\"$t$\")\nplt.legend()\n#plt.title(outputsLatex[outType]+' '+namesTest[idxClasse]+' '+str(t[0])+'-'+str(t[-1]+1))\n\n#\n#tikzplotlib.save(home+'/thesis/testSequences/'+outType+'_'+namesTest[idxClasse]+'_'+str(t[0])+'_'+str(t[-1]+1)+'.tex')\n#a = tikzplotlib.get_tikz_code()\n#print(a)\nplt.show()\n\n\n#model=get_model(['fls'],[2],[1],dropout=0.5,rnn_number=1,rnn_hidden_units=50,mlp_layers_number=0,conv=True,conv_filt=200,conv_ker=3,time_steps=100,learning_rate=0.001,metrics=['acc', f1K, precisionK, recallK],features_number=298)\n\n#smodel.load_weights('models/'+saveBestName+'-best.hdf5')\n","sub_path":"archive/print_results_thesis_DictaSign_v2.py","file_name":"print_results_thesis_DictaSign_v2.py","file_ext":"py","file_size_in_byte":5965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"480469680","text":"# -*- coding: utf-8 -*\nimport pandas as pd\nimport io\nimport requests\nimport matplotlib as mpl # 设置环境变量\nimport matplotlib.pyplot as plt # 绘图专用\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn import metrics\nimport numpy as np\nfrom sklearn.linear_model import LogisticRegression\nimport sys\n# reload(sys)\n# sys.setdefaultencoding('utf8')\nmpl.rcParams['font.sans-serif'] = ['FangSong']\nmpl.rcParams['axes.unicode_minus']=False\n\ndef iris_type(s):\n it = {'Iris-setosa':0,'Iris-versicolor':1,'Iris-virginica':2}\n return it[s]\n\nurl=\"http://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data\"\ndata = pd.read_table(io.StringIO(requests.get(url).content.decode('utf-8')), sep=\" \", delimiter=',', dtype=float, converters={4:iris_type}, header=None,names=['a','b','c','d','e']).values\n# print data\n# print type(data)\n\nx,y = np.split(data,(4,),axis=1)\nx=x[:,:2]\n# print x\n\nlogreg = LogisticRegression()\nlogreg.fit(x,y.ravel())\n\nN, M = 500, 500\nx1_min, x1_max = x[:,0].min(),x[:,0].max()\nx2_min, x2_max = x[:,1].min(),x[:,1].max()\nt1 = np.linspace(x1_min,x1_max,N)\nt2 = np.linspace(x2_min,x2_max,M)\n\nx1,x2 = np.meshgrid(t1, t2)\nx_test = np.stack((x1.flat,x2.flat), axis=1)\n\ny_hat = logreg.predict(x_test)\ny_hat = y_hat.reshape(x1.shape)\nplt.pcolormesh(x1,x2,y_hat,cmap=plt.cm.prism)\nplt.scatter(x[:,0],x[:,1], c=y, edgecolors='k',cmap=plt.cm.prism)\nplt.xlabel('Sepal Length')\nplt.ylabel('Sepal Width')\nplt.xlim(x1_min, x1_max)\nplt.ylim(x2_min, x2_max)\nplt.grid()\nplt.show()\n\ny_hat = logreg.predict(x)\ny = y.reshape(-1)\n\n# print y_hat.shape\n# print y.shape\n# result = y_hat == y\n# print y_hat\n# print y\n# print result\n# c=np.count_nonzero(result)\n# print c\n# print 'Accuracy: %.2f%%' % (100*float(c)/float(len(result)))\n","sub_path":"ML/1.Regression/LogisticRegression/LGR1.1.py","file_name":"LGR1.1.py","file_ext":"py","file_size_in_byte":1812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"618678388","text":"\"\"\"\n Funções utilizadas para a codificação do aritmético\n e a sua decodificação\n\"\"\"\n\n\"\"\"\n Função codificaAritmetico, recebe os valores de um novo\n intervalo, um somátorio de casos ocorridos e o intervalo \n anterior. Para poder então retornar o novo intervalo codificado\n\"\"\"\ndef codificaAritmetico(low, high, total, lowAnterior, highAnterior):\n lowAux = low/total # Divide o valor do low, para encontrar intervalos entre 0 e 1\n highAux = high/total # Divide o valor do high, para encontrar intervalos entre 0 e 1\n\n raio = highAnterior - lowAnterior # Armazena o tamanho do intervalo\n lw = lowAnterior + raio * lowAux # Calcula o novo low\n hi = lowAnterior + raio * highAux # Calcula o novo high\n\n lowAnterior = lw # Passa o novo valor para o low Anterior\n highAnterior = hi # Passa o novo valor para o high Anterior\n\n return lowAnterior, highAnterior # Retorna o novo intervalo\n\n\n\"\"\"\n Função decodificaAritmetico, descodifica um intervalo em um valor númerico\n permitindo assim que o caractere correspondente seja encontrado\n Esta função recebe um low, high e um valor\n\"\"\"\ndef decodificaAritmetico(low, high, valor):\n raio = high - low # Calcula a diferênça do intervalo\n\n v = (valor - low) / raio # v recebe o valor númerico da posição do caractere\n\n return v # Retorna este valor","sub_path":"PPM/Aritimetico.py","file_name":"Aritimetico.py","file_ext":"py","file_size_in_byte":1358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"595244552","text":"import numpy as np\nimport numba\nimport warnings\nimport scipy.ndimage as scnd\nimport scipy.optimize as sio\nimport scipy.signal as scisig\nimport skimage.feature as skfeat\nimport matplotlib.colors as mplc\nimport matplotlib.pyplot as plt\nimport stemtool as st\nimport warnings\n\n\ndef angle_fun(\n angle, image_orig, axis=0,\n):\n \"\"\"\n Rotation Sum Finder\n \n Parameters\n ----------\n angle: float \n Angle to rotate \n image_orig: (2,2) shape ndarray\n Input Image\n axis: int, optional\n Axis along which to perform sum\n \n Returns\n -------\n rotmin: float\n Sum of the rotated image multiplied by -1 along \n the axis specified\n\n Notes\n -----\n This is an internal minimization function for finding the \n minimum sum of the image at a particular rotation angle.\n\n See Also\n --------\n rotation_finder \n \"\"\"\n rotated_image = scnd.rotate(image_orig, angle, order=5, reshape=False)\n rotsum = (-1) * (np.sum(rotated_image, 1))\n rotmin = np.amin(rotsum)\n return rotmin\n\n\ndef rotation_finder(image_orig, axis=0):\n \"\"\"\n Angle Finder\n \n Parameters\n ----------\n image_orig: (2,2) shape ndarray\n Input Image\n axis: int, optional\n Axis along which to perform sum\n \n Returns\n -------\n min_x: float\n Angle by which if the image is rotated\n by, the sum of the image along the axis\n specified is maximum\n \n Notes\n -----\n Uses the `angle_fun` function as the minimizer.\n\n See Also\n --------\n angle_fun\n \"\"\"\n x0 = 90\n x = sio.minimize(angle_fun, x0, args=(image_orig))\n min_x = x.x\n return min_x\n\n\ndef rotate_and_center_ROI(data4D_ROI, rotangle, xcenter, ycenter):\n \"\"\"\n Rotation Corrector\n \n Parameters\n ----------\n data4D_ROI: ndarray \n Region of interest of the 4D-STEM dataset in\n the form of ROI pixels (scanning), CBED_Y, CBED_x\n rotangle: float\n angle in counter-clockwise direction to \n rotate individual CBED patterns\n xcenter: float\n X pixel co-ordinate of center of mean pattern\n ycenter: float\n Y pixel co-ordinate of center of mean pattern\n \n Returns\n -------\n corrected_ROI: ndarray\n Each CBED pattern from the region of interest\n first centered and then rotated along the center\n \n Notes\n -----\n We start by centering each 4D-STEM CBED pattern \n and then rotating the patterns with respect to the\n pattern center\n \"\"\"\n data_size = np.asarray(np.shape(data4D_ROI))\n corrected_ROI = np.zeros_like(data4D_ROI)\n for ii in range(data4D_ROI.shape[0]):\n cbed_pattern = data4D_ROI[ii, :, :]\n moved_cbed = np.abs(\n st.util.move_by_phase(\n cbed_pattern,\n (-xcenter + (0.5 * data_size[-1])),\n (-ycenter + (0.5 * data_size[-2])),\n )\n )\n rotated_cbed = scnd.rotate(moved_cbed, rotangle, order=5, reshape=False)\n corrected_ROI[ii, :, :] = rotated_cbed\n return corrected_ROI\n\n\ndef data4Dto2D(data4D):\n \"\"\"\n Convert 4D data to 2D data\n \n Parameters\n ----------\n data4D: ndarray of shape (4,4)\n the first two dimensions are Fourier\n space, while the next two dimensions\n are real space\n \n Returns\n -------\n data2D: ndarray of shape (2,2)\n Raveled 2D data where the\n first two dimensions are positions\n while the next two dimensions are spectra\n \"\"\"\n data2D = np.transpose(data4D, (2, 3, 0, 1))\n data_shape = data2D.shape\n data2D.shape = (data_shape[0] * data_shape[1], data_shape[2] * data_shape[3])\n return data2D\n\n\n@numba.jit(parallel=True, cache=True)\ndef resizer1D_numbaopt(data, res, N):\n M = data.size\n carry = 0\n m = 0\n for n in range(int(N)):\n data_sum = carry\n while ((m * N) - (n * M)) < M:\n data_sum += data[m]\n m += 1\n carry = (m - (n + 1) * (M / N)) * data[m - 1]\n data_sum -= carry\n res[n] = data_sum * (N / M)\n return res\n\n\n@numba.jit(parallel=True, cache=True)\ndef resizer2D_numbaopt(data2D, resampled_x, resampled_f, sampling):\n data_shape = np.asarray(data2D.shape)\n sampled_shape = (np.round(data_shape / sampling)).astype(int)\n for yy in numba.prange(data_shape[0]):\n resampled_x[yy, :] = resizer1D_numbaopt(\n data2D[yy, :], resampled_x[yy, :], sampled_shape[1]\n )\n for xx in numba.prange(sampled_shape[1]):\n resampled_f[:, xx] = resizer1D_numbaopt(\n resampled_x[:, xx], resampled_f[:, xx], sampled_shape[0]\n )\n return resampled_f\n\n\n@numba.jit\ndef bin4D(data4D, bin_factor):\n \"\"\"\n Bin 4D data in spectral dimensions\n \n Parameters\n ----------\n data4D: ndarray of shape (4,4)\n the first two dimensions are Fourier\n space, while the next two dimensions\n are real space\n bin_factor: int\n Value by which to bin data\n \n Returns\n -------\n binned_data: ndarray of shape (4,4)\n Data binned in the spectral dimensions\n \n Notes\n -----\n The data is binned in the first two dimensions - which are\n the Fourier dimensions using the internal numba functions \n `resizer2D_numbaopt` and `resizer1D_numbaopt`\n\n See Also\n --------\n resizer1D_numbaopt\n resizer2D_numbaopt\n \"\"\"\n data4D_flat = np.reshape(\n data4D, (data4D.shape[0], data4D.shape[1], data4D.shape[2] * data4D.shape[3])\n )\n datashape = np.asarray(data4D_flat.shape)\n res_shape = np.copy(datashape)\n res_shape[0:2] = np.round(datashape[0:2] / bin_factor)\n data4D_res = np.zeros(res_shape.astype(int), dtype=data4D_flat.dtype)\n resampled_x = np.zeros((datashape[0], res_shape[1]), data4D_flat.dtype)\n resampled_f = np.zeros(res_shape[0:2], dtype=data4D_flat.dtype)\n for zz in range(data4D_flat.shape[-1]):\n data4D_res[:, :, zz] = resizer2D_numbaopt(\n data4D_flat[:, :, zz], resampled_x, resampled_f, bin_factor\n )\n binned_data = np.reshape(\n data4D_res,\n (resampled_f.shape[0], resampled_f.shape[1], data4D.shape[2], data4D.shape[3]),\n )\n return binned_data\n\n\ndef test_aperture(pattern, center, radius, showfig=True):\n \"\"\"\n Test an aperture position for Virtual DF image\n \n Parameters\n ----------\n pattern: ndarray of shape (2,2)\n Diffraction pattern, preferably the\n mean diffraction pattern for testing out\n the aperture location\n center: ndarray of shape (1,2)\n Center of the circular aperture\n radius: float\n Radius of the circular aperture\n showfig: bool, optional\n If showfig is True, then the image is\n displayed with the aperture overlaid\n \n Returns\n -------\n aperture: ndarray of shape (2,2)\n A matrix of the same size of the input image\n with zeros everywhere and ones where the aperture\n is supposed to be\n \n Notes\n -----\n Use the showfig option to visually test out the aperture \n location with varying parameters\n \"\"\"\n center = np.asarray(center)\n yy, xx = np.mgrid[0 : pattern.shape[0], 0 : pattern.shape[1]]\n yy = yy - center[1]\n xx = xx - center[0]\n rr = ((yy ** 2) + (xx ** 2)) ** 0.5\n aperture = np.asarray(rr <= radius, dtype=np.double)\n if showfig:\n plt.figure(figsize=(15, 15))\n plt.imshow(st.util.image_normalizer(pattern) + aperture, cmap=\"Spectral\")\n plt.scatter(center[0], center[1], c=\"w\", s=25)\n return aperture\n\n\ndef aperture_image(data4D, center, radius):\n \"\"\"\n Generate Virtual DF image for a given aperture\n \n Parameters\n ----------\n data4D: ndarray of shape (4,4)\n the first two dimensions are Fourier\n space, while the next two dimensions\n are real space\n center: ndarray of shape (1,2)\n Center of the circular aperture\n radius: float\n Radius of the circular aperture\n \n Returns\n -------\n df_image: ndarray of shape (2,2)\n Generated virtual dark field image\n from the aperture and 4D data\n \n Notes\n -----\n We generate the aperture first, and then make copies\n of the aperture to generate a 4D dataset of the same \n size as the 4D data. Then we do an element wise \n multiplication of this aperture 4D data with the 4D data\n and then sum it along the two Fourier directions.\n \"\"\"\n center = np.array(center)\n yy, xx = np.mgrid[0 : data4D.shape[0], 0 : data4D.shape[1]]\n yy = yy - center[1]\n xx = xx - center[0]\n rr = ((yy ** 2) + (xx ** 2)) ** 0.5\n aperture = np.asarray(rr <= radius, dtype=data4D.dtype)\n apt_copy = np.empty(\n (data4D.shape[2], data4D.shape[3]) + aperture.shape, dtype=data4D.dtype\n )\n apt_copy[:] = aperture\n apt_copy = np.transpose(apt_copy, (2, 3, 0, 1))\n apt_mult = apt_copy * data4D\n df_image = np.sum(np.sum(apt_mult, axis=0), axis=0)\n return df_image\n\n\ndef custom_detector(data4D, det_inner, det_outer, det_center=(0, 0), mrad_calib=0):\n \"\"\"\n Generate an image with a custom annular detector \n located anywhere in diffraction space\n \n Parameters\n ----------\n data4D: ndarray of shape (4,4)\n the first two dimensions are Fourier\n space, while the next two dimensions\n are real space\n center: ndarray of shape (1,2)\n Center of the circular aperture\n radius: float\n Radius of the circular aperture\n \n Returns\n -------\n df_image: ndarray of shape (2,2)\n Generated virtual dark field image\n from the aperture and 4D data\n \n Notes\n -----\n We generate the aperture first, and then make copies\n of the aperture to generate a 4D dataset of the same \n size as the 4D data. Then we do an element wise \n multiplication of this aperture 4D data with the 4D data\n and then sum it along the two Fourier directions.\n \"\"\"\n if mrad_calib > 0:\n det_inner = det_inner * mrad_calib\n det_outer = det_outer * mrad_calib\n det_center = np.asarray(det_center) * mrad_calib\n det_center = np.asarray(det_center)\n yy, xx = np.mgrid[0 : data4D.shape[0], 0 : data4D.shape[1]]\n yy -= 0.5 * data4D.shape[0]\n xx -= 0.5 * data4D.shape[1]\n yy = yy - det_center[1]\n xx = xx - det_center[0]\n rr = (yy ** 2) + (xx ** 2)\n aperture = np.logical_and((rr <= det_outer), (rr >= det_inner))\n apt_copy = np.empty(\n (data4D.shape[2], data4D.shape[3]) + aperture.shape, dtype=data4D.dtype\n )\n apt_copy[:] = aperture\n apt_copy = np.transpose(apt_copy, (2, 3, 0, 1))\n apt_mult = apt_copy * data4D\n df_image = np.sum(np.sum(apt_mult, axis=0), axis=0)\n return df_image\n\n\ndef ROI_from_image(image, med_val, style=\"over\", showfig=True):\n if style == \"over\":\n ROI = np.asarray(image > (med_val * np.median(image)), dtype=np.double)\n else:\n ROI = np.asarray(image < (med_val * np.median(image)), dtype=np.double)\n if showfig:\n plt.figure(figsize=(15, 15))\n plt.imshow(ROI + st.util.image_normalizer(image), cmap=\"viridis\")\n plt.title(\"ROI overlaid\")\n ROI = ROI.astype(bool)\n return ROI\n\n\n@numba.jit\ndef colored_mcr(conc_data, data_shape):\n no_spectra = np.shape(conc_data)[1]\n color_hues = np.arange(no_spectra, dtype=np.float64) / no_spectra\n norm_conc = (conc_data - np.amin(conc_data)) / (\n np.amax(conc_data) - np.amin(conc_data)\n )\n saturation_matrix = np.ones(data_shape, dtype=np.float64)\n hsv_calc = np.zeros((data_shape[0], data_shape[1], 3), dtype=np.float64)\n rgb_calc = np.zeros((data_shape[0], data_shape[1], 3), dtype=np.float64)\n hsv_calc[:, :, 1] = saturation_matrix\n for ii in range(no_spectra):\n conc_image = (np.reshape(norm_conc[:, ii], data_shape)).astype(np.float64)\n hsv_calc[:, :, 0] = saturation_matrix * color_hues[ii]\n hsv_calc[:, :, 2] = conc_image\n rgb_calc = rgb_calc + mplc.hsv_to_rgb(hsv_calc)\n rgb_image = rgb_calc / np.amax(rgb_calc)\n return rgb_image\n\n\n@numba.jit\ndef fit_nbed_disks(corr_image, disk_size, positions, diff_spots, nan_cutoff=0):\n \"\"\"\n Disk Fitting algorithm for a single NBED pattern\n \n Parameters\n ----------\n corr_image: ndarray of shape (2,2)\n The cross-correlated image of the NBED that \n will be fitted\n disk_size: float\n Size of each NBED disks in pixels\n positions: ndarray of shape (n,2)\n X and Y positions where n is the number of positions.\n These are the initial guesses that will be refined\n diff_spots: ndarray of shape (n,2)\n a and b Miller indices corresponding to the\n disk positions\n nan_cutoff: float, optional\n Optional parameter that is used for thresholding disk\n fits. If the intensity ratio is below the threshold \n the position will not be fit. Default value is 0\n \n Returns\n -------\n fitted_disk_list: ndarray of shape (n,2)\n Sub-pixel precision Gaussian fitted disk\n locations. If nan_cutoff is greater than zero, then\n only the positions that are greater than the threshold \n are returned.\n center_position: ndarray of shape (1,2)\n Location of the central (0,0) disk\n fit_deviation: ndarray of shape (1,2)\n Standard deviation of the X and Y disk fits given as pixel \n ratios\n lcbed: ndarray of shape (2,2)\n Matrix defining the Miller indices axes\n \n Notes\n -----\n Every disk position is fitted with a 2D Gaussian by cutting off a circle\n of the size of disk_size around the initial poistions. If nan-cutoff is above \n zero then only the locations inside this cutoff where the maximum pixel intensity \n is (1+nan_cutoff) times the median pixel intensity will be fitted. Use this \n parameter carefully, because in some cases this may result in no disks being fitted\n and the program throwing weird errors at you. \n \"\"\"\n warnings.filterwarnings(\"ignore\")\n no_pos = int(np.shape(positions)[0])\n diff_spots = np.asarray(diff_spots, dtype=np.float64)\n fitted_disk_list = np.zeros_like(positions)\n yy, xx = np.mgrid[0 : (corr_image.shape[0]), 0 : (corr_image.shape[1])]\n for ii in range(no_pos):\n posx = positions[ii, 0]\n posy = positions[ii, 1]\n reg = ((yy - posy) ** 2) + ((xx - posx) ** 2) <= (disk_size ** 2)\n peak_ratio = np.amax(corr_image[reg]) / np.median(corr_image[reg])\n if peak_ratio < (1 + nan_cutoff):\n fitted_disk_list[ii, 0:2] = np.nan\n else:\n par = st.util.fit_gaussian2D_mask(corr_image, posx, posy, disk_size)\n fitted_disk_list[ii, 0:2] = par[0:2]\n nancount = np.int(np.sum(np.isnan(fitted_disk_list)) / 2)\n if nancount == no_pos:\n center_position = np.nan * np.ones((1, 2))\n fit_deviation = np.nan\n lcbed = np.nan\n else:\n diff_spots = (diff_spots[~np.isnan(fitted_disk_list)]).reshape(\n (no_pos - nancount), 2\n )\n fitted_disk_list = (fitted_disk_list[~np.isnan(fitted_disk_list)]).reshape(\n (no_pos - nancount), 2\n )\n disk_locations = np.copy(fitted_disk_list)\n disk_locations[:, 1] = (-1) * disk_locations[:, 1]\n center = disk_locations[\n np.logical_and((diff_spots[:, 0] == 0), (diff_spots[:, 1] == 0)), :\n ]\n if center.shape[0] > 0:\n cx = center[0, 0]\n cy = center[0, 1]\n center_position = np.asarray((cx, -cy), dtype=np.float64)\n if (nancount / no_pos) < 0.5:\n disk_locations[:, 0:2] = disk_locations[:, 0:2] - np.asarray(\n (cx, cy), dtype=np.float64\n )\n lcbed, _, _, _ = np.linalg.lstsq(diff_spots, disk_locations, rcond=None)\n calc_points = np.matmul(diff_spots, lcbed)\n stdx = np.std(\n np.divide(\n disk_locations[np.where(calc_points[:, 0] != 0), 0],\n calc_points[np.where(calc_points[:, 0] != 0), 0],\n )\n )\n stdy = np.std(\n np.divide(\n disk_locations[np.where(calc_points[:, 1] != 0), 1],\n calc_points[np.where(calc_points[:, 1] != 0), 1],\n )\n )\n fit_deviation = np.asarray((stdx, stdy), dtype=np.float64)\n else:\n fit_deviation = np.nan\n lcbed = np.nan\n else:\n center_position = np.nan\n fit_deviation = np.nan\n lcbed = np.nan\n return fitted_disk_list, center_position, fit_deviation, lcbed\n\n\n@numba.jit\ndef strain_in_ROI(\n data4D,\n ROI,\n center_disk,\n disk_list,\n pos_list,\n reference_axes=0,\n med_factor=10,\n gauss_val=3,\n hybrid_cc=0.1,\n nan_cutoff=0.5,\n):\n \"\"\"\n Get strain from a region of interest\n \n Parameters\n ----------\n data4D: ndarray\n This is a 4D dataset where the first two dimensions\n are the diffraction dimensions and the next two \n dimensions are the scan dimensions\n ROI: ndarray of dtype bool\n Region of interest\n center_disk: ndarray\n The blank diffraction disk template where\n it is 1 inside the circle and 0 outside\n disk_list: ndarray of shape (n,2)\n X and Y positions where n is the number of positions.\n These are the initial guesses that will be refined\n pos_list: ndarray of shape (n,2)\n a and b Miller indices corresponding to the\n disk positions\n reference_axes: ndarray, optional\n The unit cell axes from the reference region. Strain is\n calculated by comapring the axes at a scan position with \n the reference axes values. If it is 0, then the average \n NBED axes will be calculated and will be used as the \n reference axes.\n med_factor: float, optional\n Due to detector noise, some stray pixels may often be brighter \n than the background. This is used for damping any such pixels.\n Default is 30\n gauss_val: float, optional\n The standard deviation of the Gaussian filter applied to the\n logarithm of the CBED pattern. Default is 3\n hybrid_cc: float, optional\n Hybridization parameter to be used for cross-correlation.\n Default is 0.1\n nan_cutoff: float, optional\n Parameter that is used for thresholding disk\n fits. If the intensity ratio is below the threshold \n the position will not be fit. Default value is 0.5 \n \n Returns\n -------\n e_xx_map: ndarray\n Strain in the xx direction in the region of interest\n e_xy_map: ndarray\n Strain in the xy direction in the region of interest\n e_th_map: ndarray\n Angular strain in the region of interest\n e_yy_map: ndarray\n Strain in the yy direction in the region of interest\n fit_std: ndarray\n x and y deviations in axes fitting for the scan points\n \n Notes\n -----\n At every scan position, the diffraction disk is filtered by first taking\n the log of the CBED pattern, and then by applying a Gaussian filter. \n Following this the Sobel of the filtered dataset is calculated. \n The intensity of the Sobel, Gaussian and Log filtered CBED data is then\n inspected for outlier pixels. If pixel intensities are higher or lower than\n a threshold of the median pixel intensity, they are replaced by the threshold\n value. This is then hybrid cross-correlated with the Sobel magnitude of the \n template disk. If the pattern axes return a numerical value, then the strain\n is calculated for that scan position, else it is NaN\n \"\"\"\n warnings.filterwarnings(\"ignore\")\n # Calculate needed values\n scan_y, scan_x = np.mgrid[0 : data4D.shape[2], 0 : data4D.shape[3]]\n data4D_ROI = data4D[:, :, scan_y[ROI], scan_x[ROI]]\n no_of_disks = data4D_ROI.shape[-1]\n disk_size = (np.sum(st.util.image_normalizer(center_disk)) / np.pi) ** 0.5\n i_matrix = (np.eye(2)).astype(np.float64)\n sobel_center_disk, _ = st.util.sobel(center_disk)\n # Initialize matrices\n e_xx_ROI = np.nan * (np.ones(no_of_disks, dtype=np.float64))\n e_xy_ROI = np.nan * (np.ones(no_of_disks, dtype=np.float64))\n e_th_ROI = np.nan * (np.ones(no_of_disks, dtype=np.float64))\n e_yy_ROI = np.nan * (np.ones(no_of_disks, dtype=np.float64))\n fit_std = np.nan * (np.ones((no_of_disks, 2), dtype=np.float64))\n e_xx_map = np.nan * np.ones_like(scan_y)\n e_xy_map = np.nan * np.ones_like(scan_y)\n e_th_map = np.nan * np.ones_like(scan_y)\n e_yy_map = np.nan * np.ones_like(scan_y)\n # Calculate for mean CBED if no reference\n # axes present\n if np.size(reference_axes) < 2:\n mean_cbed = np.mean(data4D_ROI, axis=-1)\n sobel_lm_cbed, _ = st.util.sobel(st.util.image_logarizer(mean_cbed))\n sobel_lm_cbed[\n sobel_lm_cbed > med_factor * np.median(sobel_lm_cbed)\n ] = np.median(sobel_lm_cbed)\n lsc_mean = st.util.cross_corr(\n sobel_lm_cbed, sobel_center_disk, hybridizer=hybrid_cc\n )\n _, _, _, mean_axes = fit_nbed_disks(lsc_mean, disk_size, disk_list, pos_list)\n inverse_axes = np.linalg.inv(mean_axes)\n else:\n inverse_axes = np.linalg.inv(reference_axes)\n for ii in range(int(no_of_disks)):\n pattern = data4D_ROI[:, :, ii]\n sobel_log_pattern, _ = st.util.sobel(\n scnd.gaussian_filter(st.util.image_logarizer(pattern), gauss_val)\n )\n sobel_log_pattern[\n sobel_log_pattern > med_factor * np.median(sobel_log_pattern)\n ] = (np.median(sobel_log_pattern) * med_factor)\n sobel_log_pattern[\n sobel_log_pattern < np.median(sobel_log_pattern) / med_factor\n ] = (np.median(sobel_log_pattern) / med_factor)\n lsc_pattern = st.util.cross_corr(\n sobel_log_pattern, sobel_center_disk, hybridizer=hybrid_cc\n )\n _, _, std, pattern_axes = fit_nbed_disks(\n lsc_pattern, disk_size, disk_list, pos_list, nan_cutoff\n )\n if ~(np.isnan(np.ravel(pattern_axes))[0]):\n fit_std[ii, :] = std\n t_pattern = np.matmul(pattern_axes, inverse_axes)\n s_pattern = t_pattern - i_matrix\n e_xx_ROI[ii] = -s_pattern[0, 0]\n e_xy_ROI[ii] = -(s_pattern[0, 1] + s_pattern[1, 0])\n e_th_ROI[ii] = s_pattern[0, 1] - s_pattern[1, 0]\n e_yy_ROI[ii] = -s_pattern[1, 1]\n e_xx_map[ROI] = e_xx_ROI\n e_xx_map[np.isnan(e_xx_map)] = 0\n e_xx_map = scnd.gaussian_filter(e_xx_map, 1)\n e_xy_map[ROI] = e_xy_ROI\n e_xy_map[np.isnan(e_xy_map)] = 0\n e_xy_map = scnd.gaussian_filter(e_xy_map, 1)\n e_th_map[ROI] = e_th_ROI\n e_th_map[np.isnan(e_th_map)] = 0\n e_th_map = scnd.gaussian_filter(e_th_map, 1)\n e_yy_map[ROI] = e_yy_ROI\n e_yy_map[np.isnan(e_yy_map)] = 0\n e_yy_map = scnd.gaussian_filter(e_yy_map, 1)\n return e_xx_map, e_xy_map, e_th_map, e_yy_map, fit_std\n\n\n@numba.jit\ndef strain_log(\n data4D_ROI, center_disk, disk_list, pos_list, reference_axes=0, med_factor=10\n):\n warnings.filterwarnings(\"ignore\")\n # Calculate needed values\n no_of_disks = data4D_ROI.shape[-1]\n disk_size = (np.sum(center_disk) / np.pi) ** 0.5\n i_matrix = (np.eye(2)).astype(np.float64)\n # Initialize matrices\n e_xx_log = np.zeros(no_of_disks, dtype=np.float64)\n e_xy_log = np.zeros(no_of_disks, dtype=np.float64)\n e_th_log = np.zeros(no_of_disks, dtype=np.float64)\n e_yy_log = np.zeros(no_of_disks, dtype=np.float64)\n # Calculate for mean CBED if no reference\n # axes present\n if np.size(reference_axes) < 2:\n mean_cbed = np.mean(data4D_ROI, axis=-1)\n log_cbed, _ = st.util.image_logarizer(mean_cbed)\n log_cc_mean = st.util.cross_corr(log_cbed, center_disk, hybridizer=0.1)\n _, _, mean_axes = fit_nbed_disks(log_cc_mean, disk_size, disk_list, pos_list)\n inverse_axes = np.linalg.inv(mean_axes)\n else:\n inverse_axes = np.linalg.inv(reference_axes)\n for ii in range(int(no_of_disks)):\n pattern = data4D_ROI[:, :, ii]\n log_pattern, _ = st.util.image_logarizer(pattern)\n log_cc_pattern = st.util.cross_corr(log_pattern, center_disk, hybridizer=0.1)\n _, _, pattern_axes = fit_nbed_disks(\n log_cc_pattern, disk_size, disk_list, pos_list\n )\n t_pattern = np.matmul(pattern_axes, inverse_axes)\n s_pattern = t_pattern - i_matrix\n e_xx_log[ii] = -s_pattern[0, 0]\n e_xy_log[ii] = -(s_pattern[0, 1] + s_pattern[1, 0])\n e_th_log[ii] = s_pattern[0, 1] - s_pattern[1, 0]\n e_yy_log[ii] = -s_pattern[1, 1]\n return e_xx_log, e_xy_log, e_th_log, e_yy_log\n\n\n@numba.jit\ndef strain_oldstyle(data4D_ROI, center_disk, disk_list, pos_list, reference_axes=0):\n warnings.filterwarnings(\"ignore\")\n # Calculate needed values\n no_of_disks = data4D_ROI.shape[-1]\n disk_size = (np.sum(center_disk) / np.pi) ** 0.5\n i_matrix = (np.eye(2)).astype(np.float64)\n # Initialize matrices\n e_xx_ROI = np.zeros(no_of_disks, dtype=np.float64)\n e_xy_ROI = np.zeros(no_of_disks, dtype=np.float64)\n e_th_ROI = np.zeros(no_of_disks, dtype=np.float64)\n e_yy_ROI = np.zeros(no_of_disks, dtype=np.float64)\n # Calculate for mean CBED if no reference\n # axes present\n if np.size(reference_axes) < 2:\n mean_cbed = np.mean(data4D_ROI, axis=-1)\n cc_mean = st.util.cross_corr(mean_cbed, center_disk, hybridizer=0.1)\n _, _, mean_axes = fit_nbed_disks(cc_mean, disk_size, disk_list, pos_list)\n inverse_axes = np.linalg.inv(mean_axes)\n else:\n inverse_axes = np.linalg.inv(reference_axes)\n for ii in range(int(no_of_disks)):\n pattern = data4D_ROI[:, :, ii]\n cc_pattern = st.util.cross_corr(pattern, center_disk, hybridizer=0.1)\n _, _, pattern_axes = fit_nbed_disks(cc_pattern, disk_size, disk_list, pos_list)\n t_pattern = np.matmul(pattern_axes, inverse_axes)\n s_pattern = t_pattern - i_matrix\n e_xx_ROI[ii] = -s_pattern[0, 0]\n e_xy_ROI[ii] = -(s_pattern[0, 1] + s_pattern[1, 0])\n e_th_ROI[ii] = s_pattern[0, 1] - s_pattern[1, 0]\n e_yy_ROI[ii] = -s_pattern[1, 1]\n return e_xx_ROI, e_xy_ROI, e_th_ROI, e_yy_ROI\n\n\ndef ROI_strain_map(strain_ROI, ROI):\n \"\"\"\n Convert the strain in the ROI array to a strain map\n \"\"\"\n strain_map = np.zeros_like(ROI, dtype=np.float64)\n strain_map[ROI] = (strain_ROI).astype(np.float64)\n return strain_map\n\n\n@numba.jit(cache=True, parallel=True)\ndef log_sobel4D(data4D, scan_dims, med_factor=30, gauss_val=3):\n \"\"\"\n Take the Log-Sobel of a pattern. \n \n Parameters\n ----------\n data4D: ndarray \n 4D dataset whose CBED patterns will be filtered\n scan_dims: tuple\n Scan dimensions. If your scanning pixels are for \n example the first two dimensions specify it as (0,1)\n Will be converted to numpy array so pass tuple only\n med_factor: float, optional\n Due to detector noise, some stray pixels may often \n be brighter than the background. This is used for \n damping any such pixels. Default is 30\n gauss_val: float, optional\n The standard deviation of the Gaussian filter applied \n to the logarithm of the CBED pattern. Default is 3\n \n Returns\n -------\n data_lsb: ndarray\n 4D dataset where each CBED pattern has been log\n Sobel filtered\n \n Notes\n -----\n Generate the Sobel filtered pattern of the logarithm of\n a dataset. Compared to running the Sobel filter back on\n a log dataset, this takes care of somethings - notably\n a Gaussian blur is applied to the image, and Sobel spikes\n are removed when any values are too higher or lower than \n the median of the image. This is because real detector\n images often are very noisy. This code generates the filtered\n CBED at every scan position, and is dimension agnostic, in\n that your CBED dimensions can either be the first two or last\n two - just specify the dimensions. Also if loops weirdly need\n to be outside the for loops - this is a numba feature (bug?)\n Small change - made the Sobel matrix order 5 rather than 3\n \n See Also\n --------\n dpc.log_sobel\n \"\"\"\n scan_dims = np.asarray(scan_dims)\n scan_dims[scan_dims < 0] = 4 + scan_dims[scan_dims < 0]\n sum_dims = np.sum(scan_dims)\n if sum_dims < 2:\n data4D = np.transpose(data4D, (2, 3, 0, 1))\n data_lsb = np.zeros_like(data4D, dtype=np.float)\n for jj in numba.prange(data4D.shape[int(scan_dims[1])]):\n for ii in range(data4D.shape[int(scan_dims[0])]):\n pattern = data4D[:, :, ii, jj]\n pattern = 1000 * (1 + st.util.image_normalizer(pattern))\n lsb_pattern, _ = st.util.sobel(\n scnd.gaussian_filter(st.util.image_logarizer(pattern), gauss_val), 5\n )\n lsb_pattern[lsb_pattern > med_factor * np.median(lsb_pattern)] = (\n np.median(lsb_pattern) * med_factor\n )\n lsb_pattern[lsb_pattern < np.median(lsb_pattern) / med_factor] = (\n np.median(lsb_pattern) / med_factor\n )\n data_lsb[:, :, ii, jj] = lsb_pattern\n if sum_dims < 2:\n data_lsb = np.transpose(data_lsb, (2, 3, 0, 1))\n return data_lsb\n\n\ndef spectra_finder(data4D, yvals, xvals):\n spectra_data = np.ravel(\n np.mean(\n data4D[:, :, yvals[0] : yvals[1], xvals[0] : xvals[1]],\n axis=(-1, -2),\n dtype=np.float64,\n )\n )\n data_im = np.sum(data4D, axis=(0, 1))\n data_im = (data_im - np.amin(data_im)) / (np.amax(data_im) - np.amin(data_im))\n overlay = np.zeros_like(data_im)\n overlay[yvals[0] : yvals[1], xvals[0] : xvals[1]] = 1\n return spectra_data, 0.5 * (data_im + overlay)\n\n\ndef sort_edges(edge_map, edge_distance=5):\n yV, xV = np.mgrid[0 : np.shape(edge_map)[0], 0 : np.shape(edge_map)[1]]\n dist_points = np.zeros_like(yV)\n yy = yV[edge_map]\n xx = xV[edge_map]\n no_points = np.size(yy)\n points = np.arange(no_points)\n point_list = np.transpose(np.asarray((yV[edge_map], xV[edge_map])))\n truth_list = np.zeros((no_points, 2), dtype=bool)\n edge_list_1 = np.zeros((no_points, 2))\n point_number = 0\n edge_list_1[int(point_number), 0:2] = np.asarray((yy[0], xx[0]))\n truth_list[int(point_number), 0:2] = True\n edge_points = 1\n for ii in np.arange(no_points):\n last_yy = edge_list_1[int(edge_points - 1), 0]\n last_xx = edge_list_1[int(edge_points - 1), 1]\n other_points = np.reshape(\n point_list[~truth_list], (int(no_points - edge_points), 2)\n )\n dist_vals = (\n ((other_points[:, 0] - last_yy) ** 2)\n + ((other_points[:, 1] - last_xx) ** 2)\n ) ** 0.5\n min_dist = np.amin(dist_vals)\n if min_dist < edge_distance:\n n_yy = other_points[dist_vals == min_dist, 0][0]\n n_xx = other_points[dist_vals == min_dist, 1][0]\n point_number = points[\n (point_list[:, 0] == n_yy) & (point_list[:, 1] == n_xx)\n ][0]\n edge_list_1[int(edge_points), 0:2] = np.asarray((n_yy, n_xx))\n truth_list[int(point_number), 0:2] = True\n edge_points = edge_points + 1.0\n list_1 = np.reshape(point_list[truth_list], (int(edge_points), 2))\n list_2 = np.reshape(point_list[~truth_list], (int(no_points - edge_points), 2))\n edge1 = np.zeros_like(edge_map)\n edge1[list_1[:, 0], list_1[:, 1]] = 1\n edge2 = np.zeros_like(edge_map)\n edge2[list_2[:, 0], list_2[:, 1]] = 1\n edge1_sum = np.sum(edge1)\n edge2_sum = np.sum(edge2)\n if edge1_sum > edge2_sum:\n outer_edge = np.copy(edge1)\n inner_edge = np.copy(edge2)\n else:\n outer_edge = np.copy(edge2)\n inner_edge = np.copy(edge1)\n return outer_edge, inner_edge\n\n\n@numba.jit\ndef get_inside(edges, cutoff=0.95):\n big_size = (2.5 * np.asarray(edges.shape)).astype(int)\n starter = (0.5 * (big_size - np.asarray(edges.shape))).astype(int)\n bigger_aa = np.zeros(big_size)\n bigger_aa[\n starter[0] : starter[0] + edges.shape[0],\n starter[1] : starter[1] + edges.shape[1],\n ] = edges\n aa1 = bigger_aa.astype(bool)\n aa2 = (np.fliplr(bigger_aa)).astype(bool)\n yy, xx = np.mgrid[0 : big_size[0], 0 : big_size[1]]\n positions = np.zeros((bigger_aa.size, 2), dtype=int)\n positions[:, 0] = np.ravel(yy)\n positions[:, 1] = np.ravel(xx)\n yy_aa1 = yy[aa1]\n xx_aa1 = xx[aa1]\n yy_aa2 = yy[aa2]\n xx_aa2 = xx[aa2]\n ang_range1 = np.zeros_like(yy, dtype=np.float)\n ang_range2 = np.zeros_like(yy, dtype=np.float)\n for ii in numba.prange(len(positions)):\n angles1 = (180 / np.pi) * np.arctan2(\n yy_aa1 - positions[ii, 0], xx_aa1 - positions[ii, 1]\n )\n ang_range1[positions[ii, 0], positions[ii, 1]] = np.amax(angles1) - np.amin(\n angles1\n )\n for jj in numba.prange(len(positions)):\n angles2 = (180 / np.pi) * np.arctan2(\n yy_aa2 - positions[jj, 0], xx_aa2 - positions[jj, 1]\n )\n ang_range2[positions[jj, 0], positions[jj, 1]] = np.amax(angles2) - np.amin(\n angles2\n )\n ang_range2 = np.fliplr(ang_range2)\n ang_range = np.logical_and(\n ang_range1 > cutoff * np.amax(ang_range1),\n ang_range2 > cutoff * np.amax(ang_range2),\n )\n real_ang_range = np.zeros_like(edges, dtype=bool)\n real_ang_range = ang_range[\n starter[0] : starter[0] + edges.shape[0],\n starter[1] : starter[1] + edges.shape[1],\n ]\n return real_ang_range\n\n\ndef sobel_filter(image, med_filter=50):\n ls_image, _ = st.util.sobel(st.util.image_logarizer(image))\n ls_image[ls_image > (med_filter * np.median(ls_image))] = med_filter * np.median(\n ls_image\n )\n ls_image[ls_image < (np.median(ls_image) / med_filter)] = (\n np.median(ls_image) / med_filter\n )\n return ls_image\n\n\n@numba.jit\ndef strain4D_general(\n data4D,\n disk_radius,\n ROI=0,\n disk_center=np.nan,\n rotangle=0,\n med_factor=30,\n gauss_val=3,\n hybrid_cc=0.2,\n):\n \"\"\"\n Get strain from a ROI without the need for\n specifying Miller indices of diffraction spots\n \n Parameters\n ----------\n data4D: ndarray\n This is a 4D dataset where the first two dimensions\n are the diffraction dimensions and the next two \n dimensions are the scan dimensions\n disk_radius: float\n Radius in pixels of the diffraction disks\n ROI: ndarray, optional\n Region of interest. If no ROI is passed then the entire\n scan region is the ROI\n disk_center: tuple, optional\n Location of the center of the diffraction disk - closest to\n the <000> undiffracted beam\n rotangle: float, optional\n Angle of rotation of the CBED with respect to the optic axis\n This must be in degrees\n med_factor: float, optional\n Due to detector noise, some stray pixels may often be brighter \n than the background. This is used for damping any such pixels.\n Default is 30\n gauss_val: float, optional\n The standard deviation of the Gaussian filter applied to the\n logarithm of the CBED pattern. Default is 3\n hybrid_cc: float, optional\n Hybridization parameter to be used for cross-correlation.\n Default is 0.1 \n \n Returns\n -------\n e_xx_map: ndarray\n Strain in the xx direction in the region of interest\n e_xy_map: ndarray\n Strain in the xy direction in the region of interest\n e_th_map: ndarray\n Angular strain in the region of interest\n e_yy_map: ndarray\n Strain in the yy direction in the region of interest\n list_pos: ndarray\n List of all the higher order peak positions with \n respect to the central disk for all positions in the ROI\n \n Notes\n -----\n We first of all calculate the preconditioned data (log + Sobel filtered)\n for every CBED pattern in the ROI. Then the mean preconditioned \n pattern is calculated and cross-correlated with the Sobel template. The disk \n positions are as peaks in this cross-correlated pattern, with the central\n disk the one closest to the center of the CBED pattern. Using that insight\n the distances of the higher order diffraction disks are calculated with respect\n to the central transmitted beam. This is then performed for all other CBED \n patterns. The calculated higher order disk locations are then compared to the \n higher order disk locations for the median pattern to generate strain maps.\n \"\"\"\n rotangle = np.deg2rad(rotangle)\n rotmatrix = np.asarray(\n ((np.cos(rotangle), -np.sin(rotangle)), (np.sin(rotangle), np.cos(rotangle)))\n )\n diff_y, diff_x = np.mgrid[0 : data4D.shape[0], 0 : data4D.shape[1]]\n if np.isnan(np.mean(disk_center)):\n disk_center = np.asarray(np.shape(diff_y)) / 2\n else:\n disk_center = np.asarray(disk_center)\n e_xx_map = np.nan * np.ones((data4D.shape[2], data4D.shape[3]))\n e_xy_map = np.nan * np.ones((data4D.shape[2], data4D.shape[3]))\n e_th_map = np.nan * np.ones((data4D.shape[2], data4D.shape[3]))\n e_yy_map = np.nan * np.ones((data4D.shape[2], data4D.shape[3]))\n radiating = ((diff_y - disk_center[0]) ** 2) + ((diff_x - disk_center[1]) ** 2)\n disk = np.zeros_like(radiating)\n disk[radiating < (disk_radius ** 2)] = 1\n sobel_disk, _ = st.util.sobel(disk)\n if np.sum(ROI) == 0:\n imROI = np.ones_like(e_xx_map, dtype=bool)\n else:\n imROI = ROI\n ROI_4D = data4D[:, :, imROI]\n no_of_disks = ROI_4D.shape[-1]\n LSB_ROI = np.zeros_like(ROI_4D, dtype=np.float)\n for ii in range(no_of_disks):\n cbed = ROI_4D[:, :, ii]\n cbed = 1000 * (1 + st.util.image_normalizer(cbed))\n lsb_cbed, _ = st.util.sobel(\n scnd.gaussian_filter(st.util.image_logarizer(cbed), gauss_val)\n )\n lsb_cbed[lsb_cbed > med_factor * np.median(lsb_cbed)] = (\n np.median(lsb_cbed) * med_factor\n )\n lsb_cbed[lsb_cbed < np.median(lsb_cbed) / med_factor] = (\n np.median(lsb_cbed) / med_factor\n )\n LSB_ROI[:, :, ii] = lsb_cbed\n Mean_LSB = np.median(LSB_ROI, axis=(-1))\n LSB_CC = st.util.cross_corr(Mean_LSB, sobel_disk, hybrid_cc)\n data_peaks = skfeat.peak_local_max(\n LSB_CC, min_distance=int(2 * disk_radius), indices=False\n )\n peak_labels = scnd.measurements.label(data_peaks)[0]\n merged_peaks = np.asarray(\n scnd.measurements.center_of_mass(\n data_peaks, peak_labels, range(1, np.max(peak_labels) + 1)\n )\n )\n fitted_mean = np.zeros_like(merged_peaks, dtype=np.float64)\n fitted_scan = np.zeros_like(merged_peaks, dtype=np.float64)\n for jj in range(merged_peaks.shape[0]):\n par = st.util.fit_gaussian2D_mask(\n LSB_CC, merged_peaks[jj, 1], merged_peaks[jj, 0], disk_radius\n )\n fitted_mean[jj, 0:2] = np.flip(par[0:2])\n distarr = (\n np.sum(((fitted_mean - np.asarray(LSB_CC.shape) / 2) ** 2), axis=1)\n ) ** 0.5\n peaks_mean = (\n fitted_mean[distarr != np.amin(distarr), :]\n - fitted_mean[distarr == np.amin(distarr), :]\n )\n list_pos = np.zeros((int(np.sum(imROI)), peaks_mean.shape[0], peaks_mean.shape[1]))\n exx_ROI = np.ones(no_of_disks, dtype=np.float64)\n exy_ROI = np.ones(no_of_disks, dtype=np.float64)\n eth_ROI = np.ones(no_of_disks, dtype=np.float64)\n eyy_ROI = np.ones(no_of_disks, dtype=np.float64)\n for kk in range(no_of_disks):\n scan_LSB = LSB_ROI[:, :, kk]\n scan_CC = st.util.cross_corr(scan_LSB, sobel_disk, hybrid_cc)\n for qq in range(merged_peaks.shape[0]):\n scan_par = st.util.fit_gaussian2D_mask(\n scan_CC, fitted_mean[qq, 1], fitted_mean[qq, 0], disk_radius\n )\n fitted_scan[qq, 0:2] = np.flip(scan_par[0:2])\n peaks_scan = (\n fitted_scan[distarr != np.amin(distarr), :]\n - fitted_scan[distarr == np.amin(distarr), :]\n )\n list_pos[kk, :, :] = peaks_scan\n scan_strain, _, _, _ = np.linalg.lstsq(peaks_mean, peaks_scan, rcond=None)\n scan_strain = np.matmul(scan_strain, rotmatrix)\n scan_strain = scan_strain - np.eye(2)\n exx_ROI[kk] = scan_strain[0, 0]\n exy_ROI[kk] = (scan_strain[0, 1] + scan_strain[1, 0]) / 2\n eth_ROI[kk] = (scan_strain[0, 1] - scan_strain[1, 0]) / 2\n eyy_ROI[kk] = scan_strain[1, 1]\n e_xx_map[imROI] = exx_ROI\n e_xx_map[np.isnan(e_xx_map)] = 0\n e_xx_map = scnd.gaussian_filter(e_xx_map, 1)\n e_xy_map[imROI] = exy_ROI\n e_xy_map[np.isnan(e_xy_map)] = 0\n e_xy_map = scnd.gaussian_filter(e_xy_map, 1)\n e_th_map[imROI] = eth_ROI\n e_th_map[np.isnan(e_th_map)] = 0\n e_th_map = scnd.gaussian_filter(e_th_map, 1)\n e_yy_map[imROI] = eyy_ROI\n e_yy_map[np.isnan(e_yy_map)] = 0\n e_yy_map = scnd.gaussian_filter(e_yy_map, 1)\n return e_xx_map, e_xy_map, e_th_map, e_yy_map, list_pos\n\n\ndef bin_scan(data4D, bin_factor):\n \"\"\"\n Bin the data in the scan dimensions\n \n Parameters\n ----------\n data4D: ndarray\n This is a 4D dataset where the first two dimensions\n are the dffraction dimensions and the next two \n dimensions are the scan dimensions\n bin_factor: int or tuple\n Binning factor for scan dimensions\n \n Returns\n -------\n binned_4D: ndarray\n The data binned in the scanned dimensions.\n \n Notes\n -----\n You can specify the bin factor to be either an integer or\n a tuple. If you specify an integer the same binning will \n be used in both the scan X and scan Y dimensions, while if\n you specify a tuple then different binning factors for each \n dimensions.\n \n Examples\n --------\n Run as:\n \n >>> binned_4D = bin_scan(data4D, 4)\n \n This will bin the scan dimensions by 4. This is functionally\n identical to:\n \n >>> binned_4D = bin_scan(data4D, (4, 4))\n \"\"\"\n bin_factor = np.array(bin_factor, ndmin=1)\n bf = np.copy(bin_factor)\n bin_factor = np.ones(4)\n bin_factor[2:4] = bf\n ini_shape = np.asarray(data4D.shape)\n fin_shape = (np.ceil(ini_shape / bin_factor)).astype(int)\n big_shape = (fin_shape * bin_factor).astype(int)\n binned_4D = np.zeros(fin_shape[0:4], dtype=data4D.dtype)\n big4D = np.zeros(big_shape[0:4], dtype=data4D.dtype)\n big4D[:, :, 0 : ini_shape[2], 0 : ini_shape[3]] = data4D\n for ii in range(fin_shape[2]):\n for jj in range(fin_shape[3]):\n starter_ii = int(bin_factor[2] * ii)\n stopper_ii = int(bin_factor[2] * (ii + 1))\n starter_jj = int(bin_factor[3] * jj)\n stopper_jj = int(bin_factor[3] * (jj + 1))\n summed_cbed = np.sum(\n big4D[:, :, starter_ii:stopper_ii, starter_jj:stopper_jj], axis=(-1, -2)\n )\n binned_4D[:, :, ii, jj] = summed_cbed\n binned_4D = binned_4D / (bin_factor[2] * bin_factor[3])\n return (binned_4D).astype(data4D.dtype)\n\n\ndef cbed_filter(\n image, circ_vals, med_val=50, sec_med=True, hybridizer=0.25, bit_depth=32\n):\n \"\"\"\n Generate the filtered cross-correlated image for locating disk\n positions\n \n Parameters\n ----------\n image: ndarray\n The image to be filtered\n circ_vals: tuple\n Three valued tuple that holds the cross\n correlating circle values where the first\n position is the X position of the cnter, \n second value is the Y coordinate of the \n center and the third value is the circle radius.\n med_val: float, optional\n Deviation from median value to accept in the \n Sobel filtered image. Default is 50\n sec_med: bool, Optional\n Tamps out deviation from median values in the\n Sobel filtered image too if True\n hybridizer: float, optional\n The value to use for hybrid cross-correlation.\n Default is 0.25. 0 gives pure cross correlation,\n while 1 gives pure phase correlation\n bit_depth: int, optional\n Maximum power of 2 to be used for scaling the image\n when taking logarithms. Default is 32\n \n Returns\n -------\n slm_image: ndarray\n The filtered image.\n \n lsc_image: ndarray\n The filtered image cross-correlated with the circle edge\n \n Notes\n -----\n We first generate the circle centered at the X and Y co-ordinates, with \n the radius given inside the circ_vals tuple. This generated circle is \n the Sobel filtered to generate an edge of the circle.\n \n Often due to detector issues, or stray muons a single pixel may be \n much brighter. Also dead pixels can cause individual pixels to be \n much darker. To remove such errors, and values in the image, we take \n the median value of the image and then throw any values that are med_val \n times larger or med_val times smaller than the median. Then we normalize \n the image from 1 to the 2^bit_depth and then take the log of that image. \n This generates an image whose scale is between 0 and the bit_depth. To \n further decrease detector noise, this scaled image is then Gaussian filtered \n with a single pixel blur, and then finally Sobel filtered. This Sobel\n filtered image is then cross-correlated with the Sobel filtered circle edge.\n \n If there are disks in the image whose size is close to the radius of the \n circle, then the locations of them now become 2D peaks. If the \n circle radius is however too small/large rather than 2D peaks at \n diffraction disk locations, we will observe circles.\n \n Examples\n --------\n This is extremely useful for locating NBED diffraction positions. If you know\n the size and location of the central disk which you can obtain by running \n `st.util.sobel_circle` on the undiffracted CBED pattern on vacuum as:\n \n >>> beam_x, beam_y, beam_r = st.util.sobel_circle(nodiff_cbed)\n \n Then use the on the Mean_CBED to calculate the disk positions from:\n \n >>> slm_reference, lsc_reference = st.nbed.cbed_filter(Mean_CBED, (beam_x, beam_y, beam_r))\n \n \"\"\"\n # Generating the circle edge\n center_disk = st.util.make_circle(\n np.asarray(image.shape), circ_vals[0], circ_vals[1], circ_vals[2]\n )\n sobel_center_disk, _ = st.util.sobel(center_disk)\n\n # Throwing away stray pixel values\n med_image = np.copy(image)\n med_image[med_image > med_val * np.median(med_image)] = med_val * np.median(\n med_image\n )\n med_image[med_image < np.median(med_image) / med_val] = (\n np.median(med_image) / med_val\n )\n\n # Filtering the image\n slm_image, _ = st.util.sobel(\n scnd.gaussian_filter(st.util.image_logarizer(med_image, bit_depth), 1)\n )\n if sec_med:\n slm_image[slm_image > med_val * np.median(slm_image)] = med_val * np.median(\n slm_image\n )\n slm_image[slm_image < np.median(slm_image) / med_val] = (\n np.median(slm_image) / med_val\n )\n\n # Cross-correlating it\n lsc_image = st.util.cross_corr(slm_image, sobel_center_disk, hybridizer)\n return slm_image, lsc_image\n","sub_path":"stemtool/nbed/nbed_strain.py","file_name":"nbed_strain.py","file_ext":"py","file_size_in_byte":48993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"610163887","text":"# So the numbers we have seen before lead to endless recursion.\nclass Solution:\n def isHappy(self, n: int) -> bool:\n cache = set()\n while n != 1:\n n = sum([int(i)**2 for i in str(n)])\n if n in cache:\n return False\n cache.add(n)\n return True\n \n","sub_path":"leetcode/202.HappyNumber/soln.py","file_name":"soln.py","file_ext":"py","file_size_in_byte":318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"579568248","text":"import random\r\n\r\nclass State:\r\n score = [0, 0]\r\n round_no = 0\r\n human_strat = int()\r\n human_last_strat = -1\r\n ai_strat = int()\r\n fails_in_a_row = int()\r\n Probs = dict()\r\n\r\n def initProbs(self):\r\n self.Probs = {\"rock\": {\"rock\": 0, \"paper\": 0, \"scissors\": 0},\r\n \"paper\": {\"paper\": 0, \"rock\": 0, \"scissors\": 0},\r\n \"scissors\": {\"scissors\": 0, \"rock\": 0, \"paper\": 0}}\r\n\r\n\r\nst = State()\r\nst.initProbs()\r\n\r\n\r\ndef ai_choose_strat(strats):\r\n human_last_strat_str = strats[st.human_last_strat - 1]\r\n max_prob=0\r\n max_prob_strat=\"\"\r\n for strat in strats:\r\n if st.Probs[human_last_strat_str][strat] > max_prob:\r\n max_prob_strat=strat\r\n max_prob=st.Probs[human_last_strat_str][strat]\r\n if max_prob_strat == \"rock\":\r\n return 1 #paper\r\n if max_prob_strat == \"paper\":\r\n return 2 #scissors\r\n if max_prob_strat == \"scissors\":\r\n return 0 #rock\r\n return random.randint(0, len(strats) - 1)\r\n\r\n\r\ndef get_input():\r\n while True:\r\n print(\"\\tCHOOSE: 1. Rock | 2. Paper | 3. Scissors\")\r\n inp = input(\"\\t\\t\")\r\n\r\n if inp in ['1', '2', '3']:\r\n return inp\r\n\r\n\r\ndef game_logic(move1, move2):\r\n if move1 == 1:\r\n if move2 == 3:\r\n return -1\r\n elif move2 == 2:\r\n return 1\r\n else:\r\n return 0\r\n\r\n elif move1 == 2:\r\n if move2 == 1:\r\n return -1\r\n elif move2 == 3:\r\n return 1\r\n else:\r\n return 0\r\n\r\n elif move1 == 3:\r\n if move2 == 1:\r\n return 1\r\n elif move2 == 2:\r\n return -1\r\n else:\r\n return 0\r\n\r\n\r\ndef update_probs():\r\n human_last_strat_str = strats[st.human_last_strat - 1]\r\n human_strat_str = strats[st.human_strat - 1]\r\n st.Probs[human_last_strat_str][human_strat_str] += 1\r\n\r\n\r\ndef print_score():\r\n print(\"\\tAI\", st.score[0], \"- HUMAN\", st.score[1], '\\n')\r\n\r\n\r\nstrats = [\"rock\", \"paper\", \"scissors\"]\r\n\r\nwhile st.round_no < 15:\r\n st.round_no += 1\r\n\r\n if st.round_no != 1:\r\n print(\"\\n----------------------------------------------------------------------\")\r\n else:\r\n print(\"\\n\")\r\n\r\n print(\"ROUND\", st.round_no)\r\n print_score()\r\n\r\n st.ai_strat = int(ai_choose_strat(strats))\r\n st.human_strat = int(get_input())\r\n\r\n winner = game_logic(st.ai_strat + 1, st.human_strat)\r\n\r\n if winner == -1:\r\n print(\"AI chose\", strats[st.ai_strat], \"=> AI Wins\")\r\n st.score[0] += 1\r\n st.fails_in_a_row = 0\r\n elif winner == 1:\r\n print(\"AI chose\", strats[st.ai_strat], \"=> HUMAN Wins\")\r\n st.score[1] += 1\r\n if st.fails_in_a_row > 2:\r\n st.fails_in_a_row = 0\r\n st.initProbs()\r\n print(\"\\n!!!Strategy probabilities were reset!!!\\n\")\r\n else:\r\n st.fails_in_a_row += 1\r\n\r\n else:\r\n print(\"AI also chose\", strats[st.ai_strat], \"=> DRAW\")\r\n st.score[0] += 1\r\n st.score[1] += 1\r\n\r\n if st.human_last_strat > 0:\r\n update_probs()\r\n st.human_last_strat = st.human_strat\r\n\r\nprint(\"\\n_____________________________________\")\r\nprint(\"\\nFINAL SCORE:\", end=' ')\r\nprint_score()\r\nprint(\"_____________________________________\")\r\n\r\n# TO DO:\r\n# Reprezentarea unei stari (un fel de struct, ex: dictionar sau clasa)\r\n# Metoda de invatare automata: gasirea unui pattern\r\n'''\r\nIn fiecare runda, ne uitam la mutarea precedenta si alegem mutarea optima din cele 2 ramase\r\nEX: la runda 1 a fost ales scissors, in runda 2 alegem paper, din cele 2 ramase (paper, rock)\r\ndeoarece orice ar alege el (din cele 2) ori castigam, ori facem remiza\r\n'''\r\n\r\n'''\r\nStatistici din runde precedente: frecventa miscarilor etc\r\n'''\r\n","sub_path":"Rock-Paper-Scissors/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"522872543","text":"#!/usr/bin/python\n\nimport argparse\nimport os\nimport subprocess\nimport re\n\nparser = argparse.ArgumentParser(description='Compiles and converts a C/assembly file to hexcode')\nparser.add_argument('fname', metavar='fname', type=str,\n help='file to convert')\nparser.add_argument('--cc', metavar='cc', type=str,\n help='cross-compiler')\nparser.add_argument('--output', metavar='output', type=str,\n help='file to output')\n\nargs = parser.parse_args()\nfname = args.fname\nbasename = os.path.basename(fname).replace(\".c\", \"\").replace(\".s\", \"\")\nfext = fname[-2:]\nif fext != \".s\" and fext != \".c\":\n print(\"Error: File must be either ASM (.s) or C (.c)\")\n exit()\n\ncc = args.cc\nif cc is None:\n cc = \"arm-none-eabi-gcc\"\n print(f\"cc not provided, falling back to default of '{cc}'\")\n\noutfile = args.output\nif outfile is None:\n outfile = f\"{basename}.mem\"\n print(f\"output argument not provided, writing output to '{outfile}''\")\n\nasmfname = fname\nif fext == \".c\":\n subprocess.call([cc, \"-S\", fname])\n asmfname = f\"{basename}.s\"\n\nsubprocess.call([cc, \"-c\", asmfname])\n\nsplit_cc = cc.split(\"-\")\nsplit_cc[-1] = \"objdump\"\nobjdump_exec = \"-\".join(split_cc)\nobjfname = f\"{basename}.o\"\ndump = subprocess.run([objdump_exec, \"-d\", objfname], stdout=subprocess.PIPE).stdout.decode(\"utf-8\")\ndump = dump.split(\"\\n\")\n\nwith open(outfile, \"w\") as f:\n pattern = re.compile(\"^\\s*([0-9A-Fa-f]+\\:\\s*).*$\")\n previous_addr = -4\n for line in dump:\n re_match = pattern.search(line)\n if re_match:\n prefix = re_match.group(1)\n addr = int(f\"0x{prefix.strip().replace(':', '')}\", 0)\n assert(addr == (previous_addr + 4))\n start_ind = line.find(prefix) + len(prefix)\n remove_pref = line[start_ind:]\n space_ind = remove_pref.find(\" \")\n instr = remove_pref[:space_ind]\n for i in range(0, len(instr), 2):\n f.write(f'{instr[i:i+2]}') # no more spaces, memory is in words now\n f.write(\"\\n\")\n previous_addr = addr\n\nprint(\"Hexfile written, cleaning up\")\nprint(f\"Removing {objfname}...\")\nsubprocess.call([\"rm\", objfname])\n#if fext == \".c\":\n #print(f\"Removing {asmfname}...\")\n #subprocess.call([\"rm\", asmfname])\n\n\n\n\n","sub_path":"tohex.py","file_name":"tohex.py","file_ext":"py","file_size_in_byte":2293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"137323776","text":"#!/usr/bin/env python\nimport roslib\nimport rospy\nimport time\nimport wiringpi\nimport subprocess\nfrom std_msgs.msg import String\n\n#main\nif __name__ == '__main__':\n ### init io port ###\n subprocess.check_call('gpio export 14 out',shell=True)\n subprocess.check_call('gpio export 17 out',shell=True)\n ###\n rospy.init_node('led_pub')\n\n io = wiringpi.GPIO(wiringpi.GPIO.WPI_MODE_GPIO_SYS)\n io.pinMode(14,io.OUTPUT) # Setup pin 11\n io.pinMode(17,io.OUTPUT) # Setup pin 8\n\n while not rospy.is_shutdown():\n i = raw_input()\n pub = rospy.Publisher('led_flash_str', String, queue_size=1)\n pub.publish(i)\n\n if i == '0' :\n io.digitalWrite(14,0)\n io.digitalWrite(17,0)\n time.sleep(1)\n elif i == '1' :\n io.digitalWrite(14,1)\n io.digitalWrite(17,1)\n time.sleep(1)\n else :\n io.digitalWrite(14,0)\n io.digitalWrite(17,0)\n time.sleep(1)\n","sub_path":"scripts/flash_pub.py","file_name":"flash_pub.py","file_ext":"py","file_size_in_byte":985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"499235783","text":"\"\"\"저기 이거 쓰시는분들 제발 저작권 좀 지켜요... README.md 읽고 하시길 빕니다.\"\"\"\r\n\r\n\r\nimport discord, asyncio, datetime, koreanbots, datetime, os, random, math, json, aiohttp, requests, ast, dotenv, smtplib\r\nfrom email.mime.text import MIMEText\r\ndotenv.load_dotenv(verbose=True)\r\nclient = discord.Client()\r\ntoken = os.getenv(\"TOKEN\")\r\nver = \"0.0.1\"\r\nprefix = \"시스비\"\r\nowner = [726350177601978438, 700561761690189875, 352412492539887616]\r\n# 삼성해피트리, OwO(Discord-api)\r\n\r\n\"\"\"Team Heim이 Team Comma로 바뀌었습니다!\"\"\"\r\nteamcomma = [726350177601978438, 700561761690189875, 723670306102837258, 447934468603379724, 524515155254444032, 647736678815105037, 674877162557407242]\r\n# 삼성해피트리, OwO(Discord-api), 수현, 준홍, 베인블, mswgen, 플로러\r\nbughunter = [726350177601978438, 534214957110394881]\r\n# 삼성해피트리, 제토\r\nhappytree = [726350177601978438, 674877162557407242]\r\n# 삼성해피트리, 플로러\r\nBot = koreanbots.Client(client, os.getenv(\"KOREANBOTS_TOKEN\"))\r\nready = 727361177604325396\r\nbug = 727361427173670923\r\nbotsv = 727361381157830658\r\n건의 = 727361465274597388\r\npingpongurl = os.getenv(\"PINGPONG_URL\")\r\npingpongauth = os.getenv(\"PINGPONG_AUTH\")\r\n\r\n@client.event\r\nasync def on_ready():\r\n print(client.user.name)\r\n print(\"ready\")\r\n await client.get_channel(int(ready)).send(embed = discord.Embed(title=\"봇이 준비되었습니다.\").set_footer(text=client.user, icon_url=client.user.avatar_url_as(format=None, static_format=\"png\", size=1024)))\r\n\r\ndef insert_returns(body):\r\n # insert return stmt if the last expression is a expression statement\r\n if isinstance(body[-1], ast.Expr):\r\n body[-1] = ast.Return(body[-1].value)\r\n ast.fix_missing_locations(body[-1])\r\n\r\n # for if statements, we insert returns into the body and the orelse\r\n if isinstance(body[-1], ast.If):\r\n insert_returns(body[-1].body)\r\n insert_returns(body[-1].orelse)\r\n\r\n # for with blocks, again we insert returns into the body\r\n if isinstance(body[-1], ast.With):\r\n insert_returns(body[-1].body)\r\n\r\n@client.event\r\nasync def on_guild_join(guild):\r\n try:\r\n await guild.owner.send(embed = discord.Embed(title=\"봇을 초대해주셔서 감사합니다!\", description=f\"안녕하세요! {client.user.name} 개발자 삼성해피트리입니다!\\n봇을 {guild.name}에 초대해주셔서 대단히 감사드리고,\\n앞으로도 여러분의 서버를 위해 노력하겠습니다!\\n[하트를 눌러주시면 저에게 큰 힘이 됩니다!](https://koreanbots.dev/bots/726376311710548049)\").set_footer(text=client.user, icon_url=client.user.avatar_url_as(format=None, static_format=\"png\", size=1024)))\r\n except:\r\n pass\r\n await client.get_channel(int(botsv)).send(embed = discord.Embed(title=\"봇 접속 서버 수 변동됨.\", description=f\"전 : {len(client.guilds)-1}\\n후 : {len(client.guilds)}\").set_footer(text=client.user, icon_url=client.user.avatar_url_as(format=None, static_format=\"png\", size=1024))) \r\n\r\n@client.event\r\nasync def on_guild_remove(guild):\r\n await client.get_channel(int(botsv)).send(embed = discord.Embed(title=\"봇 접속 서버 수 변동됨.\", description=f\"전 : {len(client.guilds)+1}\\n후 : {len(client.guilds)}\").set_footer(text=client.user, icon_url=client.user.avatar_url_as(format=None, static_format=\"png\", size=1024))) \r\n\r\n@client.event\r\nasync def on_message(message):\r\n try:\r\n if not message.content.startswith(f\"{prefix}\"): return\r\n if message.author.bot: return\r\n if message.content == f\"{prefix} 도움말\" or message.content == f\"{prefix} help\":\r\n a = random.choice([discord.Colour.red(), discord.Colour.orange(), discord.Colour.green(), discord.Colour.blue(), discord.Colour.purple()])\r\n await message.channel.send(embed=discord.Embed(colour=a, title=f\"{client.user.name} 도움말\", description=f\"\"\"\r\n접두사 : {prefix}, 버전 : {ver}\r\n<> = 필수, [] = 선택, () = 필요한 권한\r\n\r\n**\"커맨드\"**\r\n{prefix} 정보 [@유저 맨션]\r\n> 유저의 정보를 조회합니다.\r\n{prefix} 서버정보\r\n> 서버정보를 조회합니다.\r\n{prefix} 건의 <건의내용>\r\n> {client.user.name}에서 필요한 기능을 건의합니다.\r\n{prefix} 핑퐁 <아무말>\r\n> 핑퐁빌더로 말합니다.\r\n{prefix} 초대\r\n> 봇 초대링크를 알려줍니다.\r\n{prefix} 핑\r\n> {client.user.name}의 핑입니다!\r\n{prefix} 뱃지\r\n> {client.user.name}의 뱃지입니다!\r\n{prefix} 봇정보\r\n> {client.user.name}의 봇정보를 조회합니다.\r\n{prefix} 메일 <보낼 이메일>&&<제목>&&<내용>\r\n> {client.user.name}의 봇정보를 조회합니다.\r\n\r\n**\"일정 권한이 필요한 커맨드\"**\r\n{prefix} 청소 <메세지를 청소할 숫자>\r\n> {client.user.name}으로 해당 채널의 채팅을 <메세지를 청소할 숫자>만큼 지웁니다. (메세지 관리하기 권한)\r\n{prefix} 킥 <@유저 맨션>\r\n> {client.user.name}으로 해당 유저를 추방합니다. (멤버 추방하기 권한)\r\n{prefix} 밴 <@유저 맨션>\r\n> {client.user.name}으로 해당 유저를 차단합니다. (멤버 차단하기 권한)\r\n{prefix} 언밴 <@유저 맨션>\r\n> {client.user.name}으로 해당 유저를 언밴합니다. (멤버 차단하기 권한)\r\n{prefix} 공지 <제목>&&<내용>\r\n> {client.user.name}으로 공지를 발신합니다. (Bot Developer 권한)\r\n{prefix} 건답 <내용>\r\n> {client.user.name}으로 건의한 내용을 답변합니다! (Bot Developer 권한)\r\n\"\"\"))\r\n if message.content == f\"{prefix}\" or message.content == f\"{prefix} hellothisisverification\":\r\n await message.channel.send(f\"안녕하세요! 저는 {client.user.name}이에요! 시스비는 현재 {ver} 버전이고, 주인은 {client.get_user(726350177601978438)}(726350177601978438)입니다!\\n저는 인공지능이에요! 접두사는 `{prefix}`입니다!\")\r\n\r\n if message.content.startswith(f\"{prefix} 정보\"):\r\n if str(message.content[7:]) == '':\r\n user = message.author\r\n date = datetime.datetime.utcfromtimestamp(((int(user.id) >> 22) + 1420070400000) / 1000)\r\n status_dict: dict = {discord.Status.online: '<:status_online:728527943827062804> 온라인',\r\n discord.Status.offline: '<:status_offline:728527943831126036> 오프라인',\r\n discord.Status.idle: \"<:status_idle:728527943806091364> 자리비움\",\r\n discord.Status.do_not_disturb: \"<:status_dnd:728527943684456459> 방해금지\"}\r\n user_status = status_dict[user.status]\r\n badge = \"\"\r\n b = 0\r\n if message.author.id in owner:\r\n badge += \"<:dev:715085684905345064> Sisby Developer\\n\"\r\n b = 1\r\n if message.author.id in teamcomma:\r\n badge += \"<:heimteam:730330765212254251> Team Comma\\n\"\r\n b = 1\r\n if message.author.id in bughunter:\r\n badge += \"<:bughunter:730322955212423269> Sisby Bug Hunter\\n\"\r\n b = 1\r\n if message.author.id in happytree:\r\n badge += \"<:happytree:730335761164927006> Happytree Special Badge\\n\"\r\n b = 1\r\n if not b == 1:\r\n badge += \"**뱃지가 없습니다!**\"\r\n if not len(message.author.roles) == 1:\r\n roles = [role for role in user.roles]\r\n embed=discord.Embed(colour=message.author.color, timestamp=message.created_at, title=f\"유저정보 - {user}\")\r\n else:\r\n embed=discord.Embed(colour=0xff00, timestamp=message.created_at, title=f\"유저정보 - {user}\")\r\n embed.set_thumbnail(url=user.avatar_url)\r\n embed.set_footer(text=f\"{message.author}\", icon_url=message.author.avatar_url)\r\n embed.add_field(name=\"아이디\", value=f\"{user.id}\", inline=False)\r\n embed.add_field(name=\"닉네임\", value=f\"{user.display_name}\", inline=False)\r\n embed.add_field(name=\"가입일\", value=f\"{date.year}년 {date.month}월 {date.day}일 {date.hour + 9}시 {date.minute}분\", inline=False)\r\n try:\r\n embed.add_field(name=f\"가진 역할들({len(roles)-1}개)\", value=f\" \".join([role.mention for role in roles][1:]), inline=False)\r\n embed.add_field(name=\"가장 높은 역할\", value=f\"{user.top_role.mention}\", inline=False)\r\n except:\r\n embed.add_field(name=f\"가진 역할들\", value=f\"**소유한 역할이 없습니다!**\", inline=False)\r\n embed.add_field(name=\"Sisby Badge\", value=f\"{badge}\", inline=False)\r\n embed.add_field(name=\"현재 유저 상태\", value=f\"{user_status}\", inline=False)\r\n await message.channel.send(embed=embed)\r\n else:\r\n try:\r\n user = message.guild.get_member(int(message.content.split('<@!')[1].split('>')[0]))\r\n if user.bot == False:\r\n date = datetime.datetime.utcfromtimestamp(((int(user.id) >> 22) + 1420070400000) / 1000)\r\n status_dict: dict = {discord.Status.online: '<:status_online:728527943827062804> 온라인',\r\n discord.Status.offline: '<:status_offline:728527943831126036> 오프라인',\r\n discord.Status.idle: \"<:status_idle:728527943806091364> 자리비움\",\r\n discord.Status.do_not_disturb: \"<:status_dnd:728527943684456459> 방해금지\"}\r\n user_status = status_dict[user.status]\r\n badge = \"\"\r\n b = 0\r\n if user.id in owner:\r\n badge += \"<:dev:715085684905345064> Sisby Developer\\n\"\r\n b = 1\r\n if user.id in teamcomma:\r\n badge += \"<:heimteam:730330765212254251> Team Comma\\n\"\r\n b = 1\r\n if user.id in bughunter:\r\n badge += \"<:bughunter:730322955212423269> Sisby Bug Hunter\\n\"\r\n b = 1\r\n if user.id in happytree:\r\n badge += \"<:happytree:730335761164927006> Happytree Special Badge\\n\"\r\n b = 1\r\n if not b == 1:\r\n badge += \"**뱃지가 없습니다!**\"\r\n if not len(user.roles) == 1:\r\n roles = [role for role in user.roles]\r\n embed=discord.Embed(colour=0xff00, timestamp=message.created_at, title=f\"유저정보 - {user}\")\r\n else:\r\n embed=discord.Embed(colour=user.color, timestamp=message.created_at, title=f\"유저정보 - {user}\")\r\n embed.set_thumbnail(url=user.avatar_url)\r\n embed.set_footer(text=f\"{message.author}\", icon_url=message.author.avatar_url)\r\n embed.add_field(name=\"아이디\", value=f\"{user.id}\", inline=False)\r\n embed.add_field(name=\"닉네임\", value=f\"{user.display_name}\", inline=False)\r\n embed.add_field(name=\"가입일\", value=f\"{date.year}년 {date.month}월 {date.day}일 {date.hour + 9}시 {date.minute}분\", inline=False)\r\n try:\r\n embed.add_field(name=f\"가진 역할들({len(roles)-1}개)\", value=f\" \".join([role.mention for role in roles][1:]), inline=False)\r\n embed.add_field(name=\"가장 높은 역할\", value=f\"{user.top_role.mention}\", inline=False)\r\n except:\r\n embed.add_field(name=f\"가진 역할들\", value=f\"**소유한 역할이 없습니다!**\", inline=False)\r\n embed.add_field(name=\"Sisby Badge\", value=f\"{badge}\", inline=False)\r\n embed.add_field(name=\"현재 유저 상태\", value=f\"{user_status}\", inline=False)\r\n await message.channel.send(embed=embed)\r\n else:\r\n date = datetime.datetime.utcfromtimestamp(((int(user.id) >> 22) + 1420070400000) / 1000)\r\n status_dict: dict = {discord.Status.online: '<:status_online:728527943827062804> 온라인',\r\n discord.Status.offline: '<:status_offline:728527943831126036> 오프라인',\r\n discord.Status.idle: \"<:status_idle:728527943806091364> 자리비움\",\r\n discord.Status.do_not_disturb: \"<:status_dnd:728527943684456459> 방해금지\"}\r\n user_status = status_dict[user.status]\r\n if not len(user.roles) == 1:\r\n roles = [role for role in user.roles]\r\n embed=discord.Embed(colour=message.author.color, timestamp=message.created_at, title=f\"봇정보 - {user}\")\r\n else:\r\n embed=discord.Embed(colour=0xff00, timestamp=message.created_at, title=f\"봇정보 - {user}\")\r\n embed.set_thumbnail(url=user.avatar_url)\r\n embed.set_footer(text=f\"{message.author}\", icon_url=message.author.avatar_url)\r\n embed.add_field(name=\"봇 아이디\", value=f\"{user.id}\", inline=False)\r\n embed.add_field(name=\"봇 닉네임\", value=f\"{user.display_name}\", inline=False)\r\n embed.add_field(name=\"봇 생성일\", value=f\"{str(date.year)}년 {str(date.month)}월 {str(date.day)}일\", inline=False)\r\n try:\r\n embed.add_field(name=f\"가진 역할들({len(roles)-1}개)\", value=f\" \".join([role.mention for role in roles][1:]), inline=False)\r\n embed.add_field(name=\"가장 높은 역할\", value=f\"{user.top_role.mention}\", inline=False)\r\n except:\r\n embed.add_field(name=f\"가진 역할들\", value=f\"**소유한 역할이 없습니다!**\", inline=False)\r\n embed.add_field(name=\"현재 봇 상태\", value=f\"{user_status}\", inline=False)\r\n embed.add_field(name=\"봇 초대링크 (관리자 권한)\", value=f\"[초대하기](https://discordapp.com/oauth2/authorize?client_id={user.id}&scope=bot&permissions=8)\", inline=False)\r\n await message.channel.send(embed=embed)\r\n except:\r\n user = message.guild.get_member(int(message.content.split('<@')[1].split('>')[0]))\r\n if user.bot == False:\r\n date = datetime.datetime.utcfromtimestamp(((int(user.id) >> 22) + 1420070400000) / 1000)\r\n status_dict: dict = {discord.Status.online: '<:status_online:728527943827062804> 온라인',\r\n discord.Status.offline: '<:status_offline:728527943831126036> 오프라인',\r\n discord.Status.idle: \"<:status_idle:728527943806091364> 자리비움\",\r\n discord.Status.do_not_disturb: \"<:status_dnd:728527943684456459> 방해금지\"}\r\n user_status = status_dict[user.status]\r\n badge = \"\"\r\n b = 0\r\n if user.id in owner:\r\n badge += \"<:dev:715085684905345064> Sisby Developer\\n\"\r\n b = 1\r\n if user.id in teamcomma:\r\n badge += \"<:heimteam:730330765212254251> Team Comma\\n\"\r\n b = 1\r\n if user.id in bughunter:\r\n badge += \"<:bughunter:730322955212423269> Sisby Bug Hunter\\n\"\r\n b = 1\r\n if user.id in happytree:\r\n badge += \"<:happytree:730335761164927006> Happytree Special Badge\\n\"\r\n b = 1\r\n if not b == 1:\r\n badge += \"**뱃지가 없습니다!**\"\r\n if not len(user.roles) == 1:\r\n roles = [role for role in user.roles]\r\n embed=discord.Embed(colour=0xff00, timestamp=message.created_at, title=f\"유저정보 - {user}\")\r\n else:\r\n embed=discord.Embed(colour=user.color, timestamp=message.created_at, title=f\"유저정보 - {user}\")\r\n embed.set_thumbnail(url=user.avatar_url)\r\n embed.set_footer(text=f\"{message.author}\", icon_url=message.author.avatar_url)\r\n embed.add_field(name=\"아이디\", value=f\"{user.id}\", inline=False)\r\n embed.add_field(name=\"닉네임\", value=f\"{user.display_name}\", inline=False)\r\n embed.add_field(name=\"가입일\", value=f\"{date.year}년 {date.month}월 {date.day}일 {date.hour + 9}시 {date.minute}분\", inline=False)\r\n try:\r\n embed.add_field(name=f\"가진 역할들({len(roles)-1}개)\", value=f\" \".join([role.mention for role in roles][1:]), inline=False)\r\n embed.add_field(name=\"가장 높은 역할\", value=f\"{user.top_role.mention}\", inline=False)\r\n except:\r\n embed.add_field(name=f\"가진 역할들\", value=f\"**소유한 역할이 없습니다!**\", inline=False)\r\n embed.add_field(name=\"Sisby Badge\", value=f\"{badge}\", inline=False)\r\n embed.add_field(name=\"현재 유저 상태\", value=f\"{user_status}\", inline=False)\r\n await message.channel.send(embed=embed)\r\n else:\r\n date = datetime.datetime.utcfromtimestamp(((int(user.id) >> 22) + 1420070400000) / 1000)\r\n status_dict: dict = {discord.Status.online: '<:status_online:728527943827062804> 온라인',\r\n discord.Status.offline: '<:status_offline:728527943831126036> 오프라인',\r\n discord.Status.idle: \"<:status_idle:728527943806091364> 자리비움\",\r\n discord.Status.do_not_disturb: \"<:status_dnd:728527943684456459> 방해금지\"}\r\n user_status = status_dict[user.status]\r\n if not len(user.roles) == 1:\r\n roles = [role for role in user.roles]\r\n embed=discord.Embed(colour=message.author.color, timestamp=message.created_at, title=f\"봇정보 - {user}\")\r\n else:\r\n embed=discord.Embed(colour=0xff00, timestamp=message.created_at, title=f\"봇정보 - {user}\")\r\n embed.set_thumbnail(url=user.avatar_url)\r\n embed.set_footer(text=f\"{message.author}\", icon_url=message.author.avatar_url)\r\n embed.add_field(name=\"봇 아이디\", value=f\"{user.id}\", inline=False)\r\n embed.add_field(name=\"봇 닉네임\", value=f\"{user.display_name}\", inline=False)\r\n embed.add_field(name=\"봇 생성일\", value=f\"{str(date.year)}년 {str(date.month)}월 {str(date.day)}일\", inline=False)\r\n try:\r\n embed.add_field(name=f\"가진 역할들({len(roles)-1}개)\", value=f\" \".join([role.mention for role in roles][1:]), inline=False)\r\n embed.add_field(name=\"가장 높은 역할\", value=f\"{user.top_role.mention}\", inline=False)\r\n except:\r\n embed.add_field(name=f\"가진 역할들\", value=f\"**소유한 역할이 없습니다!**\", inline=False)\r\n embed.add_field(name=\"현재 봇 상태\", value=f\"{user_status}\", inline=False)\r\n embed.add_field(name=\"봇 초대링크 (관리자 권한)\", value=f\"[초대하기](https://discordapp.com/oauth2/authorize?client_id={user.id}&scope=bot&permissions=8)\", inline=False)\r\n await message.channel.send(embed=embed)\r\n\r\n if message.content == f\"{prefix} 서버정보\":\r\n if message.guild.premium_subscription_count == 1:\r\n embed = discord.Embed(colour=0xff00, title=f\"<:boosting0:732546134018621460> {message.guild.name}\", timestamp=message.created_at)\r\n elif message.guild.premium_tier == 1:\r\n embed = discord.Embed(colour=0xff00, title=f\"<:boosting1:732546134542909500> {message.guild.name}\", timestamp=message.created_at)\r\n elif message.guild.premium_tier == 2:\r\n embed = discord.Embed(colour=0xff00, title=f\"<:boosting2:732546134379331584> {message.guild.name}\", timestamp=message.created_at)\r\n elif message.guild.premium_tier == 3:\r\n embed = discord.Embed(colour=0xff00, title=f\"<:boosting3:732546133850587208> {message.guild.name}\", timestamp=message.created_at)\r\n else:\r\n embed = discord.Embed(colour=0xff00, title=f\"{message.guild.name}\", timestamp=message.created_at)\r\n embed.add_field(name=\"서버 이름\", value=message.guild.name, inline=False)\r\n embed.add_field(name=\"서버 ID\", value=message.guild.id, inline=False)\r\n embed.add_field(name=\"서버 주인\", value=f\"{message.guild.owner}\", inline=False)\r\n embed.add_field(name=\"서버 주인 ID\", value=message.guild.owner.id, inline=False)\r\n embed.add_field(name=\"서버 국가\", value=message.guild.region, inline=False)\r\n embed.add_field(name=\"서버 제작일\", value = message.guild.created_at.strftime(\"20%y년 %m월 %d일\"), inline=False)\r\n embed.add_field(name=\"서버 멤버 수\", value = f'전체 유저 : {len(message.guild.members)}명\\n └ 유저 : {len(list(filter(lambda x: not x.bot, message.guild.members)))}명 | 봇 : {len(list(filter(lambda x: x.bot, message.guild.members)))}개', inline=False)\r\n embed.add_field(name=\"서버 채널 수\", value = f'전체 채널 : {len(message.guild.channels)}개\\n └ 채팅채널 : {len(message.guild.text_channels)}개 | 음성채널 : {len(message.guild.voice_channels)}개 | 카테고리 : {len(message.guild.categories)}개', inline=False)\r\n embed.add_field(name=\"서버 이모지 수\", value = f'{len(message.guild.emojis)}개', inline=False)\r\n\r\n if message.guild.afk_channel != None:\r\n embed.add_field(name=f'서버 잠수 채널', value=f'⭕ | 잠수 채널이 존재합니다.({message.guild.afk_channel.name} (타이머: {message.guild.afk_timeout}))', inline=False)\r\n else:\r\n embed.add_field(name=f'서버 잠수 채널', value=f'❌ | 잠수 채널이 존재하지 않습니다.', inline=False)\r\n if message.guild.system_channel != None:\r\n embed.add_field(name=f'서버 시스템 채널', value=f'⭕ | 시스템 채널이 존재합니다.({message.guild.system_channel.name} (<#{message.guild.system_channel.id}>))', inline=False)\r\n else:\r\n embed.add_field(name=f'서버 시스템 채널', value=f'❌ | 시스템 채널이 존재하지 않습니다.', inline=False)\r\n embed.add_field(name=f'서버 부스트 레벨', value=f'Level {message.guild.premium_tier}', inline=False)\r\n embed.add_field(name=f'서버 부스트 개수', value=f'Boost {message.guild.premium_subscription_count}', inline=False)\r\n if message.guild.is_icon_animated() is True:\r\n a = message.guild.icon_url_as(format=\"gif\", size=2048)\r\n elif message.guild.is_icon_animated() is False:\r\n a = message.guild.icon_url_as(format=\"png\", size=2048)\r\n embed.set_thumbnail(url=a)\r\n try:\r\n embed.set_image(url=message.guild.banner_url_as(format='png'))\r\n except:\r\n pass\r\n embed.set_footer(text=f\"{message.author}\", icon_url=message.author.avatar_url)\r\n await message.channel.send(embed=embed)\r\n\r\n if message.content.startswith(f\"{prefix} 킥\"):\r\n if message.guild.get_member(client.user.id).guild_permissions.kick_members == True:\r\n if message.author.guild_permissions.kick_members:\r\n try:\r\n try:\r\n user = message.guild.get_member(int(message.content.split('<@')[1].split('>')[0]))\r\n except:\r\n user = message.guild.get_member(int(message.content.split('<@!')[1].split('>')[0]))\r\n if user.id == message.author.id:\r\n await message.channel.send(\"자신을 킥하는것은 그른 선택이에요!\")\r\n else:\r\n try:\r\n reason = message.content.split('&&')[1]\r\n except:\r\n reason = \"사유 없음\"\r\n await message.guild.kick(user, reason = f\"{reason}\")\r\n await message.channel.send(f\"``{message.author}``에 의해서 ``{user}``를 추방하였습니다.\\n사유 : {reason}\")\r\n try:\r\n await user.send(f\"``{message.author}``에 의해서 ``{user}``를 추방하였습니다.\\n사유 : {reason}\")\r\n except:\r\n pass\r\n except IndexError:\r\n await message.channel.send(\"형식이 틀린거같아요... 형식은 ``시스비 킥 <유저 맨션>&&<사유>``에요!\")\r\n except:\r\n await message.channel.send(\"추방할 사람의 권한이 너무 높거나 그 유저가 서버에 없습니다.\")\r\n else:\r\n await message.channel.send(\"당신은 권한이 없어요!\\n필요 권한 : **``멤버 추방하기``**\")\r\n else:\r\n await message.channel.send(\"제가 킥을 할 수 있는 권한을 가지고 있지 않아요!\\n필요 권한 : **``멤버 추방하기``**\")\r\n\r\n if message.content.startswith(f\"{prefix} 밴\"):\r\n if message.guild.get_member(client.user.id).guild_permissions.ban_members == True:\r\n if message.author.guild_permissions.ban_members:\r\n try:\r\n try:\r\n user = int(message.content.split('<@')[1].split('>')[0])\r\n except:\r\n user = int(message.content.split('<@!')[1].split('>')[0])\r\n print(user)\r\n if user == message.author.id:\r\n await message.channel.send(\"자신을 밴하는것은 그른 선택이에요!\")\r\n else:\r\n try:\r\n reason = message.content.split('&&')[1]\r\n except:\r\n reason = \"사유 없음\"\r\n un = await client.fetch_user(user)\r\n await message.guild.ban(await client.fetch_user(user), reason=f\"{reason}\")\r\n await message.channel.send(f\"``{message.author}``에 의해서 ``{un}``를 차단하였습니다.\\n사유 : {reason}\")\r\n except IndexError:\r\n await message.channel.send(\"형식이 틀린거같아요... 형식은 ``시스비 밴 <유저 맨션>&&<사유>``에요!\")\r\n except Exception as ex:\r\n await message.channel.send(f\"밴할 사람의 권한이 너무 높습니다. {ex}\")\r\n else:\r\n await message.channel.send(\"당신은 권한이 없어요!\\n필요 권한 : **``멤버 차단하기``**\")\r\n else:\r\n await message.channel.send(\"제가 밴을 할 수 있는 권한을 가지고 있지 않아요!\\n필요 권한 : **``멤버 차단하기``**\")\r\n\r\n if message.content.startswith(f\"{prefix} 언밴\"):\r\n if message.guild.get_member(client.user.id).guild_permissions.ban_members:\r\n if message.author.guild_permissions.ban_members:\r\n try:\r\n try:\r\n user = int(message.content.split('<@')[1].split('>')[0])\r\n except:\r\n user = int(message.content.split('<@!')[1].split('>')[0])\r\n print(user)\r\n try:\r\n reason = message.content.split('&&')[1]\r\n except:\r\n reason = \"사유 없음\"\r\n un = await client.fetch_user(user)\r\n await message.guild.unban(await client.fetch_user(user), reason=f\"{reason}\")\r\n await message.channel.send(f\"``{message.author}``에 의해서 ``{un}``를 언밴하였습니다.\\n사유 : {reason}\")\r\n except IndexError:\r\n await message.channel.send(\"형식이 틀린거같아요... 형식은 ``시스비 언밴 <유저 맨션>&&<사유>``에요!\")\r\n except:\r\n await message.channel.send(f\"언밴할 사람의 권한이 너무 높습니다.\")\r\n else:\r\n await message.channel.send(\"당신은 권한이 없어요!\\n필요 권한 : **``멤버 차단하기``**\")\r\n else:\r\n await message.channel.send(\"제가 언밴을 할 수 있는 권한을 가지고 있지 않아요!\\n필요 권한 : **``멤버 차단하기``**\")\r\n\r\n if message.content.startswith(f\"{prefix} 건의\"):\r\n if str(message.content[7:]) == '' or str(message.content[7:]) == ' ':\r\n await message.channel.send(\"건의사항을 입력해주세요.\")\r\n else:\r\n msg = message.content[7:]\r\n await client.get_channel(int(건의)).send(embed = discord.Embed(title=\"건의가 들어왔어요!\", description=msg).set_footer(text=f\"{message.author}의 건의, {message.author.id}\", icon_url=message.author.avatar_url))\r\n await message.channel.send(f\"{message.author.mention}님! 건의가 완료되었습니다!\")\r\n try:\r\n await message.delete()\r\n except:\r\n pass\r\n\r\n if message.content == f\"{prefix} 핑\":\r\n msg = await message.channel.send(f\"**🏓 Pinging...**\")\r\n ping = round(client.latency * 1000)\r\n if ping >= 0 and ping <= 100:\r\n pings = \"매우좋음\"\r\n elif ping >= 101 and ping <= 200:\r\n pings = \"좋음\" \r\n elif ping >= 201 and ping <= 500:\r\n pings = \"보통\"\r\n elif ping >= 501 and ping <= 1000:\r\n pings = \"나쁨\"\r\n elif ping >= 1000:\r\n pings = \"매우나쁨\"\r\n embed = discord.Embed(colour=discord.Colour.red(), title=f\"{client.user.name}의 핑\", description=f\"핑은 {ping}ms입니다!\\n상태는 {pings}이네요!\")\r\n embed.set_footer(text=message.author, icon_url=message.author.avatar_url)\r\n await msg.edit(content=\"**🏓 Pong!**\", embed=embed)\r\n\r\n if message.content.startswith(f\"{prefix} 공지\"):\r\n if message.author.id in owner:\r\n if str(message.content[7:]) == '' or str(message.content[7:]) == ' ':\r\n await message.channel.send(\"메세지를 써라.\")\r\n try:\r\n msg = message.content[7:]\r\n oksv = 0\r\n embed = discord.Embed(\r\n title = msg.split('&&')[0],\r\n description = msg.split('&&')[1] + f\"\\n\\n이 채널에 공지가 오기 싫다면 `봇-공지` 채널을 만들어주세요!\\n[{client.user.name} SUPPORT](https://discord.gg/HWZBBnR)\\n[{client.user.name} 좋아요 누르기](https://koreanbots.dev/bots/726376311710548049)\\n[서비스 이용약관](https://sisby.ga/tos)\\n[개인정보 처리방침](https://sisby.ga/privacy-policy)\",\r\n colour = discord.Colour.blue(),\r\n timestamp = message.created_at\r\n ).set_footer(icon_url=message.author.avatar_url, text=f'{message.author} - 인증됨') .set_thumbnail(url=client.user.avatar_url_as(format=None, static_format=\"png\", size=1024))\r\n except IndexError:\r\n await message.channel.send(f\"형식이 틀렸습니다. ``{prefix} 공지 <제목>&&<내용>``으로 다시 시��해보세요.\")\r\n m = await message.channel.send(\"아래와 같이 공지가 발신됩니다!\", embed=embed)\r\n await m.add_reaction('✅')\r\n await m.add_reaction('❎')\r\n try:\r\n reaction, user = await client.wait_for('reaction_add', timeout = 20, check = lambda reaction, user: user == message.author and str(reaction.emoji) in ['✅', '❎'])\r\n except asyncio.TimeoutError:\r\n await m.edit(content=\"시간이 초과되었습니다.\", embed=None)\r\n else:\r\n if str(reaction.emoji) == \"❎\":\r\n await m.edit(content=\"공지 발신이 취소되었습니다.\", embed=None)\r\n elif str(reaction.emoji) == \"✅\":\r\n await m.edit(content=\" 발신중입니다...\", embed=None)\r\n for i in client.guilds:\r\n arr = [0]\r\n alla = False\r\n flag = True\r\n z = 0\r\n for j in i.channels:\r\n arr.append(j.id)\r\n z+=1\r\n if \"시스비-봇-공지\" in j.name or\"봇-공지\" in j.name or \"봇_공지\" in j.name or \"봇공지\" in j.name or \"bot_announcement\" in j.name or \"봇ㆍ공지\" in j.name:\r\n if str(j.type)=='text':\r\n try:\r\n oksv += 1\r\n await j.send(embed=embed)\r\n alla = True\r\n except:\r\n pass\r\n break\r\n if alla==False:\r\n try:\r\n chan=i.channels[1]\r\n except:\r\n pass\r\n if str(chan.type)=='text':\r\n try:\r\n oksv += 1\r\n await chan.send(embed=embed)\r\n except:\r\n pass\r\n await m.edit(content=f\"**`📢 공지 발신 완료 📢`**\\n\\n{len(client.guilds)}개의 서버 중 {oksv}개의 서버에 발신 완료, {len(client.guilds) - oksv}개의 서버에 발신 실패\")\r\n else:\r\n await message.channel.send('이 명령어를 쓰려면 최소 Bot Developer 권한이 필요합니다.')\r\n\r\n if message.content == f\"{prefix} 초대\":\r\n Data = await Bot.getBot(client.user.id)\r\n embed = discord.Embed(title=f\"{client.user.name} 봇 초대하기\", description=f\"[봇 초대하기](https://discord.com/oauth2/authorize?client_id=726376311710548049&permissions=70641734&scope=bot)\\n[KOREANBOTS](https://koreanbots.dev/bots/726376311710548049) {Data.votes} ❤\")\r\n await message.channel.send(embed=embed)\r\n\r\n if message.content.startswith(f\"{prefix} 청소\"):\r\n if message.guild.get_member(client.user.id).guild_permissions.manage_messages:\r\n if message.author.guild_permissions.manage_messages:\r\n try:\r\n number = message.content.split(' ')[2]\r\n print(number)\r\n await message.delete()\r\n await message.channel.purge(limit = int(number))\r\n embed = discord.Embed(title=\"채팅 청소 완료!\", description=f\"{int(number)}개의 메세지를 삭제했어요!\\n\\n||~~모조리 싹다 갈아엎어 주세요~~||\")\r\n embed.set_footer(text=message.author, icon_url=message.author.avatar_url)\r\n msg = await message.channel.send(embed=embed)\r\n await asyncio.sleep(5)\r\n await msg.delete()\r\n except IndexError:\r\n await message.channel.send(\"형식이 틀린거같아요... 형식은 ``시스비 청소 <삭제할 메세지 개수>``에요!\")\r\n else:\r\n await message.channel.send(\"당신은 권한이 없어요!\\n필요 권한 : **``메세지 관리하기``**\")\r\n else:\r\n await message.channel.send(\"제가 청소를 할 수 있는 권한을 가지고 있지 않아요!\\n필요 권한 : **``메세지 관리하기``**\")\r\n\r\n if message.content.startswith(f\"{prefix} 핑퐁\"):\r\n msg = message.content[7:]\r\n header = {\r\n 'Authorization': pingpongauth,\r\n 'Content-Type': 'application/json'\r\n }\r\n param = {\r\n 'request': {\r\n 'query': msg\r\n }\r\n }\r\n async with aiohttp.ClientSession(headers=header) as session:\r\n async with session.post(pingpongurl+f'/{message.author.id}', json=param) as res:\r\n data = await res.json()\r\n assert 'response' in data\r\n assert 'replies' in data['response']\r\n for reply in data['response']['replies']:\r\n if 'text' in reply:\r\n await message.channel.send(reply['text'])\r\n\r\n if message.content == f\"{prefix} 봇정보\":\r\n date = datetime.datetime.utcfromtimestamp(((int(client.user.id) >> 22) + 1420070400000) / 1000)\r\n embed = discord.Embed(title=f\"{client.user.name}\", colour=discord.Colour.green())\r\n embed.add_field(name=\"🔧 개발자\", value=client.get_user(726350177601978438), inline=False)\r\n embed.add_field(name=\"🎂 생일\", value=f\"{date.year}년 {date.month}월 {date.day}일\", inline=False)\r\n embed.add_field(name=\"<:dpy:735379231042961450> Discord.py 버전\", value=discord.__version__, inline=False)\r\n embed.add_field(name=\"👥 사용하는 서버 수 / 유저\", value=f\"{len(client.guilds)}개의 서버 / {len(client.users)}명의 유저\", inline=False)\r\n await message.channel.send(embed=embed)\r\n\r\n if message.content.startswith(f\"{prefix} 컴파일\"):\r\n if message.author.id in owner:\r\n try:\r\n prefix_count=len(prefix)+5\r\n cmd=message.content[prefix_count:]\r\n fn_name = \"_eval_expr\"\r\n cmd = cmd.strip(\"` \")\r\n # add a layer of indentation\r\n cmd = \"\\n\".join(f\" {i}\" for i in cmd.splitlines())\r\n # wrap in async def body\r\n body = f\"async def {fn_name}():\\n{cmd}\"\r\n parsed = ast.parse(body)\r\n body = parsed.body[0].body\r\n insert_returns(body)\r\n env = {\r\n 'client': client,\r\n 'discord': discord,\r\n 'message': message,\r\n '__import__': __import__\r\n }\r\n exec(compile(parsed, filename=\"\", mode=\"exec\"), env)\r\n result = (await eval(f\"{fn_name}()\", env))\r\n embed=discord.Embed(title=\"EVAL\", colour=discord.Colour.green())\r\n embed.add_field(name=\"📥 Input 📥\", value=f\"{cmd}\",inline=False)\r\n embed.add_field(name=\"📤 Output 📤\", value=f\"{result}\",inline=False)\r\n embed.add_field(name=\"🔧 Type 🔧\",value=f\"{type(result)}\",inline=False)\r\n embed.add_field(name=\"🏓 Latency 🏓\",value=str((datetime.datetime.now()-message.created_at)*1000).split(\":\")[2],inline=False)\r\n await message.channel.send(embed=embed)\r\n except Exception as e:\r\n await message.channel.send(e)\r\n else:\r\n await message.channel.send('이 명령어를 쓰려면 최소 Bot Developer 권한이 필요합니다.')\r\n\r\n if message.content.startswith(f\"{prefix} 건답\"):\r\n if message.author.id in owner:\r\n msg = message.content[7:]\r\n user = msg.split('&&')[0]\r\n description = msg.split('&&')[1]\r\n try:\r\n await client.get_user(int(user)).send(f\"{description}\\n\\n발신인 : {message.author}\")\r\n await message.channel.send(f\"{client.get_user(int(user))}님께 답변을 완료했어요!\")\r\n except Exception as ex:\r\n await message.channel.send(f\"오류가 발생했어요! 아마도 DM을 못보내서 오류난거같은데 확인해보세요!\\n오류 : {ex}\")\r\n else:\r\n await message.channel.send('이 명령어를 쓰려면 최소 Bot Developer 권한이 필요합니다.')\r\n\r\n if message.content == f\"{prefix} 뱃지\" or message.content == f\"{prefix} 배지\":\r\n a = random.choice([discord.Colour.red(), discord.Colour.orange(), discord.Colour.green(), discord.Colour.blue(), discord.Colour.purple()])\r\n await message.channel.send(embed=discord.Embed(colour=a, title=f\"{client.user.name} 뱃지\", description=f\"\"\"\r\n현재 존재하는 Sisby의 뱃지들이에요!\r\n\r\n<:dev:715085684905345064> Sisby Developer (Sisby 봇 개발자 전용 뱃지) - 현재 {len(owner)}명이 가지고 있어요!\r\n<:heimteam:730330765212254251> Team Heim (Team Heim 팀원 전용 뱃지) - 현재 {len(teamcomma)}명이 가지고 있어요!\r\n<:bughunter:730322955212423269> Sisby Bug Hunter (Sisby 버그헌터 전용 뱃지) - 현재 {len(bughunter)}명이 가지고 있어요!\r\n<:happytree:730335761164927006> Happytree Special Badge (해피트리 스폐셜 뱃지) - 현재 {len(happytree)}명이 가지고 있어요!\r\n\"\"\"))\r\n\r\n if message.content.startswith(f\"{prefix} 메일\"):\r\n msg = message.content[7:]\r\n msg1 = msg.split(\"&&\")\r\n tomail = msg1[0]\r\n title = msg1[1]\r\n description = msg1[2]\r\n a = random.choice([discord.Colour.red(), discord.Colour.orange(), discord.Colour.green(), discord.Colour.blue(), discord.Colour.purple()])\r\n embed = discord.Embed(colour=a, title=f\"이메일 제목 : {title}\", description=f\"이메일 내용 : {description}\")\r\n m = await message.channel.send(f\"아래와 같이 메일을 전송할까요?\", embed=embed)\r\n await m.add_reaction('✅')\r\n await m.add_reaction('❎')\r\n try:\r\n reaction, user = await client.wait_for('reaction_add', timeout = 20, check = lambda reaction, user: user == message.author and str(reaction.emoji) in ['✅', '❎'])\r\n except asyncio.TimeoutError:\r\n await m.edit(content=\"시간이 초과되었습니다.\", embed=None)\r\n else:\r\n if str(reaction.emoji) == \"❎\":\r\n await m.edit(content=\"메일 발신이 취소되었습니다.\", embed=None)\r\n elif str(reaction.emoji) == \"✅\":\r\n await m.edit(content=f\" 메일 전송중...\", embed=None)\r\n s = smtplib.SMTP('smtp.gmail.com', 587)\r\n s.starttls()\r\n s.login('sisbybot@gmail.com', os.getenv(\"MAIL_PW\"))\r\n msg = MIMEText(description + f'\\n\\nDiscord 유저 {message.author}({message.author.id})님의 이메일입니다.')\r\n msg['Subject'] = title\r\n s.sendmail(\"sisbybot@gmail.com\", tomail, msg.as_string())\r\n s.quit()\r\n await m.edit(content=f\" 메일 전송을 완료하였습니다.\", embed=None)\r\n\r\n except Exception as ex:\r\n await client.get_channel(int(bug)).send(embed = discord.Embed(title=\"버그가 발생하였습니다.\", description=ex).set_footer(text=message.author, icon_url=message.author.avatar_url))\r\n await message.channel.send(f\"오류가 발생하였습니다.\\n오류 내용 : {ex}\")\r\n\r\nasync def my_background_task():\r\n await client.wait_until_ready()\r\n while not client.is_closed():\r\n await client.change_presence(status=discord.Status.online, activity=discord.Game(name=f\"{prefix} 도움말 | 버전 {ver}\"))\r\n await asyncio.sleep(10)\r\n await client.change_presence(status=discord.Status.online, activity=discord.Game(name=f\"{prefix} 도움말 | {len(client.guilds)}개의 서버\"))\r\n await asyncio.sleep(10)\r\n await client.change_presence(status=discord.Status.online, activity=discord.Game(name=f\"{prefix} 도움말 | {len(client.users)}명의 유저\"))\r\n await asyncio.sleep(10)\r\n Data = await Bot.getBot(client.user.id)\r\n await client.change_presence(status=discord.Status.online, activity=discord.Game(name=f\"{prefix} 도움말 | {Data.votes}개의 Koreanbots 하트\"))\r\n await asyncio.sleep(10)\r\nclient.loop.create_task(my_background_task())\r\n\r\nclient.run(token)\r\n","sub_path":"index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":46438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"489990831","text":"#coding = utf-8\n'''\n[hyhong]\n2018-4-21\n'''\n\nimport os\nimport shutil\nfrom keras.models import load_model\nfrom keras.utils import np_utils\nfrom keras.preprocessing import sequence\nimport numpy as np\nfrom sklearn.metrics import accuracy_score\nimport plan\n\n#log设置,只显示 warning 和 Error \nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\nmaxlen = 20\nlen_wv = 400\n\nclass modelUtils():\n\n def __init__(self, _path, text_path, result_path, index, kb_number):\n '''\n _path:数据基本路径:data/smp2018/10flod_all_3600+_未转阿拉伯/\n text_path:文本数据的基本路径:data/smp2018/10fold_all_text_without_lable_3600+_未转阿拉伯/\n result_path:结果文件基本路径+方案名:result/version_0.1/\n index:随机数\n kb_number:知识表类别数(知识表个数)\n '''\n self._path = _path\n self.text_path = text_path\n self.result_path = result_path\n self.index = index\n self.kb_number = kb_number\n self.kd_table,self.kb_dim = self.table_index('./data/smp2018/artificial_kb.txt')\n self.make_file()\n\n def make_file(self):\n filelist = ['model_best', 'model_all', 'model_group', 'test_prediction', 'dev_prediction', 'acc_folder', 'other']\n\n if os.path.exists(os.path.join(os.path.abspath('.'), self.result_path)) == False:\n os.mkdir(os.path.join(os.path.abspath('.'), self.result_path))\n\n for x in filelist:\n if os.path.exists(os.path.join(os.path.abspath('.'), self.result_path + x)) == False:\n os.mkdir(os.path.join(os.path.abspath('.'), self.result_path + x))\n\n def fetch_best(self):\n '''\n 挑出每折中最优的模型,放到model_best/文件夹\n '''\n path_1 = self.result_path + \"model_best/\"\n path_2 = self.result_path + 'model_all/'\n\n files = [x for x in sorted(os.listdir(path_2))]\n temp = files[0][0:6]\n for single_file in files:\n if str(temp) != single_file[0:6]:\n # print(temp_file)\n shutil.copyfile(path_2 + temp_file, path_1 + temp_file)\n temp_file = single_file\n temp = single_file[0:6]\n shutil.copyfile(path_2 + temp_file, path_1 + temp_file)\n\n def model_to_folder(self):\n '''\n 把model_best中的十折最优按参数组合一单独文件夹的形式,划分到文件夹cross_val_case/model/中\n shutil:操作文件的一个文件函数模块\n '''\n path_1 = self.result_path + \"model_best/\"\n path_2 = self.result_path + 'model_group/' + str(self.index)\n\n files = [x for x in sorted(os.listdir(path_1))]\n if os.path.exists(os.path.join(os.path.abspath('.'), path_2)) == False:\n os.mkdir(os.path.join(os.path.abspath('.'), path_2))\n \n for single_file in files:\n if str(self.index) in single_file:\n shutil.copyfile(path_1 + single_file, path_2 + '/' + single_file)\n\n def get_models(self):\n '''\n 获取指定index对应的模型\n '''\n models = list()\n _path = self.result_path + 'model_group/' + str(self.index) + '/'\n m_files = sorted(os.listdir(_path))\n for name in m_files:\n m_path = _path + name\n models.append(load_model(m_path))\n return models\n\n\n def save_dev_class(self):\n '''\n 输出验证集的预测结果到文件中\n '''\n models = self.get_models()\n for i in range(0, 10):\n dev_x_path = self._path + 'dev_x' + str(i) + '.npy'\n dev_y_path = self._path + 'dev_y' + str(i) + '.npy'\n dev_x_tmp = np.load(dev_x_path)\n dev_y = np.load(dev_y_path)\n dev_x = sequence.pad_sequences(dev_x_tmp, maxlen=maxlen, dtype=\"float64\")\n dev_x = dev_x.reshape((len(dev_x), maxlen, len_wv))\n\n dev_x_text = list(open(self.text_path + str(i) + '_test.txt', 'r', encoding = 'utf-8'))\n dev_x_430 = self.add_dimention(dev_x_text, dev_x, i)\n\n prediction = models[i].predict_classes(dev_x_430, batch_size = 25)\n outer = open(self.result_path + 'dev_prediction/result_' + str(self.index) + '.csv', 'a')\n for j in range(0, len(prediction)):\n outer.write(self.to_label(dev_y[j]) + ',' + self.to_label(prediction[j]) + '\\n')\n print(str(dev_y[j]) + ',' + str(prediction[j]) + '\\n')\n outer.close()\n\n def valid_acc_class(self):\n '''\n 计算交叉验证的acc\n '''\n self.fetch_best()\n self.model_to_folder()\n self.save_dev_class()\n files = [f for f in sorted(os.listdir(self.result_path + 'model_group/' + str(self.index)))]\n total = 0\n #print(str(files))\n for f in files:\n total += float(f[-11:-5])\n # total += float(f[-9:-5])\n accuracy = total / 10\n return accuracy\n\n def test_acc_class(self):\n '''\n 获取测试集的acc和将预测结果写入文件\n '''\n models = self.get_models()\n t_x_path = self._path + 'test_x.npy'\n t_y_path = self._path + 'test_y.npy'\n test_x = np.load(t_x_path)\n test_y = np.load(t_y_path)\n temp_y = np_utils.to_categorical(test_y,31)\n _y_predict = np.zeros((len(temp_y[:,0]),len(temp_y[0,:])))\n test_x = sequence.pad_sequences(test_x, maxlen=maxlen, dtype=\"float64\")\n test_x = test_x.reshape((len(test_x), maxlen, len_wv))\n\n test_x_text = list(open(self.text_path + 'test_4528.txt', 'r', encoding = 'utf-8'))\n test_x_430 = self.add_dimention(test_x_text, test_x, 100)\n\n count = 0\n total = len(test_y)\n\n for model in models:\n y_predict = model.predict_classes(test_x_430)\n temp = np_utils.to_categorical(y_predict,31)\n _y_predict += temp\n \n y_result = np.zeros(len(_y_predict),dtype = 'uint8')\n output = open(self.result_path + 'test_prediction/result_' + str(self.index) + '.csv', 'a')\n output.write('正确值,预测值\\n')\n for i in range(0, len(_y_predict)):\n temp = 0\n for j in range (0, 31):\n #print('processing is ' + str(i) + ' row ' + str(j) +' column\\n')\n if(_y_predict[i,j] > temp):\n temp = _y_predict[i,j]\n flag = j\n y_result[i] = flag\n output.write(self.to_label(test_y[i]) + ',' + self.to_label(y_result[i]) + '\\n')\n if str(test_y[i]) == str(y_result[i]):\n count += 1\n print(str(test_y[i]) + ',' + str(y_result[i]) + '\\n')\n # accuracy = accuracy_score(test_y, y_result, normalize = 'true')\n accuracy = float(count / total)\n return accuracy\n\n def table_index(self, path):\n '''\n 使用人工标注知识表\n '''\n table_list = {\n 'app':0,\n 'cinemas':1,\n 'datetime':2,\n 'health':3,\n 'lottery':4,\n 'match':5,\n 'music':6,\n 'singer':7,\n 'novel':8,\n 'author':9,\n 'poetry':10,\n 'poet':11,\n 'verse':12,\n 'radio':13,\n 'stock':14,\n 'tvchannel':15,\n 'video':16,\n 'actor':17,\n 'website':18\n # 'email':19,\n # 'riddle':20,\n # 'message':21,\n # 'flight':22\n }\n table_dict = {}\n fo = open(path, 'r', encoding='utf-8')\n textlist = fo.readlines()\n for i in textlist:\n i = i.split('#')\n table_dict.setdefault(i[1].replace('\\n',''), []).append(i[0])\n fo.close()\n return table_dict,table_list\n\n def longest_string(self, word_arr, kb_arr):\n '''\n 整理匹配到的知识,并做最长串处理\n '''\n word_set = list(set(word_arr))\n d_arr = []\n kb_dict = {}\n word_set.sort(key=lambda x: len(x))\n for i in range(0, len(word_set) - 1):\n for j in range(i + 1, len(word_set)):\n if word_set[i] in word_set[j]:\n d_arr.append(word_set[i])\n break\n # print(str(word_set) + '-------' + str(d_arr) + '----------' + str(kb_arr))\n tmp = kb_arr[:]\n for u in d_arr:\n for t in kb_arr:\n if u == t.split('#')[0]:\n tmp.remove(t)\n for i in tmp:\n i = i.split('#')\n kb_dict.setdefault(i[1], []).append(i[0])\n return kb_dict\n\n def add_dimention(self, sentenceList, embeding, flag):\n '''\n 扩展400维,增加知识维度,知识维度大小=知识类别个数\n '''\n new_x = []\n zero_vector = np.zeros(self.kb_number)\n\n for i in range(0, len(sentenceList)):\n row = []\n word_arr = []\n kb_arr = []\n kb_dict = dict()\n for key in self.kd_table.keys():\n for value in self.kd_table[key]:\n value = value.replace('\\n', '')\n if value in sentenceList[i].lower(): \n word_arr.append(str(value))\n kb_arr.append(str(value) + '#' + str(key))\n kb_dict = self.longest_string(word_arr, kb_arr)\n\n # ff = open('s_vector_word.txt', 'a', encoding = 'utf-8')\n # ff.write(str(sentenceList[i].replace('\\n','')) + '&' + str(word) + '\\n')\n # ff.close()\n if len(kb_dict) > 0:\n s_vector = plan.plan_0x_2(sentenceList[i], kb_dict, self.kb_dim, self.kb_number)\n else:\n s_vector = np.zeros(self.kb_number)\n\n # if flag == 100:\n # ffo = open('kb_dict_test.txt', 'a', encoding = 'utf-8')\n # ffo.write(str(sentenceList[i].replace('\\n','')) + ',' + str(kb_dict) + ',' + str(s_vector) + '\\n')\n # ffo.close()\n for j in range(0, 19):\n row.append(np.r_[embeding[i][j],zero_vector])\n row.append(np.r_[embeding[i][-1],s_vector])\n new_x.append(row)\n new_x = np.array(new_x)\n return new_x\n\n def to_label(self,value):\n '''\n 用于转化输出结果\n '''\n label_list = {\n 0:'app',\n 1:'bus',\n 2:'calc',\n 3:'chat',\n 4:'cinemas',\n 5:'contacts',\n 6:'cookbook',\n 7:'datetime',\n 8:'email',\n 9:'epg',\n 10:'flight',\n 11:'health',\n 12:'lottery',\n 13:'map',\n 14:'match',\n 15:'message',\n 16:'music',\n 17:'news',\n 18:'novel',\n 19:'poetry',\n 20:'radio',\n 21:'riddle',\n 22:'schedule',\n 23:'stock',\n 24:'telephone',\n 25:'train',\n 26:'translation',\n 27:'tvchannel',\n 28:'video',\n 29:'weather',\n 30:'website'\n }\n return label_list[int(value)]\n\n\n\n# def table_index(path):\n# table_list = {\n# 'app':0,\n# 'bus':1,\n# 'calc':2,\n# 'cinemas':3,\n# 'contacts':4,\n# 'cookbook':5,\n# 'datetime':6,\n# 'email':7,\n# 'epg':8,\n# 'flight':9,\n# 'health':10,\n# 'lottery':11,\n# 'map':12,\n# 'match':13,\n# 'message':14,\n# 'music':15,\n# 'news':16,\n# 'novel':17,\n# 'poetry':18,\n# 'radio':19,\n# 'riddle':20,\n# 'schedule':21,\n# 'stock':22,\n# 'telephone':23,\n# 'train':24,\n# 'translation':25,\n# 'tvchannel':26,\n# 'video':27,\n# 'weather':28,\n# 'website':29\n# }\n# files = sorted(os.listdir(path))\n# table_dict = {}\n# for i in files:\n# fo = open(path + i, 'r', encoding='utf-8')\n# # print(len(fo.readlines()))\n# table_dict[i.replace('.txt', '')] = fo.readlines()\n# fo.close()\n# return table_dict,table_list\n","sub_path":"Utils.py","file_name":"Utils.py","file_ext":"py","file_size_in_byte":12935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"586769751","text":"def partition(a,left,right):\n pivot = a[right]\n j = left\n for i in range(left,right):\n if a[i] < pivot:\n a[i],a[j] = a[j],a[i]\n j+=1\n a[j],a[right] = a[right],a[j]\n return j\ndef quicksort(a,left,right):\n if right - left <= 0:\n return;\n idx = partition(a,left,right)\n quicksort(a, left, idx-1)\n quicksort(a, idx + 1,right)\n\n\ndef changearr(a):\n a[0] = 100\n\na=[1,2,3,5,4,3,2,1]\nquicksort(a,0,len(a)-1)\nprint(a)\n","sub_path":"quick_sort.py","file_name":"quick_sort.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"426137796","text":"from django.conf.urls import patterns, include, url\nfrom django.contrib.staticfiles.urls import staticfiles_urlpatterns\n\nimport autocomplete_light\n# import every app/autocomplete_light_registry.py\nautocomplete_light.autodiscover()\n\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns(\n '',\n url(r'^$', 'hl.views.show_load_status2', name='show_load_status'),\n # url(r'^blog/', include('blog.urls')),\n\n url(r'^admin/', include(admin.site.urls)),\n url(r'sc/', include('sc.urls')),\n url(r'hl/', include('hl.urls')),\n #url(\n # regex=r'^static/(?P.*)$',\n # view='django.views.static.serve',\n # kwargs={'document_root': settings.STATIC_ROOT,}\n #),\n url(r'^autocomplete/', include('autocomplete_light.urls')),\n (r'^selectable/', include('selectable.urls')),\n (r'^accounts/login/$', 'django.contrib.auth.views.login'),\n)\n\nurlpatterns += staticfiles_urlpatterns()","sub_path":"EOE/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"545743130","text":"# Qi Luo\n# A02274095\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torchvision import datasets, transforms\nimport matplotlib.pyplot as plt\n\nif torch.cuda.is_available():\n device = torch.device('cuda')\nelse:\n device = torch.device('cpu')\n\nbatch_size = 32\n\ntrain_dataset = datasets.MNIST('./data',\n train=True,\n download=True,\n transform=transforms.ToTensor())\n\nvalidation_dataset = datasets.MNIST('./data',\n train=False,\n transform=transforms.ToTensor())\n\ntest_dataset = datasets.MNIST('./data',\n train=False,\n download=True,\n transform=transforms.ToTensor())\n\n\ntrain_loader = torch.utils.data.DataLoader(dataset=train_dataset,\n batch_size=batch_size,\n shuffle=True)\n\nvalidation_loader = torch.utils.data.DataLoader(dataset=validation_dataset,\n batch_size=batch_size,\n shuffle=False)\n\ntest_loader = torch.utils.data.DataLoader(dataset=test_dataset,\n batch_size=batch_size,\n shuffle=True)\n\nclass Net(nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n self.fc1 = nn.Linear(28*28, 100)\n self.relu = nn.ReLU()\n self.fc1_drop = nn.Dropout(0.1)\n self.fc2 = nn.Linear(100, 80)\n self.relu = nn.ReLU()\n self.fc2_drop = nn.Dropout(0.1)\n self.fc3 = nn.Linear(80, 10)\n\n def forward(self, x):\n x = x.view(-1, 28*28)\n x = F.relu(self.fc1(x))\n x = self.fc1_drop(x)\n x = F.relu(self.fc2(x))\n x = self.fc2_drop(x)\n return F.softmax(self.fc3(x), dim=1)\n\n\ndef train():\n model.train()\n cost = 0\n for batch_idx, (data, target) in enumerate(train_loader):\n optimizer.zero_grad()\n output = model(data)\n loss = criterion(output, target)\n cost += loss.data.item()\n loss.backward()\n optimizer.step()\n cost /= len(train_loader)\n return cost\n\n\ndef validate():\n model.eval()\n val_loss, correct = 0, 0\n for data, target in validation_loader:\n data = data.to(device)\n target = target.to(device)\n output = model(data)\n val_loss += criterion(output, target).data.item()\n pred = output.data.max(1)[1]\n correct += pred.eq(target.data).cpu().sum()\n\n val_loss /= len(validation_loader)\n # print(val_loss)\n\n accuracy = 100. * correct.to(torch.float32) / len(validation_loader.dataset)\n\n print('Accuracy: {}/{} ({:.2f}%)\\n'.format(correct, len(validation_loader.dataset), accuracy))\n return accuracy.data.item()\n\n\ndef test():\n model.eval()\n val_loss, correct = 0, 0\n for data, target in test_loader:\n data = data.to(device)\n target = target.to(device)\n output = model(data)\n val_loss += criterion(output, target).data.item()\n pred = output.data.max(1)[1]\n correct += pred.eq(target.data).cpu().sum()\n\n val_loss /= len(test_loader)\n\n accuracy = 100. * correct.to(torch.float32) / len(test_loader.dataset)\n\n print('Accuracy: {}/{} ({:.2f}%)\\n'.format(correct, len(test_loader.dataset), accuracy))\n return accuracy\n\n\nepochs = 50\nbest = 0\nplt.figure()\n\nmodel = Net().to(device)\noptimizer = torch.optim.Adam(model.parameters(), lr=0.0005, weight_decay=0.000000045)\ncriterion = nn.CrossEntropyLoss()\n\ntrain_cost = []\nvali_acc = []\n\nfor epoch in range(1, epochs + 1):\n traincost = train()\n print(\"Train Epoch: {}\".format(epoch))\n acc = validate()\n # if acc > best:\n # torch.save(model.state_dict(), 'SGD_model.ckpt')\n\n # plt.plot(epoch, traincost, 'ro')\n\n train_cost.append(traincost)\n vali_acc.append(acc)\n\nplt.plot(train_cost)\nplt.xticks(range(1, epochs+1))\nplt.show()\n\nprint(train_cost)\nprint(vali_acc)\n","sub_path":"luoq_assignment5/prob3_1.py","file_name":"prob3_1.py","file_ext":"py","file_size_in_byte":4144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"178650167","text":"#https://codeforces.com/problemset/problem/69/A\n\nnr=int(input())\nx=0\ny=0\nz=0\nfor i in range(nr):\n x1,y1,z1=input().split(\" \")\n\n x+=int(x1)\n y+=int(y1)\n z+=int(z1)\nif(x==y and y==z and z==0):\n print(\"YES\")\nelse:\n print(\"NO\")","sub_path":"CodeForces/A. Young Physicist.py","file_name":"A. Young Physicist.py","file_ext":"py","file_size_in_byte":241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"448521374","text":"import acme\nimport numpy as np\nimport pandas as pd\nfrom random import randint\n\ndef products(number_of_products=30):\n \"\"\"products function provides a total of 30 products with random values for the name, price, weight, and flammability fields. For the name attribute, I needed a list of possible name to choose from:\n Will print a list of the product names, the total price of the products, the \n total weight of the products, and the average flammability of the products.\n \"\"\"\n\n # List of names needed for random choice\n adj_list = ['Awesome', 'Shiny', 'Impressive', 'Portable', 'Improved']\n noun_list = ['Anvil', 'Catapult' 'Disguise' 'Mousetrap', '???']\n return [acme.Product(\"{} {}\".format(random.choice(adj_list),\n random.choice(noun_list)),\n random.randint(5, 100), random.randint(5, 100),\n random.uniform(0.0, 2.5)) for i in range(amount)]\n\n# Report function\ndef report(list_of_products):\n product_name = []\n product_price = []\n product_weight = []\n product_flammability = []\n for i in list_of_products:\n product_name.append(i.product_names)\n product_price.append(i.product_prices)\n product_weight.append(i.product_weights)\n product_flammability.append(i.product_flammabilities)\n print('ACME CORPORATION OFFICIAL INVENTORY REPORT')\n print('Unique product names:', len(list(set(product_name))))\n print('Average price:', sum(product_price) / len(product_price))\n print('Average weight:', sum(product_weight) / len(product_weight))\n print('Average flammability:', sum(product_flammability) / len(product_flammability))\n\nif __name__ == '__main__':\n report(list_of_products())\n","sub_path":"acme_report.py","file_name":"acme_report.py","file_ext":"py","file_size_in_byte":1763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"6236633","text":"# 순열\ndef perm_r(k):\n # 재귀를 돌리다가 뽑아야하는 개수에 도달하면\n if k == R:\n print(result)\n # 아직 뽑아야하는 개수에 도달하지 않았다면\n else:\n # 리스트 갯수를 for문 돌면서\n for i in range(N):\n # 방문했는지 여부를 확인하고\n if visit[i] == True:\n continue\n else:\n visit[i] = True\n # result에 값을 넣고\n result[k] = lst[i]\n # 재귀 돌리기\n perm_r(k+1)\n visit[i] = False\n\n# 중복순열\ndef pi_r(k):\n if k == R:\n print(result)\n else:\n for i in range(N):\n result[k] = lst[i]\n pi_r(k+1)\n\n# 리스트 개수\nN = 3\n# 뽑아 내야 하는 개수\nR = 2\n\nresult = [0] * R\nvisit = [False] * N\n\nlst = [3, 2, 4]\n\nprint('순열이닷')\nperm_r(0)\n\nprint('중복순열이닷')\npi_r(0)\n\n","sub_path":"10 알고리즘(직접구현)/순열, 중복순열(직접구현).py","file_name":"순열, 중복순열(직접구현).py","file_ext":"py","file_size_in_byte":956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"8839948","text":"\"\"\"\r\nCreated on Fri Aug 27 15:26:04 2021\r\n\r\n@author: Rutuja\r\n\"\"\"\r\n### Question 1\r\nimport os\r\nos.chdir(r\"C:\\Users\\DELL\\Desktop\\210453083003_Rutuja_Arsule\")\r\n\r\nimport pandas as pd\r\n\r\n\r\ndf = pd.read_csv(\"K:\\set\\Set A/Glass.csv\",sep=\",\")\r\n\r\ndf.head()\r\n\r\ndf.shape\r\n\r\nX = df.iloc[:,:-1]\r\ny = df.iloc[:,-1]\r\n\r\nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis\r\nfrom sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis\r\nfrom sklearn.linear_model import LogisticRegression\r\nfrom sklearn.naive_bayes import GaussianNB\r\nfrom sklearn.model_selection import KFold\r\nfrom sklearn.model_selection import cross_val_score\r\n\r\nlda = LinearDiscriminantAnalysis()\r\nkfold = KFold(n_splits=5, random_state=2021,\r\nshuffle=True)\r\nresults = cross_val_score(lda, X, y, cv=kfold, \r\n scoring='neg_log_loss')\r\nAUCs = results\r\n\r\nprint(AUCs)\r\nprint(\"Mean AUC: %.2f\" % (AUCs.mean()*-1))\r\n\r\n\r\nqda = QuadraticDiscriminantAnalysis()\r\nkfold = KFold(n_splits=5, random_state=2021,\r\n shuffle=True)\r\nresults = cross_val_score(qda, X, y, cv=kfold, \r\n scoring='neg_log_loss')\r\nAUCs = results\r\nprint(AUCs)\r\nprint(\"Mean AUC: %.2f\" % (AUCs.mean()*-1))\r\n\r\nfrom sklearn.ensemble import RandomForestClassifier\r\n\r\nfrom sklearn.model_selection import GridSearchCV\r\nimport numpy as np\r\nparameters = {'max_features': np.arange(1,20)}\r\n\r\nfrom sklearn.model_selection import StratifiedKFold\r\nkfold = StratifiedKFold(n_splits=5, random_state=2021,shuffle=True)\r\n\r\nmodel_rf = RandomForestClassifier(random_state=2021)\r\ncv = GridSearchCV(model_rf, param_grid=parameters,\r\n cv=kfold,scoring='roc_auc_ovr')\r\n\r\ncv.fit( X , y )\r\n\r\nresults_df = pd.DataFrame(cv.cv_results_ )\r\n\r\nprint(cv.best_params_)\r\n\r\nprint(cv.best_score_)\r\n\r\nprint(cv.best_estimator_)\r\n\r\nbest_model = cv.best_estimator_\r\n\r\n##question 2\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\n\r\ndf = pd.read_csv(\"K:\\set\\Set A\\Sacremento.csv\")\r\ndf1=df.drop(['zip'],axis=1)\r\ndum_df = pd.get_dummies(df1, drop_first=True)\r\n\r\n\r\nfrom sklearn.model_selection import train_test_split \r\nfrom sklearn.linear_model import LinearRegression as LR\r\n\r\n\r\n#X = dum_df.iloc[:,:-1]\r\n#y = dum_df.iloc[:,-1]\r\n\r\nX = dum_df.drop('price',axis=1)\r\ny = dum_df['price']\r\nX.shape\r\ny.shape\r\n \r\n#Linear Regression ( K-Fold CV )\r\nfrom sklearn.model_selection import StratifiedKFold\r\nfrom sklearn.model_selection import KFold\r\nfrom sklearn.model_selection import cross_val_score\r\nfrom sklearn.linear_model import LinearRegression\r\nlinreg = LinearRegression()\r\nkfold = KFold(n_splits=5, random_state=2021,\r\n shuffle=True)\r\nresults = cross_val_score(linreg, X, y, cv=kfold, scoring='r2')\r\nprint(results)\r\nprint(\"r2: %.4f (%.4f)\" % (results.mean(), results.std()))\r\n\r\n\r\n#**********\r\n#b•\tX G Boost ( tune with few parameter sets )\r\n\r\nlr_range = [0.001,0.01,0.2,0.5,0.6,1]\r\nn_est_range = [30,70,100,120,150]\r\ndepth_range = [3,4,5,6,7,8,9]\r\n\r\n\r\nparameters = dict(learning_rate=lr_range,\r\n n_estimators=n_est_range,\r\n max_depth=depth_range)\r\n\r\n\r\nfrom sklearn.model_selection import KFold\r\nkfolds = KFold(n_splits=5, random_state=2021,shuffle=True)\r\n\r\nfrom sklearn.model_selection import GridSearchCV\r\nfrom xgboost import XGBRegressor\r\nclf = XGBRegressor()\r\ncv = GridSearchCV(clf, param_grid=parameters,\r\n cv=kfold,scoring='r2')\r\n\r\ncv.fit(X,y)\r\ndf_cv = pd.DataFrame(cv.cv_results_)\r\nprint(cv.best_params_)\r\n\r\nprint(cv.best_score_)\r\n#0.6601419778784329\r\n##Questipon 3\r\n\r\nimport numpy as np\r\ndf = pd.read_csv(\"K:\\set\\Set A/USArrests.csv\"\r\n ,index_col=0)\r\n\r\n\r\nfrom sklearn.preprocessing import StandardScaler\r\n# Create scaler: scaler\r\nscaler = StandardScaler()\r\nscaled=scaler.fit_transform(df)\r\n\r\nscaled = pd.DataFrame(scaled,\r\n columns=df.columns,\r\n index=df.index)\r\n\r\n# Import KMeans\r\nfrom sklearn.cluster import KMeans\r\n\r\n\r\nclustNos = [1,2,3,4,5,6,7,8,9,10]\r\nInertia = []\r\n\r\nfor i in clustNos :\r\n model = KMeans(n_clusters=i,random_state=2021)\r\n model.fit(scaled)\r\n Inertia.append(model.inertia_)\r\n \r\n# Import pyplot\r\nimport matplotlib.pyplot as plt\r\n\r\nplt.plot(clustNos, Inertia, '-o')\r\nplt.title(\"Scree Plot\")\r\nplt.xlabel('Number of clusters, k')\r\nplt.ylabel('Inertia')\r\nplt.xticks(clustNos)\r\nplt.show()\r\n\r\n# Create a KMeans instance with clusters: Best k model\r\nmodel = KMeans(n_clusters=2,random_state=2021)\r\n\r\n# Fit model to points\r\nmodel.fit(scaled)\r\n\r\n# Cluster Centroids\r\nprint(model.cluster_centers_)\r\n\r\n#model.n_init\r\n# Determine the cluster labels of new_points: labels\r\nlabels = model.predict(scaled)\r\n\r\n\r\nclusterID = pd.DataFrame({'ClustID':labels},index=df.index)\r\nclusteredData = pd.concat([df,clusterID],\r\n axis='columns')\r\n\r\nclusteredData.groupby('ClustID').mean()\r\nclusteredData.sort_values('ClustID')\r\n\r\n###############PCA#######################################################\r\n\r\nfrom sklearn.decomposition import PCA\r\npca = PCA()\r\nprincipalComponents = pca.fit_transform(scaled)\r\nprint(pca.explained_variance_)\r\nprint(np.sum(pca.explained_variance_))\r\nprint(pca.explained_variance_ratio_) \r\nprint(pca.explained_variance_ratio_ * 70) \r\n \r\nimport matplotlib.pyplot as plt\r\nys = pca.explained_variance_ratio_ * 70\r\nxs = np.arange(1,5)\r\nplt.plot(xs,ys)\r\nplt.show()\r\n\r\n\r\n# principalComponents are PCA scores\r\n\r\ndf_plot = pd.DataFrame(principalComponents,\r\n columns = ['PC1', 'PC2','PC3','PC4'],\r\n index = df.index)\r\n\r\npca_loadings = pd.DataFrame(pca.components_.T, index=df.columns, columns=['V1', 'V2','V3','V4'] )\r\npca_loadings\r\n\r\n\r\n#biplot\r\nimport seaborn as sns\r\n \r\n# Scatter plot based and assigne color based on 'label - y'\r\nsns.lmplot('PC1', 'PC2', data=df_plot, fit_reg = False, size = 15, scatter_kws={\"s\": 100})\r\n \r\n# set the maximum variance of the first two PCs\r\n# this will be the end point of the arrow of each *original features*\r\nxvector = pca.components_[0]\r\nyvector = pca.components_[1]\r\n \r\n# value of the first two PCs, set the x, y axis boundary\r\nxs = df_plot['PC1']\r\nys = df_plot['PC2']\r\n \r\n## visualize projections\r\n \r\n## Note: scale values for arrows and text are a bit inelegant as of now,\r\n## so feel free to play around with them\r\nfor i in range(len(xvector)):\r\n # arrows project features (ie columns from csv) as vectors onto PC axes\r\n # we can adjust length and the size of the arrow\r\n plt.arrow(0, 0, xvector[i]*max(xs), yvector[i]*max(ys),\r\n color='r', width=0.005, head_width=0.05)\r\n plt.text(xvector[i]*max(xs)*1.1, yvector[i]*max(ys)*1.1,\r\n list(df.columns.values)[i], color='r')\r\n \r\nfor i in range(len(xs)):\r\n plt.text(xs[i]*1.08, ys[i]*1.08, list(df.index)[i], color='b') # index number of each observations\r\nplt.title('PCA Plot of first PCs')\r\nplt.show()\r\n\r\n\r\n## Question 4.\r\n\r\ndf = pd.read_csv(\"K:\\set\\Set A/WGEM-IND_CPTOTNSXN.csv\")\r\ndf.head()\r\n\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nfrom math import sqrt\r\nfrom sklearn.metrics import mean_squared_error\r\n\r\n\r\ndf.plot.line(x = 'Date',y = 'Value')\r\nplt.show()\r\n\r\nfrom statsmodels.graphics.tsaplots import plot_acf\r\nplot_acf(df['Value'], lags=10)\r\nplt.show()\r\n\r\nfrom statsmodels.graphics.tsaplots import plot_pacf\r\nplot_pacf(df['Value'], lags=12)\r\nplt.show()\r\n\r\ny = df['Value']\r\ny_train = y[:25]\r\ny_test = y[25:]\r\n\r\n\r\nfrom pmdarima.arima import auto_arima\r\nmodel = auto_arima(y_train, trace=True,\r\n error_action='ignore', \r\n suppress_warnings=True)\r\n\r\nfrom statsmodels.tsa.ar_model import AR\r\n# train autoregression\r\nmodel = AR(y_train)\r\nmodel_fit = model.fit(maxlag=15)\r\nprint('Lag: %s' % model_fit.k_ar)\r\nprint('Coefficients: %s' % model_fit.params)\r\n# make predictions\r\npredictions = model_fit.predict(start=len(y_train), \r\n end=len(y_train)+len(y_test)-1, \r\n dynamic=False)\r\n \r\nerror = mean_squared_error(y_test, predictions)\r\nprint('Test RMSE: %.3f' % sqrt(error))\r\n# plot results\r\nplt.plot(y_test)\r\nplt.plot(predictions, color='red')\r\nplt.show()\r\n\r\n# plot\r\ny_train.plot(color=\"blue\")\r\ny_test.plot(color=\"pink\")\r\npredictions.plot(color=\"purple\")\r\n\r\nrms = sqrt(mean_squared_error(y_test, predictions))\r\nprint('Test RMSE: %.3f' % rms)\r\n\r\n########################## MA ##############################\r\nfrom statsmodels.tsa.arima_model import ARMA\r\n\r\n# train MA\r\nmodel = ARMA(y_train,order=(0,1))\r\nmodel_fit = model.fit()\r\nprint('Lag: %s' % model_fit.k_ar)\r\nprint('Coefficients: %s' % model_fit.params)\r\n# make predictions\r\npredictions = model_fit.predict(start=len(y_train), \r\n end=len(y_train)+len(y_test)-1, \r\n dynamic=False)\r\n \r\nerror = mean_squared_error(y_test, predictions)\r\nprint('Test RMSE: %.3f' % sqrt(error))\r\n# plot results\r\nplt.plot(y_test)\r\nplt.plot(predictions, color='red')\r\nplt.show()\r\n\r\n# plot\r\ny_train.plot(color=\"blue\")\r\ny_test.plot(color=\"pink\")\r\npredictions.plot(color=\"purple\")\r\n\r\nrms = sqrt(mean_squared_error(y_test, predictions))\r\nprint('Test RMSE: %.3f' % rms)\r\n\r\n########################## ARMA ##############################\r\nfrom statsmodels.tsa.arima_model import ARMA\r\n\r\n# train ARMA\r\nmodel = ARMA(y_train,order=(7,0))\r\nmodel_fit = model.fit()\r\nprint('Lag: %s' % model_fit.k_ar)\r\nprint('Coefficients: %s' % model_fit.params)\r\n# make predictions\r\npredictions = model_fit.predict(start=len(y_train), \r\n end=len(y_train)+len(y_test)-1, \r\n dynamic=False)\r\n \r\nerror = mean_squared_error(y_test, predictions)\r\nprint('Test RMSE: %.3f' % sqrt(error))\r\n# plot results\r\nplt.plot(y_test)\r\nplt.plot(predictions, color='red')\r\nplt.show()\r\n\r\n# plot\r\ny_train.plot(color=\"blue\")\r\ny_test.plot(color=\"pink\")\r\npredictions.plot(color=\"purple\")\r\n\r\nrms = sqrt(mean_squared_error(y_test, predictions))\r\nprint('Test RMSE: %.3f' % rms)\r\n\r\n################# ARIMA ####################################\r\n\r\n##\r\n\r\ntrain_set = data2.iloc[0:31:, :1].values\r\nsc = MinMaxScaler(feature_range = (0, 1))\r\ntraining_set_scaled = sc.fit_transform(train_set)\r\n\r\nfor i in range(11, 30):\r\n X_train.append(training_set_scaled[i-11:i, 0])\r\n y_train.append(training_set_scaled[i, 0]) \r\nX_train, y_train = np.array(X_train), np.array(y_train)\r\nX_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1))\r\n\r\n\r\n#Defining the LSTM Recurrent Model\r\nregressor = Sequential()\r\nregressor.add(LSTM(units = 50, return_sequences = True, input_shape = (X_train.shape[1], 1)))\r\nregressor.add(Dropout(0.2))\r\nregressor.add(LSTM(units = 50, return_sequences = True))\r\nregressor.add(Dropout(0.2))\r\nregressor.add(LSTM(units = 50, return_sequences = True))\r\nregressor.add(Dropout(0.2))\r\nregressor.add(LSTM(units = 50))\r\nregressor.add(Dropout(0.2))\r\nregressor.add(Dense(units = 1))\r\n\r\n\r\n#Compiling and fitting the model\r\nregressor.compile(optimizer = 'adam', loss = 'mean_squared_error')\r\nregressor.fit(X_train, y_train, epochs = 15, batch_size = 32)","sub_path":"Examsolution (1).py","file_name":"Examsolution (1).py","file_ext":"py","file_size_in_byte":11020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"611607644","text":"#!/usr/bin/python3\nimport tkinter\nimport csv\nimport subprocess\nimport shlex\n\ntop = tkinter.Tk()\ncurrent_record = 1\ntemp_new_record = []\n\ndecisionTreeExec = \"../decisionTree/decisionTree\"\nneuralNetExec = \"../neuralNetwork/neural-network\"\n\nweightsFileName = \"../example-data/EachLetter100-Bool-a-weights2.csv\"\n#inputFileName = \"../example-data/EachLetter100-Bool-a.csv\"\ninputFileName = \"../example-data/bigDataCleaned.csv\"\ntest_file_name = \"../example-data/testOutput.csv\"\ntop.checkboxVariable = tkinter.IntVar()\ntop.textboxVariable = tkinter.StringVar()\ntop.labelnnVariable = tkinter.StringVar()\ntop.labeldtVariable = tkinter.StringVar()\ntop.buttonDown = False\n\ndef goToRecord(cur):\n\tif cur < 1:\n\t\tcur = 1\n\telif cur >= len(handwriting_csv):\n\t\tcur = len(handwriting_csv) - 1\n\tfor i in range(128):\n\t\tif handwriting_csv[cur][i] == '1':\n\t\t\tC[i][\"background\"] = \"black\"\n\t\telse:\n\t\t\tC[i][\"background\"] = \"white\"\n\ttop.checkboxVariable.set(int(handwriting_csv[cur][-1]))\n\ttop.textboxVariable.set(str(cur))\n\treturn cur\n\t\ndef goToTextBox():\n\tglobal current_record\n\ttry:\n\t\tvalue = int(top.textboxVariable.get())\n\t\tif value < len(handwriting_csv):\n\t\t\tcurrent_record = value\n\t\telse:\n\t\t\tcurrent_record = len(handwriting_csv) - 1\n\t\tcurrent_record = goToRecord(current_record)\n\texcept:\n\t\tprint(\"Invalid number\",top.textboxVariable.get())\n\ndef goToNext():\n\tglobal current_record\n\tcurrent_record = current_record + 1\n\tcurrent_record = goToRecord(current_record)\n\ttestRecord()\n\ndef goToPrev():\n\tglobal current_record\n\tif current_record > 1:\n\t\tcurrent_record = current_record - 1\n\t\tcurrent_record = goToRecord(current_record)\n\t\ttestRecord()\n\ndef createNew():\n\tfor i in range(128):\n\t\tC[i][\"background\"] = \"white\"\n\ndef testRecord():\n\tglobal temp_new_record\n\tglobal test_file_name\n\ttemp_new_record = []\n\tfor i in range(128):\n\t\tif C[i][\"background\"] == \"white\":\n\t\t\ttemp_new_record.append(0)\n\t\telse:\n\t\t\ttemp_new_record.append(1)\n\tcontrol_row = [128,1,1]\n\ttemp_new_record.append(int(top.checkboxVariable.get()))\n\twith open(test_file_name, 'w') as f:\n\t\twriter = csv.writer(f)\n\t\twriter.writerow(control_row)\n\t\twriter.writerow(temp_new_record)\n\tnncmd = neuralNetExec + ' -l 1 -n 10 -f ' + test_file_name + ' -w ' + weightsFileName + ' -m 2'\n\tp1 = subprocess.Popen(shlex.split(nncmd),stdout=subprocess.PIPE)\n\tnnOut = p1.stdout.read().decode('ascii').strip()\n\ttop.labelnnVariable.set(nnOut)\n\t\n\tdtcmd = decisionTreeExec + ' ' + ' '.join(str(x) for x in temp_new_record)\n\tp2 = subprocess.Popen(shlex.split(dtcmd),stdout=subprocess.PIPE)\n\tdtOut = p2.stdout.read().decode('ascii').strip()\n\ttop.labeldtVariable.set(dtOut)\n\ndef unclick(event):\n\ttop.buttonDown = False\n\ndef click(event):\n\ttop.buttonDown = True\n\tback_colr = event.widget[\"background\"]\n\tif (back_colr == \"white\"):\n\t\tevent.widget[\"background\"] = \"black\"\n\telse:\n\t\tevent.widget[\"background\"] = \"white\"\n\ndef entered(event):\n\tif top.buttonDown:\n\t\tback_colr = event.widget[\"background\"]\n\t\tif (back_colr == \"white\"):\n\t\t\tevent.widget[\"background\"] = \"black\"\n\t\telse:\n\t\t\tevent.widget[\"background\"] = \"white\"\n\nwith open(inputFileName,'r') as f:\n\treader = csv.reader(f)\n\thandwriting_csv = list(reader)\n\nleftFrame = tkinter.Frame(top)\nleftFrame.pack(side=tkinter.LEFT)\n\ntextBoxFrame = tkinter.Frame(leftFrame)\ntextBoxFrame.pack(pady=10)\n\ntextBoxLabel = tkinter.Label(textBoxFrame, text=\"Go to record:\")\ntextBoxLabel.pack(side = tkinter.LEFT)\n\ntextBox = tkinter.Entry(textBoxFrame, width = 6, textvariable = top.textboxVariable)\ntextBox.pack(side = tkinter.LEFT)\n\ntextBoxReadButton = tkinter.Button(textBoxFrame, text=\"go\", command = goToTextBox)\ntextBoxReadButton.pack(side=tkinter.LEFT)\n\nC = []\nframes = []\ntop.bind(\"Button-1\", click)\ntop.bind(\"ButtonRelease-1\", unclick)\nfor i in range(16):\n\tframes.append(tkinter.Frame(leftFrame))\n\tframes[i].pack()\n\tfor j in range(8):\n\t\tC.append(tkinter.Canvas(frames[i], bg=\"white\", height=25,width=25))\n\t\tC[i * 8 + j].pack(side=tkinter.LEFT)\n\t\tC[i*8 + j].bind(\"\",click)\n\t\tC[i*8 + j].bind(\"\",unclick)\n\t\t#C[i*8 + j].bind(\"\",entered)\n\nbuttonFrame = tkinter.Frame(leftFrame)\nbuttonFrame.pack(pady=10, padx=10)\n\ncreateNewButton = tkinter.Button(buttonFrame, text=\"new\", command = createNew)\ncreateNewButton.pack(side=tkinter.LEFT)\n\nprevButton = tkinter.Button(buttonFrame, text=\"prev\", command = goToPrev)\nprevButton.pack(side=tkinter.LEFT)\n\nnextButton = tkinter.Button(buttonFrame, text=\"next\", command = goToNext)\nnextButton.pack(side=tkinter.LEFT)\n\ntestButton = tkinter.Button(buttonFrame, text=\"test\", command = testRecord)\ntestButton.pack(side=tkinter.LEFT)\n\npositiveCheckbox = tkinter.Checkbutton(buttonFrame, text=\"correct\", onvalue = 1, offvalue = 0, variable = top.checkboxVariable)\npositiveCheckbox.pack(side=tkinter.LEFT)\n\n#labels that will be updated when programs run\nrightFrame = tkinter.Frame(top)\nrightFrame.pack(side=tkinter.LEFT,padx=(10,30))\n\nlabelFrame = tkinter.Frame(rightFrame)\nlabelFrame.pack(side=tkinter.RIGHT)\n\ntkinter.Label(labelFrame, text = \"Neural net prediction\").pack()\nnnLabel = tkinter.Label(labelFrame, textvariable = top.labelnnVariable)\nnnLabel.pack()\n\ntkinter.Label(labelFrame, text = \"Decision tree prediction\").pack()\ndtLabel = tkinter.Label(labelFrame, textvariable = top.labeldtVariable)\ndtLabel.pack()\n\ngoToRecord(1)\n\ntop.mainloop()\n","sub_path":"CS4342/visualizer/visualizerBigData.py","file_name":"visualizerBigData.py","file_ext":"py","file_size_in_byte":5257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"74533971","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun May 17 00:56:00 2020\r\n\r\n@author: saniyy\r\n\"\"\"\r\n\r\nimport pandas as pd\r\n\r\nimport matplotlib.pyplot as plt\r\n\r\ndf1 = pd.read_excel(\"Koronalı günler 2020.xlsx\")\r\n\r\ndf2 = pd.read_excel(\"Koronasız günler 2018.xlsx\")\r\n\r\n\r\nprint(df1.columns)\r\nprint(df1.info())\r\n\r\nprint(df1.describe())\r\n\r\ndfkoronalırize = df1.drop([\"Tarih\"],axis=1) #Tarih bilgisi df1'den çıkarıldı.\r\ndfkoronasızrize = df2.drop([\"Tarih\"],axis=1) #Tarih bilgisi df2'den çıkarıldı.\r\n\r\ndfkoronalırize.plot(grid=True)\r\nplt.show()\r\n\r\ndfkoronasızrize.plot(grid=True)\r\nplt.show()\r\n\r\nplt.plot(df1[\"PM10 ( µg/m³ )\"],df2[\"PM10 ( µg/m³ )\"])\r\nplt.plot(df1[\"SO2 ( µg/m³ )\"],df2[\"SO2 ( µg/m³ )\"])\r\nplt.plot(df1[\"NO2 ( µg/m³ )\"],df2[\"NO2 ( µg/m³ )\"])\r\nplt.plot(df1[\"NOX ( µg/m³ )\"],df2[\"NOX ( µg/m³ )\"])\r\nplt.plot(df1[\"NO ( µg/m³ )\"],df2[\"NO ( µg/m³ )\"])\r\nplt.plot(df1[\"O3 ( µg/m³ )\"],df2[\"O3 ( µg/m³ )\"])\r\n\r\nplt.xlabel(\"Koronalı Günler\")\r\nplt.ylabel(\"Koronasız Günler\")\r\n\r\n\r\ndef grafik(a,b):\r\n x=df1[a]\r\n y=df2[b]\r\n \r\n\r\n fig, ax = plt.subplots()\r\n\r\n\r\n line1, = ax.plot(x, y, label= a)\r\n line1.set_dashes([2, 2, 10, 2]) \r\n\r\n line2, = ax.plot(x, y - 0.2, dashes=[6, 2], label= b)\r\n\r\n ax.legend()\r\n plt.show()\r\n plt.xlabel(\"Koronalı Günler\")\r\n plt.ylabel(\"Koronasız Günler\")\r\n\r\ngrafik(\"PM10 ( µg/m³ )\",\"PM10 ( µg/m³ )\")\r\ngrafik(\"SO2 ( µg/m³ )\",\"SO2 ( µg/m³ )\")\r\ngrafik(\"NO2 ( µg/m³ )\",\"NO2 ( µg/m³ )\")\r\ngrafik(\"NOX ( µg/m³ )\",\"NOX ( µg/m³ )\")\r\ngrafik(\"NO ( µg/m³ )\",\"NO ( µg/m³ )\")\r\ngrafik(\"O3 ( µg/m³ )\",\"O3 ( µg/m³ )\")\r\n\r\n\r\n#%%\r\n\r\n \r\n# Grafik için gerekli kütüphaneler. Axes3D 3 boyutlu bir grafik için.\r\nfrom matplotlib import pyplot as plt\r\nfrom mpl_toolkits.mplot3d import Axes3D\r\n \r\nclass knn():\r\n\r\n def __init__(self, dataset, k, nfrom, nto):\r\n self.b, self.g, self.r, self.class_attr = [], [], [], []\r\n self.inp = [264,124,183]\r\n self.k = k\r\n \r\n # Veri setimizi nfrom satırından nto satırına kadar okuyoruz.\r\n # Ayrıca veri setindeki her sutunu bir listeye atıyoruz. (r,g,b,class_attr)\r\n with open(dataset, \"r\") as f:\r\n for i in f.readlines()[nfrom:nto]:\r\n self.r.append(int(i.split()[0]))\r\n self.g.append(int(i.split()[1]))\r\n self.b.append(int(i.split()[2]))\r\n self.class_attr.append(i.split()[3])\r\n \r\n\r\n # öklid = 2, manhattan=1\r\n def distance(self, dist=1):\r\n self.dist = []\r\n # for döngüsündeki karışık gibi gelen üs alma, mutlak değer gibi işlemler\r\n # minkowski formulunun karşılığından ibarettir.\r\n for i in range(len(self.class_attr)):\r\n self.dist.append((pow((pow((\r\n abs(int(self.b[i]) - int(self.inp[0])) +\r\n abs(int(self.g[i]) - int(self.inp[1])) +\r\n abs(int(self.r[i]) - int(self.inp[2]))), dist)), 1/dist), i))\r\n \r\n return self.dist\r\n \r\n\r\n def findClass(self):\r\n self.class_values = []\r\n self.result = \"\"\r\n \r\n for i in sorted(self.dist)[:self.k]:\r\n self.class_values.append(self.class_attr[i[1]])\r\n \r\n self.first = self.class_values.count(\"1\")\r\n self.secnd = self.class_values.count(\"2\")\r\n \r\n print(\"Birinci Sınıf:\", self.first)\r\n print(\"İkinci Sınıf:\", self.secnd)\r\n \r\n if self.first > self.secnd:\r\n self.result = \"1. Sınıf(Kırmızı)\"\r\n else:\r\n self.result = \"2. Sınıf(Yeşil)\"\r\n \r\n print(\"SONUÇ: \"+self.result)\r\n \r\n#GORSELLEŞTİRME\r\n\r\n def grafik(self):\r\n fig = plt.figure()\r\n ax = fig.add_subplot(111, projection='3d')\r\n \r\n for bi, gj, rk, class_attr in zip(self.b, self.g, self.r, self.class_attr):\r\n if class_attr == \"1\":\r\n ax.scatter(bi,gj,rk, c='r', marker='.')\r\n else:\r\n ax.scatter(bi,gj,rk, c='g', marker='.')\r\n \r\n ax.scatter(int(self.inp[0]), int(self.inp[1]), int(self.inp[2]), c='b')\r\n ax.set_xlabel('X Ekseni')\r\n ax.set_ylabel('Y Ekseni')\r\n ax.set_zlabel('Z Ekseni')\r\n \r\n fig.text(0, 0, \"Kırmızı(1)[PM10] : \"+str(self.first)+\r\n \" -- Yeşil(2)[SO2] : \"+str(self.secnd)+\r\n \" -- {{SONUÇ : \"+self.result+\"}}\")\r\n \r\n plt.legend()\r\n plt.show()\r\n \r\n# Sınıfımızdan nesne türetip gerekli metodlarımızı çağırıyoruz. En yakın 17 komşuya bakıyoruz. Ola ki eşit çıkma durumu olduğundan k değerinin tek seçilmesinde yarar vardır. Ve sonuç.\r\nins = knn(\"ten_dataset.txt\", 17, 50300, 51000)\r\nins.distance(1)\r\nins.findClass()\r\nins.grafik()\r\n \r\n \r\n\r\n\r\n","sub_path":"korona.py","file_name":"korona.py","file_ext":"py","file_size_in_byte":4665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"170536295","text":"# coding: utf8\nfrom lxml.html import fromstring #, parse\n#import requests\nimport names\nfrom Parse_html import parse_html_country_season, season_to_year\n\n\n# преобразует клуб с русского на английский\ndef switch_names(country_ru, team_ru, season):\n country_lat = names.country_list[country_ru]\n year = season_to_year(country_lat, season)\n response = parse_html_country_season(country_lat, year)\n tree = fromstring(response.text)\n # генерит на лету список клубов по английски (вынимает все url'ы)\n post1 = tree.xpath('.//li[@class=\"yellow-green-bg\"][2]/ul/li/a/@href')\n teams1 = [i.split('/')[-1] for i in post1] # разбили адрес по /\n teams11 = [j.split('.')[0] for j in teams1] # разбили team.htm по точке\n teams11.insert(0, \"\") \n # генерит на лету список клубов по русски\n post2 = tree.xpath('.//li[@class=\"yellow-green-bg\"][2]/ul/li/a')\n teams2 = [i.text_content() for i in post2]\n teams2.insert(0, \"\") \n # меняем русское название на английское\n j = teams2.index(team_ru) # индекс клуба в русском списке\n team1 = teams11[j] # клуб в английском списке по индексу\n return [country_lat, team1] # вернёт имена на английском\n\n#print(switch_names('Англия','Арсенал',2016))\n\n","sub_path":"Switch_names.py","file_name":"Switch_names.py","file_ext":"py","file_size_in_byte":1577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"538399581","text":"#Dependencies\nfrom flask import Flask, render_template, jsonify\nimport requests\nimport json\nfrom bson import json_util\nfrom bson.objectid import ObjectId\nfrom flask_pymongo import PyMongo\nimport time\nimport pandas as pd\nimport numpy as np\n\n#Local dependencies\nfrom config import api_key\n\napp = Flask(__name__)\n\n# Use flask_pymongo to set up mongo connection\napp.config[\"MONGO_URI\"] = \"mongodb://localhost:27017/college_app\"\nmongo = PyMongo(app)\n\n# create route that renders index.html template\n@app.route(\"/\")\ndef home():\n return render_template(\"index.html\")\n\n@app.route(\"/compare2\")\ndef compare2():\n return render_template(\"compare2.html\")\n\n@app.route(\"/about\")\ndef about():\n return render_template(\"about.html\")\n\ndef toJson(data):\n \"\"\"Convert Mongo object(s) to JSON\"\"\"\n return json.dumps(data, default=json_util.default)\n\n@app.route(\"/schools\")\ndef schools():\n\n # URL for GET requests to retrieve school data\n base_url = \"https://api.data.gov/ed/collegescorecard/v1/schools?api_key=\" + api_key\n # Filter by State\n # ST = \"&school.state=CA\"\n min_size = \"&latest.student.size__range=15000..\"\n filter_url = base_url + min_size\n # filter_url = base_url + ST + min_size\n # filter_url = base_url\n\n #Get total results count\n response = requests.get(filter_url).json()\n time.sleep(10)\n print(\"pause for 10 seconds for results counter\")\n school_responses = response['metadata']['total']\n max_pages = 20\n pages = int(np.ceil(school_responses / max_pages))\n print(\"Number of Calls Needed to Paginate\")\n print(pages) \n\n def api_call(page):\n \n school_data = []\n\n url = filter_url + f\"&_page={page}\"\n data = requests.get(url).json()\n\n for i in range(len(data[\"results\"])):\n s_id = data[\"results\"][i][\"id\"]\n \n #SCHOOL DATA\n school_name = data[\"results\"][i][\"school\"][\"name\"]\n url = data[\"results\"][i][\"school\"][\"school_url\"]\n city = data[\"results\"][i][\"school\"]['city']\n state = data[\"results\"][i][\"school\"]['state']\n zip_code = data[\"results\"][i][\"school\"]['zip']\n lon = data[\"results\"][i][\"location\"][\"lon\"]\n lat = data[\"results\"][i][\"location\"][\"lat\"]\n ft_faculty_rate = data[\"results\"][i][\"school\"]['ft_faculty_rate']\n locale = data[\"results\"][i][\"school\"]['locale']\n title_iv_eligibility = data[\"results\"][i][\"school\"]['title_iv']['eligibility_type']\n highest_degree = data[\"results\"][i][\"school\"]['degrees_awarded']['highest']\n ownership = data[\"results\"][i][\"school\"]['ownership'] \n \n ##GRAD RATE AND EARNINGS\n completion_rate = data[\"results\"][i][\"latest\"][\"completion\"][\"rate_suppressed\"][\"overall\"]\n earnings_mean = data[\"results\"][i][\"latest\"][\"earnings\"][\"9_yrs_after_entry\"][\"mean_earnings\"]\n earning_over_25k = data[\"results\"][i][\"latest\"][\"earnings\"][\"9_yrs_after_entry\"][\"percent_greater_than_25000\"]\n \n ##COST\n cost_attendance = data[\"results\"][i][\"latest\"][\"cost\"][\"attendance\"][\"academic_year\"]\n tuition_in_state = data[\"results\"][i][\"latest\"][\"cost\"][\"tuition\"][\"in_state\"]\n tuition_out_of_state = data[\"results\"][i][\"latest\"][\"cost\"][\"tuition\"][\"out_of_state\"]\n \n ##DEMOGRAPHICS\n size = data[\"results\"][i][\"latest\"][\"student\"][\"size\"]\n black = data[\"results\"][i][\"latest\"][\"student\"][\"demographics\"][\"race_ethnicity\"][\"black\"]\n asian = data[\"results\"][i][\"latest\"][\"student\"][\"demographics\"][\"race_ethnicity\"][\"asian\"]\n white = data[\"results\"][i][\"latest\"][\"student\"][\"demographics\"][\"race_ethnicity\"][\"white\"]\n hispanic = data[\"results\"][i][\"latest\"][\"student\"][\"demographics\"][\"race_ethnicity\"][\"hispanic\"]\n asian_pacific_islander = data[\"results\"][i][\"latest\"][\"student\"][\"demographics\"][\"race_ethnicity\"][\"asian_pacific_islander\"]\n unknown = data[\"results\"][i][\"latest\"][\"student\"][\"demographics\"][\"race_ethnicity\"][\"unknown\"]\n women = data[\"results\"][i][\"latest\"][\"student\"][\"demographics\"][\"women\"]\n men = data[\"results\"][i][\"latest\"][\"student\"][\"demographics\"][\"men\"]\n \n ##PROGRAMS\n education = data[\"results\"][i][\"latest\"][\"academics\"][\"program_percentage\"][\"education\"]\n business_marketing = data[\"results\"][i][\"latest\"][\"academics\"][\"program_percentage\"][\"business_marketing\"]\n mathematics = data[\"results\"][i][\"latest\"][\"academics\"][\"program_percentage\"][\"mathematics\"]\n communications_technology = data[\"results\"][i][\"latest\"][\"academics\"][\"program_percentage\"][\"communications_technology\"]\n language = data[\"results\"][i][\"latest\"][\"academics\"][\"program_percentage\"][\"language\"]\n visual_performing = data[\"results\"][i][\"latest\"][\"academics\"][\"program_percentage\"][\"visual_performing\"]\n engineering_technology = data[\"results\"][i][\"latest\"][\"academics\"][\"program_percentage\"][\"engineering_technology\"]\n parks_recreation_fitness = data[\"results\"][i][\"latest\"][\"academics\"][\"program_percentage\"][\"parks_recreation_fitness\"]\n agriculture = data[\"results\"][i][\"latest\"][\"academics\"][\"program_percentage\"][\"agriculture\"]\n security_law_enforcement = data[\"results\"][i][\"latest\"][\"academics\"][\"program_percentage\"][\"security_law_enforcement\"]\n computer = data[\"results\"][i][\"latest\"][\"academics\"][\"program_percentage\"][\"computer\"]\n precision_production = data[\"results\"][i][\"latest\"][\"academics\"][\"program_percentage\"][\"precision_production\"]\n humanities = data[\"results\"][i][\"latest\"][\"academics\"][\"program_percentage\"][\"humanities\"]\n library = data[\"results\"][i][\"latest\"][\"academics\"][\"program_percentage\"][\"library\"]\n psychology = data[\"results\"][i][\"latest\"][\"academics\"][\"program_percentage\"][\"psychology\"]\n social_science = data[\"results\"][i][\"latest\"][\"academics\"][\"program_percentage\"][\"social_science\"]\n legal = data[\"results\"][i][\"latest\"][\"academics\"][\"program_percentage\"][\"legal\"] \n english = data[\"results\"][i][\"latest\"][\"academics\"][\"program_percentage\"][\"english\"]\n construction = data[\"results\"][i][\"latest\"][\"academics\"][\"program_percentage\"][\"construction\"]\n military = data[\"results\"][i][\"latest\"][\"academics\"][\"program_percentage\"][\"military\"]\n communication = data[\"results\"][i][\"latest\"][\"academics\"][\"program_percentage\"][\"communication\"]\n public_administration_social_service = data[\"results\"][i][\"latest\"][\"academics\"][\"program_percentage\"][\"public_administration_social_service\"]\n architecture = data[\"results\"][i][\"latest\"][\"academics\"][\"program_percentage\"][\"architecture\"]\n ethnic_cultural_gender = data[\"results\"][i][\"latest\"][\"academics\"][\"program_percentage\"][\"ethnic_cultural_gender\"]\n resources = data[\"results\"][i][\"latest\"][\"academics\"][\"program_percentage\"][\"resources\"]\n health = data[\"results\"][i][\"latest\"][\"academics\"][\"program_percentage\"]['health']\n engineering = data[\"results\"][i][\"latest\"][\"academics\"][\"program_percentage\"]['engineering']\n history = data[\"results\"][i][\"latest\"][\"academics\"][\"program_percentage\"]['history']\n theology_religious_vocation = data[\"results\"][i][\"latest\"][\"academics\"][\"program_percentage\"]['theology_religious_vocation']\n transportation = data[\"results\"][i][\"latest\"][\"academics\"][\"program_percentage\"]['transportation']\n physical_science = data [\"results\"][i][\"latest\"][\"academics\"][\"program_percentage\"]['physical_science']\n science_technology = data[\"results\"][i][\"latest\"][\"academics\"][\"program_percentage\"]['science_technology']\n biological = data[\"results\"][i][\"latest\"][\"academics\"][\"program_percentage\"]['biological']\n family_consumer_science = data[\"results\"][i][\"latest\"][\"academics\"][\"program_percentage\"]['family_consumer_science']\n philosophy_religious = data[\"results\"][i][\"latest\"][\"academics\"][\"program_percentage\"]['philosophy_religious']\n personal_culinary = data[\"results\"][i][\"latest\"][\"academics\"][\"program_percentage\"]['personal_culinary']\n multidiscipline = data[\"results\"][i][\"latest\"][\"academics\"][\"program_percentage\"]['multidiscipline']\n mechanic_repair_technology = data[\"results\"][i][\"latest\"][\"academics\"][\"program_percentage\"]['mechanic_repair_technology']\n \n ##ADMISSIONS\n avg_sat = data[\"results\"][i][\"latest\"][\"admissions\"]['sat_scores']['average']['overall']\n mid_act = data[\"results\"][i][\"latest\"][\"admissions\"]['act_scores']['midpoint']['cumulative']\n admission_rate = data[\"results\"][i][\"latest\"][\"admissions\"]['admission_rate']['overall']\n \n ##DEBT\n students_with_any_loan = data[\"results\"][i][\"latest\"][\"aid\"]['students_with_any_loan']\n median_debt = data[\"results\"][i][\"latest\"][\"aid\"]['median_debt_suppressed']['overall']\n default_rate = data[\"results\"][i][\"latest\"][\"repayment\"]['3_yr_default_rate']\n\n school_data.append({\"ID\": s_id,\n \"Name\": school_name,\n \"Website\": url,\n \"City\": city,\n \"State\": state,\n \"Zip\": zip_code,\n \"Longitude\": lon,\n \"Latitude\": lat,\n \"Faculty Rate\": ft_faculty_rate,\n \"Locale\": locale,\n \"Title IV\": title_iv_eligibility,\n \"Highest Degree\": highest_degree,\n \"Ownership\": ownership,\n \"Completion Rate\": completion_rate,\n \"Pct Earning > $25K\": earning_over_25k,\n \"Avg Earnings (9yrs)\": earnings_mean,\n \"Cost Attendance\": cost_attendance,\n \"In State Tuition\": tuition_in_state,\n \"Out-of-State Tuition\": tuition_out_of_state,\n \"Total Students\": size,\n \"Black\": black,\n \"Asian\": asian,\n \"White\": white,\n \"Hispanic\": hispanic,\n \"Islander\": asian_pacific_islander,\n \"Unknown\": unknown,\n \"Women\": women,\n \"Men\": men,\n \"education\": education,\n \"mathematics\": mathematics,\n \"business_marketing\": business_marketing,\n \"communications_technology\": communications_technology,\n \"language\": language,\n \"visual_performing\": visual_performing,\n \"engineering_technology\": engineering_technology,\n \"parks_recreation_fitness\": parks_recreation_fitness,\n \"agriculture\": agriculture,\n \"security_law_enforcement\": security_law_enforcement,\n \"computer\": computer,\n \"precision_production\": precision_production,\n \"humanities\": humanities,\n \"library\": library,\n \"psychology\": psychology,\n \"social_science\": social_science,\n \"legal\": legal,\n \"english\": english,\n \"construction\": construction,\n \"military\": military,\n \"communication\": communication,\n \"public_administration_social_service\": public_administration_social_service,\n \"architecture\": architecture,\n \"ethnic_cultural_gender\": ethnic_cultural_gender,\n \"resources\": resources,\n \"health\": health,\n \"engineering\": engineering,\n \"history\": history,\n \"theology_religious_vocation\": theology_religious_vocation,\n \"transportation\": transportation,\n \"physical_science\": physical_science,\n \"science_technology\": science_technology,\n \"biological\": biological,\n \"family_consumer_science\": family_consumer_science,\n \"philosophy_religious\": philosophy_religious,\n \"personal_culinary\": personal_culinary,\n \"multidiscipline\": multidiscipline,\n \"mechanic_repair_technology\": mechanic_repair_technology,\n \"Avg SAT\": avg_sat,\n \"Mid ACT\": mid_act,\n \"Admission Rate\": admission_rate,\n \"Pct Students with Loan\": students_with_any_loan,\n \"Median Debt\": median_debt,\n \"Default Rate\": default_rate,\n })\n return(school_data)\n\n\n # Clear out collection, Paginate API, Insert into MongoDB collection\n collection = mongo.db.items\n collection.remove()\n\n for page_iteration in range(pages):\n college_data = api_call(page_iteration)\n print(\"page -----------------------------------------\")\n print(page_iteration)\n print(\"loading...\")\n collection.insert_many(college_data)\n print(\"LOADED!\")\n \n return \"API CALLS COMPLETE\"\n\n\n\n\n@app.route(\"/coldata\")\ndef coldata():\n results = mongo.db.items.find()\n all_data = [result for result in results]\n return toJson(all_data)\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":14565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"154326033","text":"'''\nOne of the unit types is causing problems;\nit's preventing the polymer from collapsing as much as it should.\n\nYour goal is to figure out which unit type is causing the most problems,\nremove all instances of it (regardless of polarity),\nfully react the remaining polymer, and measure its length.\n\nWhat is the length of the shortest polymer you can produce by\nremoving all units of exactly one type and fully reacting the result?\n'''\n\nfrom part_1 import react_loop\n\n\ndef remove_unit_type(polymer, unit_type):\n '''\n Returns a polymer with all instances of the given unit type removed\n '''\n polymer = polymer.replace(unit_type, '').replace(unit_type.upper(), '')\n return polymer\n\n\ndef improve_polymer(polymer, unit_types):\n '''\n Returns a dictionary where every key is a unit type and the value is the\n length of polymer with unit type removed after full reaction, given the\n polymer and a string containing all the unit types\n '''\n polymer_dict = {}\n for unit_type in unit_types:\n final_polymer = react_loop(remove_unit_type(polymer, unit_type))\n polymer_dict[unit_type] = len(final_polymer)\n return polymer_dict\n\n\ndef get_shortest_polymer_length(input_dict):\n '''\n Returns the length of the shortest polymer that can be produced, given\n a dictionary where keys are unit types to be removed and value is the length\n of polymer with unit type removed after full reaction\n '''\n return min(input_dict.values())\n\n\ndef main():\n with open('input.txt') as input_file:\n polymer = input_file.read().strip()\n\n unit_types = 'abcdefghijklmnopqrstuvwxyz'\n polymer_dict = improve_polymer(polymer, unit_types)\n shortest_polymer_length = get_shortest_polymer_length(polymer_dict)\n print(\n 'The length of the shortest polymer produced by removing all units '\n f'''of exactly one type and fully reacting the result is {\n shortest_polymer_length\n }'''\n )\n\nif __name__ == '__main__':\n main()\n","sub_path":"Day 5/part_2.py","file_name":"part_2.py","file_ext":"py","file_size_in_byte":2004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"637751208","text":"#!/usr/bin/python3\r\n#coding:utf-8\r\n\r\nfrom tkinter import *\r\n#import tkinter as tk\r\nfrom PIL import Image\r\nfrom PIL import ImageTk\r\nfrom tkinter import ttk\r\nfrom tkinter import filedialog\r\nfrom tkinter.filedialog import askopenfilename\r\nimport os\r\nimport shutil\r\n\r\nBUTTONPADX = 25\r\nBUTTONPADY = 5\r\n#imagePath = \"9OPjrDeBWQCEm9XbzAw7TNTXWQHNE4ETLpfYoXTwekg.jpg\"\r\n#folderPath = \"C:\\\\Users\\\\ramic\\\\Pictures\\\\Saved Pictures\"\r\n#completePath = \"C:\\\\Users\\\\ramic\\\\Pictures\\\\Saved Pictures\\\\eden.png\"\r\n\r\nwindow = Tk()\r\n\r\nwindow.title(\"Snow Labeler\")\r\n\r\nwindow.rowconfigure(0,minsize=800,weight=1)\r\nwindow.columnconfigure(1,minsize=800,weight=1)\r\n\r\n#configure rows and columns\r\nwindow.rowconfigure(0, minsize=400, weight=1)\r\nwindow.rowconfigure(1, minsize=100, weight=1)\r\nwindow.columnconfigure(0, minsize=300, weight=1)\r\nwindow.columnconfigure(1, minsize=100, weight=1)\r\n\r\n\r\n\r\n#frames\r\nfr_labelButtons = Frame(window) #frame for labelButtons\r\nfr_navDes = Frame(window) #frame to chose image to display\r\n#image = tk.Frame(window)\r\n#image = Image.open(imagePath)\r\n#image = image.resize((200,200), Image.NEAREST)\r\n#photo = ImageTk.PhotoImage(image)\r\nmyListbox = Listbox(fr_navDes)\r\ntext_dir = Text(fr_navDes, wrap=WORD, height=1, width = 50)\r\n\r\n\r\n#function for choosing the dir\r\ndef openFolder():\r\n global folderPath\r\n folderPath = filedialog.askdirectory()\r\n list = os.listdir(folderPath)\r\n myListbox.delete(1, END)\r\n for item in list:\r\n myListbox.insert(END, item)\r\n updateTextBox(folderPath)\r\n\r\ndef onselect(event):\r\n w = event.widget\r\n idx = int(w.curselection()[0])\r\n imagePath = w.get(idx)\r\n global completePath\r\n completePath = folderPath + \"/\" + imagePath\r\n updateImage(completePath)\r\n\r\ndef moveFile(source, destination):\r\n #check if source is already there\r\n print(source, \"->\", destination )\r\n #if not (os.path.exists(destination)):\r\n #print(\"ok\")\r\n #check if destination exists\r\n if not (os.path.exists(destination)):\r\n os.makedirs(destination)\r\n shutil.move(source, destination)\r\n\r\n#updating the layout\r\ndef updateTextBox(text):\r\n text_dir.delete('1.0',END)\r\n text_dir.insert(END,text)\r\n text_dir.config(wrap=WORD)\r\n\r\ndef updateImage(path):\r\n image = Image.open(path)\r\n image = image.resize((640,480), Image.NEAREST)\r\n photo = ImageTk.PhotoImage(image)\r\n imageLabel = Label(image = photo)\r\n imageLabel.image = photo\r\n imageLabel.grid(row=0, column=1, sticky=\"nsew\", padx=25, pady=5)\r\n\r\nmyListbox.bind('<>', onselect)\r\n\r\n#widgets\r\n#for amount of Snow\r\nbtn_label_0 = Button(fr_labelButtons, text=\"0% (X)\", command =lambda: moveFile(completePath, (folderPath + \"/class0\")))\r\nbtn_label_10 = Button(fr_labelButtons, text=\"10% (1)\", command =lambda: moveFile(completePath, (folderPath + \"/class10\")))\r\nbtn_label_20 = Button(fr_labelButtons, text=\"20% (2)\", command =lambda: moveFile(completePath, (folderPath + \"/class20\")))\r\nbtn_label_30 = Button(fr_labelButtons, text=\"30% (3)\", command =lambda: moveFile(completePath, (folderPath + \"/class30\")))\r\nbtn_label_40 = Button(fr_labelButtons, text=\"40% (4)\", command =lambda: moveFile(completePath, (folderPath + \"/class40\")))\r\nbtn_label_50 = Button(fr_labelButtons, text=\"50% (5)\", command =lambda: moveFile(completePath, (folderPath + \"/class50\")))\r\nbtn_label_60 = Button(fr_labelButtons, text=\"60% (6)\", command =lambda: moveFile(completePath, (folderPath + \"/class60\")))\r\nbtn_label_70 = Button(fr_labelButtons, text=\"70% (7)\", command =lambda: moveFile(completePath, (folderPath + \"/class70\")))\r\nbtn_label_80 = Button(fr_labelButtons, text=\"80% (8)\", command =lambda: moveFile(completePath, (folderPath + \"/class80\")))\r\nbtn_label_90 = Button(fr_labelButtons, text=\"90% (9)\", command =lambda: moveFile(completePath, (folderPath + \"/class90\")))\r\nbtn_label_100 =Button(fr_labelButtons, text=\"100% (0)\", command =lambda: moveFile(completePath, (folderPath + \"/class100\")))\r\n\r\nbtn_label_rejected =Button(fr_labelButtons, text=\"rejected (r)\", command =lambda: moveFile(completePath, (folderPath + \"/rejected\")))\r\n#binding keys\r\nwindow.bind('x', lambda event: moveFile(completePath, (folderPath + \"/class0\")))\r\nwindow.bind('1', lambda event: moveFile(completePath, (folderPath + \"/class10\")))\r\nwindow.bind('2', lambda event: moveFile(completePath, (folderPath + \"/class20\")))\r\nwindow.bind('3', lambda event: moveFile(completePath, (folderPath + \"/class30\")))\r\nwindow.bind('4', lambda event: moveFile(completePath, (folderPath + \"/class40\")))\r\nwindow.bind('5', lambda event: moveFile(completePath, (folderPath + \"/class50\")))\r\nwindow.bind('6', lambda event: moveFile(completePath, (folderPath + \"/class60\")))\r\nwindow.bind('7', lambda event: moveFile(completePath, (folderPath + \"/class70\")))\r\nwindow.bind('8', lambda event: moveFile(completePath, (folderPath + \"/class80\")))\r\nwindow.bind('9', lambda event: moveFile(completePath, (folderPath + \"/class90\")))\r\nwindow.bind('0', lambda event: moveFile(completePath, (folderPath + \"/class100\")))\r\nwindow.bind('r', lambda event: moveFile(completePath, (folderPath + \"/rejected\")))\r\n\r\n\r\n#for image\r\n#imageLabel = Label(image = photo)\r\n#imageLabel.image = photo\r\n\r\n#for choosing the image\r\nbtn_choose_dir = Button(fr_navDes, text = \"Choose Folder: (Q)\", command=openFolder)\r\nwindow.bind('q', lambda event: openFolder())\r\n\r\n\r\n\r\n#grid layout\r\n#for labeling the image\r\nfr_labelButtons.grid(row=1, column=1, sticky=\"ns\")\r\nbtn_label_0.grid(row=1, column=0, sticky=\"ew\", padx=BUTTONPADX, pady=BUTTONPADY)\r\nbtn_label_10.grid(row=1, column=1, sticky=\"ew\", padx=BUTTONPADX, pady=BUTTONPADY)\r\nbtn_label_20.grid(row=1, column=2, sticky=\"ew\", padx=BUTTONPADX, pady=BUTTONPADY)\r\nbtn_label_30.grid(row=1, column=3, sticky=\"ew\", padx=BUTTONPADX, pady=BUTTONPADY)\r\nbtn_label_40.grid(row=1, column=4, sticky=\"ew\", padx=BUTTONPADX, pady=BUTTONPADY)\r\nbtn_label_50.grid(row=1, column=5, sticky=\"ew\", padx=BUTTONPADX, pady=BUTTONPADY)\r\nbtn_label_60.grid(row=2, column=0, sticky=\"ew\", padx=BUTTONPADX, pady=BUTTONPADY)\r\nbtn_label_70.grid(row=2, column=1, sticky=\"ew\", padx=BUTTONPADX, pady=BUTTONPADY)\r\nbtn_label_80.grid(row=2, column=2, sticky=\"ew\", padx=BUTTONPADX, pady=BUTTONPADY)\r\nbtn_label_90.grid(row=2, column=3, sticky=\"ew\", padx=BUTTONPADX, pady=BUTTONPADY)\r\nbtn_label_100.grid(row=2, column=4, sticky=\"ew\", padx=BUTTONPADX, pady=BUTTONPADY)\r\nbtn_label_rejected.grid(row=2, column=5, sticky=\"ew\", padx=BUTTONPADX, pady=BUTTONPADY)\r\n\r\n#for choosing the image\r\nfr_navDes.grid(row=0, column=0, sticky=\"ns\")\r\nbtn_choose_dir.grid(row=2,column=0, sticky = \"ew\", padx=25, pady=5)\r\nmyListbox.grid(row=1,column=0, padx=BUTTONPADX, pady=BUTTONPADY)\r\ntext_dir.grid(row=0, column=0, padx=BUTTONPADX, pady=BUTTONPADY)\r\n\r\n#show the image\r\n#imageLabel.grid(row=0, column=1, sticky=\"nsew\", padx=25, pady=5)\r\n\r\n\r\nwindow.mainloop()\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"366176580","text":"# numeric integration illustration\n# Roessler attractor\n\nimport pygame, time\nfrom pygame.locals import *\nfrom pygame.color import *\nfrom numpy import *\n\npygame.init()\nscreen = pygame.display.set_mode((800,600))\nbackground = pygame.Surface(screen.get_size())\nbackground.fill((128,128,255))\n\n\"\"\"\nThe Roessler attractor\n\"\"\"\n\np1 = array((10, 10, 10), dtype=float)\np2 = array((10, 10, 10.1), dtype=float)\na,b,c = 0.2,0.2,5.7\n\ndef d(state):\n x,y,z = state\n dx = -y - z\n dy = x + a*y\n dz = b + z*(x-c)\n return array((dx, dy, dz))\n\ndef rungekutta(state, dt):\n k1 = d(state)\n k2 = d(state + k1 * dt/2)\n k3 = d(state + k2 * dt/2)\n k4 = d(state + k3 * dt)\n newstate = state + (k1 + 2*k2 + 2*k3 + k4) * dt/6\n return newstate\n \nt = 0\ndt = 0.01\n\nscreen.blit(background, (0,0))\n\nclock = pygame.time.Clock()\n\ndef getpt(state):\n return 10*state[0:2] + (400, 300)\n\nrunning = 1\nwhile running:\n # clock.tick(60)\n for event in pygame.event.get():\n if event.type == QUIT:\n running = 0\n elif event.type == KEYDOWN and event.key == K_ESCAPE:\n running = 0\n oldp1 = getpt(p1)\n oldp2 = getpt(p2)\n screen.blit(background, (0,0))\n t += dt\n p1 = rungekutta(p1, dt)\n p2 = rungekutta(p2, dt)\n pygame.draw.line(background, (255,0,0), oldp1, getpt(p1), 1)\n pygame.draw.line(background, (0,255,0), oldp2, getpt(p2), 1)\n pygame.display.flip()\n \npygame.quit()\n\n","sub_path":"lectures/physics/pythondemos/strange04.py","file_name":"strange04.py","file_ext":"py","file_size_in_byte":1440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"336847074","text":"# -*- coding:utf-8 -*-\n''''''\n\n'''\nPython中还有一个比greenlet更强大的,并且能够自动切换任务的模块 gevent\n\n\n gevent是基于协程(greenlet)的网络库,底层的事件轮询基于libev(早期是libevent),\ngevent的API概念和Python标准库一致(如事件,队列)。\n\ngevent有一个很有意思的东西-monkey-patch,能够使python标准库中的阻塞操作变成异步,如socket的读写。\n\n'''\n\nimport gevent\n\ndef A():\n for i in range(5):\n print('A.........')\n print('A,,,,,,,,,')\n\ndef B():\n for i in range(5):\n print('B..........')\n print('B,,,,,,,,,,')\n\n\ngevent.spawn(A)\ngevent.spawn(B)\n\n\n\n'''\n\n执行结果:\n\nA.........\nA,,,,,,,,,\nA.........\nA,,,,,,,,,\nA.........\nA,,,,,,,,,\nA.........\nA,,,,,,,,,\nA.........\nA,,,,,,,,,\nB..........\nB,,,,,,,,,,\nB..........\nB,,,,,,,,,,\nB..........\nB,,,,,,,,,,\nB..........\nB,,,,,,,,,,\nB..........\nB,,,,,,,,,,\n\n代码仍然是顺序执行,因为代码中没有 IO 的耗时操作\n\n'''\n\n\n'''\n\n下面代码使用 sleep方式 模拟了耗时操作\n\n之前使用的是 time模块的 sleep函数,这段代码中使用的是\n gevent.sleep() gevent自带 sleep 函数\n\n'''\n\ndef C():\n for i in range(5):\n gevent.sleep(1)\n print('C..........')\n\ndef D():\n for i in range(5):\n gevent.sleep(1)\n print('D..........')\n\n\ngc = gevent.spawn(C)\ngd = gevent.spawn(D)\n\ngc.join()\ngd.join()\n","sub_path":"Exercise/多任务/协程/5、gevent 方式.py","file_name":"5、gevent 方式.py","file_ext":"py","file_size_in_byte":1428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"114170413","text":"import datetime\r\nimport json\r\nimport discord\r\nfrom discord.ext import commands\r\nfrom config import config\r\nfrom cogs.utils.fetch import fetch\r\nfrom cogs.utils.create_error import create_error\r\nfrom cogs.utils.checks import channels_allowed\r\n\r\n\r\n\"\"\"\r\nTells you the status of given twitch streamers\r\n\"\"\"\r\n\r\n\r\nclass Status:\r\n \"\"\"Stream status listings\"\"\"\r\n def __init__(self, bot):\r\n self.bot = bot\r\n self.twitch_token = config[\"tokens\"][\"twitch\"]\r\n self.streamers = config[\"streamers\"]\r\n self.channels = [config[\"channels\"][\"nlss-chat\"], config[\"channels\"][\"testing\"]]\r\n\r\n\r\n def _check_main(self, twitch_status, main):\r\n \"\"\"\r\n Checks if the channel defined as 'main' is streaming;\r\n checks the ones in 'others' as well.\r\n \"\"\"\r\n if twitch_status[\"_total\"] == 0:\r\n return False # No given streamers online\r\n\r\n for stream in twitch_status[\"streams\"]:\r\n if stream[\"channel\"][\"display_name\"] == main:\r\n return stream # main streamer online\r\n return False # only other streamers online\r\n\r\n\r\n def _build_uptime(self, created):\r\n \"\"\"Returns formatted uptime string\"\"\"\r\n started = datetime.datetime.strptime(created, \"%Y-%m-%dT%H:%M:%SZ\")\r\n now = datetime.datetime.utcnow()\r\n diff = now - started\r\n hours = diff.seconds // 3600\r\n mins = (diff.seconds // 60) - (60 * hours)\r\n return f\"{hours} hr, {mins} min\" if hours > 0 else f\"{mins} min\"\r\n\r\n\r\n def _build_embed(self, twitch_status, main):\r\n \"\"\"Returns fancy embed for main streamer\"\"\"\r\n timestr = self._build_uptime(main[\"created_at\"])\r\n\r\n emb = discord.Embed(url=main[\"channel\"][\"url\"], color=0x933bce) #Create the embed object\r\n emb.set_author(name=main[\"channel\"][\"display_name\"], icon_url=main[\"channel\"][\"logo\"])\r\n emb.set_image(url=main[\"preview\"][\"large\"]) \r\n emb.add_field(name=\"Live!\", value=main[\"channel\"][\"status\"], inline=False)\r\n emb.add_field(name=\"Currently playing\", value=main[\"channel\"][\"game\"], inline=False)\r\n emb.add_field(name=\"Viewers\", value=main[\"viewers\"])\r\n emb.add_field(name=\"Uptime\", value=timestr)\r\n\r\n if twitch_status[\"_total\"] > 1:\r\n emb.set_footer(text=f\"There are other streamers online too! Check `-status others`.\")\r\n else:\r\n emb.set_footer(text=f\"No other streamers are online at this moment.\")\r\n return emb\r\n\r\n\r\n async def _build_list(self, twitch_status, main):\r\n \"\"\"Builds a list of everyone currently streaming\"\"\"\r\n try:\r\n emb = discord.Embed(color=0x933bce) \r\n \r\n if not main: \r\n if twitch_status[\"_total\"] > 0:\r\n emb.description = f\"**[Northernlion](https://twitch.tv/Northernlion)**\\n\"\r\n emb.description += f\"Northernlion is not streaming at the moment.\"\r\n \r\n when_url = \"http://whenisnlss.com/when\"\r\n try:\r\n response = await fetch(when_url)\r\n emb.description += f\"\\n{response}\"\r\n except:\r\n print('Error getting when')\r\n \r\n else:\r\n emb.color=0x333333\r\n emb.description = \"**Offline**\\nNo NLSS members are streaming at the moment.\"\r\n\r\n when_url = \"http://whenisnlss.com/when\"\r\n try:\r\n response = await fetch(when_url)\r\n emb.description += f\"\\n{response}\"\r\n except:\r\n print('Error getting when')\r\n \r\n return emb\r\n\r\n if twitch_status[\"_total\"] > 0:\r\n build_string = \"\"\r\n\r\n for stream in twitch_status[\"streams\"]:\r\n timestr = self._build_uptime(stream[\"created_at\"])\r\n\r\n build_string += f'**[{stream[\"channel\"][\"display_name\"]}]({stream[\"channel\"][\"url\"]})**\\n'\r\n build_string += f'**{stream[\"channel\"][\"status\"]}**\\n'\r\n build_string += f'Playing {stream[\"channel\"][\"game\"]}\\n'\r\n build_string += f'`{timestr} uptime | {stream[\"viewers\"]} viewers`\\n\\n'\r\n \r\n emb.add_field(name=\"Streamers to watch\", value=build_string)\r\n \r\n return emb\r\n \r\n except Exception as e:\r\n print(e)\r\n return create_error(\"building stream list\")\r\n\r\n\r\n @commands.command(pass_context=True, invoke_without_command=True)\r\n @channels_allowed([\"nlss-chat\", \"circlejerk\"])\r\n async def status(self, ctx, *args):\r\n \"\"\"Shows the status of NL's stream. Use -status others to see a list of other live NLSS members.\"\"\"\r\n\r\n arg = \"\"\r\n try:\r\n arg = args[0]\r\n except:\r\n arg = \"None given\"\r\n\r\n channels = ','.join(self.streamers[\"other\"])\r\n twitch_url = \"https://api.twitch.tv/kraken/streams/\"\r\n params = dict(channel=channels, \r\n client_id=self.twitch_token)\r\n\r\n await self.bot.send_typing(ctx.message.channel)\r\n try:\r\n response = await fetch(twitch_url, params=params)\r\n twitch_status = json.loads(response)\r\n\r\n main = self._check_main(twitch_status, self.streamers[\"main\"]) # can be bool or object\r\n\r\n # Show status of main streamer if online\r\n if main and arg != \"others\":\r\n emb = self._build_embed(twitch_status, main)\r\n await self.bot.say(content=None, embed=emb)\r\n\r\n # Else or if specified, show other streamers instead\r\n elif not main or arg == \"others\":\r\n emb = await self._build_list(twitch_status, main)\r\n await self.bot.say(content=None, embed=emb)\r\n\r\n except Exception as e:\r\n print(f\"{type(e).__name__}, {str(e)}\")\r\n print(e)\r\n await self.bot.say(content=None, embed=create_error(\"getting stream information\"))\r\n\r\n\r\n# When we load the cog, we use the name of the file.\r\ndef setup(bot):\r\n bot.add_cog(Status(bot))\r\n","sub_path":"cogs/status.py","file_name":"status.py","file_ext":"py","file_size_in_byte":6242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"15565676","text":"# Copyright 2018 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# 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# [START gae_python37_app]\nfrom flask import Flask\nfrom flask import render_template\nfrom flask import request\nfrom flask_bootstrap import Bootstrap\nimport csv\nfrom route18 import Player\nfrom route18 import Route18_2019\nfrom route18 import FantasyPros\n\n# If `entrypoint` is not defined in app.yaml, App Engine will look for an app\n# called `app` in `main.py`.\napp = Flask(__name__)\nBootstrap(app)\n\nclass Team:\n\n def __init__(self, name):\n self.name = name\n self.roster = []\n\ndef getDraft( filename ):\n draft = []\n count = 0\n with open( filename, 'r' ) as csvfile:\n reader = csv.reader(csvfile)\n for row in reader:\n if (count > 0):\n draft.append( row[1] )\n count += 1\n\n return(draft)\n\ndef setRosters(players):\n teams = [\n Team(\"BITE ME\"),\n Team(\"Devil Cows\"),\n Team(\"Domanick Davis\"),\n Team(\"Food For Anubis\"),\n Team(\"Franks Tanks\"),\n Team(\"Fubar\"),\n Team(\"Gordon Gekko\"),\n Team(\"Have Nots\"),\n Team(\"IronCity\"),\n Team(\"O-Dog\"),\n Team(\"Piss & Vinegar\"),\n Team(\"Secret Squirrels\"),\n ]\n\n\n\n teamDict = {\n \"BITE ME\" : 0,\n \"Devil Cows\" : 1,\n \"Domanick Davis\" : 2,\n \"Food For Anubis\" : 3,\n \"Franks Tanks\" : 4,\n \"Fubar\" : 5,\n \"Gordon Gekko\" : 6,\n \"Have Nots\" : 7,\n \"IronCity\" : 8,\n \"O-Dog\" : 9,\n \"Piss & Vinegar\" : 10,\n \"Secret Squirrels\" : 11\n }\n\n for p in players:\n if (p.pick > 0):\n #print( p.name + \" \" + str(p.pick) + \" \" + p.owner)\n teamIdx = teamDict[ p.owner ]\n #print( str(teamIdx) )\n teams[teamIdx].roster.append( p )\n\n return teams, teamDict\n\ndef getPlayers( filename ):\n players = []\n with open( filename, 'r' ) as csvfile:\n reader = csv.reader(csvfile)\n count = 0\n for row in reader:\n if (count > 0) and (len(row)==15):\n p = Player()\n #print(row)\n #print( len(row) )\n p.rank = row[0]\n p.name = row[3]\n p.team = row[4]\n\n if row[5].find(\"QB\") != -1:\n p.position = \"QB\"\n elif row[5].find(\"RB\") != -1:\n p.position = \"RB\"\n elif row[5].find(\"WR\") != -1:\n p.position = \"WR\"\n elif row[5].find(\"TE\") != -1:\n p.position = \"TE\"\n elif row[5].find(\"K\") != -1:\n p.position = \"K\"\n else:\n p.position = \"DST\"\n\n p.adp = row[11]\n p.pick = int(row[13])\n if p.pick > 0:\n p.owner = row[14]\n\n players.append(p)\n\n count += 1\n\n return(players)\n\n\n\n@app.route('/', methods=['GET','POST'])\n#@app.route('/index', methods=['GET','POST'])\ndef index():\n #\"\"\"Return a friendly HTTP greeting.\"\"\"\n #return 'Hello World!'\n\n current = 1\n teams = []\n players = []\n draft = []\n teamDict = {}\n\n #players = getPlayers( \"static/players.csv\" )\n players = FantasyPros()\n #draft = getDraft(\"static/draft_order.csv\")\n draft = Route18_2019()\n #teams, teamDict = setRosters(players)\n keepers = []\n for p in players:\n if p.pick > 0:\n keepers.append(p.pick)\n\n if request.method == \"GET\":\n print(\"---GET---\")\n teams, teamDict = setRosters(players)\n\n if request.method == \"POST\":\n print(\"---POST---\")\n dat = request.form.to_dict()\n print(\"N players:\" + str(len(players)))\n\n draftIdx = -1\n\n value = dat['onclock']\n current = int(value)\n print( \"Current Pick = \" + value)\n\n pickSubmitted = False\n for key, value in dat.items():\n\n if value == 'draft':\n draftIdx = int(key)-1\n pickSubmitted = True\n\n if key.find('status') != -1:\n idx = int(key.split(':')[1])-1\n if ( idx != draftIdx ):\n inf = value.split(':')\n players[idx].pick = int(inf[0])\n players[idx].owner = inf[1]\n\n if pickSubmitted and current <= 180:\n players[draftIdx].pick = current\n players[draftIdx].owner = draft[current-1]\n previous = current\n current += 1\n\n if \"undo\" in dat:\n # FIXME = not working\n print(\"UNDO LAST PICK\")\n if current > 1:\n lastPick = current - 1\n lastOwner = draft[lastPick-1]\n while lastPick > 1 and lastPick in keepers:\n lastPick = lastPick - 1\n lawOwner = draft[lastPick-1]\n for p in players:\n if p.pick == lastPick:\n p.pick = 0\n current = lastPick\n\n if \"clear\" in dat:\n players = FantasyPros()\n draft = Route18_2019()\n current = 1\n\n teams, teamDict = setRosters(players)\n\n\n for p in players:\n if ( p.pick > 0 ):\n draft[p.pick-1] = \"K\"\n\n if current <= 180:\n nextOwner = draft[current-1]\n while nextOwner==\"K\" and current <= 180:\n current += 1\n nextOwner = draft[current-1]\n\n return render_template('index.html', page='index', players=players, teams=teams, draft=draft, current=current)\n\n@app.route('/rosters', methods=['GET'])\ndef rosters():\n\n return render_template\n\nif __name__ == '__main__':\n # This is used when running locally only. When deploying to Google App\n # Engine, a webserver process such as Gunicorn will serve the app. This\n # can be configured by adding an `entrypoint` to app.yaml.\n app.run(host='127.0.0.1', port=8080, debug=True)\n# [END gae_python37_app]\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"78074511","text":"#!/usr/bin/env python3\n\nimport codecs, os, sys, signal, tabulate\ndef signal_handler( signal, frame ):\n print( \"You pressed Ctrl+C. Exiting...\")\n sys.exit( 0 )\nsignal.signal( signal.SIGINT, signal_handler )\nfrom plexmusic import plexmusic\nfrom plexemail import emailAddress\nfrom optparse import OptionParser\n\ndef main( ):\n parser = OptionParser( )\n parser.add_option( '-a', '--artist', dest='artist_name', type=str, action='store',\n help = 'Name of the artist to get album image for.' )\n parser.add_option( '-A', '--album', dest='album_name', type=str, action='store',\n help = 'Name of the album to get album image for.' )\n parser.add_option( '--songs', dest='do_songs', action='store_true', default = False,\n help = 'If chosen, get the song listing instead of downloading the album image.')\n parser.add_option( '--formatted', dest='do_formatted', action='store_true', default = False,\n help = ' '.join([\n 'If chosen, print the song listing in a format recognized by plex_music_metafill.py',\n 'for downloading a collection of songs.' ]) )\n parser.add_option('--albums', dest='do_albums', action='store_true', default = False,\n help = 'If chosen, then get a list of all the songs in all studio albums for the artist.' )\n parser.add_option( '--debug', dest='do_debug', action='store_true', default=False,\n help = 'Run with debug mode turned on.' )\n parser.add_option('--noverify', dest='do_verify', action='store_false', default = True,\n help = 'If chosen, do not verify SSL connections.' )\n opts, args = parser.parse_args( )\n assert( opts.artist_name is not None )\n if not opts.do_albums: assert( opts.album_name is not None )\n #\n ## \n plastfm = plexmusic.PlexLastFM( verify = opts.do_verify )\n if opts.do_albums:\n plexmusic.MusicInfo.get_set_musicbrainz_useragent( emailAddress )\n mi = plexmusic.MusicInfo( opts.artist_name.strip( ) )\n mi.print_format_album_names( )\n return\n \n if not opts.do_songs: # just get the song image\n _, status = plastfm.get_album_image( opts.artist_name, opts.album_name )\n if status != 'SUCCESS':\n print( status )\n return\n\n track_listing, status = plastfm.get_song_listing(\n opts.artist_name, album_name = opts.album_name )\n if status != 'SUCCESS':\n print( status )\n return\n\n if not opts.do_formatted:\n print( '\\n%s\\n' %\n tabulate.tabulate( track_listing, headers = [ 'Song', 'Track #' ] ) )\n else:\n print( '\\n%s\\n' % ';'.join(map(lambda title_trkno: title_trkno[0], track_listing)) )\n\nif __name__ == '__main__':\n main( )\n","sub_path":"plex_music_album.py","file_name":"plex_music_album.py","file_ext":"py","file_size_in_byte":2831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"350376020","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport scipy as sp\nfrom scipy import optimize, special\n\nplt.rcParams[\"errorbar.capsize\"] = 3\nplt.rcParams[\"lines.linewidth\"] = 3\nplt.rcParams[\"lines.markersize\"] = 10\nplt.rcParams[\"figure.figsize\"] = (6*(1+np.sqrt(5))/2,6)\nplt.rcParams[\"figure.dpi\"] = 200\nplt.rcParams[\"xtick.labelsize\"] = 20\nplt.rcParams[\"ytick.labelsize\"] = 20\nplt.rcParams[\"font.size\"] = 30\nplt.rcParams[\"legend.fontsize\"] = 25\n\nerr_f = lambda x, a, b, c, d: a + b * sp.special.erf(np.sqrt(2)*(x - c) / d)\ndata = np.loadtxt('calibracion_x.csv', delimiter=',')\n\nx = data[:,0]\ny = data[:,1]\nyerr = data[:,2]\nxerr = np.ones_like(data[:,0])\n\n\nplt.figure()\n\nplt.grid()\nplt.tick_params(axis=\"both\")\nplt.xlabel(\"d[$\\mu$m]\")\nplt.ylabel(\"A[mW]\")\n\nplt.errorbar(x, y, yerr=yerr, xerr=xerr, fmt=\"ro\", label=\"Datos\")\n\np0 = [y.max()/2, -y.max()/2, (x.max() + x.min())/2, 0.5*(x.max() - x.min())]\np, cov = sp.optimize.curve_fit(err_f, x, y, p0 = p0)\n\nt = np.linspace(x.min(),x.max(),1000)\nplt.plot(t,err_f(t,*p),\"b-\", label=\"Ajuste\")\n\ntxt = \"$\\sigma$ = ({:.0f} $\\pm$ {:.0f})$\\mu$m\".format(2*p[3], 2*np.sqrt(cov[3,3]))\nplt.text(0.1,0.15, txt, transform=plt.gca().transAxes) \nprint(\"Error relativo {}\".format(100 * np.sqrt(cov[3,3]) / (2 * p[3]) ))\n\nplt.legend(loc=0)\nplt.show()\n","sub_path":"perfilador/mediciones/calibracion_fibra_f280_d_7cm/calibracion.py","file_name":"calibracion.py","file_ext":"py","file_size_in_byte":1283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"42268128","text":"from django.db import models\nfrom django.core.validators import validate_comma_separated_integer_list\n\nfrom diesel.lisp import extract_predicates, extract_predicates_from_xml\nfrom diesel.score import parse_s_predicate\nfrom diesel.similarity import triple_sim, score_structure, compute_similarity\n\nfrom genesis.tools.trips.parses import parse_sentences\nfrom genesis.tools.trips.trips_parameters import basic_experiment, no_skeleton_score\n\nimport random\nimport tempfile\nimport os\nfrom tqdm import tqdm\n\n# Create your models here.\n\nrecent_port = 6300\n\n\ndef run_trips_with_data(sentences, data, exp, max_attempts=5, port=None, parallel=False):\n global recent_port\n if type(exp) is str:\n exp = Experiment.get(exp)\n with tempfile.NamedTemporaryFile(mode='w', delete=False) as f:\n f.write(\"\\n\".join(data))\n f.close()\n print(\"creating parameters: datafile={}, adjustment={}, node_cutoff={}, pred_type={}\".format(\n f.name, exp.arange, exp.node_cutoff, exp.pred_type\n ))\n parameters = basic_experiment(\n datafile=f.name,\n adjustment=exp.arange,\n node_cutoff=exp.node_cutoff,\n pred_type=exp.pred_type\n )\n if not port:\n port = recent_port\n recent_port += max_attempts + 1\n result = parse_sentences(\n sentences=sentences,\n parameters=parameters,\n use_timeout=True,\n max_attempts=max_attempts,\n port=port,\n parallel=parallel\n )\n os.unlink(f.name)\n for s, d in result.items():\n sent = Sentence.objects.filter(text=s)\n if sent:\n sent = sent.first()\n else:\n print(s, 'was not found')\n continue\n pr = ParseResult(\n experiment=exp,\n sentence=sent,\n output=d.parse, # this is xml, should be just lisp\n dot=d.lf_graph,\n skeletons=\"\\n\".join([\"{}\\t{}\\t{}\".format(a, b, c) for a, b, c in d.skeletons]),\n hyps=d.speechacthyps\n )\n pr.save()\n\n\ndef run_parser(force=False):\n sentences = [s.text for s in Sentence.objects.all() if force or (s.parser_only == \"\")]\n print(len(sentences))\n parameters = no_skeleton_score()\n batches = [len(sentences)//10]*10\n if len(sentences) % 10 != 0:\n for i in range(len(sentences) % 10):\n batches[i] += 1\n\n sentence_batches = []\n start = 0\n for x in batches:\n sentence_batches.append(sentences[start:start+x])\n start += x\n\n def parallel_task(idx):\n b = sentence_batches[idx]\n result = parse_sentences(\n b,\n parameters=parameters,\n use_timeout=True,\n max_attempts=5,\n port=recent_port+10*idx,\n parallel=True\n )\n for r, y in result.items():\n sent = Sentence.objects.filter(text=r)\n if sent:\n sent = sent.first()\n else:\n print(r, \"was not found\")\n continue\n sent.parser_only = y.parse\n sent.save()\n\n from pathos.multiprocessing import ProcessingPool as Pool\n with Pool(5) as p:\n p.map(parallel_task, range(len(sentence_batches)))\n\n\nclass Sentence(models.Model):\n text = models.CharField(max_length=10000)\n predicates = models.ManyToManyField('Predicate')\n gold_parse = models.CharField(max_length=10000)\n parser_only = models.CharField(max_length=10000, default=\"\")\n parser_score = models.FloatField(default=-1)\n alignments = models.CharField(max_length=10000, default=\"\")\n has_non = models.BooleanField(default=False)\n has_non_gold = models.BooleanField(default=False)\n\n def __str__(self):\n return self.text\n\n def verify_text(self):\n return \"{}\\n{}\\n{}\".format(\n self.text, \n self.gold_parse, \n \"\\n\".join([p.value for p in self.predicates.all()])\n )\n \n @property\n def label(self):\n return \"sentence_{}\".format(self.pk)\n\n @staticmethod\n def add_sentence(text, parse):\n preds = extract_predicates(parse)\n exists = Sentence.objects.filter(text=text)\n if exists:\n print(text, \"is a duplicate sentence.\")\n return\n sentence = Sentence(text=text, gold_parse=parse)\n sentence.save()\n for p in preds:\n exists = Predicate.objects.filter(value=p)\n if exists:\n p = exists.first()\n else:\n p = Predicate(value=p)\n p.save()\n p.sentences.add(sentence)\n sentence.predicates.add(p)\n p.save()\n sentence.save()\n\n @staticmethod\n def list_all_non_ontology_types():\n from genesis.tools.trips import ontology\n from diesel import weights\n from collections import defaultdict as ddict\n nontypes = ddict(list)\n for s in Sentence.objects.all():\n gold = extract_predicates(s.gold_parse)\n gold = [\n parse_s_predicate(g, ontology, weights=weights.scoring_weights(), unfiltered=True) for g in gold\n ]\n for pred in gold:\n link_non = [l[1].name for l in pred.links if l[1].non]\n if link_non:\n nontypes[s.text].extend(link_non)\n if pred.root.non:\n nontypes[s.text].append(pred.root.name)\n return nontypes\n\n\nclass Predicate(models.Model):\n value = models.CharField(max_length=10000)\n sentences = models.ManyToManyField(Sentence)\n\n def __str__(self):\n return self.value\n\n @staticmethod\n def exclude_sentences(sentences):\n invert = [s for s in Sentence.objects.all() if s.text not in sentences]\n preds = set()\n for i in invert:\n preds.update(i.predicates.all())\n return preds\n\n @staticmethod\n def get_batches(n, shuffle=None):\n sentences = Sentence.objects.order_by()\n if shuffle:\n sentences = shuffle.order(sentences)\n size = len(sentences) // n\n remainder = len(sentences) % n\n parts = ([size + 1] * remainder) + ([size] * (n - remainder))\n taken = 0\n batches = []\n for x in parts:\n s = [t.text for t in sentences[taken:taken + x]]\n batches.append((s, Predicate.exclude_sentences(s)))\n taken += x\n return batches\n\n\ndef read_gold_file(gold):\n \"\"\"populate Sentence and Predicate fields\"\"\"\n with open(gold) as data:\n sentence = None\n parse = \"\"\n\n for line in data:\n if line.startswith(\";;;;\"):\n if sentence is None:\n continue\n Sentence.add_sentence(sentence, parse)\n parse = \"\"\n sentence = None\n elif line.startswith(\";;;\"):\n sentence = line.strip(\";\").strip()\n else:\n parse += line\n\n\nclass Shuffle(models.Model):\n ordering = models.CharField(max_length=10000)\n name = models.CharField(max_length=36)\n\n def order(self, sentences):\n x = [int(v) for v in self.ordering.split(\",\")]\n if len(x) != len(sentences):\n raise ValueError(\"Shuffle is out of date\")\n res = sorted(list(zip(x, sentences)), key=lambda a: a[0])\n return [r[1] for r in res]\n\n\nclass Experiment(models.Model):\n name = models.CharField(max_length=1000)\n split = models.IntegerField(default=-1)\n specific_sentences = models.ManyToManyField(Sentence)\n note = models.CharField(max_length=10000, default=\"\")\n shuffle = models.ForeignKey(Shuffle, null=True, blank=True)\n label = models.CharField(max_length=64, default=\"default\")\n arange = models.FloatField(default=0.1)\n node_cutoff = models.FloatField(default=0.9)\n pred_type = models.CharField(max_length=64, default=\"WuP\")\n\n @staticmethod\n def names():\n return [e.name for e in Experiment.objects.all()]\n\n @staticmethod\n def get(name):\n return Experiment.objects.filter(name=name).first()\n\n def duplicate(self, new_name):\n e = Experiment(name=new_name, split=self.split, shuffle=self.shuffle)\n e.save()\n for x in self.specific_sentences.all():\n e.specific_sentences.add(x)\n e.save()\n return e\n\n def count(self):\n return len(ParseResult.objects.filter(experiment=self))\n\n @staticmethod\n def scores(concise=True, force=False):\n [e.score(force=force, reruns=10, score_parser=False, concise=concise) for e in Experiment.objects.all()]\n\n def run(self, force=False, parallelize=False, parallelism=5):\n me = 5\n print(\"preparing data\")\n if self.split > 0:\n dataset = Predicate.get_batches(self.split, self.shuffle)\n elif self.split == 0:\n all_s = [t.text for t in Sentence.objects.all()]\n l = len(all_s)\n print(l)\n dataset = [\n (all_s[i*(l//5): (i+1)*(l//5)], Predicate.objects.all()) for i in range(5)\n ]\n print(len(dataset))\n for s, p in dataset:\n print(len(s))\n elif self.split == -1:\n sentences = [t.text for t in self.specific_sentences.all()]\n dataset = [([s], Predicate.exclude_sentences([s])) for s in sentences if force or not ParseResult.objects.filter(sentence__text=s, experiment=self)]\n me = 1\n else:\n dataset = []\n print(\"Data ready\")\n if parallelize and parallelism > 1:\n print(\"There are\", len(dataset), \"to go\")\n def parallel_task(task_num):\n s, d = dataset[task_num]\n run_trips_with_data(\n s,\n [x.value for x in d],\n self,\n max_attempts=me,\n port=recent_port+me*2*task_num,\n parallel=True\n )\n from pathos.multiprocessing import ProcessingPool as Pool\n with Pool(parallelism) as p:\n p.map(parallel_task, range(len(dataset)))\n else:\n for sentences, data in dataset:\n if not force:\n print('filtering preparsed')\n sentences = [s for s in sentences\n if not ParseResult.objects.filter(sentence__text=s, experiment=self)]\n if sentences:\n run_trips_with_data(sentences, [x.value for x in data], self, max_attempts=me)\n\n def add_shuffle(self):\n if self.shuffle:\n print(\"already shuffled\")\n return\n x = [str(i) for i in range(len(Sentence.objects.all()))]\n random.shuffle(x)\n shuff = Shuffle(ordering=\",\".join(x), name=self.name)\n shuff.save()\n self.shuffle = shuff\n self.save()\n\n @staticmethod\n def random_one_on_all(name, num=-1, arange=0.1, node_cutoff=0.9, pred_type=\"WuP\"):\n if num > 0:\n ix = range(len(Sentence.objects.all()))\n selected = set(list(random.sample(ix, num)))\n sentences = [s for i, s in enumerate(Sentence.objects.all()) if i in selected]\n else:\n sentences = Sentence.objects.all()\n exp = Experiment(name=name, split=-1, arange=arange, node_cutoff=node_cutoff, pred_type=pred_type)\n exp.save()\n for s in sentences:\n exp.specific_sentences.add(s)\n exp.save()\n return exp\n\n def score(self, force=False, filter_stat=lambda x: True, reruns=1, score_parser=True, concise=False):\n sg = 0\n sp = 0\n pg = 0\n num = 0\n nn = 0\n mm = 0\n avg_imp = 0\n avg_red = 0\n diffs = []\n ct = 0\n with tempfile.TemporaryDirectory() as dir:\n for pr in tqdm(ParseResult.objects.filter(experiment=self), disable=concise):\n scored = pr.score_by_smatch(dir=dir, force=force, reruns=reruns, score_parser=score_parser, concise=concise)\n if pr.is_actually_scored():\n ct += 1\n if scored and filter_stat(pr):\n a, b, c = pr.score_gold, pr.score_parser, pr.sentence.parser_score\n if a > -1 and b > -1 and c > -1 and b != 1.0 and pr.sentence.parser_only != \"\" and pr.output != \"\":\n diffs.append(a - c)\n sg += a\n sp += b\n pg += c\n if a > c:\n nn += 1\n avg_imp += a - c\n if c > a:\n mm += 1\n avg_red += c - a\n num += 1\n if concise:\n print(self.name, str((sg-pg)/num), \"pos: {}, neg: {}, tot: {}, recall: {}, total_res: {}\".format(nn, mm, num, num/ct, ct))\n return sg, sp, pg\n print(\"{} ({})\\n\".format(self.name, num) +\n \"gold: {}\\nparser: {}\\nbaseline: {}\\nnum_diff: {}\\nnum_better: {}\\navg_imp: {}\\nnum_worse: {}\\navg_red {}\"\n .format(sg/num, sp/num, pg/num, num, nn, avg_imp/nn, mm, avg_red/mm)\n )\n print((sg-pg)/(nn+mm))\n return sg, sp, pg\n\n\nclass ParseResult(models.Model):\n experiment = models.ForeignKey(Experiment, default=None)\n sentence = models.ForeignKey(Sentence)\n output = models.CharField(max_length=10000)\n skeletons = models.CharField(max_length=10000)\n dot = models.CharField(max_length=100000)\n has_non = models.BooleanField(default=False)\n\n hyps = models.CharField(max_length=100000)\n score_gold = models.FloatField(default=-1)\n gold_alignments = models.CharField(max_length=100000, default=\"\")\n score_parser = models.FloatField(default=-1)\n parser_alignments = models.CharField(max_length=100000, default=\"\")\n score_hyp = models.FloatField(default=-1)\n hyp_alignments = models.CharField(max_length=100000, default=\"\")\n is_scored = models.BooleanField(default=False)\n\n def is_actually_scored(self):\n return self.score_gold > -1 and self.score_parser > -1\n\n def score_by_smatch(self, dir, force=False, reruns=1, score_parser=True, concise=False):\n from diesel.lisp import get_amr_from_lisp as getamr\n from subprocess import check_output\n smatch = \"/Users/mechko/Projects/python/truck/tester/smatch/smatch_2.0/smatch.py\"\n\n def cmd(x, y):\n return \"python {} -f {} {}\".format(smatch, x, y)\n\n def run(x):\n return float(check_output(x, shell=True).decode(\"utf-8\").split(\":\")[1].strip())\n\n if self.is_scored and not force:\n return True\n try:\n skel = getamr(self.output, xml=True)\n parser = getamr(self.sentence.parser_only, xml=True)\n gold = getamr(self.sentence.gold_parse, xml=False)\n except RecursionError:\n return False\n except ValueError as v:\n return False\n except:\n return False\n\n s, p, g = os.path.join(dir, \"skel\"), os.path.join(dir, \"parser\"), os.path.join(dir, \"gold\")\n with open(s, 'w') as skelout:\n skelout.write(skel)\n with open(g, 'w') as goldout:\n goldout.write(gold)\n with open(p, 'w') as parsout:\n parsout.write(parser)\n\n sp, sg = 0, 0\n for i in tqdm(range(reruns), desc=\"skeleton\", disable=concise):\n sp = max(sp, run(cmd(s, p)))\n sg = max(sg, run(cmd(s, g)))\n\n if score_parser:\n pg = 0\n for i in tqdm(range(reruns), desc=\"parser\", disable=concise):\n pg = max(run(cmd(p, g)), pg)\n self.sentence.parser_score = pg\n self.sentence.save()\n\n self.score_gold = sg\n self.score_parser = sp\n self.is_scored = True\n self.save()\n\n return True\n\n def score(self, force=False):\n from genesis.tools.trips import ontology\n from diesel import weights\n if self.is_scored and not force:\n return True\n if force:\n self.is_scored = False\n self.save()\n try:\n skel = extract_predicates_from_xml(self.output, as_string=True) # is actually xml\n parser = extract_predicates_from_xml(self.sentence.parser_only, as_string=True) # is actually xml\n except:\n return False\n\n gold = extract_predicates(self.sentence.gold_parse)\n\n def hn(l):\n return any([x.has_non for x in l])\n\n skel = [parse_s_predicate(s, ontology, weights=weights.scoring_weights(), unfiltered=True) for s in skel]\n parser = [parse_s_predicate(p, ontology, weights=weights.scoring_weights(), unfiltered=True) for p in parser]\n gold = [parse_s_predicate(g, ontology, weights=weights.scoring_weights(), unfiltered=True) for g in gold]\n\n self.has_non = hn(skel)\n self.save()\n self.sentence.has_non = hn(parser)\n self.sentence.has_non_gold = hn(gold)\n self.sentence.save()\n\n metric = compute_similarity\n\n self.score_gold, self.gold_alignments = metric(gold, skel, True)\n self.score_parser, self.parser_alignments = metric(parser, skel, True)\n if self.sentence.parser_score == -1 or force:\n self.sentence.parser_score, self.sentence.alignments = metric(gold, parser, True)\n self.sentence.save()\n self.is_scored = True\n self.save()\n return True\n\n","sub_path":"predicates/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":17616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"468415626","text":"# ----------------------------------------------------------------------------\n# Copyright (c) 2020, Franck Lejzerowicz.\n#\n# Distributed under the terms of the Modified BSD License.\n#\n# The full license is in the file LICENSE, distributed with this software.\n# ----------------------------------------------------------------------------\n\nimport sys\nimport glob\nimport pkg_resources\nimport pandas as pd\nfrom os.path import dirname, isfile, splitext\n\nfrom scipy.stats import spearmanr\nfrom skbio.stats.ordination import OrdinationResults\n\nfrom routine_qiime2_analyses._routine_q2_xpbs import run_xpbs, print_message\nfrom routine_qiime2_analyses._routine_q2_io_utils import (\n get_job_folder, get_analysis_folder, get_highlights_mmbird, get_songbird_outputs)\nfrom routine_qiime2_analyses._routine_q2_taxonomy import get_split_taxonomy\n\n\ndef get_mmvec_outputs(mmvec_outputs: list):\n # print('-'*30)\n # for i in mmvec_outputs:\n # print()\n # print(i)\n # print('-'*30)\n mmvec_outputs_pd = pd.DataFrame(\n mmvec_outputs,\n columns=[\n 'pair',\n 'case',\n 'omic1',\n 'omic2',\n 'filt1',\n 'filt2',\n 'n_common',\n 'meta_common_fp',\n 'omic1_common_fp',\n 'omic2_common_fp',\n 'omic1_common_qza',\n 'omic2_common_qza',\n 'mmvec_parameters',\n 'mmvec_out'\n ])\n mmvec_outputs_pd = mmvec_outputs_pd.set_index(\n mmvec_outputs_pd.columns.tolist()[:-1]).unstack()\n mmvec_outputs_pd.columns = mmvec_outputs_pd.columns.droplevel()\n mmvec_outputs_pd.reset_index(inplace=True)\n mmvec_outputs_pd['omic_case_filt1'] = mmvec_outputs_pd[\n 'omic1'] + '__' + mmvec_outputs_pd['case'] + '__' + mmvec_outputs_pd['filt1']\n mmvec_outputs_pd['omic_case_filt2'] = mmvec_outputs_pd[\n 'omic2'] + '__' + mmvec_outputs_pd['case'] + '__' + mmvec_outputs_pd['filt2']\n mmvec_outputs_pd['pair_case_omic_filt1'] = mmvec_outputs_pd['pair'] + '__' + mmvec_outputs_pd['omic_case_filt1']\n mmvec_outputs_pd['pair_case_omic_filt2'] = mmvec_outputs_pd['pair'] + '__' + mmvec_outputs_pd['omic_case_filt2']\n return mmvec_outputs_pd\n\n\ndef merge_mmvec_songbird_outputs(mmvec_outputs_pd, songbird_outputs_pd):\n\n rename_dic1 = dict((x, '%s_omic1_songbird_common_fp' % x) for x in songbird_outputs_pd.columns)\n rename_dic1.update({'pair_case_omic_filt': 'pair_case_omic_filt1'})\n mmvec_songbird_pd = mmvec_outputs_pd.merge(\n songbird_outputs_pd.rename(columns=rename_dic1),\n on='pair_case_omic_filt1',\n how='left'\n )\n rename_dic2 = dict((x, '%s_omic2_songbird_common_fp' % x) for x in songbird_outputs_pd.columns)\n rename_dic2.update({'pair_case_omic_filt': 'pair_case_omic_filt2'})\n mmvec_songbird_pd = mmvec_songbird_pd.merge(\n songbird_outputs_pd.rename(columns=rename_dic2),\n on='pair_case_omic_filt2',\n how='left'\n )\n return mmvec_songbird_pd\n\n\ndef get_mmvec_res(mmvec_songbird_pd):\n mmvec_out_cols = [x for x in mmvec_songbird_pd.columns if x.startswith('mmvec_out__')]\n mmvec_res = {}\n # for ech row of the main table that also contain the mmvec output folders\n for r, row in mmvec_songbird_pd.iterrows():\n pair = row['pair']\n case = row['case']\n omic1 = row['omic1']\n omic2 = row['omic2']\n filt1 = row['filt1']\n filt2 = row['filt2']\n omic1_common_fp = row['omic1_common_fp']\n if str(omic1_common_fp) == 'nan':\n continue\n omic2_common_fp = row['omic2_common_fp']\n n_common = row['n_common']\n meta_fp = row['meta_common_fp']\n # for each mmvec-parameters result\n for mmvec_out_col in mmvec_out_cols:\n\n # get the current parameters output result folder\n mmvec_out = row[mmvec_out_col]\n if str(mmvec_out) == 'nan':\n continue\n\n # get the ordination file and the ranks file and skip + warning if not performed\n mmvec_out_ranks = mmvec_out + '/model/ranks.tsv'\n mmvec_out_ordi = mmvec_out + '/model/ordination.txt'\n if not isfile(mmvec_out_ranks) or not isfile(mmvec_out_ordi):\n print('\\t\\t[run mmvec first] %s (%s) %s (%s)' % (omic1, filt1, omic2, filt2))\n continue\n\n # collect the ranks + ordination + songbirds for each pair of omics and parameters\n mmvec_res[\n (\n pair, case, omic1, omic2,\n filt1, filt2, n_common,\n mmvec_out_col.replace('mmvec_out__', '')\n )\n ] = [\n mmvec_out_ranks,\n mmvec_out_ordi,\n meta_fp,\n omic1_common_fp,\n omic2_common_fp\n ]\n return mmvec_res\n\n\ndef get_qzs(ordi_fp):\n qza = ordi_fp.replace('.txt', '.qza')\n qzv = ordi_fp.replace('.txt', '_emperor.qzv')\n return qza, qzv\n\n\ndef get_heatmap_qzs(ranks_fp):\n qza = ranks_fp.replace('.tsv', '.qza')\n qzv = ranks_fp.replace('.tsv', '_heatmap.qzv')\n return qza, qzv\n\n\ndef get_order_omics(\n omic1, omic2,\n filt1, filt2, case,\n omics_pairs\n):\n omic_feature, omic_sample = ('feature', 'sample')\n omic_microbe, omic_metabolite = ('microbe', 'metabolite')\n omic_filt1 = '%s__%s__%s' % (omic1, case, filt1)\n omic_filt2 = '%s__%s__%s' % (omic2, case, filt2)\n if (omic_filt2, omic_filt1) in omics_pairs:\n omic_feature, omic_sample = ('sample', 'feature')\n omic_microbe, omic_metabolite = ('metabolite', 'microbe')\n omic1, omic2 = omic2, omic1\n filt1, filt2 = filt2, filt1\n return omic1, omic2, filt1, filt2, omic_feature, omic_sample, omic_microbe, omic_metabolite\n\n\ndef get_paired_heatmaps_command(\n ranks_fp: str, omic1_common_fp: str, omic2_common_fp: str,\n taxonomy_tsv: str, features_names: list, topn: int, paired_heatmap_qzv: str\n):\n\n RESOURCES = pkg_resources.resource_filename(\"routine_qiime2_analyses\", \"resources\")\n mmvec_pre_paired_fp = '%s/mmvec_pre_paired-heatmaps.py' % RESOURCES\n\n cmd = ''\n # if not isfile(paired_heatmap_qzv):\n if 1:\n\n omic1_common_fp_tmp = '%s_tmp.tsv' % splitext(omic1_common_fp)[0]\n omic2_common_fp_tmp = '%s_tmp.tsv' % splitext(omic2_common_fp)[0]\n omic1_common_qza_tmp = '%s_tmp.qza' % splitext(omic1_common_fp)[0]\n omic2_common_qza_tmp = '%s_tmp.qza' % splitext(omic2_common_fp)[0]\n taxonomy_tsv_tmp = '%s_tmp.tsv' % splitext(taxonomy_tsv)[0]\n ranks_fp_tmp = '%s_tmp.tsv' % splitext(ranks_fp)[0]\n ranks_qza_tmp = '%s_tmp.qza' % splitext(ranks_fp)[0]\n\n pre_paired_heatmap_py = '%s.py' % splitext(paired_heatmap_qzv)[0]\n with open(pre_paired_heatmap_py, 'w') as o, open(mmvec_pre_paired_fp) as f:\n for line in f:\n if \"'OMIC1_COMMON_FP_TMP'\" in line:\n o.write(line.replace('OMIC1_COMMON_FP_TMP', omic1_common_fp_tmp))\n elif \"'OMIC2_COMMON_FP_TMP'\" in line:\n o.write(line.replace('OMIC2_COMMON_FP_TMP', omic2_common_fp_tmp))\n elif \"'OMIC1_COMMON_QZA_TMP'\" in line:\n o.write(line.replace('OMIC1_COMMON_QZA_TMP', omic1_common_qza_tmp))\n elif \"'OMIC2_COMMON_QZA_TMP'\" in line:\n o.write(line.replace('OMIC2_COMMON_QZA_TMP', omic2_common_qza_tmp))\n elif \"'OMIC1_COMMON_FP'\" in line:\n o.write(line.replace('OMIC1_COMMON_FP', omic1_common_fp))\n elif \"'OMIC2_COMMON_FP'\" in line:\n o.write(line.replace('OMIC2_COMMON_FP', omic2_common_fp))\n elif \"'TAXONOMY_TSV_TMP'\" in line:\n o.write(line.replace('TAXONOMY_TSV_TMP', taxonomy_tsv_tmp))\n elif \"'TAXONOMY_TSV'\" in line:\n o.write(line.replace('TAXONOMY_TSV', taxonomy_tsv))\n elif \"'RANKS_FP_TMP'\" in line:\n o.write(line.replace('RANKS_FP_TMP', ranks_fp_tmp))\n elif \"'RANKS_QZA_TMP'\" in line:\n o.write(line.replace('RANKS_QZA_TMP', ranks_qza_tmp))\n elif \"'RANKS_FP'\" in line:\n o.write(line.replace('RANKS_FP', ranks_fp))\n else:\n o.write(line)\n\n cmd += '\\npython3 %s\\n' % pre_paired_heatmap_py\n\n cmd += '\\nqiime mmvec paired-heatmap'\n cmd += ' --i-ranks %s' % ranks_qza_tmp\n cmd += ' --i-microbes-table %s' % omic1_common_qza_tmp\n cmd += ' --i-metabolites-table %s' % omic2_common_qza_tmp\n cmd += ' --m-microbe-metadata-file %s' % taxonomy_tsv_tmp\n cmd += ' --m-microbe-metadata-column Taxon'\n if features_names:\n cmd += ' --p-top-k-microbes 0'\n for features_name in features_names:\n cmd += ' --p-features %s' % features_name\n else:\n cmd += ' --p-top-k-microbes %s' % topn\n cmd += ' --p-normalize rel_row'\n cmd += ' --p-top-k-metabolites 100'\n cmd += ' --p-level 6'\n cmd += ' --o-visualization %s\\n' % paired_heatmap_qzv\n\n cmd += '\\nrm %s %s %s %s\\n' % (\n ranks_qza_tmp, omic1_common_qza_tmp,\n omic2_common_qza_tmp, taxonomy_tsv_tmp\n )\n return cmd\n\n\ndef get_xmmvec_commands(\n ordi_edit_fp, omic1, omic2,\n meta1_fp, meta2_fp, xmmvecs, pair\n):\n cmd = '\\n'\n ranks_fp = ordi_edit_fp.replace('ordination.txt', 'ranks.tsv')\n nrows = None\n ncols = None\n if isfile(ranks_fp):\n nrows = pd.read_table(ranks_fp, usecols=[0, 1, 2]).shape[0]\n ncols = pd.read_table(ranks_fp, nrows=3, index_col=0).shape[1]\n\n ranks_html = ordi_edit_fp.replace('ordination.txt', 'ranks.html')\n # if not isfile(ranks_html):\n if 1:\n cmd += '\\nXmmvec'\n cmd += ' --i-ranks-path %s' % ranks_fp\n cmd += ' --o-ranks-explored %s' % ranks_html\n cmd += ' --p-omic1-name %s' % omic1\n cmd += ' --p-omic2-name %s' % omic2\n if nrows > 50:\n cmd += ' --p-omic1-max 50'\n if ncols > 50:\n cmd += ' --p-omic2-max 50'\n if xmmvecs and pair in xmmvecs:\n cmd += ' --p-omic1-metadata %s' % meta1_fp\n cmd += ' --p-omic2-metadata %s' % meta2_fp\n if omic1 in xmmvecs[pair]:\n if 'color_variable' in xmmvecs[pair][omic1]:\n cmd += ' --p-omic1-column %s' % xmmvecs[pair][omic1]['color_variable']\n if omic2 in xmmvecs[pair]:\n if 'color_variable' in xmmvecs[pair][omic2]:\n cmd += ' --p-omic2-column %s' % xmmvecs[pair][omic2]['color_variable']\n cmd += '\\n'\n return cmd\n\n\ndef get_biplot_commands(\n ordi_edit_fp, qza, qzv, omic_feature, omic_sample,\n meta1_fp, meta2_fp, n_edit, max_r\n):\n\n cmd = '\\n'\n if max_r >= 2:\n if not isfile(qza):\n cmd += '\\nqiime tools import'\n cmd += ' --input-path %s' % ordi_edit_fp\n cmd += ' --output-path %s' % qza\n cmd += ' --type \"PCoAResults %s Properties([\\'biplot\\'])\"\\nsleep 3' % '%'\n cmd += '\\nqiime emperor biplot'\n cmd += ' --i-biplot %s' % qza\n cmd += ' --m-%s-metadata-file %s' % (omic_feature, meta1_fp)\n cmd += ' --m-%s-metadata-file %s' % (omic_sample, meta2_fp)\n cmd += ' --p-number-of-features %s' % n_edit\n cmd += ' --o-visualization %s\\n' % qzv\n return cmd\n\n\ndef get_heatmap_commands(\n ranks_fp, qza, qzv, meta1, meta2,\n meta_pd1, meta_pd2):\n\n cmd = '\\n'\n if not isfile(qza):\n cmd += '\\nqiime tools import'\n cmd += ' --input-path %s' % ranks_fp\n cmd += ' --output-path %s' % qza\n cmd += ' --type FeatureData[Conditional]'\n cmd += ' --input-format ConditionalFormat\\n'\n\n cmd += '\\nqiime mmvec heatmap'\n cmd += ' --i-ranks %s' % qza\n\n for level in 'CB':\n taxolevel_microbe = 'Taxolevel_%s' % level\n if taxolevel_microbe in meta_pd1.columns:\n break\n else:\n taxolevel_microbe = ''\n\n for level in 'DCB':\n taxolevel_metabolite = 'Taxolevel_%s' % level\n if taxolevel_metabolite in meta_pd2.columns:\n break\n else:\n taxolevel_metabolite = ''\n\n if taxolevel_microbe:\n cmd += ' --m-microbe-metadata-file %s' % meta1\n cmd += ' --m-microbe-metadata-column %s' % taxolevel_microbe\n if taxolevel_metabolite:\n cmd += ' --m-metabolite-metadata-file %s' % meta2\n cmd += ' --m-metabolite-metadata-column %s' % taxolevel_metabolite\n\n cmd += ' --o-visualization %s\\n' % qzv\n return cmd\n\n\ndef edit_ordi_qzv(ordi, ordi_fp, highlight, regexes_list, meta, meta_pd):\n\n to_keep_feats = {}\n for regex in regexes_list:\n to_keep_feats[regex.lower()] = ordi.features.index.str.lower().str.contains(regex.lower())\n to_keep_feats_pd = pd.DataFrame(to_keep_feats)\n to_keep_feats = to_keep_feats_pd.any(axis=1)\n feats_subset_list = ordi.features.index[to_keep_feats].tolist()\n\n if feats_subset_list:\n ordi_edit = '%s_%s%s' % (\n splitext(ordi_fp)[0], highlight, splitext(ordi_fp)[1])\n ordi.features = ordi.features.loc[feats_subset_list, :].copy()\n ordi.write(ordi_edit)\n n_edit = ordi.features.shape[0]\n\n meta_edit = '%s_%s%s' % (\n splitext(meta)[0], highlight, splitext(meta)[1])\n meta_edit_pd = meta_pd.loc[feats_subset_list, :].copy()\n meta_edit_pd.to_csv(meta_edit, index=True, sep='\\t')\n else:\n ordi_edit = ''\n meta_edit = ''\n n_edit = 0\n return n_edit, meta_edit, ordi_edit\n\n\ndef get_tax_fp(i_datasets_folder: str, omic: str, input_to_filtered: dict) -> str:\n\n tax_dir = get_analysis_folder(i_datasets_folder, 'taxonomy')\n\n omic_taxs = [x for x, y in input_to_filtered.items() if y == omic]\n if len(omic_taxs):\n omic_tax_ = omic_taxs[0]\n if '__raref' in omic_tax_:\n omic_tax = '__raref'.join(omic_tax_.split('__raref')[:-1])\n else:\n omic_tax = omic_tax_\n else:\n print('\\nNo taxonomy file for \"%s\"' % omic)\n return ''\n\n omic_tax_fps = glob.glob('%s/%s/tax_%s*.tsv' % (tax_dir, omic_tax, omic_tax))\n if len(omic_tax_fps):\n omic_tax_fp = omic_tax_fps[0]\n else:\n omic_tax_fp = ''\n return omic_tax_fp\n\n\ndef get_pair_cmds(mmvec_res: dict, omics_pairs_metas: dict,\n omics_pairs: list, force: bool,\n highlights: dict, xmmvecs: dict):\n crowdeds = [0, 1]\n pc_sb_correlations = []\n # mmvec_tab = []\n pair_cmds = {}\n for keys, values in mmvec_res.items():\n\n pair, case, omic1, omic2, filt1, filt2, sams, mmvec = keys\n ranks_fp, ordi_fp, meta_fp, omic1_common_fp, omic2_common_fp = values\n\n order_omics = get_order_omics(\n omic1, omic2, filt1, filt2, case, omics_pairs)\n omic1 = order_omics[0]\n omic2 = order_omics[1]\n filt1 = order_omics[2]\n filt2 = order_omics[3]\n omic_feature = order_omics[4]\n omic_sample = order_omics[5]\n omic_microbe = order_omics[6]\n omic_metabolite = order_omics[7]\n\n # get differentials\n meta1, meta_pd1, diff_cols1 = omics_pairs_metas[\n (pair, case, omic1, filt1, omic2, filt2)]\n meta2, meta_pd2, diff_cols2 = omics_pairs_metas[\n (pair, case, omic2, filt2, omic1, filt1)]\n\n # features are biplot, samples are dots\n ordi = OrdinationResults.read(ordi_fp)\n\n # start = time.time()\n cur_pc_sb_correlations, max_r = get_pc_sb_correlations(\n pair, case, ordi, omic1, omic2, filt1, filt2,\n diff_cols1, meta_pd1, diff_cols2, meta_pd2,\n meta_fp, omic1_common_fp, omic2_common_fp, ranks_fp)\n pc_sb_correlations.append(cur_pc_sb_correlations)\n # end = time.time()\n # print('get_pc_sb_correlations: %s' % (end-start))\n\n cmd = ''\n if pair in highlights:\n pair_highlights = highlights[pair]\n for highlight, regexes_list in pair_highlights.items():\n n_edit, meta_edit, ordi_edit_fp = edit_ordi_qzv(\n ordi, ordi_fp, highlight, regexes_list, meta1, meta_pd1)\n if n_edit:\n qza, qzv = get_qzs(ordi_edit_fp)\n cmd += get_biplot_commands(\n ordi_edit_fp, qza, qzv,\n omic_feature, omic_sample,\n meta_edit, meta2, n_edit, max_r)\n ordi_edit_fp = ordi_fp\n qza, qzv = get_qzs(ordi_edit_fp)\n for crowded in crowdeds:\n if crowded:\n n_ordi_feats = ordi.features.shape[0]\n qzv = qzv.replace('.qzv', '_crowded.qzv')\n else:\n n_ordi_feats = 15\n # heat_qza, heat_qzv = get_heatmap_qzs(ranks_fp)\n # cmd += get_heatmap_commands(\n # ranks_fp, heat_qza, heat_qzv, meta1,\n # meta2, meta_pd1, meta_pd2)\n cmd += get_biplot_commands(\n ordi_edit_fp, qza, qzv,\n omic_feature, omic_sample,\n meta1, meta2, n_ordi_feats, max_r)\n\n cmd += get_xmmvec_commands(\n ordi_edit_fp, omic1, omic2,\n meta1, meta2, xmmvecs, pair)\n\n topn = 5\n features_names = []\n if features_names:\n paired_heatmap_qzv = '%s_paired_heatmaps_custom.qzv' % \\\n splitext(ranks_fp)[0]\n else:\n paired_heatmap_qzv = '%s_paired_heatmaps_top%s.qzv' % \\\n (splitext(ranks_fp)[0], topn)\n\n cmd += get_paired_heatmaps_command(\n ranks_fp, omic1_common_fp, omic2_common_fp, meta1,\n features_names, topn, paired_heatmap_qzv\n )\n pair_cmds.setdefault(pair, []).append(cmd)\n return pair_cmds, pc_sb_correlations\n\n\ndef get_omics_songbirds_taxa(i_datasets_folder, mmvec_songbird_pd, taxo_pds):\n omics_pairs_metas = {}\n for omicn in ['1', '2']:\n pair_case_omics_filts = ['pair', 'case', 'omic1', 'filt1', 'omic2', 'filt2']\n all_omic_sb = [x for x in mmvec_songbird_pd.columns if x.endswith('omic%s_songbird_common_fp' % omicn)]\n omicn_songbirds = mmvec_songbird_pd[(pair_case_omics_filts + all_omic_sb)].set_index(pair_case_omics_filts).T.to_dict()\n for (pair, case, omic1, filt1, omic2, filt2), sb_head_diff_fp in omicn_songbirds.items():\n if omicn == '1':\n omic = omic1\n omic_ = omic2\n filt = filt1\n filt_ = filt2\n else:\n omic = omic2\n omic_ = omic1\n filt = filt2\n filt_ = filt1\n feats_diff_cols = []\n cur_mmvec_folder = get_analysis_folder(i_datasets_folder, 'mmvec/metadata/%s/%s' % (pair, case))\n omic_diff_list = []\n if len(sb_head_diff_fp):\n for sb_head, diff_fp in sb_head_diff_fp.items():\n model = sb_head.replace('_omic%s_songbird_common_fp' % omicn, '')\n if str(diff_fp) != 'nan' and isfile(diff_fp):\n\n diff_pd = pd.read_csv(diff_fp, header=0, sep='\\t', dtype=str)\n index_header = diff_pd.columns[0]\n if diff_pd[index_header][0] == '#q2:types':\n diff_pd = diff_pd[1:]\n diff_pd = diff_pd.rename(columns={index_header: 'Feature ID'}).set_index('Feature ID')\n diff_pd = diff_pd.drop(columns=[x for x in diff_pd.columns if 'Intercept' in x])\n\n # print()\n # print(\"diff_pd.columns\")\n # print(diff_pd.columns)\n q2s = {}\n diff_htmls = glob.glob('%s/*/tensorboard.html' % dirname(diff_fp))\n if len(diff_htmls):\n for diff_html in diff_htmls:\n baseline = diff_html.split('/')[-2]\n with open(diff_html) as f:\n for line in f:\n if 'Pseudo Q-squared' in line:\n q2 = line.split('Pseudo Q-squared: ')[-1].split('<')[0]\n # print(\"q2\")\n # print(q2)\n if float(q2) > 0.01:\n q2s[baseline] = q2\n break\n # print(\"q2s\")\n # print(q2s)\n if q2s:\n diff_cols = ['%s__%s__%s' % (\n model, x, '--'.join(['%s-Q2=%s' % (b, q) if b else 'noQ2' for b, q in q2s.items()])\n ) for x in diff_pd.columns]\n diff_pd.columns = diff_cols\n feats_diff_cols.extend(diff_cols)\n omic_diff_list.append(diff_pd)\n if len(omic_diff_list):\n omic_songbird_ranks = pd.concat(omic_diff_list, axis=1, sort=False).reset_index()\n omic_songbird_ranks.rename(columns={omic_songbird_ranks.columns[0]: 'Feature ID'}, inplace=True)\n # print(\"'\\n'.join(omic_songbird_ranks.columns.tolist())\")\n # print('\\n'.join(omic_songbird_ranks.columns.tolist()))\n # print('1.', omic_songbird_ranks.shape)\n else:\n omic_common_fp = mmvec_songbird_pd.loc[\n (mmvec_songbird_pd['pair'] == pair) &\n (mmvec_songbird_pd['case'] == case) &\n (mmvec_songbird_pd['omic1'] == omic1) &\n (mmvec_songbird_pd['filt1'] == filt1) &\n (mmvec_songbird_pd['omic2'] == omic2) &\n (mmvec_songbird_pd['filt2'] == filt2),\n 'omic%s_common_fp' % omicn\n ].tolist()[0]\n omic_tax_list = []\n if not isfile(omic_common_fp):\n continue\n # print('2.', omic_common_fp)\n with open(omic_common_fp) as f:\n for ldx, line in enumerate(f):\n if ldx:\n omic_tax_list.append([line.split('\\t')[0]])\n omic_songbird_ranks = pd.DataFrame(omic_tax_list, columns=['Feature ID'])\n # print('2.', omic_songbird_ranks.shape)\n # print(\"omic\")\n # print(omic)\n # print(\"taxo_pds.keys()\")\n # print(taxo_pds.keys())\n if omic in taxo_pds:\n omic_tax_pd = taxo_pds[omic]\n if omic_tax_pd.shape[0]:\n if 'Taxon' in omic_tax_pd.columns:\n omic_split_taxa_pd = get_split_taxonomy(omic_tax_pd.Taxon.tolist(), True)\n # print()\n # print()\n # print()\n # print()\n # print(\"omic_split_taxa_pd\")\n # print(omic_split_taxa_pd)\n # print()\n # print()\n # print(\"omic_tax_pd\")\n # print(omic_tax_pd)\n omic_tax_pd = pd.concat([omic_tax_pd, omic_split_taxa_pd], axis=1, sort=False)\n # print(\"omic_tax_pd ------------\")\n # print(omic_tax_pd)\n omic_songbird_ranks = omic_songbird_ranks.merge(\n omic_tax_pd, on='Feature ID', how='left').drop_duplicates()\n # print('3.', omic_songbird_ranks.shape)\n meta_omic_fp = '%s/feature_metadata_%s_%s__%s_%s.tsv' % (cur_mmvec_folder, omic, filt, omic_, filt_)\n drop_columns = [col for col in omic_songbird_ranks.columns if omic_songbird_ranks[col].unique().size == 1]\n meta_omic_pd = omic_songbird_ranks.drop(columns=drop_columns)\n # print(\"------------\")\n # print(\"------------\")\n # print(\"------------\")\n # print(\"------------\")\n # print(\"------------\")\n # print(\"meta_omic_pd\")\n # print(meta_omic_pd)\n # print(\"------------\")\n # print(\"------------\")\n # print(\"------------\")\n # print(\"------------\")\n # print(\"------------\")\n # print(\"meta_omic_pd.columns\")\n # print(meta_omic_pd.columns)\n # print(\"feats_diff_cols\")\n # print(feats_diff_cols)\n meta_omic_pd.to_csv(meta_omic_fp, index=False, sep='\\t')\n # print('<< written: %s >>' % meta_omic_fp)\n # print('-' *50)\n meta_omic_pd.set_index('Feature ID', inplace=True)\n omics_pairs_metas[(pair, case, omic, filt, omic_, filt_)] = (meta_omic_fp, meta_omic_pd, feats_diff_cols)\n return omics_pairs_metas\n\n\ndef get_taxo_pds(i_datasets_folder, mmvec_songbird_pd, input_to_filtered):\n taxo_pds = {}\n for omicn in ['1', '2']:\n # print('omicn:', omicn)\n # print(mmvec_songbird_pd['omic%s' % omicn].unique())\n for omic in mmvec_songbird_pd['omic%s' % omicn].unique():\n omic_tax_fp = get_tax_fp(i_datasets_folder, omic, input_to_filtered)\n # print(\"omic_tax_fp\")\n # print(omic_tax_fp)\n if isfile(omic_tax_fp):\n omic_tax_pd = pd.read_csv(omic_tax_fp, header=0, sep='\\t', dtype=str)\n omic_tax_pd.rename(columns={omic_tax_pd.columns[0]: 'Feature ID'}, inplace=True)\n else:\n omic_tax_pd = pd.DataFrame()\n # print(\"omic_tax_pd.iloc[:3,:3]\")\n # print(omic_tax_pd.iloc[:3, :3])\n taxo_pds[omic] = omic_tax_pd\n return taxo_pds\n\n\ndef get_pc_sb_correlations(pair, case, ordi, omic1, omic2, filt1, filt2,\n diff_cols1, meta_pd1, diff_cols2, meta_pd2,\n meta_fp, omic1_common_fp, omic2_common_fp, ranks_fp):\n corrs = []\n max_r = 0\n for r in range(3):\n if ordi.features.shape[1] > r:\n max_r = r\n feats = ordi.features[r]\n if len(diff_cols1):\n for model in diff_cols1:\n x = meta_pd1.loc[\n [x for x in meta_pd1.index if x in feats.index],\n model\n ].astype(float)\n x = x[x.notnull()]\n y = feats[x.index]\n r2, p2 = spearmanr(x, y)\n corrs.append([pair, case, omic1, filt1,\n 'PC%s' % (r + 1), model, r2, p2, 'spearman',\n meta_fp, omic1_common_fp, ranks_fp])\n sams = ordi.samples[r]\n if len(diff_cols2):\n for model in diff_cols2:\n x = meta_pd2.loc[\n [x for x in meta_pd2.index if x in sams.index],\n model\n ].astype(float)\n x = x[x.notnull()]\n y = sams[x.index]\n r2, p2 = spearmanr(x, y)\n corrs.append([pair, case, omic2, filt2,\n 'PC%s' % (r + 1), model, r2, p2, 'spearman',\n meta_fp, omic2_common_fp, ranks_fp])\n corrs_pd = pd.DataFrame(corrs, columns=[\n 'pair',\n 'case',\n 'omic',\n 'filt',\n 'mmvec_pc',\n 'model',\n 'correlation_coefficient',\n 'pvalue',\n 'correlation_method',\n 'meta_fp',\n 'features_fp',\n 'ranks_fp'\n ])\n return corrs_pd, max_r\n\n\ndef get_log_ratios(pc_sb_correlations_pd, correlation_threshold = 0.75):\n print(' - Checking log_ratio bins for features correlating to mmvec PCs')\n pc_sb_correlations_thresh_pd = pc_sb_correlations_pd.loc[\n ((pc_sb_correlations_pd['correlation_coefficient']).apply(abs) > correlation_threshold) &\n (pc_sb_correlations_pd['pvalue'] < 0.05)\n ]\n if pc_sb_correlations_thresh_pd.shape[0]:\n print(' > found:')\n for i in [['pair'], ['omic', 'filt'], ['model']]:\n print(' * %s for %s' % (pc_sb_correlations_thresh_pd.groupby(i).count().shape[0], i))\n for pair, pair_pd in pc_sb_correlations_thresh_pd.groupby('pair'):\n print()\n print(pair)\n for row in pair_pd.values:\n pair, omic, filt, mmvec_pc, model = row[:5]\n correlation_coefficient, pvalue, correlation_method, = row[5:8]\n meta_fp, features_fp, ranks_fp = row[-3:]\n\n\ndef run_mmbird(i_datasets_folder: str, songbird_outputs: list, p_mmvec_highlights: str,\n p_xmmvec: str, mmvec_outputs: list, force: bool, prjct_nm: str,\n qiime_env: str, chmod: str, noloc: bool, filt_raref: str,\n run_params: dict, input_to_filtered: dict, jobs: bool, chunkit: int):\n\n if not mmvec_outputs:\n print('No mmvec output detected...')\n sys.exit(0)\n # if not songbird_outputs:\n # print('No songbird output detected...')\n # sys.exit(0)\n\n print('\\t-> [mmbird] Get mmvec output...', end=' ')\n mmvec_outputs_pd = get_mmvec_outputs(mmvec_outputs)\n print('Done.')\n\n print('\\t-> [mmbird] Get songbird output...', end=' ')\n if len(songbird_outputs):\n # songbird_outputs_pd = get_songbird_outputs(songbird_outputs)\n songbird_outputs_pd = get_songbird_outputs(songbird_outputs)\n mmvec_songbird_pd = merge_mmvec_songbird_outputs(mmvec_outputs_pd, songbird_outputs_pd)\n else:\n mmvec_songbird_pd = mmvec_outputs_pd.copy()\n print('Done.')\n\n omics_pairs = [tuple(x) for x in mmvec_songbird_pd[\n ['omic_case_filt1', 'omic_case_filt2']].values.tolist()]\n\n print('\\t-> [mmbird] Get taxonomy (feature metadata)...', end=' ')\n taxo_pds = get_taxo_pds(\n i_datasets_folder, mmvec_songbird_pd, input_to_filtered)\n print('Done.')\n\n print('\\t-> [mmbird] Get songbird differentials + taxonomy...', end=' ')\n omics_pairs_metas = get_omics_songbirds_taxa(\n i_datasets_folder, mmvec_songbird_pd, taxo_pds)\n print('Done.')\n\n print('\\t-> [mmbird] Get res dict...')\n mmvec_res = get_mmvec_res(mmvec_songbird_pd)\n print('Done.')\n\n print('\\t-> [mmbird] Get commands...')\n highlights = get_highlights_mmbird(p_mmvec_highlights)\n xmmvecs = get_highlights_mmbird(p_xmmvec)\n pair_cmds, pc_sb_correlations = get_pair_cmds(\n mmvec_res, omics_pairs_metas, omics_pairs, force, highlights, xmmvecs)\n\n if len(pc_sb_correlations):\n out_folder = get_analysis_folder(i_datasets_folder, 'mmbird')\n out_correlations = '%s/pc_vs_songbird_correlations.tsv' % out_folder\n pc_sb_correlations_pd = pd.concat(pc_sb_correlations)\n if pc_sb_correlations_pd.shape[0]:\n pc_sb_correlations_pd.to_csv(out_correlations, index=False, sep='\\t')\n print('\\t\\t==> Written:', out_correlations)\n else:\n print('\\t\\t==> No good songbird model to make correlations with mmvec PCs...')\n # get_log_ratios(pc_sb_correlations_pd)\n\n job_folder = get_job_folder(i_datasets_folder, 'mmbird')\n job_folder2 = get_job_folder(i_datasets_folder, 'mmbird/chunks')\n written = 0\n run_pbs = '%s/run_mmbird_%s%s.sh' % (job_folder, prjct_nm, filt_raref)\n with open(run_pbs, 'w') as o:\n for pair, cmds in pair_cmds.items():\n out_sh = '%s/run_mmbird_%s_%s%s.sh' % (job_folder2, prjct_nm, pair, filt_raref)\n out_pbs = '%s.pbs' % splitext(out_sh)[0]\n with open(out_sh, 'w') as cur_sh:\n for cmd in cmds:\n cur_sh.write(cmd)\n written += 1\n run_xpbs(out_sh, out_pbs, '%s.mmbrd.%s%s' % (prjct_nm, pair, filt_raref), qiime_env,\n run_params[\"time\"], run_params[\"n_nodes\"], run_params[\"n_procs\"],\n run_params[\"mem_num\"], run_params[\"mem_dim\"],\n chmod, written, 'single', o, noloc, jobs)\n if written:\n print_message('# Generate mmvec biplot with songbird models', 'sh', run_pbs, jobs)\n","sub_path":"routine_qiime2_analyses/_routine_q2_mmbird.py","file_name":"_routine_q2_mmbird.py","file_ext":"py","file_size_in_byte":32531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"273533852","text":"# Copyright 2018 Amazon.com, Inc. or its affiliates. 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# A copy of the License is located at\n# \n# http://www.apache.org/licenses/LICENSE-2.0\n# \n# or in the \"license\" file accompanying this file. This file is distributed \n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either \n# express or implied. See the License for the specific language governing \n# permissions and limitations under the License.\n\n\nimport os\nimport sys\nsys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../src')))\n\nfrom frontend.parser import *\n\n\ndef test(s):\n print(\"=== \" + s)\n print(parse_string(s))\n print(string_to_ast(s))\n\n# print lex_string(\"5+6\")\n# print lex_string(\"5-(6*7)\")\n\ntest(\"5+6\")\ntest(\"5-(6*7)\")\ntest(\"5-6*7\")\ntest(\"x = 6\")\ntest(\"x == 6\")\nprint(\"\")\n\ntest(\"5+6 7+8\")\ntest(\"x=6 7==8\")\ntest(\"5+6+7+8 x=6 7+9\")\ntest(\"5+6+7+8; x=6; 7+9\")\nprint(\"\")\n\ntest(\"-6\")\nprint(\"\")\n\ntest(\"x = x + 1\")\nprint(\"\")\n\ntest(\"x[0]\")\ntest(\"x.f\")\ntest(\"x.f[0]\")\ntest(\"x.f = 5\")\ntest(\"x[0] = 5\")\ntest(\"x.f[0] = 6\")\ntest(\"x.f[0] = -6\")\ntest(\"x.f[0] = x-6\")\nprint(\"\")\n\ntest(\"foo()\")\ntest(\"foo(x)\")\ntest(\"foo(x.t)\")\ntest(\"x.foo()\")\ntest(\"x.foo(x)\")\ntest(\"x.foo(x.t)\")\ntest(\"x.foo(x.t,y.p[0])\")\nprint(\"\")\n\ntest(\"foo.bar.baz\")\n# test(\"foo.bar.baz[0][1](x)(y)\")\ntest(\"foo.bar[0]\")\nprint(\"\")\n\ntest(\"new(){}\")\ntest(\"new(x=0){}\")\ntest(\"new(x=0,y=v.x){}\")\ntest(\"new(){foo(){}}\")\ntest(\"new(x=0){foo(x){x}}\")\ntest(\"new(x=0,y=v.x){foo(x,y){x=y}}\")\nprint(\"\")\n\ntest(\"if x { 6 }\")\ntest(\"if x { 6 } else { 7 }\")\ntest(\"if x.y[0] { new(x=0){} } else { new(y=0){} }\")\nprint(\"\")\n\ntest(\"new(xxx){get() {xxx}}\")\ntest(\"x = new(x=0) { foo(y) { x = (x + y) }; bar() { x } }; x.foo(3); x.foo(6); x.bar()\")\n\ntest(\"PrfC() { new () {} }\")\ntest(\"PrfC() { new () {} }; PrfC()\")\ntest(\"new(){foo(x,y){x=y 5 6 7}} 5 6 7\")\ntest(\"PrfC(x) { new () { foo() { x } } }; x = PrfC(5); x.foo()\")\n\n\ntest(\"\"\"\nFooA() { \n new (x=1) { \n bar(z) { \n x \n } \n } \n}\nFooB(x) {\n new () {\n bar(z) {\n x \n }\n }\n}\nFooA() ~ FooB(1)\n\"\"\")\n\ntest(\"new() { foo() { x y } }\")\n\ntest(\"\"\"\nnew() {}\n// foobar\nnew() {}\n\"\"\")\n\ntest(\"\"\"\n// outer comment\nnew() {\n // within an object body\n foo(x) {\n // within a method body \n x\n }\n}\"\"\")","sub_path":"tests/parsertest.py","file_name":"parsertest.py","file_ext":"py","file_size_in_byte":2421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"418066235","text":"\"\"\"\nckwg +31\nCopyright 2016-2017 by Kitware, Inc.\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and/or other materials provided with the distribution.\n\n * Neither name of Kitware, Inc. nor the names of any contributors may be used\n to endorse or promote products derived from this software without specific\n prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n==============================================================================\n\nTest Python interface to Eigen::Matrix wrapping via Numpy ndarray sub-class\n\n\"\"\"\n\nimport unittest\n\nimport nose.tools as ntools\nimport numpy\n\nfrom vital.exceptions.eigen import VitalInvalidStaticEigenShape\nfrom vital.types import EigenArray\n\n\nclass TestVitalEigenMatrix (unittest.TestCase):\n\n def test_valid_static_size_init(self):\n \"\"\"\n Test construction of some of the static sizes.\n \"\"\"\n a = EigenArray() # default shape\n ntools.assert_equal(a.shape, (2, 1))\n\n a = EigenArray(2, 1)\n ntools.assert_equal(a.shape, (2, 1))\n\n a = EigenArray(2, 2)\n ntools.assert_equal(a.shape, (2, 2))\n\n a = EigenArray(4, 4)\n ntools.assert_equal(a.shape, (4, 4))\n\n def test_dynamic_size_init(self):\n a = EigenArray(2, dynamic_rows=True)\n ntools.assert_equal(a.shape, (2, 1))\n\n a = EigenArray(300, dynamic_rows=True)\n ntools.assert_equal(a.shape, (300, 1))\n\n a = EigenArray(1234, 256, dynamic_rows=True, dynamic_cols=True)\n ntools.assert_equal(a.shape, (1234, 256))\n\n def test_invalid_shape_init(self):\n ntools.assert_raises(\n VitalInvalidStaticEigenShape,\n EigenArray,\n 5,\n )\n\n ntools.assert_raises(\n VitalInvalidStaticEigenShape,\n EigenArray,\n 400, 500\n )\n\n def test_order_transform(self):\n a = EigenArray(2, 3)\n d = a.base.base # The data pointer\n # column-major 2x3 matrix [[ 1 2 3 ] (Eigen format)\n # [ 4 5 6 ]]\n d[0] = 1; d[2] = 2; d[4] = 3\n d[1] = 4; d[3] = 5; d[5] = 6\n\n numpy.testing.assert_array_equal(a, [[1., 2., 3.],\n [4., 5., 6.]])\n\n ntools.assert_equal(a.at_eigen_base_index(0, 0), 1)\n ntools.assert_equal(a.at_eigen_base_index(0, 1), 2)\n ntools.assert_equal(a.at_eigen_base_index(0, 2), 3)\n ntools.assert_equal(a.at_eigen_base_index(1, 0), 4)\n ntools.assert_equal(a.at_eigen_base_index(1, 1), 5)\n ntools.assert_equal(a.at_eigen_base_index(1, 2), 6)\n\n def test_mutability(self):\n a = EigenArray(2, 3)\n d = a.base.base # The data pointer\n for i in xrange(6):\n d[i] = 0\n numpy.testing.assert_array_equal(a, [[0, 0, 0],\n [0, 0, 0]])\n\n a[:] = 1\n numpy.testing.assert_array_equal(a, [[1, 1, 1],\n [1, 1, 1]])\n\n a[1, 0] = 2\n numpy.testing.assert_array_equal(a, [[1, 1, 1],\n [2, 1, 1]])\n\n a[:, 2] = 3\n numpy.testing.assert_array_equal(a, [[1, 1, 3],\n [2, 1, 3]])\n\n a += 1\n numpy.testing.assert_array_equal(a, [[2, 2, 4],\n [3, 2, 4]])\n\n b = a*0\n numpy.testing.assert_array_equal(a, [[2, 2, 4],\n [3, 2, 4]])\n numpy.testing.assert_array_equal(b, [[0, 0, 0],\n [0, 0, 0]])\n\n def test_from_iterable(self):\n # from list\n expected_list = [[0.4, 0],\n [1, 1.123],\n [2.253, 4.768124]]\n ea = EigenArray.from_iterable(expected_list, target_shape=(3, 2))\n numpy.testing.assert_array_equal(ea, expected_list)\n\n # from ndarray\n expected_ndar = numpy.array(expected_list)\n ea = EigenArray.from_iterable(expected_ndar, target_shape=(3, 2))\n numpy.testing.assert_array_equal(ea, expected_ndar)\n\n # from EigenArray, which should return the input object\n ea = EigenArray(3, 2)\n ea[:] = expected_list\n ea2 = EigenArray.from_iterable(ea, target_shape=(3, 2))\n numpy.testing.assert_array_equal(ea2, ea)\n ntools.assert_is(ea, ea2)\n ntools.assert_true(ea is ea2)\n\n def test_from_iterable_1D(self):\n # 1-dim iterables/vectors are treated as column vectors\n input = [1, 2, 3, 4]\n expected = [[1],\n [2],\n [3],\n [4]]\n\n e = EigenArray.from_iterable(input)\n numpy.testing.assert_equal(e, expected)\n\n e2 = EigenArray.from_iterable(e)\n numpy.testing.assert_equal(e, e2)\n\n def test_norm(self):\n e = EigenArray.from_iterable([1,2,3,4])\n e.norm() == numpy.sqrt(1+4+9+16)\n","sub_path":"vital/bindings/python/vital/tests/test_eigen_numpy.py","file_name":"test_eigen_numpy.py","file_ext":"py","file_size_in_byte":6096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"27614599","text":"#Erick\r\nclass salesperson():\r\n name = ''\r\n idnum = 0\r\n special = ''\r\n gender = ''\r\n age = 0\r\n\r\n def __init__(self, newname, newidnum, newspecial, newgender, newage):\r\n self.name = newname\r\n self.idnum = newidnum\r\n self.special = newspecial\r\n self.gender = newgender\r\n self.age = newage\r\n\r\n def getName(self):\r\n return self.name\r\n\r\n def getID(self):\r\n return self.idnum\r\n\r\n def getSpecial(self):\r\n return self.special\r\n\r\n def getGender(self):\r\n return self.gender\r\n\r\n def getAge(self):\r\n return self.age\r\n\r\n#Erick\r\nclass purchaseOrder():\r\n # Employee Information\r\n empName = ''\r\n empID = 0\r\n empSpecial = ''\r\n empGender = ''\r\n empAge = 0\r\n\r\n # Customer Information\r\n custFirstName = ''\r\n custLastName = ''\r\n custGender = ''\r\n custAge = 0\r\n custMarital = ''\r\n\r\n # Vehicle Information\r\n carID = 0\r\n carColor = ''\r\n carType = ''\r\n carCondition = ''\r\n carPrice = 0\r\n carYear = 0\r\n\r\n def insertEmpInfo(self, newEmpName, newEmpID, newEmpSpecial, newEmpGender, newEmpAge):\r\n self.empName = newEmpName\r\n self.empID = newEmpID\r\n self.empSpecial = newEmpSpecial\r\n self.empGender = newEmpGender\r\n self.empAge = newEmpAge\r\n\r\n def insertCustInfo(self, newCustFirstName, newCustLastName, newCustGender, newCustAge, newCustMarital):\r\n self.custFirstName = newCustFirstName\r\n self.custLastName = newCustLastName\r\n self.custGender = newCustGender\r\n self.custAge = newCustAge\r\n self.custMarital = newCustMarital\r\n\r\n def insertCarInfo(self, newCarID, newCarColor, newCarType, newCarCondition, newCarPrice, newCarYear):\r\n self.carID = newCarID\r\n self.carColor = newCarColor\r\n self.carType = newCarType\r\n self.carCondition = newCarCondition\r\n self.carPrice = newCarPrice\r\n self.carYear = newCarYear\r\n\r\n def printEmployeeInfo(self):\r\n print(\"\\n\"\r\n \"SALESPERSON INFORMATION:\\n\"\r\n \"NAME: \" + str(self.empName), \"\\n\"\r\n \"ID: \" + str(self.empID), \"\\n\"\r\n \"SPECIALTY: \" + str(self.empSpecial), \"\\n\"\r\n \"GENDER: \" + str(self.empGender), \"\\n\"\r\n \"AGE: \" + str(self.empAge))\r\n\r\n def printCustomerInfo(self):\r\n print(\"\\n\"\r\n \"CUSTOMER INFORMATION:\\n\"\r\n \"FIRST NAME: \" + str(self.custFirstName), \"\\n\"\r\n \"LAST NAME: \" + str(self.custLastName), \"\\n\"\r\n \"GENDER: \" + str(self.custGender), \"\\n\"\r\n \"AGE: \" + str(self.custAge), \"\\n\"\r\n \"MARITAL STATUS: \" + str(self.custMarital))\r\n\r\n def printVehicleInfo(self):\r\n print(\"\\n\"\r\n \"VEHICLE INFORMATION:\\n\"\r\n \"ID: \" + str(self.carID), \"\\n\"\r\n \"TYPE: \" + str(self.carType), \"\\n\"\r\n \"CONDITION: \" + str(self.carCondition), \"\\n\"\r\n \"YEAR: \" + str(self.carYear), \"\\n\"\r\n \"COLOR: \" + str(self.carColor), \"\\n\"\r\n \"PRICE: \" + str(self.carPrice))\r\n\r\n#Kyle\r\nclass customer:\r\n FirstName = ''\r\n LastName = ''\r\n Age = 0\r\n Gender = ''\r\n MaritalStatus = ''\r\n\r\n def __init__(self, FirstName, LastName, Age, Gender, MaritalStatus):\r\n self.FirstName = FirstName\r\n self.LastName = LastName\r\n self.Age = Age\r\n self.Gender = Gender\r\n self.MaritalStatus = MaritalStatus\r\n\r\n def getFirstName(self):\r\n return self.FirstName\r\n\r\n def getLastName(self):\r\n return self.LastName\r\n\r\n def getAge(self):\r\n return self.Age\r\n\r\n def getGender(self):\r\n return self.Gender\r\n\r\n def getMaritalStatus(self):\r\n return self.MaritalStatus\r\n\r\n#Kyle\r\nclass vehicle:\r\n ID = 0\r\n Color = ''\r\n Type = ''\r\n Condition = ''\r\n Year = ''\r\n Price = 0\r\n\r\n def __init__(self, ID, Color, Type, Condition, Year, Price):\r\n self.ID = ID\r\n self.Color = Color\r\n self.Type = Type\r\n self.Condition = Condition\r\n self.Year = Year\r\n self.Price = Price\r\n\r\n def getID(self):\r\n return self.ID\r\n\r\n def getColor(self):\r\n return self.Color\r\n\r\n def getType(self):\r\n return self.Type\r\n\r\n def getCondition(self):\r\n return self.Condition\r\n\r\n def getYear(self):\r\n return self.Year\r\n\r\n def getPrice(self):\r\n return self.Price\r\n\r\n\r\n###############\r\n# Employees List\r\n###############\r\nRick = salesperson(\"Rick James\", 213, \"Compact Cars\", \"Male\", 48)\r\nJenny = salesperson(\"Jenny TuTone\", 8675309, \"Diesel Trucks\", \"Female\", 15)\r\nCraig = salesperson(\"Craig Michaels\", 656, \"Motorcycles\", \"Male\", 25)\r\n\r\nEmployees = list()\r\nEmployees.append(Rick)\r\nEmployees.append(Jenny)\r\nEmployees.append(Craig)\r\n\r\n##########\r\n# Cars List\r\n##########\r\nCar1 = vehicle(101, \"White\", \"Sedan\", \"New\", 2017, 22999)\r\nCar2 = vehicle(102, \"Yellow\", \"Coupe\", \"Used\", 2007, 20197)\r\nCar3 = vehicle(103, \"Black\", \"Sedan\", \"Used\", 2009, 15999)\r\nCar4 = vehicle(104, \"Green\", \"Coupe\", \"New\", 2016, 25199)\r\nTruck1 = vehicle(201, \"Silver\", \"Crew Cab\", \"New\", 2017, 32999)\r\nTruck2 = vehicle(202, \"Brown\", \"Regular Cab\", \"Used\", 2011, 25999)\r\nTruck3 = vehicle(203, \"Red\", \"Crew Cab\", \"Used\", 2013, 26999)\r\nTruck4 = vehicle(204, \"Blue\", \"Regular Cab\", \"New\", 2017, 30999)\r\nMotor1 = vehicle(301, \"Black\", \"Sport\", \"New\", 2017, 19999)\r\nMotor2 = vehicle(302, \"White\", \"Sport\", \"Used\", 2012, 15987)\r\n\r\nVehicles = list()\r\nVehicles.append(Car1)\r\nVehicles.append(Car2)\r\nVehicles.append(Car3)\r\nVehicles.append(Car4)\r\nVehicles.append(Truck1)\r\nVehicles.append(Truck2)\r\nVehicles.append(Truck3)\r\nVehicles.append(Truck4)\r\nVehicles.append(Motor1)\r\nVehicles.append(Motor2)\r\n\r\n#########################\r\n# Start of actual program\r\n#########################\r\n\r\ncount = 1\r\nwhile count == 1:\r\n choiceCount = 1\r\n while choiceCount ==1:\r\n print(\"\\n\"\r\n \"What would you like to do today?\\n\"\r\n \"\\n\"\r\n \"1. Print new purchase order.\\n\"\r\n \"2. Look up employee information.\\n\"\r\n \"3. Look up car information.\\n\"\r\n \"4. Exit.\")\r\n choice = input()\r\n try:\r\n choice = int(choice)\r\n choiceCount = 0\r\n except:\r\n print(\"Please enter a number 1 through 4\")\r\n\r\n#Erick\r\n if choice == 1:\r\n custFirstName = str(input(\"What is the customer's first name?\"))\r\n custLastName = str(input(\"What is the customer's last name?\"))\r\n\r\n ageCount = 1\r\n while ageCount == 1:\r\n custAge = input(\"What is the customer's age?\")\r\n try:\r\n custAge = int(custAge)\r\n ageCount = 0\r\n except ValueError:\r\n print(\"Please enter a number.\")\r\n\r\n genderCount = 1\r\n while genderCount == 1:\r\n custGender = str(input(\"Is the customer male or female? (Enter 'm' or 'f')\"))\r\n if custGender == 'm':\r\n genderCount = 0\r\n elif custGender == 'f':\r\n genderCount = 0\r\n else:\r\n print(\"Please enter either 'm' or 'f'\")\r\n\r\n maritalCount = 1\r\n while maritalCount == 1:\r\n custMarital = str(input(\"What is the customer's marital status? (single, married, n/a)\"))\r\n if custMarital == \"single\":\r\n maritalCount = 0\r\n elif custMarital == \"married\":\r\n maritalCount = 0\r\n elif custMarital == \"n/a\":\r\n maritalCount = 0\r\n else:\r\n print(\"Please enter 'single', 'married', or 'n/a'\")\r\n\r\n newCust = customer(custFirstName, custLastName, custAge, custGender, custMarital)\r\n\r\n purchaseOrder1 = purchaseOrder()\r\n purchaseOrder1.insertCustInfo(newCust.getFirstName(), newCust.getLastName(), newCust.getAge(),newCust.getGender(), newCust.getMaritalStatus())\r\n\r\n empCount = 1\r\n while empCount == 1:\r\n employeeInput = input(\"\\n\"\r\n \"Which employee sold the vehicle?\\n\"\r\n \"1. Rick James\\n\"\r\n \"2. Jenny Tutone\\n\"\r\n \"3. Craig Michaels\\n\")\r\n\r\n try:\r\n employeeInput = int(employeeInput)\r\n except ValueError:\r\n pass\r\n\r\n if employeeInput == 1:\r\n purchaseOrder1.insertEmpInfo(Rick.getName(), Rick.getID(), Rick.getSpecial(), Rick.getGender(),Rick.getAge())\r\n empCount = 0\r\n elif employeeInput == 2:\r\n purchaseOrder1.insertEmpInfo(Jenny.getName(), Jenny.getID(), Jenny.getSpecial(), Jenny.getGender(),Jenny.getAge())\r\n empCount = 0\r\n elif employeeInput == 3:\r\n purchaseOrder1.insertEmpInfo(Craig.getName(), Craig.getID(), Craig.getSpecial(), Craig.getGender(),Craig.getAge())\r\n empCount = 0\r\n else:\r\n print(\"Please enter a number 1 through 3.\")\r\n\r\n carCount = 1\r\n while carCount == 1:\r\n vehicleInput = input(\"\\n\"\r\n \"Which vehicle did the customer purchase?\\n\"\r\n \"1. 2017 White Sedan\\n\"\r\n \"2. 2007 Yellow Coupe\\n\"\r\n \"3. 2009 Black Sedan\\n\"\r\n \"4. 2016 Green Coupe\\n\"\r\n \"5. 2017 Silver Crew Cab Truck\\n\"\r\n \"6. 2011 Brown Regular Cab Truck\\n\"\r\n \"7. 2013 Red Crew Cab Truck\\n\"\r\n \"8. 2017 Blue Regular Cab Truck\\n\"\r\n \"9. 2017 Black Sport Motorcycle\\n\"\r\n \"10. 2012 White Sport Motorcycle\\n\")\r\n\r\n try:\r\n vehicleInput = int(vehicleInput)\r\n except:\r\n pass\r\n if vehicleInput == 1:\r\n purchaseOrder1.insertCarInfo(Car1.getID(), Car1.getColor(), Car1.getType(), Car1.getCondition(),\r\n Car1.getPrice(), Car1.getYear())\r\n carCount = 0\r\n elif vehicleInput == 2:\r\n purchaseOrder1.insertCarInfo(Car2.getID(), Car2.getColor(), Car2.getType(), Car2.getCondition(),\r\n Car2.getPrice(), Car2.getYear())\r\n carCount = 0\r\n elif vehicleInput == 3:\r\n purchaseOrder1.insertCarInfo(Car3.getID(), Car3.getColor(), Car3.getType(), Car3.getCondition(),\r\n Car3.getPrice(), Car3.getYear())\r\n carCount = 0\r\n elif vehicleInput == 4:\r\n purchaseOrder1.insertCarInfo(Car4.getID(), Car4.getColor(), Car4.getType(), Car4.getCondition(),\r\n Car4.getPrice(), Car4.getYear())\r\n carCount = 0\r\n elif vehicleInput == 5:\r\n purchaseOrder1.insertCarInfo(Truck1.getID(), Truck1.getColor(), Truck1.getType(), Truck1.getCondition(),\r\n Truck1.getPrice(), Truck1.getYear())\r\n carCount = 0\r\n elif vehicleInput == 6:\r\n purchaseOrder1.insertCarInfo(Truck2.getID(), Truck2.getColor(), Truck2.getType(), Truck2.getCondition(),\r\n Truck2.getPrice(), Truck2.getYear())\r\n carCount = 0\r\n elif vehicleInput == 7:\r\n purchaseOrder1.insertCarInfo(Truck3.getID(), Truck3.getColor(), Truck3.getType(), Truck3.getCondition(),\r\n Truck3.getPrice(), Truck3.getYear())\r\n carCount = 0\r\n elif vehicleInput == 8:\r\n purchaseOrder1.insertCarInfo(Truck4.getID(), Truck4.getColor(), Truck4.getType(), Truck4.getCondition(),\r\n Truck4.getPrice(), Truck4.getYear())\r\n carCount = 0\r\n elif vehicleInput == 9:\r\n purchaseOrder1.insertCarInfo(Motor1.getID(), Motor1.getColor(), Motor1.getType(), Motor1.getCondition(),\r\n Motor1.getPrice(), Motor1.getYear())\r\n carCount = 0\r\n elif vehicleInput == 10:\r\n purchaseOrder1.insertCarInfo(Motor2.getID(), Motor2.getColor(), Motor2.getType(), Motor2.getCondition(),\r\n Motor2.getPrice(), Motor2.getYear())\r\n carCount = 0\r\n else:\r\n print(\"Please enter a number 1 through 10.\")\r\n\r\n print(\"\\n\"\r\n \"\\n\"\r\n \"PURCHASE ORDER:\")\r\n purchaseOrder1.printVehicleInfo()\r\n purchaseOrder1.printCustomerInfo()\r\n purchaseOrder1.printEmployeeInfo()\r\n input(\"\\n\"\r\n \"PRESS ENTER TO CONTINUE...\"\r\n \"\\n\")\r\n\r\n#Kyle\r\n if choice == 2:\r\n salesCount = 1\r\n while salesCount == 1:\r\n salesInput = input(\"\\n\"\r\n \"Employee List:\\n\"\r\n \"\\n\"\r\n \"1. Rick James\\n\"\r\n \"2. Jenny Tutone\\n\"\r\n \"3. Craig Michaels\\n\")\r\n try:\r\n salesInput = int(salesInput)\r\n except:\r\n pass\r\n if salesInput == 1:\r\n print(\"Information:\")\r\n print(\"Name: Rick James\")\r\n print(\"ID Number: 213\")\r\n print(\"Specialty: Compact Cars\")\r\n print(\"Gender: Male\")\r\n print(\"Age: 48\")\r\n salesCount = 0\r\n\r\n elif salesInput == 2:\r\n print(\"Information:\")\r\n print(\"Name: Jenny Tutone\")\r\n print(\"ID Number: 8675309\")\r\n print(\"Specialty: Diesel Trucks\")\r\n print(\"Gender: Female\")\r\n print(\"Age: 15\")\r\n salesCount = 0\r\n\r\n elif salesInput == 3:\r\n print(\"Information:\")\r\n print(\"Name: Craig Michaels\")\r\n print(\"ID Number: 656\")\r\n print(\"Specialty: Motorcycles\")\r\n print(\"Gender: Male\")\r\n print(\"Age: 25\")\r\n salesCount = 0\r\n\r\n else:\r\n print(\"Please enter a number 1 through 3.\")\r\n\r\n#Kyle \r\n elif choice == 3:\r\n vehCount = 1\r\n while vehCount == 1:\r\n vehicleInput = input(\"\\n\"\r\n \"Vehicle List:\\n\"\r\n \"\\n\"\r\n \"1. White Sedan\\n\"\r\n \"2. Yellow Coupe\\n\"\r\n \"3. Black Sedan\\n\"\r\n \"4. Green Coupe\\n\"\r\n \"5. Silver crew\\n\"\r\n \"6. Brown Regular\\n\"\r\n \"7. Red Crew\\n\"\r\n \"8. Blue Regular\\n\"\r\n \"9. Black Sport\\n\"\r\n \"10. White Sport\\n\")\r\n try:\r\n vehicleInput = int(vehicleInput)\r\n except:\r\n pass\r\n if vehicleInput == 1:\r\n print(\"Information:\")\r\n print(\"Vehicle ID: 101\")\r\n print(\"Vehcile Type: Car\")\r\n print(\"Color: White\")\r\n print(\"Series: Sedan\")\r\n print(\"Condition: New\")\r\n print(\"Year: 2017\")\r\n print(\"Price: $22,999\")\r\n vehCount = 0\r\n\r\n elif vehicleInput == 2:\r\n print(\"Information: \")\r\n print(\"Vehicle ID: 102\")\r\n print(\"Vehcile Type: Car\")\r\n print(\"Color: Yellow\")\r\n print(\"Series: Coupe\")\r\n print(\"Condition: Used\")\r\n print(\"Year: 2007\")\r\n print(\"Price: $20,197\")\r\n vehCount = 0\r\n\r\n elif vehicleInput == 3:\r\n print(\"Information:\")\r\n print(\"Vehicle ID: 103\")\r\n print(\"Vehcile Type: Car\")\r\n print(\"Color: Black\")\r\n print(\"Series: Sedan\")\r\n print(\"Condition: Used\")\r\n print(\"Year: 2009\")\r\n print(\"Price: $15,999\")\r\n vehCount = 0\r\n\r\n elif vehicleInput == 4:\r\n print(\"Information:\")\r\n print(\"Vehicle ID: 104\")\r\n print(\"Vehcile Type: Car\")\r\n print(\"Color: Green\")\r\n print(\"Series: Coupe\")\r\n print(\"Condition: New\")\r\n print(\"Year: 2017\")\r\n print(\"Price: $25,199\")\r\n vehCount = 0\r\n\r\n elif vehicleInput == 5:\r\n print(\"Information:\")\r\n print(\"Vehicle ID: 201\")\r\n print(\"Vehcile Type: Truck\")\r\n print(\"Color: Silver\")\r\n print(\"Cab Size: Crew Cab\")\r\n print(\"Condition: New\")\r\n print(\"Year: 2017\")\r\n print(\"Price: $32,999\")\r\n vehCount = 0\r\n\r\n elif vehicleInput == 6:\r\n print(\"Information:\")\r\n print(\"Vehicle ID: 202\")\r\n print(\"Vehcile Type: Truck\")\r\n print(\"Color: Brown\")\r\n print(\"Cab Size: Regular Cab\")\r\n print(\"Condition: Used\")\r\n print(\"Year: 2011\")\r\n print(\"Price: $25,197\")\r\n vehCount = 0\r\n\r\n elif vehicleInput == 7:\r\n print(\"Information:\")\r\n print(\"Vehicle ID: 203\")\r\n print(\"Vehcile Type: Truck\")\r\n print(\"Color: Red\")\r\n print(\"Cab Size: Crew Cab\")\r\n print(\"Condition: Used\")\r\n print(\"Year: 2013\")\r\n print(\"Price: $26,999\")\r\n vehCount = 0\r\n\r\n elif vehicleInput == 8:\r\n print(\"Information:\")\r\n print(\"Vehicle ID: 204\")\r\n print(\"Vehcile Type: Truck\")\r\n print(\"Color: Blue\")\r\n print(\"Cab Size: Regular Cab\")\r\n print(\"Condition: New\")\r\n print(\"Year: 2017\")\r\n print(\"Price: $30,999\")\r\n vehCount = 0\r\n\r\n elif vehicleInput == 9:\r\n print(\"Information:\")\r\n print(\"Vehicle ID: 301\")\r\n print(\"Vehcile Type: Motorcycle\")\r\n print(\"Color: Black\")\r\n print(\"Series: Sport\")\r\n print(\"Condition: New\")\r\n print(\"Year: 2017\")\r\n print(\"Price: $19,999\")\r\n vehCount = 0\r\n\r\n elif vehicleInput == 10:\r\n print(\"Information:\")\r\n print(\"Vehicle ID: 302\")\r\n print(\"Vehcile Type: Motorcycle\")\r\n print(\"Color: White\")\r\n print(\"Series: Sport\")\r\n print(\"Condition: Used\")\r\n print(\"Year: 2012\")\r\n print(\"Price: $15,987\")\r\n vehCount = 0\r\n\r\n#Erick\r\n elif choice == 4:\r\n count = 0\r\n\r\n else:\r\n print(\"Please enter a number 1 through 4.\")\r\n","sub_path":"Team Squatting Wolves/Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":19484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"25089601","text":"from tekton.io.istream import IStream\nfrom tekton.lang.exceptions import SocketException\nimport sys\nimport socket\nimport select\n\n\nclass SocketStream(IStream):\n def __init__(self, socket=None, buffersize=4096):\n self.__socket = socket\n self.__buffersize = buffersize\n self.__address = None\n\n def connect(self, address):\n self.__socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n try:\n self.__socket.connect(address)\n except:\n raise SocketException(\"Failed to connect to \" + address[0] +\n \":\" + str(address[1]))\n\n def attach(self, socket):\n self.close()\n self.__socket = socket\n\n def close(self):\n if self.__socket:\n self.__socket.shutdown(socket.SHUT_RDWR)\n self.__socket.close()\n\n def get_address(self):\n return self.__address\n\n def get_socket(self):\n return self.__socket\n\n def available(self):\n available = False\n\n if self.__socket:\n fd = self.__socket.fileno()\n rlist, wlist, elist = select.select([fd], [], [], 0.0)\n if fd in rlist:\n available = True\n\n return available\n\n def istream_read(self, count=None):\n try:\n if count:\n buffer = self.__socket.recv(count)\n else:\n buffer = self.__socket.recv(self.__buffersize)\n except:\n raise SocketException(exc_info=sys.exc_info())\n\n return buffer\n\n def istream_read_blocked(self, count):\n bytesRead = 0\n buffer = \"\"\n\n while bytesRead < count:\n tmpbuf = self.istream_read(count - bytesRead)\n if len(tmpbuf) == 0:\n break\n buffer += tmpbuf\n bytesRead += len(tmpbuf)\n\n if bytesRead != count:\n raise SocketException(\"Not enough data\")\n\n return buffer\n\n # -------------------------------------------------------------------------\n def istream_write(self, buffer):\n self.__socket.sendall(buffer)\n\n # -------------------------------------------------------------------------\n def istream_flush(self):\n return\n","sub_path":"libraries/tekton/net/socketstream.py","file_name":"socketstream.py","file_ext":"py","file_size_in_byte":2221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"28096109","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Oct 8 12:37:29 2019\n\n@author: mac\n\"\"\"\n#\nresult_f = open(\"scores_list.txt\",'r')\nfor line in result_f:\n print(line.strip())\nresult_f.close()\n\ntry:\n result_f = open(\"no_file.txt\")\nexcept:\n print(\"해당하는 파일이 없습니다.\")\n\n#점수들 프린트 하기\nresult_f = open(\"scores_list.txt\",'r')\nfor line in result_f:\n record = line.split()\n print(record[1])\nresult_f.close()\n\n#일등찾는법========================================\n\nresult_f = open(\"scores_list.txt\",'r')\nhighest_score = 0\nsecond_highest_score = 0\nthird_highest_score = 0\n\nfor line in result_f:\n record = line.split()\n try:\n score = float(record[1])\n except:\n continue # 첫줄에 score값은 수치로 변환이 안되서 그냥 예외처리!\n if highest_score < score:\n third_highest_score = second_highest_score\n second_highest_score - highest_score\n highest_score = score\n \n elif second_highest_score < score:\n second_highest_score = score\n elif third_highest_score < score:\n third_highest_score = score\n else:\n continue\n \nresult_f.close()\nprint(\"1등의 점수\", highest_score)\nprint(\"2등의 점수\", second_highest_score)\nprint(\"3등의 점수\", third_highest_score)\n#=====================================================\n\nresult_f = open(\"scores_list.txt\",'r')\nscore_list = [] #공리스트 만든느 법\n\nfor line in result_f:\n name, score = line.split()\n try:\n score_list.append(float(score))\n except:\n continue\nresult_f.close()\nprint(score_list) #여기까지 리스트에 담는법\n\n#이제 list 정렬하는법!\n\nscore_list.sort()\nprint(score_list)\nscore_list.reverse()\nprint(score_list)\nprint(\"1등의 점수는\", score_list[0])\nprint(\"2등의 점수는\", score_list[2])\n\ndef ranking(rank):\n result_f = open(\"scores_list.txt\",'r')\n score_list = [] #공리스트 만든느 법\n for line in result_f:\n name, score = line.split()\n try:\n score_list.append(float(score))\n except:\n continue\n result_f.close()\n score_list.sort()\n score_list.reverse()\n return score_list[rank-1]\n\nprint(ranking(1))\n\n\n\n#======================================================\n\nprint([1,2,3] + [4,5])\nprint([1,2,3] *3)\n\n#1. 공리스트 \nempty_list = [] \n\n#2. 리스트의 길이\nprint(len(empty_list))\n\n#3. 리스트 안에 리스트! 갯수는 1이 나옴\na_sinflenton=[[]]\nprint(len(a_sinflenton))\n\na_list = [1,2,[3,4],[[5,6,7],8]]\nprint(len(a_list))\n\n# 1) a_list 에서 2를 찾는법\nprint(a_list[1])\n# 2) a_list 에서 [3,4]를 찾는법\nprint(a_list[2])\n# 3) a_list 에서 3 를 찾는법\nprint(a_list[2][0])\n# 4) a_list 에서 4 를 찾는법\nprint(a_list[2][1])\n# 5) a_list 에서 7 를 찾는법\nprint(a_list[3][0][2])\n\n\n#========================================================\n\n\nanimals = ['dog', 'cat', 'pig']\n\nanimals.append('coq')\nprint(animals)\nanimals.append(['eagle','bear'])\nprint(animals)\nanimals.remove(['eagle','bear'])\nprint(animals)\nanimals.extend(['eagle', 'bear'])\nprint(animals)\nanimals[1] = 'cow' #cat을 cow로 바꿈\nprint(animals)\nprint(animals[1:4])\nanimals[1:2] = ['tiger','lion','rabbit']\nprint(animals)\nanimals[1:2] = [] #tiger 사라짐\nprint(animals)\n\nprint(animals.index('pig')) #인덱스 번호 알려줌.\n\nanimals.pop(3) #인덱스가 3인게 사라짐.\nprint(animals)\nanimals.pop() #맨뒤가 사라짐\nprint(animals)\nprint(animals.pop())\n\ndel animals[-1] #맨마지막 꺼 지워줌\n\nanimals.insert(1,'leopard') # insert(어디 위치에, 어떤거를.)\n\nprint(animals)\nprint(animals.count('leopard')) #레오파드가 몇게 들어가 있는지 확인하는것. \n\n\n\n\n\n\n\n","sub_path":"20191008.py","file_name":"20191008.py","file_ext":"py","file_size_in_byte":3746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"321801967","text":"# -*- coding: utf-8 -*-\nfrom collections import defaultdict\nfrom collections import Counter\n\n\nclass Node:\n def __init__(self, NodeName):\n self.name = NodeName\n self.adjust_info = []\n\n\nclass Graph:\n def __init__(self):\n self.nodes = {}\n self.path = []\n self.all_path = []\n self.step = 0\n self.max_length = 5\n self.begin_node = ''\n self.end_node = ''\n self.relation_paths = []\n\n def set_init_state(self, begin_node, end_node, max_length, relation):\n self.begin_node = begin_node\n self.end_node = end_node\n self.relation = relation\n self.max_length = max_length\n self.path = [('root', self.begin_node)] # 存储两节点之间的某条路径[('root', self.begin_node), (relation, next_node)....]\n self.all_path = [] # 两个正样本节点之间,可能存在多条路径,dfs的时候我们将所有路径进行存储[('root', self.begin_node), (relation, next_node)....]\n self.relation_paths = [] # 将all_path中的所有relation提取出来\n\n def add_node(self, node, relation, next_node):\n if node in self.nodes:\n if next_node not in self.nodes:\n self.nodes[next_node] = Node(next_node)\n self.nodes[node].adjust_info.append((relation, next_node))\n else:\n self.nodes[node] = Node(node)\n self.add_node(node, relation, next_node)\n\n def dfs(self, begin_node):\n if begin_node == self.end_node:\n tem = []\n if len(self.path) == 2 and self.path[1][0] == self.relation:\n return\n else:\n for item in self.path:\n tem.append(item)\n self.all_path.append(tem)\n return\n try:\n if self.nodes[begin_node].adjust_info is None:\n return\n if len(self.path) == self.max_length + 1:\n return\n for (_relation, _next_node) in self.nodes[begin_node].adjust_info:\n if (_relation, _next_node) not in self.path:\n self.path.append((_relation, _next_node))\n self.dfs(_next_node)\n self.path.remove((_relation, _next_node))\n except:\n print('存在非法实体%s\\n' % begin_node)\n return\n\n def extract_relation_path(self):\n for path in self.all_path:\n tem = ''\n for i in path:\n tem = tem + i[0] + '\\t'\n self.relation_paths.append(tem)\n return\n","sub_path":"temp/.ipynb_checkpoints/GraphDFS-checkpoint.py","file_name":"GraphDFS-checkpoint.py","file_ext":"py","file_size_in_byte":2579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"317104721","text":"from __future__ import print_function\n\n\nimport pandas as pd\nimport numpy as np\nimport os\nimport matplotlib.pyplot as plt\n\nseed = 7\nnp.random.seed(seed)\n\n\ndata=pd.read_csv(\"../../X.csv\")\ndata.shape\n# Convert yes/no to 1/0 in all columns\ndata = pd.get_dummies(data, drop_first=True)\nlabel=pd.read_csv(\"../../Y.csv\");\n\ndata=np.array(data).astype(float)\nlabel=np.array(label).astype(float)\nfrom scipy import stats\ndisc= stats.describe(data[:,0])\n\nprint(disc)\n#np.random.shuffle(label)\ny_train = label[:20000]\n\ny_val = label[20000:]\n\n\nx_test = data[20000:]\ny_test = label[20000:]\n\n\nepochs = range(1, len(label)+1 )\n\n# \"bo\" is for \"blue dot\"\n#plt.plot(epochs, label, 'bo', label='y')\n# b is for \"solid blue line\"\n#plt.plot(label[0:100], 'b', label='y')\nc=data[:,0][0:1000];\n\nplt.plot(c, 'b', label='y')\nplt.title('')\nplt.xlabel('sample')\nplt.ylabel('y')\nplt.legend()\n\nplt.show()\n\n_, ax = plt.subplots()\nax.hist(c )\nax.set_ylabel(\"y_label\")\nax.set_xlabel(\"x_label\")\nax.set_title(\"title\")\nplt.show()\n\n\n_, ax = plt.subplots()\nax.hist(c )\nax.set_ylabel(\"y_label\")\nax.set_xlabel(\"x_label\")\nax.set_title(\"title\")\nplt.show()\n\n","sub_path":"e2e_pipe/hyper_optimation/Gridsearch/SearchHyperparamters_plot_x_y.py","file_name":"SearchHyperparamters_plot_x_y.py","file_ext":"py","file_size_in_byte":1113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"217083922","text":"# The 6.00 Word Game\r\n\r\nimport random\r\nimport string\r\n\r\nVOWELS = 'aeiou'\r\nCONSONANTS = 'bcdfghjklmnpqrstvwxyz'\r\nHAND_SIZE = 7\r\n\r\nSCRABBLE_LETTER_VALUES = {\r\n 'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2, 'h': 4, 'i': 1, 'j': 8, 'k': 5, 'l': 1, 'm': 3, 'n': 1, 'o': 1, 'p': 3, 'q': 10, 'r': 1, 's': 1, 't': 1, 'u': 1, 'v': 4, 'w': 4, 'x': 8, 'y': 4, 'z': 10\r\n}\r\n\r\n# -----------------------------------\r\n# Helper code\r\n# (you don't need to understand this helper code)\r\n\r\nWORDLIST_FILENAME = \"words.txt\"\r\n\r\ndef loadWords():\r\n \"\"\"\r\n Returns a list of valid words. Words are strings of lowercase letters.\r\n \r\n Depending on the size of the word list, this function may\r\n take a while to finish.\r\n \"\"\"\r\n print(\"Loading word list from file...\")\r\n # inFile: file\r\n inFile = open(WORDLIST_FILENAME, 'r')\r\n # wordList: list of strings\r\n wordList = []\r\n for line in inFile:\r\n wordList.append(line.strip().lower())\r\n print(\" \", len(wordList), \"words loaded.\")\r\n return wordList\r\n\r\ndef getFrequencyDict(sequence):\r\n \"\"\"\r\n Returns a dictionary where the keys are elements of the sequence\r\n and the values are integer counts, for the number of times that\r\n an element is repeated in the sequence.\r\n\r\n sequence: string or list\r\n return: dictionary\r\n \"\"\"\r\n # freqs: dictionary (element_type -> int)\r\n freq = {}\r\n for x in sequence:\r\n freq[x] = freq.get(x,0) + 1\r\n return freq\r\n\t\r\n\r\n# (end of helper code)\r\n# -----------------------------------\r\n\r\n#\r\n# Problem #1: Scoring a word\r\n#\r\ndef getWordScore(word, n):\r\n \"\"\"\r\n Returns the score for a word. Assumes the word is a valid word.\r\n\r\n The score for a word is the sum of the points for letters in the\r\n word, multiplied by the length of the word, PLUS 50 points if all n\r\n letters are used on the first turn.\r\n\r\n Letters are scored as in Scrabble; A is worth 1, B is worth 3, C is\r\n worth 3, D is worth 2, E is worth 1, and so on (see SCRABBLE_LETTER_VALUES)\r\n\r\n word: string (lowercase letters)\r\n n: integer (HAND_SIZE; i.e., hand size required for additional points)\r\n returns: int >= 0\r\n \"\"\"\r\n # TO DO ... <-- Remove this comment when you code this function\r\n \r\n score = 0\r\n wordFreq = getFrequencyDict(word)\r\n \r\n for key in wordFreq:\r\n \r\n if key in SCRABBLE_LETTER_VALUES:\r\n \r\n score += SCRABBLE_LETTER_VALUES[key] * wordFreq[key]\r\n \r\n score = score * len(word)\r\n \r\n if len(word) == n:\r\n \r\n score += 50\r\n \r\n return score\r\n \r\n\r\n\r\n#\r\n# Problem #2: Make sure you understand how this function works and what it does!\r\n#\r\ndef displayHand(hand):\r\n \"\"\"\r\n Displays the letters currently in the hand.\r\n\r\n For example:\r\n >>> displayHand({'a':1, 'x':2, 'l':3, 'e':1})\r\n Should print out something like:\r\n a x x l l l e\r\n The order of the letters is unimportant.\r\n\r\n hand: dictionary (string -> int)\r\n \"\"\"\r\n for letter in hand.keys():\r\n for j in range(hand[letter]):\r\n print(letter,end=\" \") # print all on the same line\r\n print() # print an empty line\r\n\r\n#\r\n# Problem #2: Make sure you understand how this function works and what it does!\r\n#\r\ndef dealHand(n):\r\n \"\"\"\r\n Returns a random hand containing n lowercase letters.\r\n At least n/3 the letters in the hand should be VOWELS.\r\n\r\n Hands are represented as dictionaries. The keys are\r\n letters and the values are the number of times the\r\n particular letter is repeated in that hand.\r\n\r\n n: int >= 0\r\n returns: dictionary (string -> int)\r\n \"\"\"\r\n hand={}\r\n numVowels = n // 3\r\n \r\n for i in range(numVowels):\r\n x = VOWELS[random.randrange(0,len(VOWELS))]\r\n hand[x] = hand.get(x, 0) + 1\r\n \r\n for i in range(numVowels, n): \r\n x = CONSONANTS[random.randrange(0,len(CONSONANTS))]\r\n hand[x] = hand.get(x, 0) + 1\r\n \r\n return hand\r\n\r\n#\r\n# Problem #2: Update a hand by removing letters\r\n#\r\ndef updateHand(hand, word):\r\n \"\"\"\r\n Assumes that 'hand' has all the letters in word.\r\n In other words, this assumes that however many times\r\n a letter appears in 'word', 'hand' has at least as\r\n many of that letter in it. \r\n\r\n Updates the hand: uses up the letters in the given word\r\n and returns the new hand, without those letters in it.\r\n\r\n Has no side effects: does not modify hand.\r\n\r\n word: string\r\n hand: dictionary (string -> int) \r\n returns: dictionary (string -> int)\r\n \"\"\"\r\n # TO DO ... <-- Remove this comment when you code this function\r\n updatedHand = {}\r\n wordFreq = getFrequencyDict(word)\r\n \r\n for key in hand:\r\n if key not in wordFreq:\r\n wordFreq[key] = 0\r\n \r\n \r\n for letter in hand.keys():\r\n if letter in wordFreq.keys():\r\n updatedHand[letter] = hand[letter] - wordFreq.get(letter,0)\r\n \r\n return updatedHand\r\n\r\n# Problem #3: Test word validity\r\n#\r\ndef isValidWord(word, hand, wordList):\r\n \"\"\"\r\n Returns True if word is in the wordList and is entirely\r\n composed of letters in the hand. Otherwise, returns False.\r\n\r\n Does not mutate hand or wordList.\r\n \r\n word: string\r\n hand: dictionary (string -> int)\r\n wordList: list of lowercase strings\r\n \"\"\"\r\n # TO DO ... <-- Remove this comment when you code this function\r\n updatedHand = {}\r\n count = 0\r\n wordFreq = getFrequencyDict(word)\r\n invalidInput = False\r\n \r\n \r\n for letter in wordFreq:\r\n if letter not in hand:\r\n invalidInput = True\r\n \r\n if invalidInput == True:\r\n print(\"11111111111111111111111111\")\r\n return False\r\n \r\n \r\n if word in wordList:\r\n \r\n updatedHand = updateHand(hand, word)\r\n for letter in word:\r\n if updatedHand[letter] == hand[letter] - wordFreq.get(letter,0):\r\n count += 1\r\n if count == len(word):\r\n return True\r\n else:\r\n return False\r\n \r\n ","sub_path":"untitled0.py","file_name":"untitled0.py","file_ext":"py","file_size_in_byte":6082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"572749789","text":"#!/usr/bin/python3\n\"\"\"\nThis python script will start a flask web app\n\"\"\"\n\nfrom models import storage\nfrom models.state import State\nfrom models.city import City\nfrom collections import OrderedDict\nfrom flask import Flask, render_template\n\n\napp = Flask(__name__)\n\n\n@app.teardown_appcontext\ndef sesclose(self):\n \"\"\"docs\"\"\"\n storage.close()\n\n\n@app.route('/states/', defaults={'id': None}, strict_slashes=False)\n@app.route('/states/', strict_slashes=False)\ndef stateonly(id):\n \"\"\"This function will send all the states in the storage\n to the template\"\"\"\n cities = storage.all(City).values()\n states = storage.all(State).values()\n cities = sorted(cities, key=lambda cities: cities.name)\n states = sorted(states, key=lambda states: states.name)\n result = '7-states_list.html'\n existance = 0\n if id:\n for n in states:\n if n.id == id:\n existance = 1\n result = '9-states.html'\n if existance == 0:\n id = None\n return render_template(result, stateobj=states,\n cityobj=cities, id=id)\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=5000, debug=True)\n","sub_path":"web_flask/9-states.py","file_name":"9-states.py","file_ext":"py","file_size_in_byte":1168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"112069797","text":"#!/usr/bin/python3\n#\n# Copyright (c) 2017, Intel Corporation\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 of conditions 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 materials provided with the\n# distribution.\n#\n# * Neither the name of Intel Corporation nor the names of its\n# contributors may be used to endorse or promote products derived\n# from this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE 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 FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nfrom sys import exc_info, stderr\nimport argparse\nimport struct\n\nSTATE_INIT = 0\nSTATE_IN_ENTRY = 1\nSTATE_ENTRY = 2\nSTATE_EXITED = 3\nSTATE_CORRUPTED = 4\nSTATE_UNKNOWN_EVENT = 5\n\nE_KP_ENTRY = 0\nE_KP_EXIT = 1\nE_TP_ENTRY = 2\nE_TP_EXIT = 3\n\n\n###############################################################################\n# open_file -- open file with error handling\n###############################################################################\ndef open_file(path, flags):\n fh = -1\n try:\n fh = open(path, flags)\n except FileNotFoundError:\n print(\"Error: file not found:\", path, file=stderr)\n exit(1)\n return fh\n\n\n###############################################################################\n# read_bdata - read binary data from file\n###############################################################################\ndef read_bdata(fh, size):\n bdata = fh.read(size)\n if len(bdata) < size:\n raise EndOfFile(len(bdata))\n return bdata\n\n\n###############################################################################\n# read_fmt_data -- read formatted data from file fh\n###############################################################################\ndef read_fmt_data(fh, fmt):\n size = struct.calcsize(fmt)\n bdata = read_bdata(fh, size)\n return struct.unpack(fmt, bdata)\n\n\n###############################################################################\nclass EndOfFile(Exception):\n def __init__(self, val):\n self.val = val\n\n def __str__(self):\n return repr(self.val)\n\n\n###############################################################################\nclass SyscallInfo:\n def __init__(self, num, num_str, pname, name, length, nargs, mask, avail, nstrargs, positions):\n bname = bytes(name)\n sname = str(bname.decode(errors=\"ignore\"))\n\n self.num = num\n self.num_str = num_str\n self.pname = pname\n self.name = sname.split('\\0')[0]\n self.length = length\n self.nargs = nargs\n self.mask = mask\n self.avail = avail\n self.nstrargs = nstrargs\n self.positions = positions\n\n\n###############################################################################\nclass SyscallTable:\n def __init__(self):\n self.table = []\n\n def get(self, ind):\n if ind < len(self.table):\n i = ind\n else:\n i = len(self.table) - 1\n return self.table[i]\n\n def read(self, path_to_syscalls_table_dat):\n fmt = 'I4sP32sIIIiI6s6s'\n size_fmt = struct.calcsize(fmt)\n\n fh = open_file(path_to_syscalls_table_dat, 'rb')\n\n size_check, = read_fmt_data(fh, 'i')\n if size_check != size_fmt:\n print(\"Error: wrong format of syscalls table file:\", path_to_syscalls_table_dat, file=stderr)\n print(\" format size : \", size_fmt, file=stderr)\n print(\" data size : \", size_check, file=stderr)\n return -1\n\n while True:\n try:\n data = read_fmt_data(fh, fmt)\n num, num_str, pname, name, length, nargs, mask, avail, nstrargs, positions, _padding = data\n syscall = SyscallInfo(num, num_str, pname, name, length, nargs, mask, avail, nstrargs, positions)\n except EndOfFile as err:\n if err.val > 0:\n print(\"Input file is truncated:\", path_to_syscalls_table_dat, file=stderr)\n break\n except:\n print(\"Unexpected error:\", exc_info()[0], file=stderr)\n raise\n else:\n self.table.append(syscall)\n\n fh.close()\n return 0\n\n\n###############################################################################\nclass Timestamp:\n def __init__(self):\n self.time0 = 0\n\n def get_rel_time(self, timestamp):\n if self.time0:\n return timestamp - self.time0\n else:\n self.time0 = timestamp\n return 0\n\n\n###############################################################################\nclass Syscall:\n __str = \"---------------- ----------------\"\n __arg_str_mask = [1, 2, 4, 8, 16, 32]\n\n ###############################################################################\n def __init__(self, pid_tid, sc_id, sc_info, buf_size):\n self.state = STATE_INIT\n\n self.pid_tid = pid_tid\n self.sc_id = sc_id\n self.time_start = 0\n self.time_end = 0\n self.args = []\n self.ret = 0\n self.err = 0\n\n self.sc = sc_info\n self.name = sc_info.name\n self.length = sc_info.length\n\n self.string = \"\"\n self.num_str = 0\n self.str_fini = -1\n\n self.packet = 0\n self.arg_begin = 0\n self.arg_end = 7\n self.arg_is_cont = 0\n self.arg_will_cont = 0\n self.truncated = 0\n\n self.all_strings = []\n\n self.BUF_SIZE = int(buf_size)\n self.BUF_SIZE_2 = int(buf_size / 2)\n self.BUF_SIZE_3 = int(buf_size / 3)\n\n self.STR_MAX_1 = self.BUF_SIZE - 2\n self.STR_MAX_2 = self.BUF_SIZE_2 - 2\n self.STR_MAX_3 = self.BUF_SIZE_3 - 2\n\n ###############################################################################\n def is_cont(self):\n return self.arg_begin == self.arg_end\n\n ###############################################################################\n def is_string(self, n):\n if self.sc.mask & self.__arg_str_mask[n] == self.__arg_str_mask[n]:\n return 1\n else:\n return 0\n\n ###############################################################################\n def get_str_arg(self, aux_str):\n string = \"\"\n max_len = 0\n\n if self.packet:\n max_len = self.STR_MAX_1\n string = aux_str\n\n elif self.sc.nstrargs == 1:\n max_len = self.STR_MAX_1\n string = aux_str\n\n elif self.sc.nstrargs == 2:\n max_len = self.STR_MAX_2\n self.num_str += 1\n if self.num_str == 1:\n string = aux_str[0:self.BUF_SIZE_2]\n elif self.num_str == 2:\n string = aux_str[self.BUF_SIZE_2: 2 * self.BUF_SIZE_2]\n else:\n assert (self.num_str <= 2)\n\n elif self.sc.nstrargs == 3:\n max_len = self.STR_MAX_3\n self.num_str += 1\n if self.num_str == 1:\n string = aux_str[0:self.BUF_SIZE_3]\n elif self.num_str == 2:\n string = aux_str[self.BUF_SIZE_3: 2 * self.BUF_SIZE_3]\n elif self.num_str == 3:\n string = aux_str[2 * self.BUF_SIZE_3: 3 * self.BUF_SIZE_3]\n else:\n assert (self.num_str <= 3)\n\n else:\n print(\"\\n\\nERROR: unsupported number of string arguments:\", self.sc.nstrargs)\n assert (self.sc.nstrargs <= 3)\n\n str_p = str(string.decode(errors=\"ignore\"))\n str_p = str_p.split('\\0')[0]\n self.string += str_p\n\n # check if string ended\n if len(str_p) == (max_len + 1):\n # string did not ended\n self.str_fini = 0\n if self.arg_will_cont == 0:\n # error: string is truncated\n self.truncated = 1\n self.str_fini = 1\n else:\n # string is completed, save it\n self.str_fini = 1\n\n if self.str_fini:\n self.all_strings.append(self.string)\n self.string = \"\"\n return len(self.all_strings) - 1\n else:\n return -1\n\n ###############################################################################\n def print_entry(self):\n print(\"{0:016X} {1:016X} {2:s} {3:s}\".format(\n self.time_start, self.pid_tid, self.__str, self.name[4:self.length]), end='')\n for n in range(0, self.sc.nargs):\n print(\" \", end='')\n if self.is_string(n):\n print(self.all_strings[self.args[n]], end='')\n else:\n print(\"{0:016X}\".format(self.args[n]), end='')\n print()\n\n ###############################################################################\n def print_exit(self):\n if self.sc.avail:\n print(\"{0:016X} {1:016X} {2:016X} {3:016X} {4:s}\".format(\n self.time_end, self.pid_tid, self.err, self.ret, self.name[4:self.length]))\n else:\n print(\"{0:016X} {1:016X} {2:016X} {3:016X} sys_exit {4:016X}\".format(\n self.time_end, self.pid_tid, self.err, self.ret, self.sc_id))\n\n ###############################################################################\n def add_data(self, packet_type, bdata, timestamp):\n etype = packet_type & 0x03\n packet_type >>= 2\n if etype == E_KP_ENTRY:\n # kprobe entry handler\n return self.add_kprobe_entry(packet_type, bdata, timestamp)\n elif (etype == E_KP_EXIT) or (etype == E_TP_EXIT):\n # kprobe exit handler or raw tracepoint sys_exit\n return self.add_exit(bdata, timestamp)\n else:\n return STATE_UNKNOWN_EVENT\n\n ###############################################################################\n def add_kprobe_entry(self, packet, bdata, timestamp):\n self.time_start = timestamp\n if packet:\n self.packet = packet\n self.arg_begin = packet & 0x7 # bits 0-2\n self.arg_end = (packet >> 3) & 0x7 # bits 3-5\n self.arg_will_cont = (packet >> 6) & 0x1 # bit 6 (will be continued)\n self.arg_is_cont = (packet >> 7) & 0x1 # bit 7 (is a continuation)\n\n if self.state == STATE_INIT and self.arg_begin > 0:\n print(\"Error: missed first packet:\", self.name, file=stderr)\n self.state = STATE_CORRUPTED\n return self.state\n\n # is it a continuation of a string ?\n if self.is_cont():\n if self.str_fini:\n return self.state\n fmt_args = 'qqqqqq'\n size_fmt_args = struct.calcsize(fmt_args)\n if len(bdata) <= size_fmt_args:\n return self.state\n aux_str = bdata[size_fmt_args:]\n\n str_p = str(aux_str.decode(errors=\"ignore\"))\n str_p = str_p.split('\\0')[0]\n\n self.string += str_p\n\n max_len = self.BUF_SIZE - 2\n # check if string ended\n if len(str_p) == (max_len + 1):\n # string did not ended\n self.str_fini = 0\n if self.arg_will_cont == 0:\n # error: string is truncated\n self.truncated = 1\n self.str_fini = 1\n else:\n # string is completed, save it\n self.str_fini = 1\n\n if self.str_fini:\n self.all_strings.append(self.string)\n self.args.append(len(self.all_strings) - 1)\n self.string = \"\"\n\n return self.state\n\n # is it a continuation of last argument (full name mode)?\n if self.arg_is_cont:\n # it is a continuation of the last string argument\n if self.str_fini:\n # printing string was already finished, so skip it\n self.arg_begin += 1\n self.arg_is_cont = 0\n self.str_fini = 0\n else:\n # syscall.arg_begin argument was printed in the previous packet\n self.arg_begin += 1\n\n # is it the last packet of this syscall (end of syscall) ?\n if self.arg_end == 7:\n end_of_syscall = 1\n # and set the true number of the last argument\n self.arg_end = self.sc.nargs\n else:\n end_of_syscall = 0\n\n fmt_args = 'QQQQQQ'\n size_fmt_args = struct.calcsize(fmt_args)\n data_args = bdata[0: size_fmt_args]\n aux_str = bdata[size_fmt_args:]\n\n if len(data_args) < size_fmt_args:\n if self.sc.nargs == 0:\n self.state = STATE_ENTRY\n else:\n self.state = STATE_CORRUPTED\n return self.state\n\n args = struct.unpack(fmt_args, data_args)\n\n for n in range((self.arg_begin - 1), self.arg_end):\n if self.is_string(n):\n index = self.get_str_arg(aux_str)\n if index >= 0:\n if len(self.args) < n + 1:\n self.args.append(index)\n else:\n self.args[n] = index\n else:\n if len(self.args) < n + 1:\n self.args.append(args[n])\n else:\n self.args[n] = args[n]\n\n if end_of_syscall:\n self.num_str = 0 # reset counter of string arguments\n self.str_fini = 1\n self.state = STATE_ENTRY\n else:\n self.state = STATE_IN_ENTRY\n\n return self.state\n\n ###############################################################################\n def add_exit(self, bdata, timestamp):\n self.time_end = timestamp\n\n fmt_exit = 'q'\n size_fmt_exit = struct.calcsize(fmt_exit)\n bdata = bdata[0: size_fmt_exit]\n retval, = struct.unpack(fmt_exit, bdata)\n\n # split return value into result and errno\n if retval >= 0:\n self.ret = retval\n self.err = 0\n else:\n self.ret = 0xFFFFFFFFFFFFFFFF\n self.err = -retval\n\n self.state = STATE_EXITED\n\n return self.state\n\n\n###############################################################################\n# convert_bin2txt - convert binary log to text\n###############################################################################\ndef convert_bin2txt(path_to_syscalls_table_dat, path_to_trace_log):\n sizei = struct.calcsize('i')\n sizeI = struct.calcsize('I')\n sizeQ = struct.calcsize('Q')\n\n syscall_table = SyscallTable()\n if syscall_table.read(path_to_syscalls_table_dat):\n print(\"Error while reading syscalls table\")\n exit(-1)\n\n fh = open_file(path_to_trace_log, 'rb')\n\n # read and init global BUF_SIZE\n BUF_SIZE, = read_fmt_data(fh, 'i')\n\n # read length of CWD\n cwd_len, = read_fmt_data(fh, 'i')\n bdata = fh.read(cwd_len)\n cwd = str(bdata.decode(errors=\"ignore\"))\n CWD = cwd.replace('\\0', ' ')\n print(\"Current working directory:\", CWD)\n\n # read header = command line\n data_size, argc = read_fmt_data(fh, 'ii')\n data_size -= sizei\n bdata = fh.read(data_size)\n argv = str(bdata.decode(errors=\"ignore\"))\n argv = argv.replace('\\0', ' ')\n print(\"Command line:\", argv)\n\n ts = Timestamp()\n state = STATE_EXITED\n # read data\n while True:\n try:\n data_size, packet_type, pid_tid, sc_id, timestamp = read_fmt_data(fh, 'IIQQQ')\n data_size = data_size - (sizeI + 3 * sizeQ)\n\n # read the rest of data\n bdata = read_bdata(fh, data_size)\n\n timestamp = ts.get_rel_time(timestamp)\n\n if state != STATE_IN_ENTRY:\n # noinspection PyTypeChecker\n syscall = Syscall(pid_tid, sc_id, syscall_table.get(sc_id), BUF_SIZE)\n state = syscall.add_data(packet_type, bdata, timestamp)\n\n if state == STATE_ENTRY:\n syscall.print_entry()\n elif state == STATE_EXITED:\n syscall.print_exit()\n\n except EndOfFile as err:\n if err.val > 0:\n print(\"Log file is truncated:\", path_to_trace_log, file=stderr)\n break\n except:\n print(\"Unexpected error:\", exc_info()[0], file=stderr)\n raise\n\n fh.close()\n return\n\n\n###############################################################################\n# main\n###############################################################################\n\ndef main():\n parser = argparse.ArgumentParser(description=\"Convert tracing logs from binary to text format\")\n parser.add_argument(\"-s\", \"--table\", required=True, help=\"path to 'syscalls_table.dat'\")\n parser.add_argument(\"-b\", \"--binlog\", required=True, help=\"input file - tracing log in binary format\")\n parser.add_argument(\"-t\", \"--txtlog\", required=False, help=\"output file - tracing log in text format\")\n args = parser.parse_args()\n\n convert_bin2txt(args.table, args.binlog)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"test/convert_bin2txt.py","file_name":"convert_bin2txt.py","file_ext":"py","file_size_in_byte":17984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"53101258","text":"# -*- coding: utf-8 -*-\n\"\"\"The json serializer object implementation.\"\"\"\n\nimport binascii\nimport collections\nimport json\n\nfrom dfvfs.path import path_spec as dfvfs_path_spec\nfrom dfvfs.path import factory as dfvfs_path_spec_factory\n\nfrom plaso.containers import interface as containers_interface\nfrom plaso.containers import manager as containers_manager\nfrom plaso.lib import event\nfrom plaso.lib import py2to3\nfrom plaso.serializer import interface\nfrom plaso.storage import collection\n\nimport pytz # pylint: disable=wrong-import-order\n\n\nclass _PreprocessObjectJSONDecoder(json.JSONDecoder):\n \"\"\"A class that implements a preprocessing object JSON decoder.\"\"\"\n\n _CLASS_TYPES = frozenset([\n u'bytes', u'collections.Counter', u'PreprocessObject', u'range',\n u'timezone'])\n\n def __init__(self, *args, **kargs):\n \"\"\"Initializes the JSON decoder object.\"\"\"\n super(_PreprocessObjectJSONDecoder, self).__init__(\n *args, object_hook=self._ConvertDictToObject, **kargs)\n\n def _ConvertDictToCollectionsCounter(self, json_dict):\n \"\"\"Converts a JSON dict into a collections.Counter object.\n\n The dictionary of the JSON serialized objects consists of:\n {\n '__type__': 'collections.Counter'\n ...\n }\n\n Here '__type__' indicates the object base type. In this case this should\n be 'collections.Counter'. The rest of the elements of the dictionary make up\n the preprocessing object properties.\n\n Args:\n json_dict (dict[str, object]): JSON serialized objects.\n\n Returns:\n collections.Counter: counter.\n \"\"\"\n collections_counter = collections.Counter()\n\n for key, value in iter(json_dict.items()):\n collections_counter[key] = value\n\n return collections_counter\n\n def _ConvertDictToPreprocessObject(self, json_dict):\n \"\"\"Converts a JSON dict into a preprocessing object.\n\n The dictionary of the JSON serialized objects consists of:\n {\n '__type__': 'PreprocessObject'\n 'collection_information': { ... }\n 'counter': { ... }\n 'plugin_counter': { ... }\n 'store_range': { ... }\n 'stores': { ... }\n 'zone': { ... }\n ...\n }\n\n Here '__type__' indicates the object base type. In this case this should\n be 'PreprocessObject'. The rest of the elements of the dictionary make up\n the preprocessing object properties.\n\n Args:\n json_dict (dict[str, object]): JSON serialized objects.\n\n Returns:\n A preprocessing object (instance of PreprocessObject).\n \"\"\"\n preprocessing_object = event.PreprocessObject()\n\n for key, value in iter(json_dict.items()):\n setattr(preprocessing_object, key, value)\n\n return preprocessing_object\n\n def _ConvertDictToObject(self, json_dict):\n \"\"\"Converts a JSON dict into an object.\n\n Note that json_dict is a dict of dicts and the _ConvertDictToObject\n method will be called for every dict. That is how the deserialized\n objects are created.\n\n Args:\n json_dict (dict[str, object]): JSON serialized objects.\n\n Returns:\n A deserialized object which can be:\n * a counter (instance of collections.Counter);\n * a dictionary;\n * a preprocessing object (instance of PreprocessObject);\n * a pytz timezone object.\n \"\"\"\n # Use __type__ to indicate the object class type.\n class_type = json_dict.get(u'__type__', None)\n\n if class_type not in self._CLASS_TYPES:\n # Dealing with a regular dict.\n return json_dict\n\n # Remove the class type from the JSON dict since we cannot pass it.\n del json_dict[u'__type__']\n\n if class_type == u'bytes':\n return binascii.a2b_qp(json_dict[u'stream'])\n\n elif class_type == u'collections.Counter':\n return self._ConvertDictToCollectionsCounter(json_dict)\n\n elif class_type == u'range':\n return tuple([json_dict[u'start'], json_dict[u'end']])\n\n elif class_type == u'timezone':\n return pytz.timezone(json_dict.get(u'zone', u'UTC'))\n\n return self._ConvertDictToPreprocessObject(json_dict)\n\n\nclass _PreprocessObjectJSONEncoder(json.JSONEncoder):\n \"\"\"A class that implements a preprocessing object JSON encoder.\"\"\"\n\n def _ConvertCollectionInformationToDict(self, collection_information):\n \"\"\"Converts a collection information dictionary into a JSON dictionary.\n\n Args:\n collection_information: a collection information dictionary.\n\n Returns:\n dict[str, object]: JSON serialized objects.\n \"\"\"\n json_dict = {}\n for attribute_name, attribute_value in iter(collection_information.items()):\n if attribute_value is None:\n continue\n\n if attribute_name == u'configured_zone':\n attribute_value = {\n u'__type__': u'timezone',\n u'zone': u'{0!s}'.format(attribute_value)\n }\n\n elif isinstance(attribute_value, py2to3.BYTES_TYPE):\n attribute_value = {\n u'__type__': u'bytes',\n u'stream': u'{0:s}'.format(binascii.b2a_qp(attribute_value))\n }\n\n json_dict[attribute_name] = attribute_value\n\n return json_dict\n\n def _ConvertCollectionsCounterToDict(self, collections_counter):\n \"\"\"Converts a collections.Counter object into a JSON dictionary.\n\n The resulting dictionary of the JSON serialized objects consists of:\n {\n '__type__': 'collections.Counter'\n ...\n }\n\n Here '__type__' indicates the object base type. In this case\n 'collections.Counter'. The rest of the elements of the dictionary make up\n the collections.Counter object attributes.\n\n Args:\n collections_counter (collections.Counter): counter.\n\n Returns:\n dict[str, object]: JSON serialized objects.\n\n Raises:\n TypeError: if not an instance of collections.Counter.\n \"\"\"\n if not isinstance(collections_counter, collections.Counter):\n raise TypeError\n\n json_dict = {u'__type__': u'collections.Counter'}\n for attribute_name, attribute_value in iter(collections_counter.items()):\n if attribute_value is None:\n continue\n\n if isinstance(attribute_value, py2to3.BYTES_TYPE):\n attribute_value = {\n u'__type__': u'bytes',\n u'stream': u'{0:s}'.format(binascii.b2a_qp(attribute_value))\n }\n\n json_dict[attribute_name] = attribute_value\n\n return json_dict\n\n # Note: that the following functions do not follow the style guide\n # because they are part of the json.JSONEncoder object interface.\n\n # pylint: disable=method-hidden\n def default(self, preprocessing_object):\n \"\"\"Converts a preprocessing object into a JSON dictionary.\n\n The resulting dictionary of the JSON serialized objects consists of:\n {\n '__type__': 'PreprocessObject'\n 'collection_information': { ... }\n 'counter': { ... }\n 'plugin_counter': { ... }\n 'store_range': { ... }\n 'stores': { ... }\n 'zone': { ... }\n ...\n }\n\n Here '__type__' indicates the object base type. In this case\n 'PreprocessObject'. The rest of the elements of the dictionary\n make up the preprocessing object attributes.\n\n Args:\n preprocessing_object: a preprocessing object (instance of\n PreprocessObject).\n\n Returns:\n dict[str, object]: JSON serialized objects.\n\n Raises:\n TypeError: if not an instance of PreprocessObject.\n \"\"\"\n if not isinstance(preprocessing_object, event.PreprocessObject):\n raise TypeError\n\n json_dict = {u'__type__': u'PreprocessObject'}\n for attribute_name in iter(preprocessing_object.__dict__.keys()):\n attribute_value = getattr(preprocessing_object, attribute_name, None)\n if attribute_value is None:\n continue\n\n if attribute_name == u'collection_information':\n attribute_value = self._ConvertCollectionInformationToDict(\n attribute_value)\n\n elif attribute_name in [u'counter', u'plugin_counter']:\n attribute_value = self._ConvertCollectionsCounterToDict(attribute_value)\n\n elif attribute_name == u'store_range':\n attribute_value = {\n u'__type__': u'range',\n u'end': attribute_value[1],\n u'start': attribute_value[0]\n }\n\n elif attribute_name == u'zone':\n attribute_value = {\n u'__type__': u'timezone',\n u'zone': u'{0!s}'.format(attribute_value)\n }\n\n elif isinstance(attribute_value, py2to3.BYTES_TYPE):\n attribute_value = {\n u'__type__': u'bytes',\n u'stream': u'{0:s}'.format(binascii.b2a_qp(attribute_value))\n }\n\n json_dict[attribute_name] = attribute_value\n\n return json_dict\n\n\nclass JSONAttributeContainerSerializer(interface.AttributeContainerSerializer):\n \"\"\"Class that implements the json attribute container serializer.\"\"\"\n\n @classmethod\n def _ConvertAttributeContainerToDict(cls, attribute_container):\n \"\"\"Converts an attribute container object into a JSON dictionary.\n\n The resulting dictionary of the JSON serialized objects consists of:\n {\n '__type__': 'AttributeContainer'\n '__container_type__': ...\n ...\n }\n\n Here '__type__' indicates the object base type. In this case\n 'AttributeContainer'.\n\n '__container_type__' indicates the container type and rest of the elements\n of the dictionary make up the attributes of the container.\n\n Args:\n attribute_container (AttributeContainer): attribute container.\n\n Returns:\n dict[str, object]: JSON serialized objects.\n\n Raises:\n TypeError: if not an instance of AttributeContainer.\n ValueError: if the attribute container type is not supported.\n \"\"\"\n if not isinstance(\n attribute_container, containers_interface.AttributeContainer):\n raise TypeError(u'Not an attribute container type.')\n\n container_type = getattr(attribute_container, u'CONTAINER_TYPE', None)\n if not container_type:\n raise ValueError(u'Unuspported attribute container type: {0:s}.'.format(\n type(attribute_container)))\n\n json_dict = {\n u'__type__': u'AttributeContainer',\n u'__container_type__': container_type,\n }\n\n for attribute_name, attribute_value in attribute_container.GetAttributes():\n if attribute_value is None:\n continue\n\n json_dict[attribute_name] = cls._ConvertAttributeValueToDict(\n attribute_value)\n\n return json_dict\n\n @classmethod\n def _ConvertAttributeValueToDict(cls, attribute_value):\n \"\"\"Converts an attribute value into a JSON dictionary.\n\n Args:\n attribute_value: an attribute value.\n\n Returns:\n The JSON serialized object which can be:\n * a dictionary;\n * a list.\n \"\"\"\n if isinstance(attribute_value, py2to3.BYTES_TYPE):\n attribute_value = {\n u'__type__': u'bytes',\n u'stream': u'{0:s}'.format(binascii.b2a_qp(attribute_value))\n }\n\n elif isinstance(attribute_value, (list, tuple)):\n json_list = []\n for list_element in attribute_value:\n json_dict = cls._ConvertAttributeValueToDict(list_element)\n json_list.append(json_dict)\n\n if isinstance(attribute_value, list):\n attribute_value = json_list\n else:\n attribute_value = {\n u'__type__': u'tuple',\n u'values': json_list\n }\n\n elif isinstance(attribute_value, collections.Counter):\n attribute_value = cls._ConvertCollectionsCounterToDict(attribute_value)\n\n elif isinstance(attribute_value, dfvfs_path_spec.PathSpec):\n attribute_value = cls._ConvertPathSpecToDict(attribute_value)\n\n elif isinstance(attribute_value, containers_interface.AttributeContainer):\n attribute_value = cls._ConvertAttributeContainerToDict(attribute_value)\n\n return attribute_value\n\n @classmethod\n def _ConvertCollectionsCounterToDict(cls, collections_counter):\n \"\"\"Converts a collections.Counter object into a JSON dictionary.\n\n The resulting dictionary of the JSON serialized objects consists of:\n {\n '__type__': 'collections.Counter'\n ...\n }\n\n Here '__type__' indicates the object base type. In this case\n 'collections.Counter'. The rest of the elements of the dictionary make up\n the collections.Counter object attributes.\n\n Args:\n collections_counter (collections.Counter): counter.\n\n Returns:\n dict[str, object]: JSON serialized objects.\n\n Raises:\n TypeError: if not an instance of collections.Counter.\n \"\"\"\n if not isinstance(collections_counter, collections.Counter):\n raise TypeError\n\n json_dict = {u'__type__': u'collections.Counter'}\n for attribute_name, attribute_value in iter(collections_counter.items()):\n if attribute_value is None:\n continue\n\n if isinstance(attribute_value, py2to3.BYTES_TYPE):\n attribute_value = {\n u'__type__': u'bytes',\n u'stream': u'{0:s}'.format(binascii.b2a_qp(attribute_value))\n }\n\n json_dict[attribute_name] = attribute_value\n\n return json_dict\n\n @classmethod\n def _ConvertDictToObject(cls, json_dict):\n \"\"\"Converts a JSON dict into an object.\n\n The dictionary of the JSON serialized objects consists of:\n {\n '__type__': 'AttributeContainer'\n '__container_type__': ...\n ...\n }\n\n Here '__type__' indicates the object base type. In this case\n 'AttributeContainer'.\n\n '__container_type__' indicates the attribute container type.\n\n The rest of the elements of the dictionary make up the attributes.\n\n Args:\n json_dict (dict[str, object]): JSON serialized objects.\n\n Returns:\n A deserialized object which can be:\n * an attribute container (instance of AttributeContainer);\n * a dictionary;\n * a list;\n * a tuple.\n\n Raises:\n ValueError: if the class type or container type is not supported.\n \"\"\"\n # Use __type__ to indicate the object class type.\n class_type = json_dict.get(u'__type__', None)\n if not class_type:\n # Dealing with a regular dict.\n return json_dict\n\n if class_type == u'bytes':\n return binascii.a2b_qp(json_dict[u'stream'])\n\n elif class_type == u'tuple':\n return tuple(cls._ConvertListToObject(json_dict[u'values']))\n\n elif class_type == u'collections.Counter':\n return cls._ConvertDictToCollectionsCounter(json_dict)\n\n elif class_type == u'AttributeContainer':\n # Use __container_type__ to indicate the attribute container type.\n container_type = json_dict.get(u'__container_type__', None)\n\n # Since we would like the JSON as flat as possible we handle decoding\n # a path specification.\n elif class_type == u'PathSpec':\n return cls._ConvertDictToPathSpec(json_dict)\n\n # Provide backwards compatibility.\n elif class_type == u'EventObject':\n container_type = u'event'\n\n elif class_type == u'EventTag':\n container_type = u'event_tag'\n\n elif class_type == u'AnalysisReport':\n container_type = u'analysis_report'\n\n else:\n raise ValueError(u'Unsupported class type: {0:s}'.format(class_type))\n\n container_class = (\n containers_manager.AttributeContainersManager.GetAttributeContainer(\n container_type))\n if not container_class:\n raise ValueError(u'Unsupported container type: {0:s}'.format(\n container_type))\n\n container_object = container_class()\n for attribute_name, attribute_value in iter(json_dict.items()):\n if attribute_name.startswith(u'__'):\n continue\n\n # Be strict about which attributes to set in non event objects.\n if (container_type != u'event' and\n attribute_name not in container_object.__dict__):\n continue\n\n # Note that \"_tags\" is the name for \"labels\" in EventTag prior to\n # version 1.4.1-20160131\n if container_type == u'event_tag' and attribute_name == u'_event_tags':\n attribute_name = u'labels'\n\n if isinstance(attribute_value, dict):\n attribute_value = cls._ConvertDictToObject(attribute_value)\n\n elif isinstance(attribute_value, list):\n attribute_value = cls._ConvertListToObject(attribute_value)\n\n setattr(container_object, attribute_name, attribute_value)\n\n return container_object\n\n @classmethod\n def _ConvertDictToCollectionsCounter(cls, json_dict):\n \"\"\"Converts a JSON dict into a collections.Counter.\n\n The dictionary of the JSON serialized objects consists of:\n {\n '__type__': 'collections.Counter'\n ...\n }\n\n Here '__type__' indicates the object base type. In this case this should\n be 'collections.Counter'. The rest of the elements of the dictionary make up\n the preprocessing object properties.\n\n Args:\n json_dict (dict[str, object]): JSON serialized objects.\n\n Returns:\n collections.Counter: counter.\n \"\"\"\n collections_counter = collections.Counter()\n\n for key, value in iter(json_dict.items()):\n if key == u'__type__':\n continue\n collections_counter[key] = value\n\n return collections_counter\n\n @classmethod\n def _ConvertListToObject(cls, json_list):\n \"\"\"Converts a JSON list into an object.\n\n Args:\n json_list: a list of the JSON serialized objects.\n\n Returns:\n A deserialized list.\n \"\"\"\n list_value = []\n for json_list_element in json_list:\n if isinstance(json_list_element, dict):\n list_value.append(cls._ConvertDictToObject(json_list_element))\n\n elif isinstance(json_list_element, list):\n list_value.append(cls._ConvertListToObject(json_list_element))\n\n else:\n list_value.append(json_list_element)\n\n return list_value\n\n @classmethod\n def _ConvertDictToPathSpec(cls, json_dict):\n \"\"\"Converts a JSON dict into a path specification object.\n\n The dictionary of the JSON serialized objects consists of:\n {\n '__type__': 'PathSpec'\n 'type_indicator': 'OS'\n 'parent': { ... }\n ...\n }\n\n Here '__type__' indicates the object base type. In this case this should\n be 'PathSpec'. The rest of the elements of the dictionary make up the\n path specification object properties.\n\n Args:\n json_dict (dict[str, object]): JSON serialized objects.\n\n Returns:\n path.PathSpec: path specification.\n \"\"\"\n type_indicator = json_dict.get(u'type_indicator', None)\n if type_indicator:\n del json_dict[u'type_indicator']\n\n if u'parent' in json_dict:\n json_dict[u'parent'] = cls._ConvertDictToPathSpec(json_dict[u'parent'])\n\n # Remove the class type from the JSON dict since we cannot pass it.\n del json_dict[u'__type__']\n\n return dfvfs_path_spec_factory.Factory.NewPathSpec(\n type_indicator, **json_dict)\n\n @classmethod\n def _ConvertPathSpecToDict(cls, path_spec_object):\n \"\"\"Converts a path specification object into a JSON dictionary.\n\n The resulting dictionary of the JSON serialized objects consists of:\n {\n '__type__': 'PathSpec'\n 'type_indicator': 'OS'\n 'parent': { ... }\n ...\n }\n\n Here '__type__' indicates the object base type. In this case 'PathSpec'.\n The rest of the elements of the dictionary make up the path specification\n object properties. The supported property names are defined in\n path_spec_factory.Factory.PROPERTY_NAMES. Note that this method is called\n recursively for every path specification object and creates a dict of\n dicts in the process.\n\n Args:\n path_spec_object (dfvfs.PathSpec): path specification.\n\n Returns:\n dict[str, object]: JSON serialized objects.\n\n Raises:\n TypeError: if not an instance of dfvfs.PathSpec.\n \"\"\"\n if not isinstance(path_spec_object, dfvfs_path_spec.PathSpec):\n raise TypeError\n\n json_dict = {u'__type__': u'PathSpec'}\n for property_name in dfvfs_path_spec_factory.Factory.PROPERTY_NAMES:\n property_value = getattr(path_spec_object, property_name, None)\n if property_value is not None:\n json_dict[property_name] = property_value\n\n if path_spec_object.HasParent():\n json_dict[u'parent'] = cls._ConvertPathSpecToDict(path_spec_object.parent)\n\n json_dict[u'type_indicator'] = path_spec_object.type_indicator\n location = getattr(path_spec_object, u'location', None)\n if location:\n json_dict[u'location'] = location\n\n return json_dict\n\n @classmethod\n def ReadSerialized(cls, json_string):\n \"\"\"Reads an attribute container from serialized form.\n\n Args:\n json_string: a JSON string containing the serialized form.\n\n Returns:\n AttributeContainer: attribute container or None.\n \"\"\"\n if not json_string:\n return\n\n json_dict = json.loads(json_string)\n return cls.ReadSerializedDict(json_dict)\n\n @classmethod\n def ReadSerializedDict(cls, json_dict):\n \"\"\"Reads an attribute container from serialized dictionary form.\n\n Args:\n json_dict (dict[str, object]): JSON serialized objects.\n\n Returns:\n AttributeContainer: attribute container or None.\n \"\"\"\n if not json_dict:\n return\n\n return cls._ConvertDictToObject(json_dict)\n\n @classmethod\n def WriteSerialized(cls, attribute_container):\n \"\"\"Writes an attribute container to serialized form.\n\n Args:\n attribute_container (AttributeContainer): attribute container.\n\n Returns:\n A JSON string containing the serialized form.\n \"\"\"\n json_dict = cls.WriteSerializedDict(attribute_container)\n return json.dumps(json_dict)\n\n @classmethod\n def WriteSerializedDict(cls, attribute_container):\n \"\"\"Writes an attribute container to serialized form.\n\n Args:\n attribute_container (AttributeContainer): attribute container.\n\n Returns:\n dict[str, object]: JSON serialized objects.\n \"\"\"\n return cls._ConvertAttributeContainerToDict(attribute_container)\n\n\nclass JSONPreprocessObjectSerializer(interface.PreprocessObjectSerializer):\n \"\"\"Class that implements the json preprocessing object serializer.\"\"\"\n\n @classmethod\n def ReadSerialized(cls, json_string):\n \"\"\"Reads a path filter from serialized form.\n\n Args:\n json_string: a JSON string containing the serialized form.\n\n Returns:\n A preprocessing object (instance of PreprocessObject).\n \"\"\"\n json_decoder = _PreprocessObjectJSONDecoder()\n return json_decoder.decode(json_string)\n\n @classmethod\n def WriteSerialized(cls, preprocess_object):\n \"\"\"Writes a preprocessing object to serialized form.\n\n Args:\n preprocess_object: a preprocessing object (instance of PreprocessObject).\n\n Returns:\n A JSON string containing the serialized form.\n \"\"\"\n return json.dumps(preprocess_object, cls=_PreprocessObjectJSONEncoder)\n\n\nclass JSONCollectionInformationObjectSerializer(\n interface.CollectionInformationObjectSerializer):\n \"\"\"Class that implements the collection information serializer interface.\"\"\"\n\n @classmethod\n def ReadSerialized(cls, serialized):\n \"\"\"Reads a path filter from serialized form.\n\n Args:\n serialized: an object containing the serialized form.\n\n Returns:\n A collection information object (instance of CollectionInformation).\n \"\"\"\n json_dict = json.loads(serialized)\n collection_information_object = collection.CollectionInformation()\n\n for key, value in iter(json_dict.items()):\n if key == collection_information_object.RESERVED_COUNTER_KEYWORD:\n for identifier, value_dict in iter(value.items()):\n collection_information_object.AddCounterDict(identifier, value_dict)\n else:\n collection_information_object.SetValue(key, value)\n\n return collection_information_object\n\n @classmethod\n def WriteSerialized(cls, collection_information_object):\n \"\"\"Writes a collection information object to serialized form.\n\n Args:\n collection_information_object: a collection information object (instance\n of CollectionInformation).\n\n Returns:\n An object containing the serialized form.\n \"\"\"\n if not hasattr(collection_information_object, u'GetValues'):\n raise RuntimeError(\n u'Unable to serialize collection information, missing value getting.')\n\n if not hasattr(collection_information_object, u'AddCounter'):\n raise RuntimeError(\n u'Unable to serialize collection information, missing counters.')\n\n full_dict = dict(collection_information_object.GetValueDict())\n\n if collection_information_object.HasCounters():\n counter_dict = dict(collection_information_object.GetCounters())\n full_dict[\n collection_information_object.RESERVED_COUNTER_KEYWORD] = counter_dict\n\n return json.dumps(full_dict)\n","sub_path":"plaso/serializer/json_serializer.py","file_name":"json_serializer.py","file_ext":"py","file_size_in_byte":24575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"271322658","text":"import threading\nimport time\nimport sys\n\nimport ftplib\nimport httplib\nimport csv\n\n\"\"\"\nDATA FORMAT IN CSV FILE:\nSTART TIMESTAMP seconds; DURATION seconds; SIZE byte; SPEED byte per second\n\"\"\"\n\nDL_URL = \"rogue-01.informatik.uni-bonn.de\"\nDL_FILE = \"PA.log\"\ncsv.register_dialect('kivs', delimiter=';', quoting=csv.QUOTE_NONE)\nNKS = 9 # NACHKOMMASTELLEN\n\nftp_size = 0\n\ndef download_ftp(mfile, mwriter):\n\n\tdef size_callback(chunk):\n\t\tglobal ftp_size\n\t\tftp_size += len(chunk) # sum up the size of the chunks\n\n\tglobal ftp_size # reinitialize the size value\n\tftp_size = 0\n\n\tbefore = time.time()\n\tcon = ftplib.FTP(DL_URL)\n\tcon.login()\n\tcon.retrbinary('RETR ' + DL_FILE, size_callback)\n\tcon.close()\n\tafter = time.time()\n\n\tprint_and_write(mfile, mwriter, before, after, ftp_size, 'FTP ')\n\n\ndef download_http(mfile, mwriter):\n\t\n\tbefore = time.time()\n\n\tconn = httplib.HTTPConnection(DL_URL)\n\tconn.request(\"GET\", '/'+DL_FILE)\n\tresp = conn.getresponse()\n\t_ = resp.read() ## Daten auch wirklich einmal auslesen\n\tsize = int(resp.getheader('content-length'))\n\tconn.close()\n\n\tafter = time.time()\n\n\tprint_and_write(mfile, mwriter, before, after, size, 'HTTP')\n\n\ndef print_and_write(mfile, mwriter, before, after, size, proto):\n\tduration = after - before\n\tprint(proto+': start:%.f duration:%.3fs size:%.fbyte speed:%.fbyte/s'\n\t\t % (before, duration, size, size/duration))\n\tmwriter.writerow((before, round(duration, NKS), size))\n\tmfile.flush()\n\n\nif __name__ == \"__main__\":\n\tftp_file = open('measurements_ftp.csv', 'a+')\n\tftp_writer = csv.writer(ftp_file, 'kivs')\n\n\thttp_file = open('measurements_http.csv', 'a+')\n\thttp_writer = csv.writer(http_file, 'kivs')\n\n\twhile True:\n\t\tthread_ftp = threading.Thread(target=download_ftp,\n\t\t args=(ftp_file, ftp_writer))\n\t\tthread_ftp.start()\n\t\tthread_http = threading.Thread(target=download_http,\n\t\t args=(http_file, http_writer))\n\t\tthread_http.start()\n\n\t\ttime.sleep(10)\n","sub_path":"Tools/aufgabe4/downloader.py","file_name":"downloader.py","file_ext":"py","file_size_in_byte":1948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"129339433","text":"import pathlib \n\nfile_name = \"e.txt\"\n\n# 取得脚本所在目录\ncurrent_path = pathlib.PurePath(__file__).parent\n\n# 和脚本同目录下的文件绝对路径\nfile = current_path.joinpath(file_name)\n\nwith open(file, encoding='utf8') as f:\n\n content = f.read()\n words = content.rstrip()\n number = len(words)\n print(number)\n # 15\n ","sub_path":"productivity_python/7.word_count/单文件字数统计.py","file_name":"单文件字数统计.py","file_ext":"py","file_size_in_byte":348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"471639160","text":"# -*- coding: utf-8 -*-\n\n\n\nfrom planeta import Planeta\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.stats\n\ndef es_afelio(r, valor, tolerancia):\n '''Recibe un valor de r, ve si está en el rango de tolerancia '''\n return (valor-tolerancia\n # index = 0\n # for form in soup.find_all('form'):\n # print(\"index {0}\".format(index))\n # index += 1\n # print(form)\n # print(\"\\n\\n\")\n\n # form index 2 ->
        \n # print(soup.find_all('form')[2])\n\n # extract Tag\n # td_all = soup.find_all('form')[2].find('table').find('table').find_all('td') # old version\n td_all = soup.find_all('form')[2].find('table').find_all('td')\n \n # filter
        金融機構牌告存放利率\n\n title = tr_all[1].string\n # print(tr_all[2].find_all('td'))\n # [金融機構:臺灣銀行, 0040000, 資料日期:107/04/03]\n\n bank_info = tr_all[2].find_all('td')\n bank_title = bank_info[0].string\n bank_code = bank_info[1].string\n bank_date = bank_info[2].string\n # print(tr_all[3])\n # 單位: 年息百分比率\n # print(tr_all[3].string)\n # 單位: 年息百分比率\n unit_rate = tr_all[3].string\n\n bank_name = bank_title[5:]\n column_bank_title = bank_title[0:4]\n column_bank_code = 'Bank_Code'\n column_bank_date = bank_date[0:4]\n info_date = bank_date[5:]\n column_unit = unit_rate[0:2]\n annual_rate = unit_rate[4:]\n # print(bank_name, info_date, annual_rate, column_bank_title, column_bank_code, column_bank_date, column_unit)\n # 臺灣銀行 105/08/02 年息百分比率 金融機構 Bank_Code 資料日期 單位\n \n # http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_html.html\n # Read HTML tables into a list of DataFrame objects.\n # This function will always return a list of DataFrame or it will fail, e.g., it will not return an empty list.\n tables = pd.read_html(r.text)\n # print(tables)\n data_table = tables[-1] # grab the last table\n # print(data_table)\n sql_table = data_table\n\n columns = sql_table.values[0,0:]\n column_list = list(columns) # transfer to list\n # print(column_list)\n # ['牌告利率項目', '牌告利率存期', '額度別', '生效日期', '固定利率', '機動利率']\n\n for h in [column_bank_date, column_bank_code, column_bank_title]:\n column_list.insert(0, h)\n\n column_list.append(column_unit)\n # print(column_list)\n # ['金融機構', 'Bank_Code', '資料日期', '牌告利率項目', '牌告利率存期', '額度別', '生效日期', '固定利率', '機動利率', '單位']\n\n sql_numpy = sql_table.values[1:,0:] # remove first row\n sql_df = pd.DataFrame(sql_numpy) # transfer to DataFrame\n sql_df.columns = column_list[3:9] # rename columns\n\n # add new columns and values\n x_list = [column_bank_title, column_bank_code, column_bank_date, column_unit]\n y_list = [bank_name, bank_code, info_date, annual_rate]\n # print(sql_df.values.shape) # e.g. (45, 6)\n # print(type(sql_df.values.shape)) # \n # print(type(sql_df.values)) # \n for temp in range(4):\n sql_df[x_list[temp]] = pd.Series([y_list[temp] for i in range(sql_df.values.shape[0])], index=sql_df.index)\n\n # reindex columns\n sql_df = sql_df.reindex(columns=column_list)\n\n # combine all dataframe\n if bank_num == 0:\n total_df = sql_df\n else:\n total_df = total_df.append(sql_df)\n bank_num += 1\n\n # data processing and export to excel\n data_table.loc[-2] = [title, bank_title, bank_code, bank_date, unit_rate, \"\"] # adding a row\n data_table.loc[-1] = [\"\" for k in range(6)] # adding a row (blank space)\n data_table.index = data_table.index + 2 # shifting index\n # data_table = data_table.sort() # sort was deprecated for DataFrame\n data_table = data_table.sort_index() # sorting by index\n excel_file = \"./{0}/{1}.xlsx\".format(dir_path, create_file_name(lable_list[x]))\n print(excel_file)\n data_table.to_excel(excel_file, encoding=\"utf-8\", header=False, index=False, sheet_name='Sheet1')\n # time.sleep(1)\n # for <<<\n\n return total_df\n \ndef export_to_sql(total_df):\n global dir_path\n # export to sqlite3 db\n interest_db_path = './{0}/interest_rate{1}.db'.format(dir_path, time.strftime(\"_%Y%m%d_%H%M%S\", time.localtime()))\n print(interest_db_path)\n # ./20180410_interest_rate/interest_rate_20180410_013639.db\n\n import sqlite3\n conn = sqlite3.connect(interest_db_path)\n total_df.to_sql(name=\"interest_rate\", con=conn, index=False, if_exists=\"replace\")\n\n cursor = conn.cursor()\n sql = \"SELECT * FROM interest_rate LIMIT 10\"\n print('\\nShow 10 records from {0} \\n'.format(interest_db_path))\n for record in cursor.execute(sql):\n print(record)\n\n conn.close()\n\ndef main():\n initial_action()\n final_df = target_action()\n export_to_sql(final_df)\n\nif __name__ == '__main__':\n main()\n","sub_path":"interest_rate_demo.py","file_name":"interest_rate_demo.py","file_ext":"py","file_size_in_byte":8426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"289714377","text":"import re\nimport os\nimport csv\nfrom scrapy.spider import BaseSpider\nfrom scrapy.selector import HtmlXPathSelector\nfrom scrapy.http import Request, HtmlResponse\nfrom scrapy.utils.response import get_base_url\nfrom scrapy.utils.url import urljoin_rfc\nfrom product_spiders.items import Product, ProductLoaderWithNameStrip as ProductLoader\nfrom scrapy import log\nfrom urlparse import urlparse\nimport time\n\nHERE = os.path.abspath(os.path.dirname(__file__))\n\nclass AmazonCoUkSpider(BaseSpider):\n name = 'amazon.co.uk-bosch-diy'\n allowed_domains = ['amazon.co.uk', 'www.amazon.co.uk']\n start_urls = ['http://www.amazon.co.uk/']\n \n def parse(self, response):\n with open(os.path.join(HERE, 'amazon_co_uk.csv')) as f:\n reader = csv.DictReader(f)\n for row in reader:\n if not len(row['url'].strip()):\n continue\n url = re.sub(r'#.+$', '', row['url'])\n log.msg('URL: %s' % url)\n if urlparse(url).scheme != 'http':\n continue\n request = Request(url, callback=self.parse_product)\n request.meta['sku'] = row['sku']\n yield request\n\n def parse_product(self, response):\n hxs = HtmlXPathSelector(response)\n base_url = get_base_url(response)\n \n product_loader = ProductLoader(item=Product(), response=response)\n product_loader.add_xpath('name', '//span[@id=\"btAsinTitle\"]/text()')\n price = hxs.select('//span[@id=\"actualPriceValue\"]//b/text()')\n if not price:\n price = hxs.select('//div[@id=\"secondaryUsedAndNew\"]//span[@class=\"price\"]//text()')\n if price:\n product_loader.add_value('price', price.extract()[0].replace(u'\\xa3', ''))\n else:\n product_loader.add_value('price', 0)\n product_loader.add_value('sku', response.meta['sku'])\n product_loader.add_value('url', response.url)\n yield product_loader.load_item()\n","sub_path":"portfolio/Python/scrapy/bosch_uk_diy/amazon_co_uk.py","file_name":"amazon_co_uk.py","file_ext":"py","file_size_in_byte":1997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"606129026","text":"\"\"\"\n@brief Loader class for importing python based channel dictionaries\n\n@date Created July 11, 2018\n@author R. Joseph Paetz\n\n@bug No known bugs\n\"\"\"\n\nfrom fprime_gds.common.templates.ch_template import ChTemplate\n\n# Custom Python Modules\nfrom .python_loader import PythonLoader\n\n\nclass ChPyLoader(PythonLoader):\n \"\"\"Class to load python based telemetry channel dictionaries\"\"\"\n\n # Field names in the python module files (used to construct dictionaries)\n ID_FIELD = \"ID\"\n NAME_FIELD = \"NAME\"\n COMP_FIELD = \"COMPONENT\"\n DESC_FIELD = \"CHANNEL_DESCRIPTION\"\n TYPE_FIELD = \"TYPE\"\n FMT_STR_FIELD = \"FORMAT_STRING\"\n LOW_R_FIELD = \"LOW_RED\"\n LOW_O_FIELD = \"LOW_ORANGE\"\n LOW_Y_FIELD = \"LOW_YELLOW\"\n HIGH_Y_FIELD = \"HIGH_YELLOW\"\n HIGH_O_FIELD = \"HIGH_ORANGE\"\n HIGH_R_FIELD = \"HIGH_RED\"\n\n def construct_dicts(self, path):\n \"\"\"\n Constructs and returns python dictionaries keyed on id and name\n\n This function should not be called directly, instead, use\n get_id_dict(path) and get_name_dict(path)\n\n Args:\n path: Path to the python module file dictionary to convert. This\n should be a directory. If using a regular fprime deployment,\n this should be a path to the events dictionary in your\n generated folder:\n ${GENERATED_FOLDER_LOCATION}/generated/${DEPLOYMENT}/channels\n\n Returns:\n A tuple with two channel dictionaries (python type dict):\n (id_dict, name_dict). The keys should be the channels' id and\n name fields respectively and the values should be ChTemplate\n objects.\n \"\"\"\n # We do need it sometimes, so if we don't always set it to true, we will need to pass an arg\n module_dicts = self.read_dict(path, use_superpkg=True)\n\n id_dict = dict()\n name_dict = dict()\n\n for ch_dict in module_dicts:\n # Create a channel template object\n ch_temp = ChTemplate(\n ch_dict[self.ID_FIELD],\n ch_dict[self.NAME_FIELD],\n ch_dict[self.COMP_FIELD],\n ch_dict[self.TYPE_FIELD],\n ch_dict[self.FMT_STR_FIELD],\n ch_dict[self.DESC_FIELD],\n ch_dict[self.LOW_R_FIELD],\n ch_dict[self.LOW_O_FIELD],\n ch_dict[self.LOW_Y_FIELD],\n ch_dict[self.HIGH_Y_FIELD],\n ch_dict[self.HIGH_O_FIELD],\n ch_dict[self.HIGH_R_FIELD],\n )\n\n id_dict[ch_dict[self.ID_FIELD]] = ch_temp\n name_dict[ch_dict[self.NAME_FIELD]] = ch_temp\n\n return (id_dict, name_dict)\n","sub_path":"Gds/src/fprime_gds/common/loaders/ch_py_loader.py","file_name":"ch_py_loader.py","file_ext":"py","file_size_in_byte":2698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"90821230","text":"import logging\nfrom river.handlers.backends.base import powerset\n\nfrom river.handlers.backends.memory import MemoryHandlerBackend\nfrom river.models.handler import Handler\n\n__author__ = 'ahmetdal'\n\nLOGGER = logging.getLogger(__name__)\n\n\nclass DatabaseHandlerBackend(MemoryHandlerBackend):\n\n def initialize_handlers(self):\n self.__register(Handler.objects.filter(enabled=True))\n\n def __register(self, handler_objs):\n handlers = []\n if handler_objs.exists():\n for handler in handler_objs:\n if handler.hash not in self.handlers:\n module, method_name = handler.method.rsplit('.', 1)\n try:\n method = getattr(__import__(module, fromlist=[method_name]), method_name, None)\n if method:\n self.handlers[handler.hash] = method\n handlers.append(method)\n LOGGER.debug(\"Handler '%s' from database is registered initially from database as method '%s' and module '%s'. \" % (handler.hash, method_name, module))\n else:\n LOGGER.warning(\"Handler '%s' from database can not be registered. Because method '%s' is not in module '%s'. \" % (handler.hash, method_name, module))\n except ImportError:\n LOGGER.warning(\"Handler '%s' from database can not be registered. Because module '%s' does not exists. \" % (handler.hash, module))\n return handlers\n\n def register(self, handler_cls, handler, workflow_object, override=False, *args, **kwargs):\n hash = super(DatabaseHandlerBackend, self).register(handler_cls, handler, workflow_object, override=override, *args, **kwargs)\n handler_obj, created = Handler.objects.update_or_create(\n hash=hash,\n defaults={\n 'method': '%s.%s' % (handler.__module__, handler.__name__),\n 'handler_cls': '%s.%s' % (handler_cls.__module__, handler_cls.__name__),\n }\n )\n if created:\n LOGGER.debug(\"Handler '%s' is registered in database as method %s and module %s. \" % (handler_obj.hash, handler.__name__, handler.__module__))\n else:\n LOGGER.warning(\"Handler '%s' is already registered in database as method %s and module %s. \" % (handler_obj.hash, handler.__name__, handler.__module__))\n\n return hash\n\n def get_handlers(self, handler_cls, workflow_object, *args, **kwargs):\n handlers = super(DatabaseHandlerBackend, self).get_handlers(handler_cls, workflow_object, *args, **kwargs)\n if not handlers:\n hashes = []\n for c in powerset(kwargs.keys()):\n skwargs = {}\n for f in c:\n skwargs[f] = kwargs.get(f)\n hash = self.get_handler_class(handler_cls).get_hash(workflow_object, **skwargs)\n hashes.append(self.get_handler_class_prefix(self.get_handler_class(handler_cls)) + hash)\n handlers = self.__register(Handler.objects.filter(hash__in=hashes))\n return handlers\n","sub_path":"venv/Lib/site-packages/river/handlers/backends/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":3141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"606421106","text":"\"\"\" RAID Validation.\nThis module validate the RAID configuration from the GCF. It uses the\nRAID_CONTAINER node.\n\nAuthor: Lorenzo Hernandez\nDate: 04/14/2015\n\"\"\"\n\nimport xml.etree.ElementTree as ET\n\ndef main(GCF):\n controllers = getControllers(GCF)\n return validate(controllers)\n\ndef exception(GCF):\n \"\"\" Validate all the exceptions.\n \"\"\"\n if 'R0206' in GCF:\n return True\n else:\n return False\n\ndef getControllers(GCF):\n \"\"\" Parse the GCF in order to extract the controllers information.\n (Drives and RAIDDContainers). Return a controllers list.\n node: /GCF/DATACONTAINERS/CONTAINER/CONTROLLERS/\n \"\"\"\n root = ET.fromstring(GCF)\n controllers = []\n for item in root.iter('CONTROLLER'):\n controller = {\n 'info': item.attrib,\n 'drives': [],\n 'raids': []\n }\n for drive in item.iter('DRIVE'):\n dr = {}\n for att in drive.iter('ATTRIBUTE'):\n e = att.attrib.values()\n dr.update({e[0]:e[1]})\n controller['drives'].append(dr)\n for raid in item.iter('RAID_CONTAINERS'):\n for con in raid.iter('RAID_CONTAINER'):\n controller['raids'].append(con.attrib)\n controllers.append(controller)\n\n return controllers\n\ndef validate(controllers):\n \"\"\" Recursive function to validate every controller information.\n RAID, RAIDLevel, Capacity and Speed. Return True if OK, else\n return an error message.\n \"\"\"\n if len(controllers) <= 0:\n return True\n else:\n drives = controllers[0]['drives']\n raids = controllers[0]['raids']\n\n RAIDLevel = isValidRAIDLevel(raids)\n if RAIDLevel == True: pass\n else: return RAIDLevel\n\n RAID = isValidRAID(raids)\n if RAID == True: pass\n else: return RAID\n\n capacity=isSameCapacityAndSpeed(drives,raids)\n if capacity == True: return validate(controllers[1:])\n else: return capacity\n\ndef isValidRAIDLevel(raids):\n \"\"\" Evaluate the RAID level to int type, and check if\n exists in valid RAID Levels. Return True if OK, else return\n an error message.\n \"\"\"\n validRAIDLevels = [0,1,5,6,10,50,60]\n if len(raids) <= 0:\n return True\n else:\n if int(raids[0]['level']) in validRAIDLevels:\n return isValidRAIDLevel(raids[1:])\n else:\n return 'Invalid RAID level %s' % raids[0]['level']\n\ndef isValidRAID(raids):\n \"\"\" Compare slots quantity vs rules min/max.\n Return True if OK, else return an error message.\n \"\"\"\n rules = {\n 0: [1, 999],\n 1: [2, 2],\n 5: [3, 999],\n 6: [4, 999],\n 10: [4, 999],\n 50: [6, 999],\n 60: [8, 999]\n }\n if len(raids) <= 0:\n return True\n else:\n slots = len(set(raids[0]['sas_id'].split(',')))\n level = int(raids[0]['level'])\n rule = rules[level]\n if slots < rule[0] or slots > rule[1]:\n msg = (slots,rule[0],rule[1])\n return 'Invalid RAID, %s slots, min %s - max %s' % msg\n else:\n return isValidRAID(raids[1:])\n\ndef isSameCapacityAndSpeed(drives,raids):\n \"\"\" Check if all the HDDs in the RAID container have the\n same capacity and speed. Return True if so, if not\n return an error message.\n \"\"\"\n if len(raids) <= 0:\n return True\n else:\n slots = raids[0]['sas_id'].split(',')\n drivesOnRAID = filter(lambda x: x['driveChannelId'] in slots, drives)\n sameCapacity = getSameCapacity(drivesOnRAID)\n sameSpeed = getSameSpeed(drivesOnRAID)\n\n if len(drivesOnRAID) != len(sameCapacity):\n return 'Drives with diff capacity in RAID Ctrl. %s '%str(drivesOnRAID)\n elif len(drivesOnRAID) != len(sameSpeed):\n return 'Drives with diff speed in RAID Ctrl. %s '%str(drivesOnRAID)\n else:\n return isSameCapacityAndSpeed(drives,raids[1:])\n\ndef getSameCapacity(drives):\n \"\"\" Return a drives list of same capacity\n \"\"\"\n capacity = drives[0]['capacity(MB)'] # get capacity frm first drive\n return filter(lambda x:x['capacity(MB)']==capacity,drives)\n\ndef getSameSpeed(drives):\n \"\"\" Return a drives list of same capacity if attribute\n 'spindle_speed' exists in each drive information.\n\n Return an empty list if 'spindle_speed' exists only in\n some drives, otherwise, return the drives list without\n the attribute.\n \"\"\"\n try:\n speed = drives[0]['spindle_speed(RPM)']# get speed from first drive\n return filter(lambda x:x['spindle_speed(RPM)']== speed,drives)\n except KeyError:\n if len(set(map(len,drives))) > 1:\n return []\n else:\n return drives\n\n\nif __name__ == '__main__':\n gcf = None\n with open('gcf.xml', 'r') as file:\n gcf = file.read()\n\n getControllers(gcf)\n\n","sub_path":"raid.py","file_name":"raid.py","file_ext":"py","file_size_in_byte":4877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"597065144","text":"from datetime import datetime\nimport os\nimport urllib.request\n\nSHUTDOWN_EVENT = 'Shutdown initiated'\n\n# prep: read in the logfile\ntmp = os.getenv(\"TMP\", \"/tmp\")\nlogfile = os.path.join(tmp, 'log')\nurllib.request.urlretrieve(\n 'https://bites-data.s3.us-east-2.amazonaws.com/messages.log',\n logfile\n)\n\nwith open(logfile) as f:\n loglines = f.readlines()\n\n\ndef convert_to_datetime(line):\n try:\n return datetime.strptime(line.split(' ')[1], '%Y-%m-%dT%X')\n except ValueError:\n print(f'Invalid timestamp found for {line}')\n\n\ndef time_between_shutdowns(loglines):\n shutdowns = [line for line in loglines if SHUTDOWN_EVENT in line]\n return convert_to_datetime(shutdowns[-1]) - convert_to_datetime(shutdowns[0])\n\n","sub_path":"days/01-03-datetimes/code/logtimes.py","file_name":"logtimes.py","file_ext":"py","file_size_in_byte":738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"181657691","text":"import os\nimport tempfile\nimport subprocess\nimport sys\nfrom lxml import etree\nfrom pprint import PrettyPrinter\n\n\ndef save(text):\n fd, filename = tempfile.mkstemp()\n os.write(fd, text)\n os.close(fd)\n return filename\n\ndef less(text):\n filename = save(text)\n subprocess.call('less %s' % filename, shell=True)\n os.unlink(filename)\n\ndef grep(args, text):\n filename = save(text)\n subprocess.call('ack-grep %s %s' % (args, filename), shell=True)\n os.unlink(filename)\n\ndef xmlprint(text, encoding=sys.stdout.encoding):\n print(xmlformat(text, encoding))\n\ndef xmlformat(text, encoding=sys.stdout.encoding):\n tree = etree.fromstring(text)\n return etree.tostring(tree, encoding=encoding, pretty_print=True)\n\ndef pprint(obj, stream=None, indent=1, width=80, depth=None):\n\n class _PrettyPrinter(PrettyPrinter):\n def format(self, *args, **kwargs):\n repr, readable, recursive = PrettyPrinter.format(self, *args, **kwargs)\n if repr:\n if repr[0] in ('\"', \"'\"):\n repr = repr.decode('string_escape')\n elif repr[0:2] in (\"u'\", 'u\"'):\n repr = repr.decode('unicode_escape').encode(sys.stdout.encoding)\n return repr, readable, recursive\n\n printer = _PrettyPrinter(stream=stream, indent=indent, width=width, depth=depth)\n printer.pprint(obj)\n\ndef uprint(value):\n if hasattr(value, '__iter__'):\n print(print(value))\n else:\n print(repr(value))\n\ndef _print(seq):\n\n def _repr(value):\n if hasattr(value, '__iter__'):\n return _print(value)\n return u'\"%s\"' % value.replace(u'\"', u'\\\\\"') \n\n if isinstance(seq, tuple):\n template = u'(%s,)'\n return template % ', '.join([_repr(item) for item in seq])\n elif isinstance(seq, list):\n template = u'[%s,]'\n return template % ', '.join([_repr(item) for item in seq])\n elif isinstance(seq, dict):\n template = u'{%s,}'\n return template % ', '.join([u\"%s:%s\" % (_repr(k), _repr(v)) for k,v in seq.iteritems()])\n else:\n return repr(seq)\n\n\n","sub_path":"venv/lib/python3.5/site-packages/dt/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"181809283","text":"\n\nclass Encodeur:\n\n def __init__(self):\n fichier_sources = open(\"ressources/sources.txt\", \"r\")\n fichier_emis = open(\"ressources/emis.txt\", \"r+\")\n strSources = fichier_sources.read()\n print(\"Lecture du fichier source.txt: \")\n print(strSources)\n\n strChaineMonoligne = strSources.replace('\\n', '')\n\n listeBlock = []\n tailleChaine = len(strChaineMonoligne)\n reste = tailleChaine % 4\n nbBlock = (tailleChaine-reste) / 4\n indice = 0\n while indice < tailleChaine-reste:\n listeBlock.append(strChaineMonoligne[indice:(indice+4)])\n indice += 4\n if reste > 0:\n blockPartiel = strChaineMonoligne[indice:-1]\n nbBit = 0\n while nbBit <= (4-reste):\n blockPartiel += '0'\n nbBit += 1\n listeBlock.append(blockPartiel)\n print('Block Partiel :' + blockPartiel)\n\n matriceHamming = ['1000', '0100', '0010', '0001', '1011', '0111', '1101']\n\n listeEncodee = []\n for block in listeBlock:\n strBlockEncode = ''\n for ligne in matriceHamming:\n result = bool(int(ligne[0], 2) & int(block[0], 2))\n result ^= bool(int(ligne[1], 2) & int(block[1], 2))\n result ^= bool(int(ligne[2], 2) & int(block[2], 2))\n result ^= bool(int(ligne[3], 2) & int(block[3], 2))\n if result:\n strBlockEncode += '1'\n else:\n strBlockEncode += '0'\n listeEncodee.append(strBlockEncode)\n\n strSourceEncodee = ''.join(listeEncodee)\n fichier_emis.write(strSourceEncodee)\n print('Encodage termine')\n\n","sub_path":"Encodeur.py","file_name":"Encodeur.py","file_ext":"py","file_size_in_byte":1747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"43327193","text":"import numpy as np\n\ndef cosine_grid(length,height,n,m,strain):\n col,row=np.meshgrid(np.arange(0,length,1),np.arange(0,height,1))\n\n length_b = m/n*(length+strain*length)/(1.+m/n+m/n*strain)\n length_a = n/m*length_b/(1+strain)\n\n img_a = (-np.cos(2*np.pi*col / (length_a/n)) - np.cos(2*np.pi*row / (height/(n+m))) + 2.)/4.\n img_b = (-np.cos(2*np.pi*(col-length_a) / (length_b/m)) - np.cos(2*np.pi*row / (height/(n+m))) + 2.)/4.\n\n img = img_a.copy()\n img[col>length_a] = img_b[col>length_a]\n \n return img","sub_path":"tia/testtools.py","file_name":"testtools.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"333521021","text":"import sys\n#\n# >>> Escriba el codigo del mapper a partir de este punto <<<\n#\nif __name__ == \"__main__\":\n for line in sys.stdin:\n col2 = ''\n line = line.strip()\n\n splits = line.split(\" \")\n\n if len(splits) != 2: \n col2 = splits[1] \n for x in col2:\n col2S = col2.split(\"-\")\n print(col2S[1]+ '\\t1')\n ","sub_path":"01-hadoop-50/q05-10/mapper.py","file_name":"mapper.py","file_ext":"py","file_size_in_byte":371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"67924712","text":"\n\nfrom xai.brain.wordbase.nouns._quiver import _QUIVER\n\n#calss header\nclass _QUIVERED(_QUIVER, ):\n\tdef __init__(self,): \n\t\t_QUIVER.__init__(self)\n\t\tself.name = \"QUIVERED\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"quiver\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_quivered.py","file_name":"_quivered.py","file_ext":"py","file_size_in_byte":240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"338785974","text":"\"\"\" PGT: Accurate News Recommendation Coalescing Personal and Global Temporal Preferences\n\nCode Authors:\n - Bonhun Koo, (darkgs@snu.ac.kr) Data Mining Lab. at Seoul National University.\n - U Kang, (ukang@snu.ac.kr) Associate Professor.\n\n File: src/generate_torch_rnn_input.py\n - Generate the preprocessed rnn input of torch\n\n\"\"\"\n\nimport os\nimport json\nimport itertools\n\nimport torch\nimport numpy as np\n\nfrom optparse import OptionParser\nfrom multiprocessing import Pool\n\nfrom ad_util import get_files_under_path\nfrom ad_util import write_log\n\nparser = OptionParser()\nparser.add_option('-d', '--data_path', dest='data_path', type='string', default=None)\nparser.add_option('-o', '--output_dir_path', dest='output_dir_path', type='string', default=None)\n\ndict_per_user = {}\nlist_per_time = []\n\ndict_url_idx = {}\n#dict_url_vec = {}\ndict_usr2idx = {}\n\noutput_dir_path = None\nseparated_output_dir_path = None\nmerged_sequences = []\n\n\ndef load_per_datas(per_user_path=None, per_time_path=None):\n \"\"\"\n load the datas seperated by user and time\n :per_user_path: path of data seperated by the user\n :per_time_path: path of data seperated by the time\n :return: loaded data\n \"\"\"\n global dict_per_user, list_per_time\n\n dict_per_user = {}\n list_per_time = []\n\n if (per_user_path == None) or (per_time_path == None):\n return\n\n with open(per_user_path, 'r') as f_user:\n dict_per_user = json.load(f_user)\n\n with open(per_time_path, 'r') as f_time:\n list_per_time = json.load(f_time)\n\ndef generate_usr2idx(dict_per_user):\n \"\"\"\n generate the user2idx dictionary\n :dict_per_user: dictionary translating user id to idx\n :return: user2idx dictionary\n \"\"\"\n dict_usr2idx = {}\n set_usr = set([])\n\n # \"cx:i68bn3gbf0ql786n:1hyr7mridb1el\": [[1483570820, \"http://adressa.no/100sport/ballsport/byasen-fiasko-mot-tabelljumboen-228288b.html\"]]\n for user_id, _ in dict_per_user.items():\n set_usr.update([user_id])\n\n for i, user_id in enumerate(set_usr):\n dict_usr2idx[user_id] = i\n\n return dict_usr2idx\n\n\ndef generate_unique_url_idxs():\n \"\"\"\n generate the unique url indices for each news\n :return: output dictionary\n \"\"\"\n global dict_per_user, dict_url_idx\n\n dict_url_idx = {}\n\n # \"cx:i68bn3gbf0ql786n:1hyr7mridb1el\": [[1483570820, \"http://adressa.no/100sport/ballsport/byasen-fiasko-mot-tabelljumboen-228288b.html\"]]\n for user_id, sequence in dict_per_user.items():\n for timestamp, url in sequence:\n dict_url_idx[url] = 0\n\n dict_url_idx['url_pad'] = 0\n cur_idx = 1\n for url, _ in dict_url_idx.items():\n if url == 'url_pad':\n continue\n dict_url_idx[url] = cur_idx\n cur_idx += 1\n\n\ndef separated_process(args=(-1, [])):\n \"\"\"\n multi-processed implementation of the taskes\n :args: tasks\n :return: none\n \"\"\"\n global dict_per_user, dict_url_idx, separated_output_dir_path\n\n worker_id, user_ids = args\n\n dict_data = {}\n for user_id in user_ids:\n # remove duplication\n sequence = []\n\n # \"cx:i68bn3gbf0ql786n:1hyr7mridb1el\": [[1483570820, \"http://adressa.no/100sport/ballsport/byasen-fiasko-mot-tabelljumboen-228288b.html\"]]\n prev_url = None\n for seq_entry in dict_per_user[user_id]:\n timestamp, url = seq_entry\n if (prev_url == None) or (url != prev_url):\n prev_url = url\n sequence.append(seq_entry)\n\n seq_len = len(sequence)\n\n # Minimum valid sequence length\n if seq_len < 2:\n continue\n\n # Maximum valid sequence length\n# if seq_len > 20:\n# sequence = sequence[-20:]\n\n start_time = sequence[0][0]\n end_time = sequence[-1][0]\n\n idx_sequence = [dict_url_idx[url] for timestamp, url in sequence]\n time_sequence = [timestamp for timestamp, url in sequence]\n\n dict_data[user_id] = {\n 'start_time': start_time,\n 'end_time': end_time,\n 'sequence': idx_sequence,\n 'time_sequence': time_sequence,\n }\n\n with open('{}/{}_data.json'.format(separated_output_dir_path, worker_id), 'w') as f_out:\n json.dump(dict_data, f_out)\n\n\ndef generate_merged_sequences():\n \"\"\"\n generate the merges sequences from the seperated inputs\n :return: merges sequences for all users\n \"\"\"\n global separated_output_dir_path, merged_sequences, dict_per_user, dict_usr2idx\n\n\n merged_sequences = []\n separated_files = get_files_under_path(separated_output_dir_path)\n\n for separated_file in separated_files:\n with open(separated_file, 'r') as f_dict:\n separated_dict = json.load(f_dict)\n\n# separated_dict[user_id] = {\n# 'start_time': start_time,\n# 'end_time': end_time,\n# 'sequence': idx_sequence,\n# 'time_sequence': time_sequence,\n# }\n\n for user_id, dict_data in separated_dict.items():\n seq_len = len(dict_data['sequence'])\n if seq_len <= 1:\n continue\n\n sequence_entry = (dict_data['start_time'], dict_data['end_time'], dict_usr2idx[user_id],\n dict_data['sequence'], dict_data['time_sequence'])\n merged_sequences.append(sequence_entry)\n# st = 0\n# st_step = max(1, int((seq_len - 20) / 5) + 1)\n# while (st == 0) or (st + 20 <= seq_len):\n# cur_seq = dict_data['sequence'][st:st+20]\n# cur_t_seq = dict_data['time_sequence'][st:st+20]\n#\n# sequence_entry = (cur_t_seq[0], cur_t_seq[-1], dict_usr2idx[user_id],\n# cur_seq, cur_t_seq)\n#\n# merged_sequences.append(sequence_entry)\n#\n# st += st_step\n\n merged_sequences.sort(key=lambda x:x[0])\n\n\n#def load_url2vec(url2vec_path=None):\n# global dict_url_vec\n#\n# dict_url_vec = {}\n# if url2vec_path == None:\n# return\n#\n# with open(url2vec_path, 'r') as f_u2v:\n# dict_url_vec = json.load(f_u2v)\n#\n\ndef extract_current_popular_indices(dict_time_idx, item_count=50, window_size=60*60*3):\n \"\"\"\n extract current populr news indices\n :dict_time_idx: dictionary of time indices\n :item_count: number of popular news to be extracted\n :window_size: size of time window (sec)\n :return: current popular news indices\n \"\"\"\n dict_trendy_idx = {}\n def generate_trendy_items(dict_target, padding):\n ret = sorted(dict_target.items(), key=lambda x: x[1], reverse=True)\n#assert(len(ret) > 10)\n assert(len(ret) > 0)\n if len(ret) < item_count:\n ret += [(padding,0)] * (item_count - len(ret))\n\n return ret[:item_count]\n\n prev_timestamp = list_per_time[0][0]\n cur_timestamp = prev_timestamp\n dict_cur_trendy = {}\n\n # Initialize setting\n while cur_timestamp != None and (int(cur_timestamp) - int(prev_timestamp)) < window_size:\n for idx, count in dict_time_idx[cur_timestamp]['indices'].items():\n dict_cur_trendy[idx] = dict_cur_trendy.get(idx, 0) + count\n\n cur_timestamp = dict_time_idx[cur_timestamp]['next_time']\n\n copy_timestamp = prev_timestamp\n while(copy_timestamp is not cur_timestamp):\n dict_trendy_idx[copy_timestamp] = generate_trendy_items(dict_cur_trendy, dict_url_idx['url_pad'])\n\n copy_timestamp = dict_time_idx[copy_timestamp]['next_time']\n dict_trendy_idx[cur_timestamp] = generate_trendy_items(dict_cur_trendy, dict_url_idx['url_pad'])\n\n # main step\n while(True):\n # move cur\n cur_timestamp = dict_time_idx[cur_timestamp]['next_time']\n\n if cur_timestamp == None:\n break\n\n for idx, count in dict_time_idx[cur_timestamp]['indices'].items():\n dict_cur_trendy[idx] = dict_cur_trendy.get(idx, 0) + count\n\n # move prev\n to_be_removed = []\n while prev_timestamp != None and int(cur_timestamp) > int(prev_timestamp) and \\\n (int(cur_timestamp) - int(prev_timestamp)) > window_size:\n\n for idx, count in dict_time_idx[prev_timestamp]['indices'].items():\n dict_cur_trendy[idx] = dict_cur_trendy.get(idx, 0) - count\n if dict_cur_trendy[idx] <= 0:\n to_be_removed.append(idx)\n\n prev_timestamp = dict_time_idx[prev_timestamp]['next_time']\n\n for idx in to_be_removed:\n dict_cur_trendy.pop(idx, None)\n\n # Update trendy data\n dict_trendy_idx[cur_timestamp] = generate_trendy_items(dict_cur_trendy, dict_url_idx['url_pad'])\n\n return dict_trendy_idx\n\ndef extract_recency_indices(dict_time_idx, item_count=50, window_size=60*60):\n \"\"\"\n extract current fresh news indices\n :dict_time_idx: dictionary of time indices\n :item_count: number of fresh news to be extracted\n :window_size: size of time window (sec)\n :return: current fresh news indices\n \"\"\"\n dict_indices = {}\n def generate_recency_items(dict_target, padding):\n ret = sorted(dict_target.items(), key=lambda x: x[1], reverse=True)\n#assert(len(ret) > 10)\n assert(len(ret) > 0)\n if len(ret) < item_count:\n ret += [(padding,0)] * (item_count - len(ret))\n\n return ret[:item_count]\n\n prev_timestamp = list_per_time[0][0]\n cur_timestamp = prev_timestamp\n dict_cur_trendy = {}\n\n # Initialize setting\n while cur_timestamp != None and (int(cur_timestamp) - int(prev_timestamp)) < window_size:\n for idx, count in dict_time_idx[cur_timestamp]['indices'].items():\n dict_cur_trendy[idx] = int(cur_timestamp)\n\n cur_timestamp = dict_time_idx[cur_timestamp]['next_time']\n\n copy_timestamp = prev_timestamp\n while(copy_timestamp is not cur_timestamp):\n dict_indices[copy_timestamp] = generate_recency_items(dict_cur_trendy, dict_url_idx['url_pad'])\n\n copy_timestamp = dict_time_idx[copy_timestamp]['next_time']\n dict_indices[cur_timestamp] = generate_recency_items(dict_cur_trendy, dict_url_idx['url_pad'])\n\n # main step\n while(True):\n # move cur\n cur_timestamp = dict_time_idx[cur_timestamp]['next_time']\n\n if cur_timestamp == None:\n break\n\n for idx, count in dict_time_idx[cur_timestamp]['indices'].items():\n dict_cur_trendy[idx] = cur_timestamp\n\n # move prev\n to_be_removed = []\n while prev_timestamp != None and int(cur_timestamp) > int(prev_timestamp) and (int(cur_timestamp) - int(prev_timestamp)) > window_size:\n\n for idx, timestamp in dict_time_idx[prev_timestamp]['indices'].items():\n if dict_cur_trendy.get(idx, None) != None and dict_cur_trendy[idx] <= int(prev_timestamp):\n to_be_removed.append(idx)\n\n prev_timestamp = dict_time_idx[prev_timestamp]['next_time']\n\n for idx in to_be_removed:\n dict_cur_trendy.pop(idx, None)\n\n # Update trendy data\n dict_indices[cur_timestamp] = generate_recency_items(dict_cur_trendy, dict_url_idx['url_pad'])\n\n return dict_indices\n\ndef generate_torch_rnn_input():\n \"\"\"\n generate torch rnn inputs for each data_types\n :return: none\n \"\"\"\n global merged_sequences, dict_url_idx, list_per_time, output_dir_path, dict_usr2idx\n\n # idx2url\n dict_idx2url = {idx:url for url, idx in dict_url_idx.items()}\n\n # sequence_datas\n total_seq_count = len(merged_sequences)\n\n division_infos = [\n ('train', 0, int(total_seq_count*0.8)),\n ('valid', int(total_seq_count*0.8), int(total_seq_count*0.9)),\n ('test', int(total_seq_count*0.9), int(total_seq_count)),\n ]\n\n dict_seq_datas = {}\n for dataset_name, idx_st, idx_ed in division_infos:\n dict_seq_datas[dataset_name] = merged_sequences[idx_st:idx_ed]\n\n # shuffle and clip test set\n#dict_seq_datas['test'] = [ dict_seq_datas['test'][idx] for idx in np.random.permutation(len(dict_seq_datas['test'])).tolist()[:200000] ]\n dict_seq_datas['test'] = [ dict_seq_datas['test'][idx] for idx in np.random.permutation(len(dict_seq_datas['test'])).tolist() ]\n\n # candidates\n dict_time_idx = {}\n\n prev_timestamp = None\n for (timestamp, user_id, url) in list_per_time:\n if prev_timestamp != timestamp:\n if prev_timestamp != None:\n dict_time_idx[prev_timestamp]['next_time'] = timestamp\n dict_time_idx[timestamp] = {\n 'prev_time': prev_timestamp,\n 'next_time': None,\n 'indices': {},\n }\n\n idx_of_url = dict_url_idx[url]\n dict_time_idx[timestamp]['indices'][idx_of_url] = \\\n dict_time_idx[timestamp]['indices'].get(idx_of_url, 0) + 1\n\n prev_timestamp = timestamp\n\n # trendy\n dict_trendy_idx = extract_current_popular_indices(dict_time_idx, item_count=100, window_size=60*60*3)\n\n # recency\n dict_recency_idx = extract_recency_indices(dict_time_idx, item_count=15, window_size=60*60)\n\n # save\n dict_torch_rnn_input = {\n 'dataset': dict_seq_datas,\n# 'idx2vec': dict_idx_vec,\n 'idx2url': dict_idx2url,\n 'time_idx': dict_time_idx,\n 'pad_idx': dict_url_idx['url_pad'],\n# 'embedding_dimension': embeding_dimension,\n 'trendy_idx': dict_trendy_idx,\n 'recency_idx': dict_recency_idx,\n 'user_size': len(dict_usr2idx),\n }\n\n with open('{}/torch_rnn_input.dict'.format(output_dir_path), 'w') as f_extra:\n json.dump(dict_torch_rnn_input, f_extra)\n\n\ndef main():\n \"\"\"\n main function\n \"\"\"\n global dict_per_user, separated_output_dir_path, output_dir_path, dict_usr2idx\n\n options, args = parser.parse_args()\n\n if (options.data_path == None) or (options.output_dir_path == None):\n return\n\n per_time_path = options.data_path + '/per_time.json'\n per_user_path = options.data_path + '/per_user.json'\n\n output_dir_path = options.output_dir_path\n\n if not os.path.exists(output_dir_path):\n os.system('mkdir -p {}'.format(output_dir_path))\n\n print('Loading Sequence datas : start')\n load_per_datas(per_user_path=per_user_path, per_time_path=per_time_path)\n print('Loading Sequence datas : end')\n\n print('Generate unique url indices : start')\n generate_unique_url_idxs()\n print('Generate unique url indices : end')\n\n dict_usr2idx = generate_usr2idx(dict_per_user)\n\n print('Seperated by user process : start')\n separated_output_dir_path = '{}/separated'.format(output_dir_path)\n if not os.path.exists(separated_output_dir_path):\n os.system('mkdir -p {}'.format(separated_output_dir_path))\n\n n_div = 100 # degree of separate\n n_multi = 5 # degree of multiprocess\n user_ids = [user_id for user_id, _ in dict_per_user.items()]\n works = [(i, user_ids[i::n_div]) for i in range(n_div)]\n\n pool = Pool(n_multi)\n pool.map(separated_process, works)\n pool = None\n print('Seperated by user process : end')\n\n print('Merging separated infos...')\n generate_merged_sequences()\n print('Merging separated infos... Done')\n\n\n# print('Loading url2vec : start')\n# load_url2vec(url2vec_path=url2vec_path)\n# print('Loading url2vec : end')\n\n print('Generate torch_rnn_input : start')\n generate_torch_rnn_input()\n print('Generate torch_rnn_input : end')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"src/generate_torch_rnn_input.py","file_name":"generate_torch_rnn_input.py","file_ext":"py","file_size_in_byte":15547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"267779900","text":"#!/usr/bin/env python\nfrom pprint import pprint\nimport re\n\ndata = [] # empty list\n\nwith open('DATA/testscores.dat') as scores_in:\n for line in scores_in:\n last_name, first_name, raw_score = re.split(r'(?:,\\s*|:)',line.rstrip())\n data.append((last_name, first_name, int(raw_score)))\n\nwith open('scorereport.txt', \"\"\"w\"\"\") as report_out:\n for last_name, first_name, score in sorted(data):\n print(f\"{first_name:20s} {last_name:20s} {score:2d}\")\n report_out.write(f\"{first_name:20s} {last_name:20s} {score:2d}\")\n","sub_path":"read_file_into_list_of_tuples.py","file_name":"read_file_into_list_of_tuples.py","file_ext":"py","file_size_in_byte":543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"197874322","text":"import unittest\nimport os\nfrom log_analyzer.log_analyzer import check_latest_logfile, parse_url, parse_req_time, count, time_sum, time_max, sort_dict_by_key_value\nfrom log_analyzer.log_analyzer import table_json\n\n\nclass MyTest(unittest.TestCase):\n def test_check_latest_logfile(self):\n res = check_latest_logfile(os.path.abspath('dir_not_exist'))\n self.assertEqual(res, 'Dir not exist')\n res = check_latest_logfile(os.path.abspath('empty_dir'))\n self.assertEqual(res, 'Log file dir is empty')\n\n def test_parse_url(self):\n res = parse_url('1.196.116.32 - - [29/Jun/2017:03:50:22 +0300] \"GET /api/v2/banner/25019354 HTTP/1.1\" 200 927 \"-\" \"Lynx/2.8.8dev.9 libwww-FM/2.14 SSL-MM/1.4.1 GNUTLS/2.10.5\" \"-\" \"1498697422-2190034393-4708-9752759\" \"dc7161be3\" 0.390')\n self.assertEqual(res, '/api/v2/banner/25019354')\n res = parse_url('1.195.208.16 - - [29/Jun/2017:03:50:23 +0300] \"POST /api/v2/target/12988/list?status=1 HTTP/1.0\" 200 2 \"https://rb.mail.ru/api/v2/target/12988/list?status=1\" \"MR HTTP Monitor\" \"-\" \"1498697423-1957913694-4708-9752787\" \"-\" 0.003')\n self.assertEqual(res, '/api/v2/target/12988/list?status=1')\n res = parse_url('rehretwhr32534trg')\n self.assertEqual(res, None)\n res = parse_url('')\n self.assertEqual(res, None)\n\n def test_parse_req_time(self):\n res = parse_req_time('1.196.116.32 - - [29/Jun/2017:03:50:22 +0300] \"GET /api/v2/banner/25019354 HTTP/1.1\" 200 927 \"-\" \"Lynx/2.8.8dev.9 libwww-FM/2.14 SSL-MM/1.4.1 GNUTLS/2.10.5\" \"-\" \"1498697422-2190034393-4708-9752759\" \"dc7161be3\" 0.390')\n self.assertEqual(res, 0.39)\n\n def test_count(self):\n res = count('/api/v2/target/12988/list?status=1')\n self.assertIsInstance(res, int)\n\n def test_time_sum(self):\n res = time_sum('/api/v2/target/12988/list?status=1', 0.39)\n self.assertEqual(res, 0.39)\n\n table_json['/api/v2/target/12988/list?status=1']['time_sum'] = 100.01\n # проверяем, что функция проверила, что данный url есть в словаре и прибавила к нему текущее значении\n self.assertEqual(time_sum('/api/v2/target/12988/list?status=1', 99.99), 200.00)\n\n\n def test_time_max(self):\n res = time_max('/api/v2/target/12988/list?status=1', 0.39)\n # значение указывается впервые\n self.assertEqual(res, 0.39)\n\n table_json['/api/v2/target/12988/list?status=1']['time_max'] = 567.01\n\n # проверяем, что в словаре, остается вышеуказанное заначение, т.к. оно максимальное\n res = time_max('/api/v2/target/12988/list?status=1', 0.39)\n self.assertEqual(res, 567.01)\n\n # проверяем что новое значение заносится в словарь, т.к. оно больше предыдущего\n res = time_max('/api/v2/target/12988/list?status=1', 999.39)\n self.assertEqual(res, 999.39)\n\n\n def test_sort_dict_by_key_value(self):\n # возвращает сортированный по ключу список из словарей\n dict = {'/agency/banners_stats/3': {'count': 1, 'time_sum': 8.427, 'time_max': 4.427, 'count_perc': 0.217, 'time_perc': 0.164, 'time_avg': 1.427},\n '/agency/banners_stats/2': {'count': 1, 'time_sum': 5.418, 'time_max': 6.418, 'count_perc': 0.517, 'time_perc': 0.264, 'time_avg': 2.418},\n '/agency/banners_stats/1': {'count': 1, 'time_sum': 7.276, 'time_max': 1.276, 'count_perc': 0.117, 'time_perc': 0.362, 'time_avg': 3.276},\n '/agency/banners_stats/0': {'count': 1, 'time_sum': 0.276, 'time_max': 0.999, 'count_perc': 0.917, 'time_perc': 0.462, 'time_avg': 4.276}\n }\n\n res = sort_dict_by_key_value(dict, 'time_sum', 3)\n self.assertEqual(res, [\n {'count': 1, 'time_sum': 8.427, 'time_max': 4.427, 'count_perc': 0.217, 'time_perc': 0.164, 'time_avg': 1.427, 'url': '/agency/banners_stats/3'},\n {'count': 1, 'time_sum': 7.276, 'time_max': 1.276, 'count_perc': 0.117, 'time_perc': 0.362, 'time_avg': 3.276, 'url': '/agency/banners_stats/1'},\n {'count': 1, 'time_sum': 5.418, 'time_max': 6.418, 'count_perc': 0.517, 'time_perc': 0.264, 'time_avg': 2.418, 'url': '/agency/banners_stats/2'}])\n\n res = sort_dict_by_key_value(dict, 'time_max', 2)\n self.assertEqual(res, [\n {'count': 1, 'time_sum': 5.418, 'time_max': 6.418, 'count_perc': 0.517, 'time_perc': 0.264, 'time_avg': 2.418, 'url': '/agency/banners_stats/2'},\n {'count': 1, 'time_sum': 8.427, 'time_max': 4.427, 'count_perc': 0.217, 'time_perc': 0.164, 'time_avg': 1.427, 'url': '/agency/banners_stats/3'}])\n\n res = sort_dict_by_key_value(dict, 'time_avg', 4)\n self.assertEqual(res, [\n {'count': 1, 'time_sum': 0.276, 'time_max': 0.999, 'count_perc': 0.917, 'time_perc': 0.462, 'time_avg': 4.276, 'url': '/agency/banners_stats/0'},\n {'count': 1, 'time_sum': 7.276, 'time_max': 1.276, 'count_perc': 0.117, 'time_perc': 0.362, 'time_avg': 3.276, 'url': '/agency/banners_stats/1'},\n {'count': 1, 'time_sum': 5.418, 'time_max': 6.418, 'count_perc': 0.517, 'time_perc': 0.264, 'time_avg': 2.418, 'url': '/agency/banners_stats/2'},\n {'count': 1, 'time_sum': 8.427, 'time_max': 4.427, 'count_perc': 0.217, 'time_perc': 0.164, 'time_avg': 1.427, 'url': '/agency/banners_stats/3'}])","sub_path":"log_analyzer/test_log_analizer.py","file_name":"test_log_analizer.py","file_ext":"py","file_size_in_byte":5550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"281233728","text":"from bisect import bisect_left\nfrom collections import defaultdict, deque, namedtuple\n\nclass Vec(tuple):\n def __new__(cls, *args):\n return tuple.__new__(cls, args)\n\n def __add__(self, vec):\n return Vec(*map(sum, zip(self, vec)))\n\n def __sub__(self, vec):\n return Vec(*map(lambda x, y: x - y, self, vec))\n\n def __neg__(self):\n return Vec(*map(lambda x: -x, self))\n\n @property\n def x(self):\n return self[0]\n\n @property\n def y(self):\n return self[1]\n\n @property\n def z(self):\n return self[2]\n\nclass Puz:\n DIRECTIONS = [Vec(0, 1), Vec(0, -1), Vec(1, 0), Vec(-1, 0)]\n State = namedtuple(\"State\", ('keys', 'droids'))\n\n def __init__(self, grid):\n self.grid = grid\n self.init_grid()\n self.init_keys()\n self.init_tables()\n\n def init_keys(self):\n self.total_keys = 0\n self.all_keys = []\n for vec, tile in self.iterate():\n if tile.islower():\n self.total_keys += 1\n self.all_keys.append(tile)\n\n def init_grid(self):\n self.droid_positions = []\n for vec, tile in self.iterate():\n if tile == '@':\n self.droid_positions.append(vec)\n\n def init_tables(self):\n self.tables = []\n for pos in self.droid_positions:\n self.tables.append(self.tables_from_pos(pos)) \n\n def tables_from_pos(self, pos):\n tables = {}\n to_do = [pos]\n tile_at_pos = self.grid[pos.y][pos.x]\n if tile_at_pos in ('.', '#'):\n raise RuntimeError(\"Invalid start point.\")\n done = []\n while to_do:\n next_to_do = []\n for pos in to_do:\n tile = self.grid[pos.y][pos.x]\n tables[tile] = self.keys_from_pos(pos)\n done.append(tile)\n for destination, entry in tables[tile].items():\n if destination not in done:\n next_to_do.append(entry.pos)\n to_do = next_to_do\n return tables\n\n\n def keys_from_pos(self, pos, locked=()):\n Node = namedtuple('Node', ('pos', 'parent', 'dist'))\n to_do = [Node(pos, 0, None)]\n visited = deque([pos])\n dist = 0\n def have_visited(vec):\n tot_visited = len(visited)\n index = bisect_left(visited, vec)\n if index >= tot_visited:\n return (False, index)\n else:\n if visited[index] != vec:\n return (False, index)\n else:\n return (True, index)\n\n keys_reached = {}\n while to_do:\n next_to_do = []\n dist += 1\n for node in to_do:\n tile = self.grid[node.pos.y][node.pos.x]\n if tile.islower() and node.pos != pos:\n keys_reached[tile] = node\n continue\n\n for direction in self.DIRECTIONS:\n test_vec = node.pos + direction\n test_tile = self.grid[test_vec.y][test_vec.x]\n if test_tile != '#' and test_tile not in locked:\n is_visited, index = have_visited(test_vec)\n if not is_visited:\n next_to_do.append(Node(test_vec, node, dist))\n visited.insert(index, test_vec)\n to_do = next_to_do\n \n # We want to return the distances from this position for each key, plus\n # any doors along the way.\n table = {}\n Entry = namedtuple(\"Entry\", ('pos', 'distance', 'doors'))\n for key_name in keys_reached:\n node = keys_reached[key_name]\n key_pos = node.pos\n path = []\n while node.parent:\n path.append(node)\n node = node.parent\n path_doors = []\n for node in path:\n tile = self.grid[node.pos.y][node.pos.x]\n if tile.isupper():\n path_doors.append(tile)\n table[key_name] = Entry(key_pos, len(path), path_doors[::-1])\n return table\n\n def get_initial_state(self):\n return self.State((), ('@',)*len(self.droid_positions))\n\n def min_path(self):\n # Each state of an explored solution will be represented by a\n # collection of values. This will be a tuple of two tuples. The first\n # being the list of all keys currently held, in alphabetal order. The\n # second being the current location of each droid, represented by the\n # character value of its tile. i.e. @ for start, or key name otherwise.\n # We don't store intermediate positions, we hop directly to the next\n # key. For each number of steps taken, we will have a deque of all\n # states to explore from that point.\n State = self.State\n initial = self.get_initial_state()\n distances = defaultdict(list, {0: [initial]})\n visited_states = deque([initial])\n visited_distances = deque([0])\n counter = 0\n\n def find_state(state):\n index = bisect_left(visited_states, state)\n total = len(visited_states)\n if index >= total:\n return (False, index)\n if visited_states[index] != state:\n return (False, index)\n else:\n return (True, index)\n\n max_keys_found = 0\n while 1:\n for state in distances[counter]:\n if len(state.keys) >= self.total_keys:\n return counter\n if len(state.keys) > max_keys_found:\n max_keys_found = len(state.keys)\n max_keys_found = max(max_keys_found, len(state.keys))\n for index, start in enumerate(state.droids):\n table = self.tables[index][start]\n for end, entry in table.items():\n if not all(d.lower() in state.keys for d in entry.doors):\n # We cannot get to this key, locked doors in way.\n continue\n new_dist = counter + entry.distance\n if end in state.keys:\n new_keys = state.keys\n else:\n new_keys = tuple(sorted(state.keys + (end,)))\n new_droids = list(state.droids)\n new_droids[index] = end\n new_droids = tuple(new_droids)\n new_state = State(new_keys, new_droids)\n have_state, new_index = find_state(new_state)\n if not have_state:\n distances[new_dist].append(new_state)\n visited_states.insert(new_index, new_state)\n visited_distances.insert(new_index, new_dist)\n else:\n dist_for_state = visited_distances[new_index]\n if dist_for_state > new_dist:\n distances[dist_for_state].remove(new_state)\n distances[new_dist].append(new_state)\n visited_distances[new_index] = new_dist\n del distances[counter]\n counter += 1\n\n def iterate(self):\n for y, row in enumerate(self.grid):\n for x, tile in enumerate(row):\n yield Vec(x, y), tile\n\n def __str__(self):\n return '\\n'.join(''.join(row) for row in self.grid)\n\n\ndef solve_1(grid):\n puz = Puz(grid)\n answer = puz.min_path()\n return answer\n\n\ndef solve_2(grid):\n puz = Puz(grid)\n start_vec = None\n for vec, tile in puz.iterate():\n if tile == '@':\n start_vec = vec\n break\n\n for dy in range(-1, 2):\n for dx in range(-1, 2):\n v = vec + (dx, dy)\n if dx and dy:\n grid[v.y][v.x] = '@'\n else:\n grid[v.y][v.x] = '#'\n\n # We will split the grid into four. Remove doors for keys that are not in\n # that sector, and solve each like normal, then add the results.\n sub_grids = [\n [row[:v.x] for row in grid[:v.y]],\n [row[v.x - 1:] for row in grid[:v.y]],\n [row[:v.x] for row in grid[v.y - 1:]],\n [row[v.x - 1:] for row in grid[v.y - 1:]]\n ]\n total = 0\n for grid in sub_grids:\n puz = Puz(grid)\n for vec, tile in puz.iterate():\n if tile.isupper() and tile.lower() not in puz.all_keys:\n puz.grid[vec.y][vec.x] = '.'\n puz = Puz(grid) # to reinitialise...\n total += puz.min_path()\n return total\n\n\ndef main():\n text = open('input.txt').read()\n grid = [list(line) for line in text.splitlines()]\n print(solve_1(grid))\n print(solve_2(grid))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"day18/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"428009592","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Sep 29 20:42:00 2018\n\n@author: Administrator\n\"\"\"\n\nclass HMM(object):\n def __init__(self):\n import os \n self.model_file = './data/hmm_model.pkl'\n self.state_list = ['B','M','E','S']\n self.load_para = False\n \n def try_load_model(self,trained):\n if trained:\n import pickle\n with open(self.model_file,'rb') as f:\n self.A_dic = pickle.load(f) #转移概率\n self.B_dic = pickle.load(f) #发射概率\n self.Pi_dic = pickle.load(f) #初始概率\n self.load_para = True\n else:\n self.A_dic = {}\n self.B_dic = {}\n self.Pi_dic = {}\n self.load_para = False\n \n def train(self,path):\n self.try_load_model(False)\n Count_dic = {} #计数的字典\n def init_parameters():\n for state in self.state_list:\n self.A_dic[state] = {s:0.0 for s in self.state_list} #字典嵌套了\n self.Pi_dic[state] = 0.0 \n self.B_dic[state] = {}\n \n Count_dic[state] = 0\n \n def makeLabel(text): #给一行字打上标签\n out_text = []\n if len(text) ==1:\n out_text.append('S')\n else:\n out_text += ['B'] + ['M'] * (len(text)-2) + ['E']\n return out_text\n \n init_parameters()\n line_num = -1\n \n words = set()\n with open(path,encoding='utf8') as f:\n for line in f:\n line_num += 1\n line = line.strip() #去掉字符串首和尾的空格\n if not line:\n continue\n word_list = [i for i in line if i !='']\n words |= set(word_list) #更新字库,先将每个word_list去重排序,让后求并集\n \n linelist = line.split() #空格划分\n line_state = []\n for w in linelist:\n line_state.extend(makeLabel(w))\n \n assert len(word_list) == len(line_state)\n \n for k,v in enumerate(line_state):\n Count_dic[v] += 1\n if k == 0:\n self.Pi_dic[v] += 1\n else:#转移概率,发射概率,初始概率的字典相关值加一,注意A_dic为字典嵌套\n self.A_dic[line_state[k -1]][v] += 1\n self.B_dic[line_state[k]][word_list[k]] = \\\n self.B_dic[line_state[k]].get(word_list[k],0) + 1.0 #字典的get(key,value)用来判断key对应的值是否存在,不存在则返回value\n \n \n ","sub_path":"HMM.py","file_name":"HMM.py","file_ext":"py","file_size_in_byte":2838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"203085793","text":"import os\r\nfrom ebooklib import epub\r\n\r\n\r\ndef get_epub_style(uid, filename):\r\n style = None\r\n content = ''\r\n if os.path.isfile(filename):\r\n with open(filename, encoding='utf-8') as f:\r\n content = f.read()\r\n style = epub.EpubItem(\r\n uid=uid,\r\n file_name='{filepath}.css'.format(filepath = uid.replace('_','/')),\r\n media_type='text/css',\r\n content=content)\r\n return style","sub_path":"src/langproject/get_epub_style.py","file_name":"get_epub_style.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"27391777","text":"from tkinter import *\nroot = Tk()\n \ndef click(event):\n print(\"클릭위치\", event.x, event.y)\n \nframe = Frame(root, width=300, height=300)\n \n #왼쪽 마우스 버튼 바인딩\nframe.bind(\"\", click) \n \nframe.pack()\nroot.mainloop()","sub_path":"04. EventBinding.py","file_name":"04. EventBinding.py","file_ext":"py","file_size_in_byte":244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"380997879","text":"# Program that will renmae files in a directory to numerical names\n# starting at 0 going up until there are no files left.\n#\n# Christoffer Gustafsson\n# 2016-07-30\n#\n# Quirks:\n# This program ignores all file endings except .jpg\n\nimport os\n\ndef getJpgFiles(folder):\n dirtyFiles = os.listdir(folder)\n cleanFiles = []\n \n for _file in dirtyFiles:\n if str.lower(_file[len(_file)-4:]) == \".jpg\" :\n cleanFiles.append(_file)\n\n return cleanFiles\n\ndef getFolder():\n validFolder = False\n\n while not validFolder:\n print(\"enter name of folder: \")\n folder = input()\n try:\n print(\"These files will be renamed:\")\n print(getJpgFiles(folder))\n validFolder = True\n \n except Exception as e:\n print(\"The name you entered was not valid, reason: \" + str(e) + \"\\nPlease try again.\")\n\n return folder\n\ndef askIfSure(folder):\n while True:\n print(\"\\nThe folder \" + folder + \" will have \" + str(len(getJpgFiles(folder))) + \" files renamed. Do you want to procede? (Y/n): \")\n answer = input()\n try:\n if answer == \"y\" or answer == \"Y\":\n return True\n elif answer == \"n\" or answer == \"N\":\n return False\n\n except:\n pass\n\ndef fileExist(files, index):\n for _file in files:\n if _file == str(index) + \".jpg\": #or _file == str(index) + \".png\":\n return True\n \n return False\n \ndef renameFiles(folder):\n files = getJpgFiles(folder)\n index = 0\n\n for _file in files:\n print(index)\n try:\n if not fileExist(files, index):\n os.rename(folder + \"/\" + _file, folder + \"/\" + str(index+1) + _file[len(_file)-4:])\n index += 1\n\n except Exception as e:\n print(\"Something went wrong, tell this to the developer:\\n\" + str(e))\n return\n \ndef main():\n folder = getFolder()\n\n if askIfSure(folder) == False:\n return\n \n renameFiles(folder)\n \n\nif __name__ == \"__main__\":\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"448618809","text":"from scipy import *\nfrom pylab import plot, show, legend,xlim,ylim,savefig,title,xlabel,ylabel,clf, loglog\nimport csv\nimport os\nfrom Serre3 import *\nfrom numpy.linalg import norm\nfrom time import time\nfrom scipy.special import erf\n\ndef copyarraytoC(a):\n n = len(a)\n b = mallocPy(n)\n for i in range(n):\n writetomem(b,i,a[i])\n return b\n \ndef copyarrayfromC(a,n):\n b = [0]*n\n for i in range(n):\n b[i] = readfrommem(a,i)\n \n return b\n \ndef TDMApy(a,b,c,d):\n n = len(d)\n alpha = []\n beta = []\n x = [0]*n\n \n alpha.append((1.0*c[0])/b[0])\n beta.append((1.0*d[0])/b[0] ) \n \n for i in range(1,n-1):\n m = 1.0 / (b[i] - a[i-1]*alpha[i-1])\n alpha.append(c[i]* m)\n beta.append((d[i] - a[i-1]*beta[i-1]) * m)\n \n m = 1.0 / (b[n-1] - a[n-2]*alpha[n-2])\n beta.append((d[n-1] - a[n-2]*beta[n-2]) * m) \n\n x[n-1] = beta[n-1]\n \n for i in range(n-2,-1,-1):\n x[i] = beta[i] - alpha[i]*x[i+1]\n \n return array(x)\n \n#Tested from CFD forum post\ndef pentadiagsolve(e,a,d,c,f,B):\n n = len(d)\n X = zeros(n)\n \n for i in range(1,n-1):\n xmult = float(a[i-1]) / d[i-1]\n \n d[i] = d[i] - xmult*c[i-1]\n c[i] = c[i] - xmult*f[i-1]\n B[i] = B[i] - xmult*B[i-1]\n \n xmult = float(e[i-1]) /d[i-1]\n a[i] = a[i] - xmult*c[i-1]\n d[i+1] = d[i+1] - xmult*f[i-1]\n B[i+1] = B[i+1] - xmult*B[i-1]\n \n xmult = float(a[n-2]) / d[n-2]\n d[n-1] = d[n-1] - xmult*c[n-2]\n X[n-1] = (B[n-1] - xmult*B[n-2]) / float(d[n-1])\n X[n-2] = (B[n-2] - c[n-2]*X[n-1]) / float(d[n-2])\n \n for i in range(n-3,-1,-1):\n X[i] = (B[i] - f[i]*X[i+2] - c[i]*X[i+1])/float(d[i])\n \n return X \n \ndef makevar(sx,ex,dx,st,et,dt): \n x = arange(sx, ex, dx)\n t = arange(st, et, dt)\n \n return x,t \n \ndef midpointtocellaverages(mq,dx):\n #no BC required, assumes that the averages and midpoints at the boundaries are the same\n idx = 1.0/dx\n i24 = 1.0 / 24.0\n n = len(mq)\n \n a = zeros(n-1)\n b = zeros(n)\n c = zeros(n-1)\n for i in range(1,n-1):\n ai = -i24\n bi = 26*i24\n ci = -i24\n\n a[i-1] = ai\n b[i] = bi\n c[i] = ci\n \n #i = 0\n i = 0\n ai =0.0 #-i24\n bi =1.0 #26*i24\n ci =0.0 #-i24\n\n b[i] = bi\n c[i] = ci\n \n #mq[i] = mq[i] - ai*qbeg[0]\n \n #i = 0\n i = n-1\n ai =0.0# -i24\n bi =1.0# 26*i24\n ci =0.0# -i24\n\n a[i-1] = ai\n b[i] = bi\n \n #mq[i] = mq[i] - ci*qend[0]\n \n q = TDMApy(a,b,c,mq)\n \n return q\n \ndef cellaveragestomidpoints(q,dx):\n #no BC required, assumes that the averages and midpoints at the boundaries are the same\n i24 = 1.0 / 24.0\n n = len(q)\n mq = zeros(n)\n for i in range(1,n-1):\n #iterate over the cell midpoints, there are 2 edge values for each (except the first and last cell)\n \n #variables\n #ai = (q[i+1] - 2*q[i] + q[i-1])*0.5*idx*idx\n #bi = (q[i+1] - q[i-1])*0.5*idx\n ci = i24*(-q[i+1] + 26*q[i] -q[i-1])\n mq[i] = ci\n \n #i = 0\n i = 0\n ci = q[i] #i24*(-q[i+1] + 26*q[i] - qbeg[0])\n mq[i] = ci\n \n #i = n-1\n i = n-1\n ci = q[i]#i24*(-qend[0] + 26*q[i] - q[i-1])\n mq[i] = ci \n \n return mq\n \ndef havg(x,t,a0,a1,a2,a3,a4):\n return a0*x - sqrt(pi/2.0)*a1*sqrt(a4)*erf(- ((x - a2*t) - a3)/ sqrt(2*a4))\n \ndef uavg(x,t,a0,a1,a2,a3,a4):\n return a0*x - sqrt(pi/2.0)*a1*sqrt(a4)*erf(- ((x - a2*t) - a3)/ sqrt(2*a4)) \n \ndef hI(x,t,a0,a1,a2,a3,a4,a5,a6,a7):\n return a0*x - a1*sqrt(a4)*sqrt(pi/2.)*erf((a3 + a2*t - x)/(sqrt(2)*sqrt(a4)))\n \ndef hA(xi1,xi2,t,a0,a1,a2,a3,a4,a5,a6,a7):\n hxi1 = hI(xi1,t,a0,a1,a2,a3,a4,a5,a6,a7)\n hxi2 = hI(xi2,t,a0,a1,a2,a3,a4,a5,a6,a7)\n hAv = (hxi2 - hxi1)/(xi2 - xi1)\n return hAv\n\ndef uI(x,t,a0,a1,a2,a3,a4,a5,a6,a7):\n return - a5*sqrt(a4)*sqrt(pi/2.)*erf((a3 + a2*t - x)/(sqrt(2)*sqrt(a4)))\n\ndef uA(xi1,xi2,t,a0,a1,a2,a3,a4,a5,a6,a7):\n uxi1 = uI(xi1,t,a0,a1,a2,a3,a4,a5,a6,a7)\n uxi2 = uI(xi2,t,a0,a1,a2,a3,a4,a5,a6,a7)\n uAv = (uxi2 - uxi1)/(xi2 - xi1)\n return uAv\n\n \ndef GI(x,t,a0,a1,a2,a3,a4,a5,a6,a7):\n return (a5*(2*pow(e,((a3 + a2*t)*x)/a4)*pow(a1*pow(e,((a3 + a2*t)*x)/a4) + a0*pow(e,(pow(a3,2) + 2*a2*a3*t + pow(a2,2)*pow(t,2) + pow(x,2))/(2.*a4)),3)*(-a3 - a2*t + x) + \\\n 3*a1*pow(a4,1.5)*pow(e,(2*(pow(a3,2) + 2*a2*a3*t + pow(a2,2)*pow(t,2) + pow(x,2)))/a4)*sqrt(pi)*erf((-a3 - a2*t + x)/sqrt(a4)) + \\\n 3*a0*pow(a4,1.5)*pow(e,(2*(pow(a3,2) + 2*a2*a3*t + pow(a2,2)*pow(t,2) + pow(x,2)))/a4)*sqrt(2*pi)*erf((-a3 - a2*t + x)/(sqrt(2)*sqrt(a4)))))/(6.*a4*pow(e,(2*(pow(a3 + a2*t,2) + pow(x,2)))/a4))\n\ndef GA(xi1,xi2,t,a0,a1,a2,a3,a4,a5,a6,a7):\n Gxi1 = GI(xi1,t,a0,a1,a2,a3,a4,a5,a6,a7)\n Gxi2 = GI(xi2,t,a0,a1,a2,a3,a4,a5,a6,a7)\n GAv = (Gxi2 - Gxi1)/ (xi2 - xi1)\n return GAv\n \ndef ForcedbedA(x,t,a0,a1,a2,a3,a4,a5,a6,a7,g,dx):\n n = len(x)\n ha = zeros(n)\n ua = zeros(n)\n Ga = zeros(n)\n \n for i in range(n):\n xi1 = x[i] - 0.5*dx\n xi2 = x[i] + 0.5*dx\n ha[i] = hA(xi1,xi2,t,a0,a1,a2,a3,a4,a5,a6,a7)\n ua[i] = uA(xi1,xi2,t,a0,a1,a2,a3,a4,a5,a6,a7)\n Ga[i] = GA(xi1,xi2,t,a0,a1,a2,a3,a4,a5,a6,a7)\n\n return ha,ua,Ga\n \ndef ForcedbedM(x,t,a0,a1,a2,a3,a4,a5,a6,a7,g,dx):\n n = len(x)\n h = zeros(n)\n u = zeros(n)\n G = zeros(n)\n \n for i in range(n):\n phi = x[i] - a2*t \n \n \n h[i] = a0 + a1*exp(-(phi - a3)**2/(2*a4))\n u[i] = a5*exp(-(phi - a3)**2/(2*a4))\n \n hxi = -a1/a4*(phi - a3)*exp(-(phi - a3)**2/(2*a4))\n uxi = -a5/a4*(phi - a3)*exp(-(phi - a3)**2/(2*a4))\n\n uxxi = -a5/(a4**2)*exp(-(phi - a3)**2/(2*a4))*(a4 - ((phi) - a3)**2)\n \n \n G[i] = u[i]*h[i] - h[i]*h[i]*hxi*uxi - h[i]*h[i]*h[i]/3.0*uxxi\n \n return h,u,G\n \n \n \n #Forcing Problem \nwdir = \"../../../../../../../data/raw/Forced/FDVM3NoBed/GaussBedAll/New1/EvoObvious2/\" \n\nif not os.path.exists(wdir):\n os.makedirs(wdir)\n\nfor j in range(4,15):\n g =9.81\n\n a0 = 1\n a1 = 0.2\n a2 = 1.3\n a3 = 0.4\n a4 = 1.5\n a5 = 0.1\n a6 = 0\n a7 = 0\n \n width = 20.0\n \n g = 9.81\n \n dx = width / (2.0)**(j)\n l = 0.5 / (a5 + sqrt(g*(a0 + a1)))\n dt = l*dx\n startx = -width/2\n endx = width/2\n startt = 0.0\n endt = 0.1\n \n \n t = startt\n \n #number of boundary conditions (one side)\n nfcBC = 4 #for flux calculation\n nGsBC = 2 #for solving G from u,h\n niBC = nGsBC + nfcBC #total\n \n \n #x,t = makevar(startx,endx +0.1*dx,dx,startt,endt,dt)\n \n x = arange(startx,endx +0.1*dx, dx)\n \n xmbeg = arange(startx - niBC*dx ,x[0], dx)\n xmend = arange(x[-1] + dx ,x[-1] + (niBC+ 0.1)*dx, dx)\n \n\n ts = []\n \n n = len(x) \n theta = 2\n \n gap = int(1.0/dt)\n \n hm,um,Gm = ForcedbedM(x,t,a0,a1,a2,a3,a4,a5,a6,a7,g,dx)\n hmbeg,umbeg,Gmbeg = ForcedbedM(xmbeg,t,a0,a1,a2,a3,a4,a5,a6,a7,g,dx)\n hmend,umend,Gmend = ForcedbedM(xmend,t,a0,a1,a2,a3,a4,a5,a6,a7,g,dx)\n \n cnBC = niBC - nGsBC\n ha,ua,Ga = ForcedbedA(x,t,a0,a1,a2,a3,a4,a5,a6,a7,g,dx)\n habeg,uabeg,Gabeg = ForcedbedA(xmbeg,t,a0,a1,a2,a3,a4,a5,a6,a7,g,dx)\n haend,uaend,Gaend = ForcedbedA(xmend,t,a0,a1,a2,a3,a4,a5,a6,a7,g,dx)\n\n Ga_c = copyarraytoC(Ga)\n Gabeg_c = copyarraytoC(Gabeg)\n Gaend_c = copyarraytoC(Gaend)\n ha_c = copyarraytoC(ha)\n \n habeg_c = copyarraytoC(habeg)\n haend_c = copyarraytoC(haend)\n \n uabeg_c = copyarraytoC(uabeg)\n uaend_c = copyarraytoC(uaend)\n \n hmbeg_c = copyarraytoC(hmbeg)\n hmend_c = copyarraytoC(hmend)\n \n umbeg_c = copyarraytoC(umbeg)\n umend_c = copyarraytoC(umend)\n \n u_c = mallocPy(n)\n G_c = mallocPy(n)\n h_c = mallocPy(n)\n x_c = copyarraytoC(x)\n\n ts.append(t)\n #Just an FEM solve here\n while t < endt: \n evolvewrap(Ga_c,ha_c,Gabeg_c,Gaend_c,habeg_c,haend_c,hmbeg_c,hmend_c,uabeg_c,uaend_c,umbeg_c,umend_c,nfcBC,nGsBC,g,dx,dt,n,cnBC,niBC,x_c,t,a0,a1,a2,a3,a4,a5,a6,a7)\n t = t + dt\n ts.append(t)\n print(t)\n \n ca2midpt(ha_c,dx,n,h_c)\n ca2midpt(Ga_c,dx,n,G_c)\n \n GaC = copyarrayfromC(Ga_c,n)\n haC = copyarrayfromC(ha_c,n)\n \n GC = copyarrayfromC(G_c,n)\n hC = copyarrayfromC(h_c,n)\n\n\n ufromGh(G_c,h_c,hmbeg_c,hmend_c,umbeg_c,umend_c,dx,n,niBC, u_c)\n\n\n uC = copyarrayfromC(u_c,n)\n \n hmA,umA,GmA = ForcedbedM(x,t,a0,a1,a2,a3,a4,a5,a6,a7,g,dx)\n\n \n hnorm = norm(hC - hmA, ord=2)/ norm(hmA, ord=2)\n unorm = norm(uC - umA, ord=2)/ norm(umA, ord=2)\n Gnorm = norm(GC - GmA, ord=2)/ norm(GmA, ord=2)\n \n \n \n s = wdir + \"h.dat\"\n with open(s,'a') as file1:\n s =\"%3.8f%5s%1.20f\\n\" %(dx,\" \",hnorm)\n file1.write(s)\n \n\n \n s = wdir + \"G.dat\"\n with open(s,'a') as file1:\n s =\"%3.8f%5s%1.20f\\n\" %(dx,\" \",Gnorm)\n file1.write(s) \n \n s = wdir + \"u.dat\"\n with open(s,'a') as file1:\n s =\"%3.8f%5s%1.20f\\n\" %(dx,\" \",unorm)\n file1.write(s) \n\n deallocPy(ha_c)\n deallocPy(Ga_c)\n\n deallocPy(h_c)\n deallocPy(G_c)\n deallocPy(u_c) \n \n deallocPy(hmbeg_c)\n deallocPy(umbeg_c)\n deallocPy(hmend_c)\n deallocPy(umend_c)\n \n deallocPy(habeg_c)\n deallocPy(Gabeg_c)\n deallocPy(uabeg_c)\n deallocPy(haend_c)\n deallocPy(Gaend_c)\n deallocPy(uaend_c)\n\n\n\n \n\n\"\"\"\n##Accuracy Test\n### Soliton Accuracy ################\nwdir = \"../../../data/raw/Solnon0p7/o3/\"\n\nif not os.path.exists(wdir):\n os.makedirs(wdir)\n\ns = wdir + \"savenorms.txt\"\nwith open(s,'a') as file1:\n writefile = csv.writer(file1, delimiter = ',', quotechar='|', quoting=csv.QUOTE_MINIMAL)\n\n writefile.writerow(['dx','Normalised L1-norm Difference Height', ' Normalised L1-norm Difference Velocity','Hamiltonian Difference'])\n \nfor k in range(6,21):\n dx = 100.0 / (2**k)\n a0 = 1.0\n a1 = 0.7\n g = 9.81\n #g = 1.0\n Cr = 0.5\n l = 1.0 / (sqrt(g*(a0 + a1)))\n dt = Cr*l*dx\n startx = -250.0\n endx = 250.0 + dx\n startt = 0.0\n endt = 50 + dt\n \n print(dx,dt)\n \n szoomx = startx\n ezoomx = endx\n \n #number of boundary conditions (one side)\n nfcBC = 4 #for flux calculation\n nGsBC = 2 #for solving G from u,h\n niBC = nGsBC + nfcBC #total\n \n \n wdatadir = wdir+ str(k) + \"/\" \n if not os.path.exists(wdatadir):\n os.makedirs(wdatadir)\n \n gap =int(10.0/dt)\n \n x,t = makevar(startx,endx,dx,startt,endt,dt)\n n = len(x)\n \n t0 = 0.0 \n hm,um = solitoninit(n,a0,a1,g,x,t0,dx)\n \n umbeg = um[0]*ones(niBC)\n umend = um[-1]*ones(niBC)\n hmbeg = hm[0]*ones(niBC)\n hmend = hm[-1]*ones(niBC) \n \n #calculate G midpoint\n cnBC = niBC - nGsBC\n \n umbc = concatenate([umbeg[-cnBC:],um,umend[0:cnBC]]) \n hmbc = concatenate([hmbeg[-cnBC:],hm,hmend[0:cnBC]]) \n Gmbc = solveGfromuh(umbc,hmbc,hmbeg[0:-cnBC],hmend[-cnBC:],umbeg[0:-cnBC],umend[-cnBC:],dx) \n \n #calculate averages\n Gabc = midpointtocellaverages(Gmbc,dx)\n habc = midpointtocellaverages(hmbc,dx)\n uabc = midpointtocellaverages(umbc,dx)\n \n #so we can just go from here with Ga ang ha?\n Gabeg = Gabc[0:cnBC]\n Ga = Gabc[cnBC:-cnBC]\n Gaend = Gabc[-cnBC:]\n habeg = habc[0:cnBC]\n ha = habc[cnBC:-cnBC]\n haend = habc[-cnBC:]\n uabeg = uabc[0:cnBC]\n ua = uabc[cnBC:-cnBC]\n uaend = uabc[-cnBC:]\n \n Ga_c = copyarraytoC(Ga)\n Gabeg_c = copyarraytoC(Gabeg)\n Gaend_c = copyarraytoC(Gaend)\n ha_c = copyarraytoC(ha)\n \n habeg_c = copyarraytoC(habeg)\n haend_c = copyarraytoC(haend)\n \n uabeg_c = copyarraytoC(uabeg)\n uaend_c = copyarraytoC(uaend)\n \n hmbeg_c = copyarraytoC(hmbeg)\n hmend_c = copyarraytoC(hmend)\n \n umbeg_c = copyarraytoC(umbeg)\n umend_c = copyarraytoC(umend)\n \n u_c = mallocPy(n)\n G_c = mallocPy(n)\n h_c = mallocPy(n)\n \n xbeg = arange(startx - niBC*dx,startx,dx)\n xend = arange(endx + dx,endx + (niBC+1)*dx) \n \n xbc = concatenate([xbeg,x,xend]) \n \n xbc_c = copyarraytoC(xbc)\n hbc_c = mallocPy(n + 2*niBC)\n ubc_c = mallocPy(n + 2*niBC)\n Evals = []\n \n for i in range(1,len(t)):\n \n if(i % gap == 0 or i ==1):\n \n ca2midpt(ha_c,dx,n,h_c)\n ca2midpt(Ga_c,dx,n,G_c)\n ufromGh(G_c,h_c,hmbeg_c,hmend_c,umbeg_c,umend_c,dx,n,niBC, u_c)\n \n conc(hmbeg_c , h_c,hmend_c,niBC,n ,niBC , hbc_c)\n conc(umbeg_c , u_c,umend_c,niBC,n ,niBC , ubc_c) \n Eval = HankEnergyall(xbc_c,hbc_c,ubc_c,g,n + 2*niBC,niBC,dx)\n \n Evals.append(Eval)\n u = copyarrayfromC(u_c,n)\n G = copyarrayfromC(G_c,n)\n h = copyarrayfromC(h_c,n)\n \n \n c = sqrt(g*(a0 + a1))\n htrue = zeros(n)\n utrue = zeros(n)\n for j in range(n): \n he = soliton(x[j],t[i],g,a0,a1)\n htrue[j] = he\n utrue[j] = c* ((he - a0) / he) \n \n s = wdatadir + \"saveoutputts\" + str(i) + \".txt\"\n print t[i]\n print(h[3],G[3]) \n with open(s,'a') as file2:\n writefile2 = csv.writer(file2, delimiter = ',', quotechar='|', quoting=csv.QUOTE_MINIMAL)\n \n writefile2.writerow(['dx' ,'dt','time','xi','Eval', 'height(m)', 'G' , 'u(m/s)','true height', 'true velocity' ]) \n \n for j in range(n):\n writefile2.writerow([str(dx),str(dt),str(t[i]),str(x[j]),str(Eval), str(h[j]) , str(G[j]) , str(u[j]), str(htrue[j]), str(utrue[j])]) \n \n \n evolvewrap(Ga_c,ha_c,Gabeg_c,Gaend_c,habeg_c,haend_c,hmbeg_c,hmend_c,uabeg_c,uaend_c,umbeg_c,umend_c,nfcBC,nGsBC,g,dx,dt,n,cnBC,niBC)\n print t[i]\n print(h[3],G[3]) \n \n \n ca2midpt(ha_c,dx,n,h_c)\n ca2midpt(Ga_c,dx,n,G_c)\n ufromGh(G_c,h_c,hmbeg_c,hmend_c,umbeg_c,umend_c,dx,n,niBC, u_c)\n \n conc(hmbeg_c , h_c,hmend_c,niBC,n ,niBC , hbc_c)\n conc(umbeg_c , u_c,umend_c,niBC,n ,niBC , ubc_c) \n Eval = HankEnergyall(xbc_c,hbc_c,ubc_c,g,n + 2*niBC,niBC,dx)\n \n Evals.append(Eval)\n u = copyarrayfromC(u_c,n)\n G = copyarrayfromC(G_c,n)\n h = copyarrayfromC(h_c,n)\n \n c = sqrt(g*(a0 + a1))\n htrue = zeros(n)\n utrue = zeros(n)\n for j in range(n): \n he = soliton(x[j],t[i],g,a0,a1)\n htrue[j] = he\n utrue[j] = c* ((he - a0) / he) \n \n s = wdatadir + \"saveoutputtslast.txt\"\n with open(s,'a') as file2:\n writefile2 = csv.writer(file2, delimiter = ',', quotechar='|', quoting=csv.QUOTE_MINIMAL)\n \n writefile2.writerow(['dx' ,'dt','time','xi','Eval', 'height(m)', 'G' , 'u(m/s)','true height', 'true velocity' ]) \n \n for j in range(n):\n writefile2.writerow([str(dx),str(dt),str(t[i]),str(x[j]),str(Eval), str(h[j]) , str(G[j]) , str(u[j]), str(htrue[j]), str(utrue[j])]) \n \n normhdiffi = norm(h - htrue,ord=1) / norm(htrue,ord=1)\n normudiffi = norm(u -utrue,ord=1) / norm(utrue,ord=1)\n normHamdiff = (Evals[-1] - Evals[0])/ Evals[0]\n\n s = wdir + \"savenorms.txt\"\n with open(s,'a') as file1:\n writefile = csv.writer(file1, delimiter = ',', quotechar='|', quoting=csv.QUOTE_MINIMAL)\n\n writefile.writerow([str(dx),str(normhdiffi), str(normudiffi),str(normHamdiff)])\n\"\"\"\n\n","sub_path":"CODE/experimentcode/Thesis/Forced/GaussianBumpoverPeriodicBed/o3fixAvg/Run.py","file_name":"Run.py","file_ext":"py","file_size_in_byte":15674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"571838566","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport datetime\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ('login', '0006_remove_details_user'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='details',\n name='user',\n field=models.ForeignKey(default=datetime.datetime(2015, 6, 3, 23, 25, 40, 466000), to=settings.AUTH_USER_MODEL, unique=True),\n preserve_default=False,\n ),\n ]\n","sub_path":"login/migrations/0007_details_user.py","file_name":"0007_details_user.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"436236970","text":"from django import forms\n\nfrom .models import Person\n\n\nmy_default_errors = {\n 'required': 'This field is required',\n 'invalid': 'Enter a valid value',\n}\n\nclass SelectorForm(forms.Form):\n name = forms.ModelChoiceField(queryset=Person.objects.all(), initial = '1', label=\"Name\")\n datefrom = forms.DateField(label=\"Initial Date\", widget=forms.widgets.DateInput(attrs={'type': 'date'}))\n dateto = forms.DateField(label=\"End Date\", widget=forms.widgets.DateInput(attrs={'type': 'date'}))\n \n def clean(self):\n cleaned_data = super(SelectorForm, self).clean()\n dfrom = cleaned_data.get(\"datefrom\")\n dto = cleaned_data.get(\"dateto\")\n\n if dfrom and dto:\n # Only do something if both fields are valid so far.\n if dfrom > dto:\n raise forms.ValidationError( 'The Initial date is after the End date' )\n \n","sub_path":"nouapp/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"260911941","text":"from __future__ import division\n\nimport numpy as np\nfrom skimage import io\nfrom skimage._shared._warnings import expected_warnings\nimport matplotlib.pyplot as plt\n\n\ndef setup():\n io.reset_plugins()\n\n# test images. Note that they don't have their full range for their dtype,\n# but we still expect the display range to equal the full dtype range.\nim8 = np.array([[0, 64], [128, 240]], np.uint8)\nim16 = im8.astype(np.uint16) * 256\nim64 = im8.astype(np.uint64)\nimf = im8 / 255\nim_lo = imf / 1000\nim_hi = imf + 10\n\n\ndef n_subplots(ax_im):\n \"\"\"Return the number of subplots in the figure containing an ``AxesImage``.\n\n Parameters\n ----------\n ax_im : matplotlib.pyplot.AxesImage object\n The input ``AxesImage``.\n\n Returns\n -------\n n : int\n The number of subplots in the corresponding figure.\n\n Notes\n -----\n This function is intended to check whether a colorbar was drawn, in\n which case two subplots are expected. For standard imshows, one\n subplot is expected.\n \"\"\"\n return len(ax_im.get_figure().get_axes())\n\n\ndef test_uint8():\n plt.figure()\n with expected_warnings([\"tight_layout : Falling back to Agg|\\A\\Z\",\n \"CObject type is marked|\\A\\Z\"]):\n ax_im = io.imshow(im8)\n assert ax_im.cmap.name == 'gray'\n assert ax_im.get_clim() == (0, 255)\n assert n_subplots(ax_im) == 1\n assert ax_im.colorbar is None\n\n\ndef test_uint16():\n plt.figure()\n with expected_warnings([\"tight_layout : Falling back to Agg|\\A\\Z\",\n \"CObject type is marked|\\A\\Z\"]):\n ax_im = io.imshow(im16)\n assert ax_im.cmap.name == 'gray'\n assert ax_im.get_clim() == (0, 65535)\n assert n_subplots(ax_im) == 1\n assert ax_im.colorbar is None\n\n\ndef test_float():\n plt.figure()\n with expected_warnings([\"tight_layout : Falling back to Agg|\\A\\Z\",\n \"CObject type is marked|\\A\\Z\"]):\n ax_im = io.imshow(imf)\n assert ax_im.cmap.name == 'gray'\n assert ax_im.get_clim() == (0, 1)\n assert n_subplots(ax_im) == 1\n assert ax_im.colorbar is None\n\n\ndef test_low_dynamic_range():\n with expected_warnings([\"Low image dynamic range|CObject type is marked\",\n \"tight_layout : Falling back to Agg|\\A\\Z\"]):\n ax_im = io.imshow(im_lo)\n assert ax_im.get_clim() == (im_lo.min(), im_lo.max())\n # check that a colorbar was created\n assert ax_im.colorbar is not None\n\n\ndef test_outside_standard_range():\n plt.figure()\n # Warning raised by matplotlib on Windows:\n # \"The CObject type is marked Pending Deprecation in Python 2.7.\n # Please use capsule objects instead.\"\n # Ref: https://docs.python.org/2/c-api/cobject.html\n with expected_warnings([\"out of standard range|CObject type is marked\",\n \"tight_layout : Falling back to Agg|\\A\\Z\"]):\n ax_im = io.imshow(im_hi)\n assert ax_im.get_clim() == (im_hi.min(), im_hi.max())\n assert n_subplots(ax_im) == 2\n assert ax_im.colorbar is not None\n\n\ndef test_nonstandard_type():\n plt.figure()\n # Warning raised by matplotlib on Windows:\n # \"The CObject type is marked Pending Deprecation in Python 2.7.\n # Please use capsule objects instead.\"\n # Ref: https://docs.python.org/2/c-api/cobject.html\n with expected_warnings([\"Low image dynamic range|CObject type is marked\",\n \"tight_layout : Falling back to Agg|\\A\\Z\"]):\n ax_im = io.imshow(im64)\n assert ax_im.get_clim() == (im64.min(), im64.max())\n assert n_subplots(ax_im) == 2\n assert ax_im.colorbar is not None\n\n\ndef test_signed_image():\n plt.figure()\n im_signed = np.array([[-0.5, -0.2], [0.1, 0.4]])\n\n with expected_warnings([\"tight_layout : Falling back to Agg|\\A\\Z\",\n \"CObject type is marked|\\A\\Z\"]):\n ax_im = io.imshow(im_signed)\n assert ax_im.get_clim() == (-0.5, 0.5)\n assert n_subplots(ax_im) == 2\n assert ax_im.colorbar is not None\n\n\nif __name__ == '__main__':\n np.testing.run_module_suite()\n","sub_path":"pkgs/scikit-image-0.12.3-np110py27_0/lib/python2.7/site-packages/skimage/io/tests/test_mpl_imshow.py","file_name":"test_mpl_imshow.py","file_ext":"py","file_size_in_byte":4056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"498373684","text":"import matplotlib.pyplot as plt\nfrom helpers import assert_equality\n\n# the picture 'lena.png' with origin='lower' is flipped upside-down.\n# So it has to be upside-down in the pdf-file as well.\n\n\ndef plot():\n import os\n\n import matplotlib.image as mpimg\n from matplotlib import rcParams\n\n this_dir = os.path.dirname(os.path.realpath(__file__))\n img = mpimg.imread(os.path.join(this_dir, \"lena.png\"))\n\n dpi = rcParams[\"figure.dpi\"]\n figsize = img.shape[0] / dpi, img.shape[1] / dpi\n\n fig = plt.figure(figsize=figsize)\n ax = plt.axes([0, 0, 1, 1], frameon=False)\n ax.set_axis_off()\n plt.imshow(img, cmap=\"viridis\", origin=\"lower\")\n # Setting the current color map to HSV messes up other plots\n # plt.hsv()\n plt.colorbar()\n return fig\n\n\ndef test():\n assert_equality(plot, \"test_image_plot_lower_reference.tex\")\n return\n","sub_path":"test/test_image_plot_lower.py","file_name":"test_image_plot_lower.py","file_ext":"py","file_size_in_byte":866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"445285504","text":"from datetime import datetime\nfrom django.shortcuts import render, get_object_or_404\n\nfrom apps.common.email_smtp import send_email\nfrom apps.newsletter.models import Newsletter, NewsletterStatistics\nfrom areas.hb_admin.models import ReturnUrl\nfrom areas.hb_admin.views import BaseAdminView\nfrom hobbytown import settings\n\n\nclass NewsLetterTestView(BaseAdminView):\n template_name = 'hb_admin/newsletter/newsletters/newsletter_send.html'\n template_vars = None\n form = None\n return_url = None\n pk = None\n newsletter = None\n\n def load_view(self, request, *args, **kwargs):\n\n # get the vars\n self.pk = kwargs.get('pk', None)\n\n # save the return url\n self.return_url = ReturnUrl(request, ReturnUrl.HB_ADMIN.NEWSLETTER_TEST)\n self.return_url.push()\n\n # show form\n self.template_name = 'hb_admin/edit_form.html'\n\n # edit\n self.newsletter = get_object_or_404(Newsletter, pk=self.pk)\n\n # setup the form\n self.form = EditForm(\n request.POST or None,\n instance=self.newsletter,\n return_url=self.return_url.previous()\n )\n\n # set the template vars\n self.template_vars = {\n 'form': self.form\n }\n\n def get(self, request, *args, **kwargs):\n\n # load the view\n self.load_view(request, *args, **kwargs)\n\n # return\n return render(request, self.template_name, self.template_vars)\n\n def send_emails(self):\n email_field = self.form.cleaned_data['to']\n\n # get email content\n content = self.form.cleaned_data['main_content']\n\n # add unsubscribe message\n content = '{0}

        To unsubscribe click here.

        '\\\n .format(content, settings.BASE_URL)\n\n sentTo = []\n\n sendDate = datetime.now()\n\n # send the email\n for email in email_field.split(';'):\n email = email.strip()\n if email not in sentTo:\n sentTo.append(email)\n send_email(email, self.form.cleaned_data['title'], content)\n\n NewsletterStatistics(\n email=email,\n newsletter=self.newsletter,\n send_date = sendDate,\n test=True\n ).save()\n\n return email_field\n\n def post(self, request, *args, **kwargs):\n\n template = self.template_name\n\n # load the view\n self.load_view(request, *args, **kwargs)\n\n if self.form.is_valid():\n\n # send the emails\n emails = self.send_emails()\n\n # setup display template\n self.template_name = template\n\n # set the template vars\n self.template_vars = {\n 'email': emails,\n 'email_sent': True,\n 'return_url': self.return_url.previous(),\n 'rurl': self.return_url.get_query_string()\n }\n\n # return\n return render(request, self.template_name, self.template_vars)\n\n\nfrom djangocms_text_ckeditor.widgets import TextEditorWidget\nfrom crispy_forms.layout import Layout, Fieldset\nfrom crispy_forms.bootstrap import Field\nfrom django.forms import CharField, Textarea\n\nfrom areas.hb_admin.forms import BaseEditForm\n\n\n#\n# Newsletter Test Form\n#\nclass EditForm(BaseEditForm):\n to = CharField()\n\n def __init__(self, *args, **kwargs):\n return_url = kwargs.pop('return_url')\n super(EditForm, self).__init__(*args, **kwargs)\n\n self.helper.cancel_url = return_url\n self.helper.save_icon = False\n self.helper.action_text = 'Send Test Email'\n self.update_col_size(0)\n\n self.helper.layout = Layout(\n Fieldset(\n 'Newsletter Test',\n Field('to', css_class='control-md'),\n Field('title', css_class='control-lg'),\n 'main_content'\n )\n )\n\n self.fields['to'].help_text = '(Separate emails by semi-colon \";\")'\n self.fields['title'].label = 'Email Subject'\n self.fields['main_content'].label = 'Email Content'\n\n class Meta:\n model = Newsletter\n fields = [\n 'main_content', 'title'\n ]\n widgets = {\n 'main_content': TextEditorWidget()\n }","sub_path":"areas/hb_admin/newsletter/newsletters/newsletter_test.py","file_name":"newsletter_test.py","file_ext":"py","file_size_in_byte":4344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"335409433","text":"from unittest import TestCase\n\nfrom log_proxy.logger import Logger\n\nimport pygame\n\nclass T(TestCase):\n def setUp(self):\n pygame.quit()\n self.logger = Logger().mock()\n def test1mock_init_and_error(self):\n self.assertRaises(pygame.error, pygame.event.get)\n def test2all_mock_and_no_error(self):\n l = self.logger\n a = l.call(pygame.init, 'a')\n b = l.call(pygame.event.get, 'b')\n expected0 = [(pygame.init, ('a',), {}), (pygame.event.get, ('b',), {})],\n expected1 = 'a', 'b'\n expected = expected0 + expected1\n got = l.log, a, b\n self.assertEqual(expected, got)\n","sub_path":"tests/z00logger01mock.py","file_name":"z00logger01mock.py","file_ext":"py","file_size_in_byte":643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"568932327","text":"import jax\nimport jax.numpy as jnp\nfrom jax import vmap, random, jit\nfrom jax.flatten_util import ravel_pytree\nfrom functools import partial\n\n\n@partial(jit, static_argnums=(2, 3, 4, 5, 6, 9, 10, 11))\ndef mmdagg(\n X,\n Y,\n alpha=0.05,\n kernel=\"laplace_gaussian\",\n number_bandwidths=10,\n weights_type=\"uniform\", \n B1=2000, \n B2=2000, \n B3=50,\n seed=42,\n return_dictionary=False,\n permutations_same_sample_size=False,\n bandwidths=None,\n):\n \"\"\"\n Two-Sample MMDAgg test.\n \n Given data from one distribution and data from another distribution,\n return 0 if the test fails to reject the null \n (i.e. data comes from the same distribution), \n or return 1 if the test rejects the null \n (i.e. data comes from different distributions).\n \n Fixing the two sample sizes and the dimension, the first time the function is\n run it is getting compiled. After that, the function can fastly be evaluated on \n any data with the same sample sizes and dimension.\n \n Parameters\n ----------\n X : array_like\n The shape of X must be of the form (m, d) where m is the number\n of samples and d is the dimension.\n Y: array_like\n The shape of X must be of the form (n, d) where m is the number\n of samples and d is the dimension.\n alpha: scalar\n The value of alpha must be between 0 and 1.\n kernel: str\n The value of kernel must be \"gaussian\", \"laplace\", \"imq\", \"matern_0.5_l1\",\n \"matern_1.5_l1\", \"matern_2.5_l1\", \"matern_3.5_l1\", \"matern_4.5_l1\", \n \"matern_0.5_l2\", \"matern_1.5_l2\", \"matern_2.5_l2\", \"matern_3.5_l2\", \n \"matern_4.5_l2\", \"all_matern_l1\", \"all_matern_l2\", \"all_matern_l1_l2\", \n \"all\", \"laplace_gaussian\", or \"gaussian_laplace\". \n number_bandwidths: int\n The number of bandwidths per kernel to include in the collection.\n weights_type: str\n Must be \"uniform\", \"centred\", \"increasing\", or \"decreasing\".\n B1: int\n Number of simulated test statistics (through a wild bootstrap or permutations) \n to approximate the quantiles.\n B2: int\n Number of simulated test statistics (through a wild bootstrap or permutations) \n to approximate the level correction.\n B3: int\n Number of steps of bissection method to perform to estimate the level correction.\n seed: int \n Random seed used for the randomness of the wild bootstrap or permutations.\n return_dictionary: bool\n If true, a dictionary is returned containing for each single test: \n the test output, the kernel, the bandwidth, the MMD value, the MMD quantile value, \n the p-value and the p-value threshold value. \n permutations_same_sample_size: bool \n If the sample sizes are different, permutations are used.\n If the sample sizes are equal, a wild bootstrap is used by default, \n if permutations_same_sample_size is true then permutations are used instead.\n bandwidths: array_like or None\n If bandwidths is None, the bandwidths for each kernel are computed automatically. \n If bandwidths is array_like of one dimension, the bandwidths provided are used\n for each kernel.\n Note that number_bandwidths is overwritten by the length of bandwidths.\n \n Returns\n -------\n output : int\n 0 if the aggregated MMDAgg test fails to reject the null \n (i.e. data comes from the same distribution)\n 1 if the aggregated MMDAgg test rejects the null \n (i.e. data comes from different distributions)\n dictionary: dict\n Returned only if return_dictionary is True.\n Dictionary containing the overall output of the MMDAgg test, and for each single test: \n the test output, the kernel, the bandwidth, the MMD value, the MMD quantile value, \n the p-value and the p-value threshold value.\n \n Examples\n --------\n # import modules\n >>> import jax.numpy as jnp\n >>> from jax import random\n >>> from mmdagg.jax import mmdagg, human_readable_dict\n\n # generate data for two-sample test\n >>> key = random.PRNGKey(0)\n >>> key, subkey = random.split(key)\n >>> subkeys = random.split(subkey, num=2)\n >>> X = random.uniform(subkeys[0], shape=(500, 10))\n >>> Y = random.uniform(subkeys[1], shape=(500, 10)) + 1\n\n # run MMDAgg test\n >>> output = mmdagg(X, Y)\n >>> output\n Array(1, dtype=int32)\n >>> output.item()\n 1\n >>> output, dictionary = mmdagg(X, Y, return_dictionary=True)\n >>> output\n Array(1, dtype=int32)\n >>> human_readable_dict(dictionary)\n >>> dictionary\n {'MMDAgg test reject': True,\n 'Single test 1': {'Bandwidth': 1.0,\n 'MMD': 5.788900671177544e-05,\n 'MMD quantile': 0.0009193826699629426,\n 'Kernel IMQ': True,\n 'Reject': False,\n 'p-value': 0.41079461574554443,\n 'p-value threshold': 0.01699146442115307},\n ...\n }\n \"\"\" \n # Assertions\n m = X.shape[0]\n n = Y.shape[0]\n mn = m + n\n assert n >= 2 and m >= 2\n if m != n or permutations_same_sample_size:\n approx_type =\"permutations\"\n else:\n approx_type = \"wild bootstrap\"\n assert 0 < alpha and alpha < 1\n assert kernel in (\n \"gaussian\", \n \"laplace\", \n \"imq\", \n \"matern_0.5_l1\", \n \"matern_1.5_l1\", \n \"matern_2.5_l1\", \n \"matern_3.5_l1\", \n \"matern_4.5_l1\", \n \"matern_0.5_l2\", \n \"matern_1.5_l2\", \n \"matern_2.5_l2\", \n \"matern_3.5_l2\", \n \"matern_4.5_l2\", \n \"all_matern_l1\", \n \"all_matern_l2\", \n \"all_matern_l1_l2\", \n \"all\", \n \"laplace_gaussian\", \n \"gaussian_laplace\", \n )\n assert number_bandwidths > 1 and type(number_bandwidths) == int\n assert weights_type in (\"uniform\", \"decreasing\", \"increasing\", \"centred\")\n assert B1 > 0 and type(B1) == int\n assert B2 > 0 and type(B2) == int\n assert B3 > 0 and type(B3) == int\n\n # Collection of bandwidths \n if type(bandwidths) == jnp.ndarray:\n assert bandwidths.ndim == 1\n number_bandwidths = len(bandwidths)\n bandwidths_l1 = bandwidths\n bandwidths_l2 = bandwidths_l1\n else:\n def compute_bandwidths(distances, number_bandwidths):\n # lambda_min / 2 * C^r for r = 0, ..., number_bandwidths -1\n # where C is such that lambda_max * 2 = lambda_min / 2 * C^(number_bandwidths - 1)\n distances = distances + (distances == 0) * jnp.median(distances)\n dd = jnp.sort(distances)\n lambda_min = jax.lax.cond(\n jnp.min(distances) < 10 ** (-1), \n lambda : jnp.maximum(dd[(jnp.floor(len(dd) * 0.05).astype(int))], 10 ** (-1)), \n lambda : jnp.min(distances),\n )\n lambda_min = lambda_min / 2\n lambda_max = jnp.maximum(jnp.max(distances), 3 * 10 ** (-1))\n lambda_max = lambda_max * 2\n power = (lambda_max / lambda_min) ** (1 / (number_bandwidths - 1))\n bandwidths = jnp.array([power ** i * lambda_min for i in range(number_bandwidths)])\n return bandwidths\n # bandwidths L1 for laplace, matern_0.5_l1, matern_1.5_l1, matern_2.5_l1, matern_3.5_l1, matern_4.5_l1\n if kernel in (\n \"laplace\", \n \"matern_0.5_l1\", \n \"matern_1.5_l1\", \n \"matern_2.5_l1\", \n \"matern_3.5_l1\", \n \"matern_4.5_l1\", \n \"all_matern_l1\", \n \"all_matern_l1_l2\", \n \"all\", \n \"laplace_gaussian\", \n \"gaussian_laplace\", \n ):\n distances_l1 = jax_distances(X, Y, \"l1\", max_samples=500)\n bandwidths_l1 = compute_bandwidths(distances_l1, number_bandwidths)\n # bandwidths L2 for gaussian, imq, matern_0.5_l2, matern_1.5_l2, matern_2.5_l2, matern_3.5_l2, matern_4.5_l2\n if kernel in (\n \"gaussian\", \n \"imq\", \n \"matern_0.5_l2\", \n \"matern_1.5_l2\", \n \"matern_2.5_l2\", \n \"matern_3.5_l2\", \n \"matern_4.5_l2\", \n \"all_matern_l2\", \n \"all_matern_l1_l2\", \n \"all\", \n \"laplace_gaussian\", \n \"gaussian_laplace\", \n ):\n distances_l2 = jax_distances(X, Y, \"l2\", max_samples=500)\n bandwidths_l2 = compute_bandwidths(distances_l2, number_bandwidths)\n \n # Kernel and bandwidths list (order: \"l1\" first, \"l2\" second)\n if kernel in ( \n \"laplace\", \n \"matern_0.5_l1\", \n \"matern_1.5_l1\", \n \"matern_2.5_l1\", \n \"matern_3.5_l1\", \n \"matern_4.5_l1\", \n ):\n kernel_bandwidths_l_list = [(kernel, bandwidths_l1, \"l1\"), ]\n elif kernel in (\n \"gaussian\", \n \"imq\", \n \"matern_0.5_l2\", \n \"matern_1.5_l2\", \n \"matern_2.5_l2\", \n \"matern_3.5_l2\", \n \"matern_4.5_l2\", \n ):\n kernel_bandwidths_l_list = [(kernel, bandwidths_l2, \"l2\"), ]\n elif kernel in (\"laplace_gaussian\", \"gaussian_laplace\"):\n kernel_bandwidths_l_list = [(\"laplace\", bandwidths_l1, \"l1\"), (\"gaussian\", bandwidths_l2, \"l2\")]\n elif kernel == \"all_matern_l1\":\n kernel_list = [\"matern_\" + str(i) + \".5_l1\" for i in range(5)]\n kernel_bandwidths_l_list = [(kernel, bandwidths_l1, \"l1\") for kernel in kernel_list]\n elif kernel == \"all_matern_l2\":\n kernel_list = [\"matern_\" + str(i) + \".5_l2\" for i in range(5)]\n kernel_bandwidths_l_list = [(kernel, bandwidths_l2, \"l2\") for kernel in kernel_list]\n elif kernel == \"all_matern_l1_l2\":\n kernel_list = [\n \"matern_\" + str(i) + \".5_l\" + str(j) for j in (1, 2) for i in range(5) \n ]\n bandwidths_list = [bandwidths_l1, ] * 5 + [bandwidths_l2, ] * 5\n l_list = [\"l1\", ] * 5 + [\"l2\", ] * 5\n kernel_bandwidths_l_list = [\n (kernel_list[i], bandwidths_list[i], l_list[i]) for i in range(10)\n ]\n elif kernel == \"all\":\n kernel_list = [\n \"matern_\" + str(i) + \".5_l\" + str(j) for j in (1, 2) for i in range(5) \n ] + [\"gaussian\", \"imq\"] \n bandwidths_list = [] + [bandwidths_l1, ] * 5 + [bandwidths_l2, ] * 7\n l_list = [\"l1\", ] * 5 + [\"l2\", ] * 7\n kernel_bandwidths_l_list = [\n (kernel_list[i], bandwidths_list[i], l_list[i]) for i in range(12)\n ]\n else:\n raise ValueError(\"Kernel not defined.\")\n \n # Weights \n weights = create_weights(number_bandwidths, weights_type) / len(\n kernel_bandwidths_l_list\n )\n \n # Setup for wild bootstrap or permutations (efficient as in Appendix C in our paper)\n if approx_type == \"wild bootstrap\":\n key = random.PRNGKey(seed)\n key, subkey = random.split(key)\n R = random.choice(subkey, jnp.array([-1.0, 1.0]), shape=(B1 + B2 + 1, n)) # (B1+B2+1, n) Rademacher\n R = R.at[B1].set(jnp.ones(n))\n R = R.transpose()\n R = jnp.concatenate((R, -R)) # (2n, B1+B2+1) \n elif approx_type == \"permutations\":\n key = random.PRNGKey(seed)\n key, subkey = random.split(key)\n # (B1+B2+1, m+n): rows of permuted indices\n idx = random.permutation(subkey, jnp.array([[i for i in range(m + n)]] * (B1 + B2 + 1)), axis=1, independent=True) \n #11\n v11 = jnp.concatenate((jnp.ones(m), -jnp.ones(n))) # (m+n, )\n V11i = jnp.tile(v11, (B1 + B2 + 1, 1)) # (B1+B2+1, m+n)\n V11 = jnp.take_along_axis(V11i, idx, axis=1) # (B1+B2+1, m+n): permute the entries of the rows\n V11 = V11.at[B1].set(v11) # (B1+1)th entry is the original MMD (no permutation)\n V11 = V11.transpose() # (m+n, B1+B2+1)\n #10\n v10 = jnp.concatenate((jnp.ones(m), jnp.zeros(n)))\n V10i = jnp.tile(v10, (B1 + B2 + 1, 1))\n V10 = jnp.take_along_axis(V10i, idx, axis=1)\n V10 = V10.at[B1].set(v10)\n V10 = V10.transpose() \n #01\n v01 = jnp.concatenate((jnp.zeros(m), -jnp.ones(n)))\n V01i = jnp.tile(v01, (B1 + B2 + 1, 1))\n V01 = jnp.take_along_axis(V01i, idx, axis=1)\n V01 = V01.at[B1].set(v01)\n V01 = V01.transpose() \n else:\n raise ValueError(\"Approximation type not defined.\")\n \n # Step 1: compute all simulated MMD estimates (efficient as in Appendix C in our paper)\n N = number_bandwidths * len(kernel_bandwidths_l_list)\n M = jnp.zeros((N, B1 + B2 + 1))\n last_l_pairwise_matrix_computed = \"\"\n for j in range(len(kernel_bandwidths_l_list)):\n kernel, bandwidths, l = kernel_bandwidths_l_list[j]\n # since kernel_bandwidths_l_list is ordered \"l1\" first, \"l2\" second\n # compute pairwise matrices the minimum amount of time\n # store only one pairwise matrix at once\n if l != last_l_pairwise_matrix_computed:\n Z = jnp.concatenate((X, Y))\n pairwise_matrix = jax_distances(Z, Z, l, matrix=True)\n last_l_pairwise_matrix_computed = l\n for i in range(number_bandwidths):\n bandwidth = bandwidths[i]\n K = kernel_matrix(pairwise_matrix, l, kernel, bandwidth)\n if approx_type == \"wild bootstrap\": \n # set diagonal elements of all four submatrices to zero\n paired_indices = jnp.diag_indices(n)\n K = K.at[paired_indices].set(0)\n K = K.at[paired_indices[0] + n, paired_indices[1]].set(0)\n K = K.at[paired_indices[0], paired_indices[1] + n].set(0)\n K = K.at[paired_indices[0] + n, paired_indices[1] + n].set(0)\n # compute MMD bootstrapped values\n M = M.at[number_bandwidths * j + i].set(jnp.sum(R * (K @ R), 0) / (n * (n - 1)))\n elif approx_type == \"permutations\": \n # set diagonal elements to zero\n K = K.at[jnp.diag_indices(K.shape[0])].set(0)\n # compute MMD permuted values\n M = M.at[number_bandwidths * j + i].set(\n jnp.sum(V10 * (K @ V10), 0) * (n - m + 1) / (m * n * (m - 1))\n + jnp.sum(V01 * (K @ V01), 0) * (m - n + 1) / (m * n * (n - 1))\n + jnp.sum(V11 * (K @ V11), 0) / (m * n)\n ) \n else:\n raise ValueError(\"Approximation type not defined.\") \n MMD_original = M[:, B1]\n M1_sorted = jnp.sort(M[:, :B1 + 1]) # (N, B1+1)\n M2 = M[:, B1 + 1:] # (N, B2)\n\n # Step 2: compute u_alpha_hat using the bisection method\n quantiles = jnp.zeros((N, 1)) # (1-u*w_lambda)-quantiles for the N bandwidths\n u_min = 0.\n u_max = jnp.min(1 / weights)\n for _ in range(B3): \n u = (u_max + u_min) / 2\n for j in range(len(kernel_bandwidths_l_list)):\n for i in range(number_bandwidths):\n quantiles = quantiles.at[number_bandwidths * j + i].set(\n M1_sorted[\n number_bandwidths * j + i, \n (jnp.ceil((B1 + 1) * (1 - u * weights[i]))).astype(int) - 1\n ]\n )\n P_u = jnp.sum(jnp.max(M2 - quantiles, 0) > 0) / B2\n u_min, u_max = jax.lax.cond(P_u <= alpha, lambda: (u, u_max), lambda: (u_min, u))\n u = u_min\n for j in range(len(kernel_bandwidths_l_list)):\n for i in range(number_bandwidths):\n quantiles = quantiles.at[number_bandwidths * j + i].set(\n M1_sorted[\n number_bandwidths * j + i, \n (jnp.ceil((B1 + 1) * (1 - u * weights[i]))).astype(int) - 1\n ]\n )\n \n # Step 3: output test result\n p_vals = jnp.mean((M1_sorted - MMD_original.reshape(-1, 1) >= 0), -1)\n all_weights = jnp.zeros(p_vals.shape)\n for j in range(len(kernel_bandwidths_l_list)):\n for i in range(number_bandwidths):\n all_weights = all_weights.at[number_bandwidths * j + i].set(weights[i])\n thresholds = u * all_weights\n # reject if p_val <= threshold\n reject_p_vals = p_vals <= thresholds\n\n mmd_vals = MMD_original\n quantiles = quantiles.reshape(-1)\n # reject if mmd_val > quantile\n reject_mmd_vals = mmd_vals > quantiles\n \n # create rejection dictionary \n reject_dictionary = {}\n reject_dictionary[\"MMDAgg test reject\"] = False\n for j in range(len(kernel_bandwidths_l_list)):\n kernel, bandwidths, l = kernel_bandwidths_l_list[j]\n for i in range(number_bandwidths):\n index = \"Single test \" + str(j + 1) + \".\" + str(i + 1)\n idx = number_bandwidths * j + i\n reject_dictionary[index] = {}\n reject_dictionary[index][\"Reject\"] = reject_p_vals[idx]\n reject_dictionary[index][\"Kernel \" + kernel] = True\n reject_dictionary[index][\"Bandwidth\"] = bandwidths[i]\n reject_dictionary[index][\"MMD\"] = mmd_vals[idx]\n reject_dictionary[index][\"MMD quantile\"] = quantiles[idx]\n reject_dictionary[index][\"p-value\"] = p_vals[i]\n reject_dictionary[index][\"p-value threshold\"] = thresholds[idx]\n # Aggregated test rejects if one single test rejects\n reject_dictionary[\"MMDAgg test reject\"] = jnp.any(ravel_pytree(\n (reject_dictionary[\"MMDAgg test reject\"],\n reject_p_vals[idx])\n )[0])\n\n if return_dictionary:\n return (reject_dictionary[\"MMDAgg test reject\"]).astype(int), reject_dictionary\n else:\n return (reject_dictionary[\"MMDAgg test reject\"]).astype(int)\n\n \ndef kernel_matrix(pairwise_matrix, l, kernel, bandwidth):\n \"\"\"\n Compute kernel matrix for a given kernel and bandwidth. \n\n inputs: pairwise_matrix: (2m,2m) matrix of pairwise distances\n l: \"l1\" or \"l2\" or \"l2sq\"\n kernel: string from (\"gaussian\", \"laplace\", \"imq\", \"matern_0.5_l1\", \"matern_1.5_l1\", \"matern_2.5_l1\", \"matern_3.5_l1\", \"matern_4.5_l1\", \"matern_0.5_l2\", \"matern_1.5_l2\", \"matern_2.5_l2\", \"matern_3.5_l2\", \"matern_4.5_l2\")\n output: (2m,2m) pairwise distance matrix\n\n Warning: The pair of variables l and kernel must be valid.\n \"\"\"\n d = pairwise_matrix / bandwidth\n if kernel == \"gaussian\" and l == \"l2\":\n return jnp.exp(-d ** 2)\n elif kernel == \"imq\" and l == \"l2\":\n return (1 + d ** 2) ** (-0.5)\n elif (kernel == \"matern_0.5_l1\" and l == \"l1\") or (kernel == \"matern_0.5_l2\" and l == \"l2\") or (kernel == \"laplace\" and l == \"l1\"):\n return jnp.exp(-d)\n elif (kernel == \"matern_1.5_l1\" and l == \"l1\") or (kernel == \"matern_1.5_l2\" and l == \"l2\"):\n return (1 + jnp.sqrt(3) * d) * jnp.exp(- jnp.sqrt(3) * d)\n elif (kernel == \"matern_2.5_l1\" and l == \"l1\") or (kernel == \"matern_2.5_l2\" and l == \"l2\"):\n return (1 + jnp.sqrt(5) * d + 5 / 3 * d ** 2) * jnp.exp(- jnp.sqrt(5) * d)\n elif (kernel == \"matern_3.5_l1\" and l == \"l1\") or (kernel == \"matern_3.5_l2\" and l == \"l2\"):\n return (1 + jnp.sqrt(7) * d + 2 * 7 / 5 * d ** 2 + 7 * jnp.sqrt(7) / 3 / 5 * d ** 3) * jnp.exp(- jnp.sqrt(7) * d)\n elif (kernel == \"matern_4.5_l1\" and l == \"l1\") or (kernel == \"matern_4.5_l2\" and l == \"l2\"):\n return (1 + 3 * d + 3 * (6 ** 2) / 28 * d ** 2 + (6 ** 3) / 84 * d ** 3 + (6 ** 4) / 1680 * d ** 4) * jnp.exp(- 3 * d)\n else:\n raise ValueError(\n 'The values of \"l\" and \"kernel\" are not valid.'\n )\n\n \ndef create_weights(N, weights_type):\n \"\"\"\n Create weights as defined in Section 5.1 of our paper.\n inputs: N: number of bandwidths to test\n weights_type: \"uniform\" or \"decreasing\" or \"increasing\" or \"centred\"\n output: (N,) array of weights\n \"\"\"\n if weights_type == \"uniform\":\n weights = jnp.array([1 / N,] * N)\n elif weights_type == \"decreasing\":\n normaliser = sum([1 / i for i in range(1, N + 1)])\n weights = jnp.array([1 / (i * normaliser) for i in range(1, N + 1)])\n elif weights_type == \"increasing\":\n normaliser = sum([1 / i for i in range(1, N + 1)])\n weights = jnp.array([1 / ((N + 1 - i) * normaliser) for i in range(1, N + 1)])\n elif weights_type == \"centred\":\n if N % 2 == 1:\n normaliser = sum([1 / (abs((N + 1) / 2 - i) + 1) for i in range(1, N + 1)])\n weights = jnp.array(\n [1 / ((abs((N + 1) / 2 - i) + 1) * normaliser) for i in range(1, N + 1)]\n )\n else:\n normaliser = sum(\n [1 / (abs((N + 1) / 2 - i) + 0.5) for i in range(1, N + 1)]\n )\n weights = jnp.array(\n [\n 1 / ((abs((N + 1) / 2 - i) + 0.5) * normaliser)\n for i in range(1, N + 1)\n ]\n )\n else:\n raise ValueError(\n 'The value of weights_type should be \"uniform\" or'\n '\"decreasing\" or \"increasing\" or \"centred\".'\n )\n return weights\n\n\ndef jax_distances(X, Y, l, max_samples=None, matrix=False):\n if l == \"l1\":\n def dist(x, y):\n z = x - y\n return jnp.sum(jnp.abs(z))\n elif l == \"l2\":\n def dist(x, y):\n z = x - y\n return jnp.sqrt(jnp.sum(jnp.square(z)))\n else:\n raise ValueError(\"Value of 'l' must be either 'l1' or 'l2'.\")\n vmapped_dist = vmap(dist, in_axes=(0, None))\n pairwise_dist = vmap(vmapped_dist, in_axes=(None, 0))\n output = pairwise_dist(X[:max_samples], Y[:max_samples])\n if matrix:\n return output\n else:\n return output[jnp.triu_indices(output.shape[0])]\n\n \ndef human_readable_dict(dictionary):\n \"\"\"\n Transform all jax arrays of one element into scalars.\n \"\"\"\n meta_keys = dictionary.keys()\n for meta_key in meta_keys:\n if isinstance(dictionary[meta_key], jnp.ndarray):\n dictionary[meta_key] = dictionary[meta_key].item()\n elif isinstance(dictionary[meta_key], dict):\n for key in dictionary[meta_key].keys():\n if isinstance(dictionary[meta_key][key], jnp.ndarray):\n dictionary[meta_key][key] = dictionary[meta_key][key].item()\n","sub_path":"mmdagg/jax.py","file_name":"jax.py","file_ext":"py","file_size_in_byte":22064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"609035687","text":"import string\r\n\r\n\r\ndef clear(text):\r\n translator = str.maketrans('', '', string.punctuation + '—«»')\r\n return text.translate(translator).split()\r\n\r\n\r\nclass Model:\r\n def __init__(self):\r\n self.words = {}\r\n\r\n def fit(self, raw_text):\r\n text = clear(raw_text)\r\n words = {}\r\n for i in range(len(text) - 1):\r\n if text[i] in words:\r\n if text[i + 1] in words[text[i]][0]:\r\n words[text[i]][1][words[text[i]][0].index(text[i + 1])] += 1\r\n else:\r\n words[text[i]][0].append(text[i + 1])\r\n words[text[i]][1].append(1)\r\n else:\r\n words[text[i]] = ([text[i + 1]], [1])\r\n self.words = words\r\n\r\n def generate(self, word, l):\r\n res = [word]\r\n words = self.words\r\n for _ in range(l):\r\n if res[-1] in words:\r\n res.append(words[res[-1]][0][words[res[-1]][1].index(max(words[res[-1]][1]))])\r\n else:\r\n res.append(list(words.keys())[0])\r\n return res\r\n","sub_path":"2.1.py","file_name":"2.1.py","file_ext":"py","file_size_in_byte":1085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"583866676","text":"from __future__ import print_function\n\nimport numpy as np\nimport tensorflow as tf\nfrom libtiff import TIFF\nfrom scipy.misc import imread, imsave\n\nimport tensor_utils_5_channels as utils\n\nFLAGS = tf.flags.FLAGS\ntf.flags.DEFINE_integer(\"batch_size\", \"1\", \"batch size for training\")\ntf.flags.DEFINE_string(\"logs_dir\", \"../logs-vgg19/\", \"path to logs directory\")\ntf.flags.DEFINE_string(\"data_dir\", \"ISPRS_semantic_labeling_Potsdam\", \"path to dataset\")\ntf.flags.DEFINE_string(\"model_dir\", \"ISPRS_semantic_labeling_Potsdam/imagenet-vgg-verydeep-19.mat\", \"Path to vgg model mat\")\ntf.flags.DEFINE_bool('debug', \"False\", \"Debug mode: True/ False\")\nMAX_ITERATION = int(1e6 + 1)\nNUM_OF_CLASSESS = 6\nIMAGE_SIZE = 224\n\ndef vgg_net(weights, image):\n layers = (\n 'conv1_1', 'relu1_1', 'conv1_2', 'relu1_2', 'pool1',\n\n 'conv2_1', 'relu2_1', 'conv2_2', 'relu2_2', 'pool2',\n\n 'conv3_1', 'relu3_1', 'conv3_2', 'relu3_2', 'conv3_3',\n 'relu3_3', 'conv3_4', 'relu3_4', 'pool3',\n\n 'conv4_1', 'relu4_1', 'conv4_2', 'relu4_2', 'conv4_3',\n 'relu4_3', 'conv4_4', 'relu4_4', 'pool4',\n\n 'conv5_1', 'relu5_1', 'conv5_2', 'relu5_2', 'conv5_3',\n 'relu5_3', 'conv5_4', 'relu5_4'\n )\n\n net = {}\n current = image\n for i, name in enumerate(layers):\n kind = name[:4]\n if kind == 'conv':\n kernels, bias = weights[i][0][0][0][0]\n # matconvnet: weights are [width, height, in_channels, out_channels]\n # tensorflow: weights are [height, width, in_channels, out_channels]\n if name == 'conv1_1':\n append_channels= np.random.normal(loc=0,scale=0.02,size=(3,3,3,64))\n print(append_channels)\n kernels = np.concatenate((kernels, append_channels), axis=2)\n kernels = utils.get_variable(np.transpose(kernels, (0, 1, 2, 3)), name=name + \"_w\")\n else:\n kernels = utils.get_variable(np.transpose(kernels, (0, 1, 2, 3)), name=name + \"_w\")\n bias = utils.get_variable(bias.reshape(-1), name=name + \"_b\")\n current = utils.conv2d_basic(current, kernels, bias)\n elif kind == 'relu':\n current = tf.nn.relu(current, name=name)\n if FLAGS.debug:\n utils.add_activation_summary(current)\n elif kind == 'pool':\n current = utils.avg_pool_2x2(current)\n net[name] = current\n\n return net\n\n\ndef inference(image, keep_prob):\n \"\"\"\n Semantic segmentation network definition\n :param image: input image. Should have values in range 0-255\n :param keep_prob:\n :return:\n \"\"\"\n print(\"setting up vgg initialized conv layers ...\")\n model_data = utils.get_model_data(FLAGS.model_dir)\n\n mean = model_data['normalization'][0][0][0]\n mean_pixel = np.mean(mean, axis=(0, 1))\n mean_pixel = np.append(mean_pixel, [97.6398951221, 45.548982716, 31.4374])\n weights = np.squeeze(model_data['layers'])\n\n processed_image = utils.process_image(image, mean_pixel)\n\n with tf.variable_scope(\"inference\"):\n image_net = vgg_net(weights, processed_image)\n conv_final_layer = image_net[\"conv5_3\"]\n\n pool5 = utils.max_pool_2x2(conv_final_layer)\n\n W6 = utils.weight_variable([7, 7, 512, 4096], name=\"W6\")\n b6 = utils.bias_variable([4096], name=\"b6\")\n conv6 = utils.conv2d_basic(pool5, W6, b6)\n relu6 = tf.nn.relu(conv6, name=\"relu6\")\n if FLAGS.debug:\n utils.add_activation_summary(relu6)\n relu_dropout6 = tf.nn.dropout(relu6, keep_prob=keep_prob)\n\n W7 = utils.weight_variable([1, 1, 4096, 4096], name=\"W7\")\n b7 = utils.bias_variable([4096], name=\"b7\")\n conv7 = utils.conv2d_basic(relu_dropout6, W7, b7)\n relu7 = tf.nn.relu(conv7, name=\"relu7\")\n if FLAGS.debug:\n utils.add_activation_summary(relu7)\n relu_dropout7 = tf.nn.dropout(relu7, keep_prob=keep_prob)\n\n W8 = utils.weight_variable([1, 1, 4096, NUM_OF_CLASSESS], name=\"W8\")\n b8 = utils.bias_variable([NUM_OF_CLASSESS], name=\"b8\")\n conv8 = utils.conv2d_basic(relu_dropout7, W8, b8)\n # annotation_pred1 = tf.argmax(conv8, dimension=3, name=\"prediction1\")\n\n # now to upscale to actual image size\n deconv_shape1 = image_net[\"pool4\"].get_shape()\n W_t1 = utils.weight_variable([4, 4, deconv_shape1[3].value, NUM_OF_CLASSESS], name=\"W_t1\")\n b_t1 = utils.bias_variable([deconv_shape1[3].value], name=\"b_t1\")\n conv_t1 = utils.conv2d_transpose_strided(conv8, W_t1, b_t1, output_shape=tf.shape(image_net[\"pool4\"]))\n fuse_1 = tf.add(conv_t1, image_net[\"pool4\"], name=\"fuse_1\")\n\n deconv_shape2 = image_net[\"pool3\"].get_shape()\n W_t2 = utils.weight_variable([4, 4, deconv_shape2[3].value, deconv_shape1[3].value], name=\"W_t2\")\n b_t2 = utils.bias_variable([deconv_shape2[3].value], name=\"b_t2\")\n conv_t2 = utils.conv2d_transpose_strided(fuse_1, W_t2, b_t2, output_shape=tf.shape(image_net[\"pool3\"]))\n fuse_2 = tf.add(conv_t2, image_net[\"pool3\"], name=\"fuse_2\")\n\n shape = tf.shape(image)\n deconv_shape3 = tf.stack([shape[0], shape[1], shape[2], NUM_OF_CLASSESS])\n W_t3 = utils.weight_variable([16, 16, NUM_OF_CLASSESS, deconv_shape2[3].value], name=\"W_t3\")\n b_t3 = utils.bias_variable([NUM_OF_CLASSESS], name=\"b_t3\")\n conv_t3 = utils.conv2d_transpose_strided(fuse_2, W_t3, b_t3, output_shape=deconv_shape3, stride=8)\n\n annotation_pred = tf.argmax(conv_t3, axis=3, name=\"prediction\")\n\n return tf.expand_dims(annotation_pred, dim=3), conv_t3\n\n\ndef infer_little_img(input_image_path,patch_size=224,stride_ver=112,stride_hor=112):\n tf.reset_default_graph()\n input_image = TIFF.open(input_image_path,'r')\n input_image = input_image.read_image()\n\n # need to be fixed\n element = input_image_path.split('_')\n if len(element[7]) ==1:\n element[7]= '0' + element[7]\n if len(element[8]) ==1:\n element[8]= '0' + element[8]\n print('ISPRS_semantic_labeling_Potsdam/1_DSM/dsm_potsdam_'+element[7]+\"_\"+element[8]+\".tif\")\n #dsm_image= imread('ISPRS_semantic_labeling_Potsdam/1_DSM/dsm_potsdam_'+element[7]+\"_\"+element[8]+\".tif\")\n\n dsm_image = TIFF.open('ISPRS_semantic_labeling_Potsdam/1_DSM/dsm_potsdam_'+element[7]+\"_\"+element[8]+\".tif\",'r')\n dsm_image = dsm_image.read_image()\n dsm_image = np.expand_dims(dsm_image, axis=2)\n ndsm_image= imread('ISPRS_semantic_labeling_Potsdam/1_DSM_normalisation/dsm_potsdam_'+element[7]+\"_\"+element[8]+\"_normalized_lastools.jpg\")\n ndsm_image= np.expand_dims(ndsm_image,axis=2)\n\n height = np.shape(input_image)[0]\n width = np.shape(input_image)[1]\n output_image = np.zeros(shape=(height,width,3))\n print(np.shape(input_image))\n print(np.shape(ndsm_image))\n print(np.shape(dsm_image))\n input_image= np.concatenate((input_image,ndsm_image,dsm_image),axis=2)\n output_map = np.zeros((height, width, 6), dtype=np.float32)\n number_of_vertical_points = (height - patch_size) // stride_ver + 1\n number_of_horizontial_points = (width - patch_size) // stride_hor + 1\n sess= tf.Session()\n keep_probability = tf.placeholder(tf.float32, name=\"keep_probabilty\")\n image = tf.placeholder(tf.float32, shape=[None, IMAGE_SIZE, IMAGE_SIZE, 6], name=\"input_image\")\n _, logits = inference(image, keep_probability)\n saver = tf.train.Saver()\n sess.run(tf.global_variables_initializer())\n ckpt = tf.train.get_checkpoint_state(FLAGS.logs_dir)\n if ckpt and ckpt.model_checkpoint_path:\n saver.restore(sess, ckpt.model_checkpoint_path)\n print(\"Model restored...\")\n input_image= np.expand_dims(input_image,axis=0)\n for i in range(number_of_vertical_points):\n for j in range(number_of_horizontial_points):\n current_patch = input_image[:,i * stride_ver:i * stride_ver + patch_size,\n j * stride_hor:j * stride_hor + patch_size, :]\n logits_result = sess.run(logits, feed_dict={image: current_patch, keep_probability: 1.0})\n logits_result = tf.squeeze(logits_result)\n patch_result= sess.run(logits_result)\n output_map[i * stride_ver:i * stride_ver + patch_size, j * stride_hor:j * stride_hor + patch_size,\n :] += patch_result\n print('stage 1: i='+str(i)+\"; j=\"+str(j))\n for i in range(number_of_vertical_points):\n current_patch= input_image[:,i*stride_ver:i*stride_ver+patch_size,width-patch_size:width,:]\n logits_result = sess.run(logits, feed_dict={image: current_patch, keep_probability: 1.0})\n logits_result = tf.squeeze(logits_result)\n patch_result = sess.run(logits_result)\n output_map[i*stride_ver:i*stride_ver+patch_size,width-patch_size:width,:]+=patch_result\n print('stage 2: i=' + str(i) + \"; j=\" + str(j))\n for i in range(number_of_horizontial_points):\n current_patch= input_image[:,height-patch_size:height,i*stride_hor:i*stride_hor+patch_size,:]\n logits_result = sess.run(logits, feed_dict={image: current_patch, keep_probability: 1.0})\n logits_result = tf.squeeze(logits_result)\n patch_result = sess.run(logits_result)\n output_map[height-patch_size:height,i*stride_hor:i*stride_hor+patch_size,:]+=patch_result\n print('stage 3: i=' + str(i) + \"; j=\" + str(j))\n current_patch = input_image[:,height - patch_size:height, width - patch_size:width, :]\n logits_result = sess.run(logits, feed_dict={image: current_patch, keep_probability: 1.0})\n logits_result = tf.squeeze(logits_result)\n patch_result = sess.run(logits_result)\n output_map[height - patch_size:height, width - patch_size:width, :] += patch_result\n predict_annotation_image = np.argmax(output_map, axis=2)\n print(np.shape(predict_annotation_image))\n for i in range(height):\n for j in range(width):\n if predict_annotation_image[i,j]==0:\n output_image[i,j,:]=[255,255,255]\n elif predict_annotation_image[i,j]==1:\n output_image[i,j,:]=[0,0,255]\n elif predict_annotation_image[i,j]==2:\n output_image[i,j,:]=[0,255,255]\n elif predict_annotation_image[i,j]==3:\n output_image[i,j,:]=[0,255,0]\n elif predict_annotation_image[i,j]==4:\n output_image[i,j,:]=[255,255,0]\n elif predict_annotation_image[i,j]==5:\n output_image[i,j,:]=[255,0,0]\n return output_image\n\nif __name__ == \"__main__\":\n #tf.app.run()\n # imsave(\"top_potsdam_2_13_RGBIR.tif\",\n # infer_little_img(\"ISPRS_semantic_labeling_Potsdam/4_Ortho_RGBIR/top_potsdam_2_13_RGBIR.tif\"))\n # imsave(\"top_potsdam_2_14_RGBIR.tif\",\n # infer_little_img(\"ISPRS_semantic_labeling_Potsdam/4_Ortho_RGBIR/top_potsdam_2_14_RGBIR.tif\"))\n imsave(\"top_potsdam_3_13_RGBIR.tif\",\n infer_little_img(\"ISPRS_semantic_labeling_Potsdam/4_Ortho_RGBIR/top_potsdam_3_13_RGBIR.tif\"))\n # imsave(\"top_potsdam_3_14_RGBIR.tif\",\n # infer_little_img(\"ISPRS_semantic_labeling_Potsdam/4_Ortho_RGBIR/top_potsdam_3_14_RGBIR.tif\"))\n # imsave(\"top_potsdam_4_13_RGBIR.tif\",\n # infer_little_img(\"ISPRS_semantic_labeling_Potsdam/4_Ortho_RGBIR/top_potsdam_4_13_RGBIR.tif\"))\n # imsave(\"top_potsdam_4_14_RGBIR.tif\",\n # infer_little_img(\"ISPRS_semantic_labeling_Potsdam/4_Ortho_RGBIR/top_potsdam_4_14_RGBIR.tif\"))\n # imsave(\"top_potsdam_4_15_RGBIR.tif\",\n # infer_little_img(\"ISPRS_semantic_labeling_Potsdam/4_Ortho_RGBIR/top_potsdam_4_15_RGBIR.tif\"))\n #\n # imsave(\"top_potsdam_5_13_RGBIR.tif\",\n # infer_little_img(\"ISPRS_semantic_labeling_Potsdam/4_Ortho_RGBIR/top_potsdam_5_13_RGBIR.tif\"))\n # imsave(\"top_potsdam_5_14_RGBIR.tif\",\n # infer_little_img(\"ISPRS_semantic_labeling_Potsdam/4_Ortho_RGBIR/top_potsdam_5_14_RGBIR.tif\"))\n # imsave(\"top_potsdam_5_15_RGBIR.tif\",\n # infer_little_img(\"ISPRS_semantic_labeling_Potsdam/4_Ortho_RGBIR/top_potsdam_5_15_RGBIR.tif\"))\n #\n # imsave(\"top_potsdam_6_13_RGBIR.tif\",\n # infer_little_img(\"ISPRS_semantic_labeling_Potsdam/4_Ortho_RGBIR/top_potsdam_6_13_RGBIR.tif\"))\n # imsave(\"top_potsdam_6_14_RGBIR.tif\",\n # infer_little_img(\"ISPRS_semantic_labeling_Potsdam/4_Ortho_RGBIR/top_potsdam_6_14_RGBIR.tif\"))\n # imsave(\"top_potsdam_6_15_RGBIR.tif\",\n # infer_little_img(\"ISPRS_semantic_labeling_Potsdam/4_Ortho_RGBIR/top_potsdam_6_15_RGBIR.tif\"))\n #\n # imsave(\"top_potsdam_7_13_RGBIR.tif\",\n # infer_little_img(\"ISPRS_semantic_labeling_Potsdam/4_Ortho_RGBIR/top_potsdam_7_13_RGBIR.tif\"))","sub_path":"infer_little_image_potsdam.py","file_name":"infer_little_image_potsdam.py","file_ext":"py","file_size_in_byte":12648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"444404259","text":"from __future__ import division, print_function\nimport subprocess\nimport numpy as np\nimport sys, os\nimport logging\nfrom sutils.utils import ini, common, util\nfrom .. import version\n#import ini\n#import lacommon\n#import common\nimport shutil\nimport glob\nimport time\nimport pickle\n#import util\n\nPY_VER = sys.version\nif int(PY_VER[0]) < 3:\n import exceptions\n\n\n\nVERSION_MAJOR = version.VERSION_MAJOR\nVERSION_MINOR = version.VERSION_MINOR\nVERSION_PATCH = version.VERSION_PATCH\nVERSION = version.version()\n\nAUTHOR = \"Thomas Mertz\"\nCOPYRIGHT_YEARS = sorted([2016, 2018])\nCOPYRIGHT_RANGE = \"{}-{}\".format(COPYRIGHT_YEARS[0], COPYRIGHT_YEARS[-1])\n\n# make this an optional feature\ndb_dir = os.path.expanduser(os.path.join('~','.ssubmit'))\nutil.assert_dir(db_dir)\n\nlogging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')\n\n\n\n# ================================================================================\n\n\n\nclass ConfigPathError(Exception):\n \"\"\"\n Raised when invalid config path is detected.\n \"\"\"\n def __init__(self, value=''):\n self._value = value\n \n def __str__(self):\n return repr(self._value)\n\nclass MissingDirectoryError(Exception):\n \"\"\"\n Raised when directory is not found by StatusChecker.\n \"\"\"\n def __init__(self, value=''):\n self._value = value\n \n def __str__(self):\n return repr(self._value)\n\nclass MissingOutfileError(Exception):\n \"\"\"\n Raised when no outfile is found by StatusChecker.\n \"\"\"\n def __init__(self, value=''):\n self._value = value\n \n def __str__(self):\n return repr(self._value)\n\nclass InvalidDirectoryNameError(Exception):\n \"\"\"Raised when directory name does not comply with the parameters defined.\"\"\"\n def __init__(self, value=''):\n self._value = value\n \n def __str__(self):\n return repr(self._value)\n\n\n# ================================================================================\n\n\n\nclass Jobs(object):\n \"\"\"\n Handles job success and fail count.\n \"\"\"\n def __init__(self):\n self._success = 0\n self._skipped = 0\n self._failed = 0\n self._total = 0\n\n\n def success(self):\n \"\"\"\n Register one successful job.\n \"\"\"\n self._success += 1\n self._total += 1\n\n def failed(self):\n \"\"\"\n Register one failed job.\n \"\"\"\n self._failed += 1\n self._total += 1\n \n def skipped(self):\n \"\"\"\n Register one skipped job.\n \"\"\"\n self._skipped += 1\n self._total += 1\n \n def reset(self):\n \"\"\"\n Reset job counters.\n \"\"\"\n self._success = 0\n self._failed = 0\n self._total = 0\n \n def set_total(self, total):\n \"\"\"\n Set total number of jobs.\n \"\"\"\n self._total = total\n \n def get_success_ratio(self):\n return self._success / self._total\n \n def get_fail_ratio(self):\n return self._failed / self._total\n\n def get_fail(self):\n return self._failed\n\n def get_success(self):\n return self._success\n \n def get_skipped(self):\n return self._skipped\n \n def get_total(self):\n return self._total\n\n\n\n# ==================================================================================\n\n\n\nclass JobStatusCounter(Jobs):\n def __init__(self):\n Jobs.__init__(self)\n self._pending = 0\n self._running = 0\n self._cancelled = 0\n \n def pending(self):\n self._pending += 1\n self._total += 1\n \n def running(self):\n self._running += 1\n self._total += 1\n \n def cancelled(self):\n self._cancelled += 1\n self._total += 1\n\n def get_pending(self):\n return self._pending\n\n def get_running(self):\n return self._running\n\n def get_cancelled(self):\n return self._cancelled\n\n\n# Here the actual program begins\n\n# ================================================================================\n\n\n\nclass ParameterIterator(object):\n\n def __init__(self, root_path=None, config_file=None):\n self._supdate = None\n self._settings = None\n self._params = None\n self._pid_inds = None\n\n self._dformat_str = None\n self._pformat_str = None\n self._pformat_list_all = None\n\n self.setup_default_settings()\n root_path = \".\" if root_path is None else root_path\n root_path = os.path.abspath(root_path)\n self._settings.update({'init_path': os.getcwd()})\n config_file = config_file if config_file is not None else self._settings['config_path'] \n self._settings.update({'config_path': os.path.join(root_path, config_file)})\n self._settings.update({'root_path': root_path})\n self.update_ini_settings() # we need this to setup the parameters before we can fix 'par_in_dirname'\n self.fix_settings_format()\n self.create_par_in_dirname_inds()\n\n self.create_dformat_str()\n self.create_pformat_str()\n\n def __del__(self):\n try:\n os.chdir(self._settings['init_path']) # make sure we leave the cwd unchanged\n except:\n pass\n\n def fix_settings_format(self):\n\n if self._params is not None:\n # fix formatting of parameters\n if 'par_in_dirname' in self._settings and \\\n len(self._settings['par_in_dirname'].split(',')) > 0:\n self._settings.update([['par_in_dirname', \\\n [v.strip() for v in self._settings['par_in_dirname'].split(',')]]])\n else:\n self._settings.update([['par_in_dirname', self._params.get_names()]])\n \n if not common.list_prod([p in self._params.get_names() for p in self._settings.get('par_in_dirname')]):\n raise RuntimeError(\"Invalid parameter found in `par_in_dirname` settings.\")\n\n def iterate(self, start=0):\n \"\"\"\n Iterate through parameters and call `execute`.\n The method `execute` is overridden by subclasses.\n \"\"\"\n\n for job_idx, cur_p in enumerate(self._params[start:]):\n self.execute(job_idx, cur_p)\n \n def finalize(self):\n pass\n \n def execute(self, job_idx, params):\n pass\n \n def setup_default_settings(self):\n \"\"\"\n Setup the default settings dictionary.\n \"\"\"\n\n #raise NotImplementedError(\"ParameterIterator.setup_default_settings\")\n\n settings = dict()\n settings.update([['script_path', 'slurm.sh']])\n settings.update([['config_path', 'config.ini']])\n settings.update([['submit_as', 'sbatch']])\n settings.update([['overwrite_dir', False]])\n settings.update([['test_mode', True]])\n settings.update([['jobname_prefix', '']])\n settings.update([['logfile_name', 'slurm.log']])\n settings.update([['cmd_arguments', '']])\n settings.update([['write_parameter_info', True]])\n settings.update([['use_index', False]])\n\n self._settings = settings\n \n def update_ini_settings(self):\n \"\"\"\n Update default settings with config file.\n \"\"\"\n #raise NotImplementedError(\"ParameterIterator.update_ini_settings\")\n\n try:\n params, f_settings = ini.parameters_from_ini(self._settings.get('config_path'))\n except ini.IniFormatError as e:\n sys.stdout.write('Error! Wrong format in config file:\\n')\n sys.stdout.write(str(e) + '\\n')\n sys.exit(1)\n except IOError:\n sys.stdout.write('Error! Could not read file `{}`.\\n'.format(self._settings.get('config_path')))\n sys.exit(1)\n #except TypeError:\n # sys.stdout.write('Error! Could not read file `{}`.\\n'.format(self._settings.get('config_path')))\n # sys.exit(1)\n except:\n raise\n\n # set params and update settings\n self._params = params\n self._settings.update(f_settings)\n\n def update_cmd_settings(self):\n \"\"\"\n Update default settings with command line options.\n \"\"\"\n \n #raise NotImplementedError(\"ParameterIterator.update_cmd_settings\")\n \n self._settings.update(self._supdate)\n \n def create_dformat_str(self):\n \"\"\"\n Get format string for directory name.\n \"\"\"\n num_dname_vals = len(self._settings['par_in_dirname'])\n dtypes = [ type(self._params.get_values_ax(name)[0]) for name in self._settings['par_in_dirname']]\n decimals = None\n format_str = util.generate_format_spec(num_dname_vals, \"_\", dtypes, decimals)\n\n if self._settings['use_index']:\n format_str = util.generate_named_index_format_spec(self._settings['par_in_dirname'], \"_\")\n\n self._dformat_str = format_str\n\n def create_par_in_dirname_inds(self):\n \"\"\"\n Create array with indices of parameters in directory names.\n \"\"\"\n \n pid_inds = []\n for p in self._settings.get('par_in_dirname'):\n pid_inds.append(self._params.get_axis(p))\n \n self._pid_inds = np.asarray(pid_inds, dtype=int)\n\n def get_dirname(self, plist, job_idx):\n \"\"\"Create a directory name given a set of parameter values.\"\"\"\n if self._settings['use_index']:\n return self._dformat_str.format(*list(np.asarray(self._params.get_inds_per_ax(job_idx), dtype=int)[self._pid_inds]))\n else:\n return self._dformat_str.format(*list(np.asarray(plist)[self._pid_inds]))\n\n def get_plist(self, dirname):\n \"\"\"Inversion of get_dirname.\"\"\"\n plist = []\n\n\n ax_names = self._params.get_names()\n\n valuestr_list = dirname.strip().split(\"_\")\n for i, p in enumerate(ax_names):\n try:\n pos = self._settings['par_in_dirname'].index(p)\n plist.append(float(valuestr_list[pos].replace(p, '')))\n except ValueError:\n plist.append(self._params.get_values_ax(i)[0])\n \n return plist\n \n def get_index(self, dirname):\n \"\"\"Inversion of get_dirname in case indices are used in directory names.\"\"\"\n job_idx = None\n job_idx_list = []\n \n ax_names = self._params.get_names()\n\n indexstr_list = dirname.strip().split(\"_\")\n for i, p in enumerate(ax_names):\n try:\n pos = self._settings['par_in_dirname'].index(p)\n job_idx_list.append(int(indexstr_list[pos].replace(p, '')))\n except ValueError:\n job_idx_list.append(0)\n except IndexError:\n # this can only happen if the directory name does not comply with the convention set by the config file\n raise InvalidDirectoryNameError(dirname)\n\n job_idx = self._params.get_number_by_indexlist(job_idx_list)\n\n return job_idx\n\n def create_pformat_str(self, all=False):\n\n if all:\n pars = self._params.get_names()\n num = self._params.get_dim()\n dtypes = self._params.get_types()\n else:\n pars = self._settings['par_in_dirname']\n num = len(self._settings['par_in_dirname'])\n dtypes = [ type(self._params.get_values_ax(name)[0]) for name in self._settings['par_in_dirname']]\n \n decimals = self._params.get_maxdecimals()\n format_str = util.generate_format_spec(num, \"_\", dtypes, decimals, self._params.get_maxdigits())\n \n format_ids = format_str.split(\"_\")\n format_strs = [\"{name}={id}, \".format(name=name, id=format_ids[i]) for i,name in enumerate(pars)]\n format_str = \"\"\n for sstr in format_strs:\n format_str += sstr\n if len(format_str) > 0:\n format_str = format_str[:-2]\n\n if all:\n self._pformat_str_all = format_str\n else:\n self._pformat_str = format_str\n \n def get_pformat_str(self, plist, all=False):\n\n if all:\n return self._pformat_str_all.format(*plist)\n else:\n try:\n return self._pformat_str.format(*list(np.array(plist)[self._pid_inds]))\n except:\n #print(plist, self._pid_inds)\n raise\n \n def create_pformat_list(self):\n \"\"\"\n Create list of formatter strings for all parameters.\n \"\"\"\n num = self._params.get_dim()\n dtypes = self._params.get_types()\n formatter = util.generate_format_spec(num, \"_\", dtypes, None)\n formatter = formatter.split(\"_\")\n\n self._pformat_list_all = formatter\n\n def create_dformatlist_str(self):\n \"\"\"\n Create formatter string for list of all parameters listed in directory names.\n \"\"\"\n format_str = util.generate_named_index_format_spec(self._settings['par_in_dirname'], \"_\", \"=\")\n formatter_lst = format_str.split(\"_\")\n formatter = \", \".join(formatter_lst)\n\n self._dformatlist_str = formatter\n\n# ================================================================================\n\n\n\nclass JobDB(object):\n \n _db_path = os.path.join(db_dir, 'jobs.db')\n\n def __init__(self):\n \n # initialize as False\n # creating an empty db file updates value to True\n self._isempty = self.isempty()\n\n if not self.check_job_db():\n self.create_empty_job_db()\n else:\n pass\n\n def create_empty_job_db(self):\n \"\"\"\n Create an empty database file in the `db_path` location.\n \"\"\"\n #with open('jobs.db', 'wb') as db:\n # pass\n new_db = []\n db_file = open(self._db_path, 'wb')\n\n pickle.dump(new_db, db_file, -1)\n\n db_file.flush()\n db_file.close()\n\n self._isempty = True\n \n def update_job_db(self, plist, dirname, job_id):\n \"\"\"\n Update job database with parameter list, directory name, job index and a time stamp.\n \"\"\"\n\n submit_time = time.time()\n #with open('jobs.db', 'ab') as db:\n # db.write(\".{},{},{}\".format(dirname, job_idx, submit_time))\n\n # read old data\n db_file = open(self._db_path, 'rb')\n db_data = pickle.load(db_file)\n db_file.close()\n\n\n # write new data\n db_data.append([plist, dirname, job_id, submit_time])\n db_file = open(self._db_path, 'wb')\n pickle.dump(db_data, db_file, -1)\n db_file.flush()\n db_file.close()\n\n # database is no longer empty\n self._isempty = False\n \n def check_job_db(self):\n \"\"\"\n Check if job database file exists.\n \"\"\"\n return True if util.fexists(self._db_path) else False\n \n def isempty(self):\n \"\"\"\n Check if empty flag attribute is set.\n \"\"\"\n if self.check_job_db():\n with open(self._db_path, 'rb') as db_file:\n db_data = pickle.load(db_file)\n return len(db_data) == 0\n return True\n \n def read_job_db(self):\n \"\"\"\n Read the job database file. Returns empty job array if database file \n does not exist or database is empty.\n \"\"\"\n \n # check if database file exists and is not empty\n if self.check_job_db() and not self.isempty():\n \"\"\"\n db_list = []\n with open('jobs.db', 'rb') as db:\n for line in db:\n db_list += line.split('.')\n \n njobs = len(db_list)\n times = np.zeros(njobs)\n dirnames = np.zeros(njobs)\n job_idx = np.zeros(njobs)\n\n for i,itm in enumerate(db_list):\n data = itm.split(',')\n dirnames[i] = data[0]\n job_idx[i] = data[1]\n times[i] = data[2]\n \n self.job_db = np.vstack([dirnames, job_idx, times])\n \"\"\"\n db_file = open(self._db_path, 'rb')\n #for line in db_file:\n # print(line)\n #db_data = [[]]\n db_data = pickle.load(db_file)\n db_file.close()\n return np.vstack(db_data)\n else:\n # database is empty, return empty job array\n return np.vstack([[]])\n\n def find_in_job_db(self, plist, ret='all'):\n job_db = self.read_job_db()\n\n db_entry = job_db[np.where(job_db[:, 0] == plist)[0]]\n\n if ret == 'id':\n return db_entry[2]\n elif ret == 'dirname':\n return db_entry[1]\n elif ret == 'all':\n return db_entry\n\n\n\n# ===============================================================================\n\n\n\nclass Submitter(ParameterIterator, JobDB):\n \"\"\"\n Handles the submission of SLURM jobs. A job database is created for each job \n and can be used to check the status of each particular job.\n \"\"\"\n\n _logfile_name = \"ssubmit.log\"\n\n def __init__(self, argv):\n\n # determine the execution mode and supdate settings\n self.process_input(argv)\n #print(self._mode, self._supdate.get('ini_dst'))\n\n if self._mode == 'print_ini':\n # copy the default ini file to the destination\n copy_default_ini(self._supdate.get('ini_dst'))\n elif self._mode == 'run':\n # call base class constructors\n JobDB.__init__(self)\n ParameterIterator.__init__(self)\n self.process_input(argv) # this needs to be repeated since the base constructor\n # above resets _supdate to None.\n # maybe separate mode determination and processing input\n # in run mode? Or have process_input() return supdate?\n \n # load the job database\n self._job_db = self.read_job_db()\n\n # setup the correct settings.\n # this is done in order: default > ini > commandline\n # later settings override earlier settings.\n\n self.setup_default_settings()\n self.update_ini_settings()\n self.update_cmd_settings()\n self.fix_settings_format()\n\n self._job_count = Jobs()\n\n # create array with indices of parameters in directory names\n self.create_par_in_dirname_inds()\n\n # setup format strings for directory names and parameter lists\n self.create_dformat_str()\n self.create_dformatlist_str()\n self.create_pformat_str()\n self.create_pformat_str(all=True)\n self.create_pformat_list()\n\n def get_mode(self):\n \"\"\"\n Getter method for execution mode. \n Possible values are:\n\n * 'help' : displays help\n * 'print_ini' : copies default ini file to directory\n * 'run' : runs program\n \"\"\"\n return self._mode\n \n def process_input(self, argv):\n \"\"\"\n Determine if the program is supposed to run or print help.\n If the mode is `run`, also determine the settings from `argv`.\n \"\"\"\n argc = len(argv[1:])\n if argc < 1:\n self._mode = 'help'\n else:\n self._mode = 'run'\n \n if self._mode == 'run':\n supdate = dict()\n\n num_set = [] # list of numbers set\n\n #print(argc, argv)\n\n i = 1\n while (i <= argc):\n \n if argv[i].strip() == \"-f\":\n if argc >= i+1:\n try:\n supdate.update([['config_path', argv[i+1]]])\n except:\n raise ConfigPathError(\"Invalid config path: \" + str(argv[i+1]))\n else:\n supdate.update([['config_path', '.']])\n \n i += 2\n elif argv[i].strip() == '-F':\n self._mode = 'print_ini'\n\n #print(i)\n\n if argc >= i+1:\n dst = argv[i+1]\n else:\n dst = '.'\n supdate.update([['ini_dst', dst]])\n break\n elif argv[i].strip() == '-h':\n self._mode = 'help'\n return\n else:\n try:\n num = int(argv[i])\n except:\n raise\n num_set.append(num)\n i += 1\n \n if len(num_set) == 1:\n supdate.update([['start_index', 1]])\n supdate.update([['num_submits', num_set[0]]])\n elif len(num_set) > 1:\n supdate.update([['start_index', num_set[0]]])\n supdate.update([['num_submits', num_set[1]]])\n\n self._supdate = supdate\n\n\n def display_help(self):\n \"\"\"\n Display welcome screen and help message in the console.\n \"\"\"\n \n sep = \"-\"*80 + \"\\n\"\n vert = \"|\"\n help_msg = \"\\n\"\n help_msg += sep\n help_msg += vert + \" \"*21 + \"You are running ssubmit version {}\".format(VERSION) + \" \"*22 + vert + \"\\n\"\n help_msg += \"|\" + \" \"*78 + \"|\\n\"\n help_msg += \"|\" + \" \"*21 + \"Copyright (c) {} {}\".format(COPYRIGHT_RANGE, AUTHOR) + \" \"*21 + vert + \"\\n\"\n help_msg += sep\n help_msg += \"\\nHelp mode is active\\n\\n\"\n help_msg += sep\n help_msg += \"\\nCommand list:\\n\"\n help_msg += get_underline(\"Command list:\")\n help_msg += \">> ssubmit \\nSubmit the jobs with indices 1...n\\n\"\n help_msg += \" = number of submits\\n\"\n help_msg += \"\\n>> ssubmit \\nSubmit the jobs with indices s...s+n-1\\n\"\n help_msg += \" = start index\\n\"\n help_msg += \" = number of submits\\n\"\n help_msg += \"\\n-f (default =./config.ini)\\n\" + \" \"*12 + \"Path to the .ini configuration file.\\n\"\n help_msg += \"\\n-F (default =.)\\n\" + \" \"*12 + \"Save default config.ini file to the path.\\n\"\n \n \n sys.stdout.write(help_msg)\n \n\n def iterate(self):\n \"\"\"\n Iterate through parameters and call `execute`.\n This overrides the base class method and implements iteration only over select \n parameters.\n \"\"\"\n\n # get first and last index from settings\n first = self._settings.get('start_index')\n last = first + self._settings.get('num_submits') - 1\n\n # check if number of submits from input is reasonable\n changed_num, num = self.get_num_jobs(first, self._settings.get('num_submits'))\n if changed_num:\n last = first + num - 1\n self.log(\"INFO: Highest specified job out of range ({}/{}). Overriding.\\n\".format(first+self._settings.get('num_submits')-1, self._params.get_maxnum()))\n self._settings.update([['num_submits', num]])\n \n # log number of jobs to submit \n self.log(\"Submitting jobs {first} to {last} of {total}:\\n\".format(first=first, last=last, total=self._params.get_maxnum()), new=True)\n\n # do the iteration, call execute for every job\n for job_idx, cur_p in enumerate(self._params[first-1:last]):\n self.log(\"{}. Submitting job for \".format(first+job_idx) + self._pformat_str.format(*cur_p) + \" | indices: \" + self._dformatlist_str.format(*self._params.get_inds_per_ax(first-1+job_idx)))\n self.execute(first-1+job_idx, cur_p)\n\n def get_num_jobs(self, start, num):\n \"\"\"\n Get number of jobs to submit. Takes into account the maximal number of\n jobs available.\n\n Returns:\n bool num changed?\n int num\n \"\"\"\n total = self._params.get_maxnum() + 1\n if start + num > total:\n return True, total - start\n else:\n return False, num\n\n def finalize(self):\n \"\"\"\n Print final information about success to logfile.\n \"\"\"\n\n # get first and last index from settings\n first = self._settings.get('start_index')\n last = first + self._settings.get('num_submits') - 1\n\n # get number of submits from settings\n num_submits = self._settings.get('num_submits')\n\n # determine if there has been an error, set the summary string accordingly\n if self._job_count.get_total() == num_submits and \\\n self._job_count.get_success() == self._job_count.get_total():\n err_str = \"without\"\n else:\n err_str = \"with\"\n\n # get the grammar right\n if num_submits > 1:\n job_str = \"jobs\"\n else:\n job_str = \"job\"\n \n # compose and log the summary string\n self.log(\"\\nSummary:\")\n self.log(get_underline(\"Summary:\"))\n self.log(\"Submission of {} {} completed {} errors.\".format(num_submits, job_str, err_str))\n self.log(\"\\n{:8s}: {:3d}\".format(\"Success\", self._job_count.get_success()))\n self.log(\"{:8s}: {:3d}\".format(\"Skipped\", self._job_count.get_skipped()))\n self.log(\"{:8s}: {:3d}\\n\".format(\"Failed\", self._job_count.get_fail()))\n\n # log the next job index\n if last >= self._params.get_maxnum():\n self.log(\"All {} jobs submitted.\".format(self._params.get_maxnum()))\n else:\n self.log(\"Next job: {}\".format(last+1))\n\n def execute(self, job_idx, cur_p):\n \n # get directory name\n dirname = self.get_dirname(cur_p, job_idx)\n\n # create directory if it doesn't exist, returns True if directory existed\n retval = util.assert_dir(dirname)\n\n # else if settings.get('overwrite')\n if (not retval) or self._settings.get('overwrite_dir'):\n\n # if settings.get('submit_as') is 'sbatch'\n if self._settings.get('submit_as') == 'sbatch':\n retval, message = self.submit_sbatch(dirname, cur_p)\n else:\n raise NotImplementedError\n \n if retval:\n self._job_count.success()\n\n # add job to job database\n job_id = message.strip().split()[-1]\n self.update_job_db(cur_p, os.path.realpath(dirname), job_id)\n\n self.log(\"> Submission succeeded. ({})\\n\".format(message))\n else:\n self._job_count.failed()\n\n self.log(\"> Submission failed. ({})\\n\".format(message))\n else:\n self.log(\"> Directory existed and overwrite is disabled. Skipping this value.\\n\")\n self._job_count.skipped()\n\n def submit_sbatch(self, dirname, plist):\n \n # create wildcard list\n wildcard_list = get_wildcard_list(self._params)\n\n # name and path of the script file\n filename = os.path.basename(self._settings.get('script_path'))\n filepath = os.path.join(dirname, filename)\n\n # create jobname\n jobname = self._settings.get('jobname_prefix') + dirname\n\n # copy-replace script file\n #print(self._pformat_list_all)\n #print(plist)\n #replace_items = [fstr.format(p) for fstr, p in zip(self._pformat_list_all, plist)] #.append(jobname)\n replace_items = [str(p) for p in plist]\n replace_items.append(jobname)\n #print(replace_items)\n util.copy_replace(self._settings.get('script_path'), filepath, wildcard_list, replace_items)\n # make sure copying was successful\n if not os.access(filepath, os.F_OK):\n print(\"There was a problem copying the script file. Exiting.\")\n sys.exit(1)\n\n # copy also other files and replace occurrences of parameters\n if 'other_files' in self._settings:\n for filename in self._settings.get('other_files'):\n tmp_filename = os.path.basename(filename)\n tmp_filepath = os.path.join(dirname, tmp_filename)\n util.copy_replace(filename, tmp_filepath, wildcard_list, replace_items)\n\n if not self._settings.get('test_mode'):\n # submit script file\n cmd_args = self._settings.get('cmd_arguments')\n if cmd_args == \"\":\n cmd_list = [\"sbatch\", '-D', dirname, filepath]\n else:\n cmd_list = [\"sbatch\", cmd_args, '-D', dirname, filepath]\n p = subprocess.Popen(cmd_list, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n out_str, err_str = p.communicate()\n p.wait()\n else:\n # pretend submission was successful\n self.log(\"> Test mode active, not submitting.\")\n out_str = \"JOB 1 SUBMITTED\"\n \n message = out_str.decode('utf-8').strip()\n\n # determine if submission was successful\n if \"FAILED\" in message.upper():\n retval = False\n elif \"SUBMITTED\" in message.upper():\n retval = True\n else:\n retval = False\n\n # return message\n return retval, message\n \n def submit_srun(self, dirname, plist):\n \n raise NotImplementedError(\"Submitter.submit_srun\")\n \n def log(self, logstring, to_screen=True, new=False):\n \n log_exists = util.fexists(self._logfile_name)\n with open(self._logfile_name, 'a') as logfile:\n if new and log_exists:\n logfile.write(\"\\n\" + \"-\"*80 + \"\\n\\n\")\n logfile.write(logstring + \"\\n\")\n \n if to_screen:\n sys.stdout.write(logstring + \"\\n\")\n\n\n\n# ====================================================================================\n\n\n\nclass StatusChecker(ParameterIterator, JobDB):\n \"\"\"\n Handles status of jobs from job database or output files.\n \"\"\"\n\n def __init__(self, argv):\n \n # source of job information\n # a : job database (all)\n # d : directories\n # f : configuration file\n self._src_mode = 'all'\n\n # jobs to include\n # A : all\n # R : running\n # C : cancelled\n # F : failed\n # P : pending\n self._include = 'A'\n self.process_input(argv)\n\n if self._mode == 'run':\n ParameterIterator.__init__(self)\n JobDB.__init__(self)\n self._job_db = self.read_job_db()\n self._job_count = JobStatusCounter()\n if self._src_mode == 'file':\n self.setup_default_settings()\n self.update_ini_settings()\n\n def get_mode(self):\n return self._mode\n\n\n def process_input(self, argv):\n \"\"\"\n Process command line arguments.\n \"\"\"\n \n argc = len(sys.argv[1:])\n if argc < 1:\n self._mode = 'help'\n else:\n self._mode = 'run'\n \n i = 1\n include = ''\n while (i <= argc):\n cur_arg = argv[i].strip()\n if cur_arg[0] == '-' and len(cur_arg) > 1:\n if 'a' in cur_arg:\n # use job database\n self._src_mode = 'all'\n if 'd' in cur_arg:\n # use created directories\n self._src_mode = 'dir'\n if 'f' in cur_arg:\n # use config file\n self._src_mode = 'file'\n if 'A' in cur_arg:\n # all\n include += 'A'\n self._include = include\n if 'R' in cur_arg:\n # running\n include += 'R'\n self._include = include\n if 'C' in cur_arg:\n # cancelled\n include += 'C'\n self._include = include\n if 'F' in cur_arg:\n # failed\n include += 'F'\n self._include = include\n if 'P' in cur_arg:\n # pending\n include += 'P'\n self._include = include\n if cur_arg == '-c':\n # clear database\n try:\n confirm = raw_input(\"Confirm deletion of job database (y/n): \")\n except NameError:\n # use in Python 3.x\n confirm = input(\"Confirm deletion of job database (y/n): \")\n \n if confirm.lower() in ['y', 'yes']:\n raise NotImplementedError(\"clear database option\")\n else:\n print(\"Clear database cancelled.\")\n sys.exit(0)\n else:\n raise RuntimeError(\"Unrecognized commandline option {}\".format(argv[i]))\n i += 1\n\n\n def display_help(self):\n \"\"\"\n Display welcome screen and help message in the console.\n \"\"\"\n \n sep = \"-\"*80 + \"\\n\"\n vert = \"|\"\n help_msg = \"\\n\"\n help_msg += sep\n help_msg += vert + \" \"*21 + \"You are running sstatus version {}\".format(VERSION) + \" \"*22 + vert + \"\\n\"\n help_msg += \"|\" + \" \"*78 + \"|\\n\"\n help_msg += \"|\" + \" \"*21 + \"Copyright (c) {} {}\".format(COPYRIGHT_RANGE, AUTHOR) + \" \"*21 + vert + \"\\n\"\n help_msg += sep\n help_msg += \"\\nHelp mode is active\\n\\n\"\n help_msg += sep\n help_msg += \"\\nCommand list:\\n\"\n help_msg += get_underline(\"Command list:\")\n help_msg += \">> sstatus \\nCheck status of the jobs specified by current `config.ini` file\\n\"\n\n help_msg += \"\\n-a\" + \" \"*10 + \"Check status of all jobs in the job database.\\n\"\n help_msg += \"\\n-d\" + \" \"*10 + \"Check status of all jobs running in subdirectories of the current working directory.\\n\"\n help_msg += \"\\n-f\" + \" \"*10 + \"Check status of all jobs specified in the configuration file in the current working directory.\\n\"\n \n help_msg += \"\\nFilters:\\n\"\n help_msg += \"-A\" + \" \"*10 + \"Show all jobs.\\n\"\n help_msg += \"-R\" + \" \"*10 + \"Show running jobs.\\n\"\n help_msg += \"-C\" + \" \"*10 + \"Show cancelled jobs.\\n\"\n help_msg += \"-F\" + \" \"*10 + \"Show failed jobs.\\n\"\n help_msg += \"-P\" + \" \"*10 + \"Show pending jobs.\\n\"\n\n help_msg += \"\\n-c\" + \" \"*10 + \"Clear job database.\\n\"\n\n \n \n \n sys.stdout.write(help_msg)\n \n def find_last_job(self, dirname):\n \"\"\"\n Return the highest job index from outfiles in the directory `dirname`.\n \"\"\"\n filelist = glob.glob(os.path.join(dirname, \"*.out\"))\n job_id_list = [int(name.split('.')[0].split('-')[1]) for name in filelist]\n\n return max(job_id_list) if len(job_id_list) > 0 else None\n \n def check_accounting(self, job_id):\n \n raise NotImplementedError(\"StatusChecker.check_accounting\")\n\n p = subprocess.Popen(['sacct', '-j', str(job_id)], stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n p.wait()\n try:\n sacct_outstr = p.communicate()[0].split('\\n')[2]\n #print sacct_outstr\n\n job_no = sacct_outstr.split()[0]\n slurm_status = sacct_outstr.split()[5]\n\n if slurm_status.lower() == 'cancelled':\n self._job_count.cancelled()\n elif slurm_status.lower() == 'failed':\n self._job_count.failed()\n elif slurm_status.lower() == 'running':\n self._job_count.running()\n elif slurm_status.lower() == 'pending':\n self._job_count.pending()\n\n #print sacct_outstr\n\n except:\n slurm_status = \"job ID not found\"\n \n #self._pformat_str.format(*cur_p)\n\n #self.log(std_string + \"job {0} {1}\".format(job_id, slurm_status))\n\n return slurm_status\n\n def check_squeue(self, job_id):\n p = subprocess.Popen(['squeue', '-h', '-j', str(job_id)], stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n \n p_outstr, p_errstr = p.communicate()\n try:\n p_outline = p_outstr.split('\\n')[0] # this should be the line containing the job info\n except IndexError:\n return JobStatusMessage(JobStatusMessage.not_found_in_queue)\n \n p.wait()\n\n if 'invalid job id' in p_errstr.lower():\n slurm_status = JobStatusMessage(JobStatusMessage.not_found_in_queue)\n elif len(p_errstr.strip()) > 0:\n print(\"Unexpected error: \" + p_errstr.strip())\n else:\n #print(p_outline, p_outstr, p_errstr)\n job_no = p_outline.split()[0].strip()\n slurm_status = p_outline.split()[4].strip()\n\n if slurm_status == 'R':\n self._job_count.running()\n slurm_status = JobStatusMessage(JobStatusMessage.running)\n elif slurm_status == 'PD':\n self._job_count.pending()\n slurm_status = JobStatusMessage(JobStatusMessage.pending)\n\n return slurm_status\n\n \n def check_outfile(self, job_id):\n raise NotImplementedError(\"StatusChecker.check_outfile\")\n \n def find_in_dir(self, plist, job_idx):\n \"\"\"\n Find job ID from out files in subdirectory corresponding to `plist`.\n \"\"\"\n dirname = self.get_dirname(plist, job_idx)\n if not os.access(dirname, os.F_OK):\n if False:\n print(\"Directory not found: \" + dirname + \", plist={}, job_idx={}\".format(plist, job_idx))\n raise MissingDirectoryError(dirname)\n outfiles = glob.glob(os.path.join(dirname, \"slurm-*.out\"))\n\n try:\n job_id = int(sorted(outfiles)[-1].split(\".\")[0].split('-')[1])\n except IndexError:\n raise MissingOutfileError('')\n \n\n return job_id\n\n def iterate(self):\n \"\"\"\n Iterate over the parameters and call the `execute` method.\n\n This overloads the base class method to implement different modes.\n The `file` mode simply executes the base class method.\n \"\"\"\n \n if self._src_mode == \"all\":\n raise NotImplementedError(\"option -a\")\n\n elif self._src_mode == \"dir\":\n\n #raise NotImplementedError(\"option -d\")\n\n # get list of subdirectories\n dirlist = sorted(util.listdirs('.'))\n\n # iterate over list\n for idx, directory in enumerate(dirlist):\n # find parameters from dirname\n try:\n if self._settings['use_index']:\n linear_idx = self.get_index(directory)\n plist = self._params.get_values(linear_idx) # bug: this can produce the same linear index for different directories\n else:\n plist = self.get_plist(directory)\n linear_idx = self._params.get_number(plist) # linear index of the parameters\n self.execute(linear_idx, plist)\n except InvalidDirectoryNameError:\n print(\"Ignoring {}\".format(directory))\n \n \n elif self._src_mode == \"file\":\n #raise NotImplementedError(\"option -f\")\n\n # use base class method\n ParameterIterator.iterate(self)\n\n def execute(self, job_idx, plist):\n \"\"\"\n Call the status checks and print outputs to screen.\n \"\"\"\n\n dirname = self.get_dirname(plist, job_idx)\n\n status = None\n\n skip_misses = True # setting this skips output for directories, which have not been created yet\n skip = False # indicates if output is to be skipped for this job_idx\n\n # find job in job_db\n try:\n #idx = np.where(self._job_db[0] == os.path.realpath(dirname))[0]\n #job_id = self._job_db[1, idx]\n job_id = self.find_in_job_db(plist, 'id')\n except:\n try:\n job_id = self.find_in_dir(plist, job_idx)\n except MissingDirectoryError:\n job_id = -1\n status = JobStatusMessage(JobStatusMessage.dir_not_found)\n skip = True\n except MissingOutfileError:\n job_id = -1\n status = JobStatusMessage(JobStatusMessage.outfile_not_found)\n\n # if job ID could be retrieved\n if status is None:\n status = self.check_squeue(job_id)\n if status == 0:\n try:\n status = self.check_accounting(job_id)\n except NotImplementedError:\n pass\n \n if status == 0:\n try:\n status = self.check_outfile(job_id)\n except NotImplementedError:\n pass\n\n sep = \" \"*4\n if not skip:\n pstr = self.get_pformat_str(plist)\n self.log(\"{job_id:6d}{sep}{parameters:10}{sep}{dirname:10}{sep}{status}\".format(job_id=job_id, sep=sep, parameters=pstr, dirname=dirname,status=str(status)))\n\n def log(self, logstring):\n\n sys.stdout.write(logstring + \"\\n\")\n\n\nclass JobStatusMessage(object):\n not_found_in_queue = 0\n not_found = 1\n dir_not_found = 2\n outfile_not_found = 3\n running = 4\n pending = 5\n cancelled = 6\n failed = 7\n\n str_list = [\"ID not found in queue\",\n \"ID not found\",\n \"Job and directory not found\",\n \"No output file found\",\n \"running\",\n \"pending\",\n \"cancelled\",\n \"failed\",\n ]\n\n def __init__(self, value):\n if value < 8:\n self._value = value\n else:\n raise ValueError(\"Invalid status\")\n \n def __str__(self):\n return JobStatusMessage.str_list[self._value]\n\nclass DataProcessor(ParameterIterator):\n \"\"\"\n Defines an instance that allows easy iteration through data folders for \n data processing purposes.\n In each folder the method `process` is executed.\n \"\"\"\n\n def process(self, dirname, job_idx, plist):\n \"\"\"\n Overload this function to do some processing.\n \"\"\"\n raise NotImplementedError(\"Do not use base class `DataProcessor`.\")\n \n def execute(self, job_idx, plist):\n dirname = self.get_dirname(plist, job_idx)\n try:\n os.chdir(os.path.join(self._settings['root_path'], dirname)) # do we want to change current working directory?\n except OSError:\n print(\"Directory {} not found. Found the following:\".format(dirname), file=sys.stderr)\n for d in sorted(util.listdirs('.')):\n print(d, file=sys.stderr)\n sys.exit(0)\n\n self.process(dirname, job_idx, plist)\n\n os.chdir('..') # change directory back\n\n# ==================================================================================\n# ==================================================================================\n\n# global static methods\n\ndef get_dist_path():\n return os.path.split(os.path.dirname(os.path.realpath(__file__)))[0]\n\ndef copy_default_ini(dst):\n\n path = os.path.split(os.path.dirname(os.path.realpath(__file__)))[0]\n \n #print(path, dst)\n\n shutil.copy(os.path.join(path, 'config', 'config.ini'), dst)\n\n\ndef get_underline(string):\n \"\"\"\n Return an underline string of the same length as `str`.\n \"\"\"\n return \"=\"*len(string) + \"\\n\"\n\ndef get_wildcard(name):\n \"\"\"\n Create a wildcard of the form `_VAL` from name.\n This is supposed to ensure that when replacing the wildcard in the bash script,\n no accidental mismatch occurs.\n \"\"\"\n return name.upper() + \"_VAL\"\n\ndef get_wildcard_list(params):\n \"\"\"\n Return a list of wildcard strings of the form `_VAL`, where are \n the (uppercase) names of the parameters in params. The additional wildcard `JOBNAME` is included.\n \"\"\"\n wildcard_list = []\n\n for name in params.get_names():\n wildcard_list.append(get_wildcard(name))\n \n # include jobname\n wildcard_list.append(\"JOBNAME\")\n\n return wildcard_list\n\ndef get_version():\n return VERSION\n\ndef main(mode, *argv):\n try:\n if mode is 'submit':\n ssub_iter = Submitter(argv)\n elif mode is 'status':\n ssub_iter = StatusChecker(argv)\n else:\n sys.exit()\n \n if ssub_iter.get_mode() == 'help':\n ssub_iter.display_help()\n elif ssub_iter.get_mode() == 'run':\n ssub_iter.iterate()\n ssub_iter.finalize()\n except NotImplementedError as e:\n print(\"ERROR: Method {} not implemented.\".format(str(e)))\n except Exception as e:\n print(\"An error occured: \" + str(e))\n raise\n","sub_path":"sutils/core/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":44763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"207205487","text":"# coding=utf-8\n\"\"\"\n\"\"\"\n__author__ = 'Alisue '\nimport sys\nimport numpy as np\nimport maidenhair\nimport maidenhair.statistics\nfrom txt2contincd.utils import ichunk\n\n@np.vectorize\ndef molar_concentration(c, m):\n \"\"\"\n Calculate molar concentration (mol/L)\n\n Args:\n c (float): concentration in g/L\n m (float): molecular weight in kDa (=kg/mol)\n \"\"\"\n m = m * 10e+3 # kDa -> Da (=g/mol)\n return c / m\n\n@np.vectorize\ndef mean_residue_ellipticity(phi, n, c, l):\n \"\"\"\n Calculate mean residue ellipticity (millideg cm2 / decimol) from\n ellipticity (mdeg)\n\n Args:\n phi (float): a ellipticity (milli deg)\n n (int): the number of residues\n c (float): the molar concentration of the polymer (mol/L)\n l (float): the length of the cuvette (cm)\n\n Returns:\n a mean residue ellipticity (deg cm2 decimol^{-1} residue^{-1})\n \"\"\"\n return phi / (10 * l * n * c)\n\ndef translate_dataset(dataset, n, m, c, L,\n is_molar_concentration=False):\n \"\"\"\n Translate dataset from mdeg into mean residue ellipticities\n\n Args:\n n (int): the number of residues\n m (float): molecular weight in kDa (=kg/mol)\n c (float): concentration in g/L\n L (float): the length of the cuvette (cm)\n is_molar_concentration (bool): True if the specified concentration is \n a molar concentration (mol/L)\n\n Returns:\n a dataset with mean residue ellipticity (deg cm2 decimol^{-1})\n \"\"\"\n if not is_molar_concentration:\n # g/L to mol/L\n c = molar_concentration(c, m)\n for i, (x, y) in enumerate(dataset):\n dataset[i][1] = mean_residue_ellipticity(y, n, c, L)\n return dataset\n\ndef print_contincd_in(dataset, title, out=sys.stdout, strict=True):\n \"\"\"\n Print dataset in CONTINT-CD format \n\n Args:\n dataset (list): A maidenhair output dataset\n title (str): A title prefix of each dataset\n strict (bool): True for regulate the CD spectrum region\n \"\"\"\n for i, (x, y) in enumerate(dataset):\n x = maidenhair.statistics.average(x)\n y = maidenhair.statistics.average(y)\n if strict:\n where = np.where((x >= 190) & (x <= 240))\n x, y = x[where], y[where]\n # a heading of the block\n print >> out, \" {} - {:d}\".format(title, i)\n if i == 0:\n # specify the input FORMAT of the mean residue ellipticities\n print >> out, \" IFORMY\"\n print >> out, \" (7F9.0)\"\n # print LAST if there is more than one dataset\n if len(dataset) > 1:\n if i == 0:\n print >> out, \" LAST\" + (\" \" * 18) + \"-1.\"\n elif i == len(dataset) - 1:\n print >>out, \" LAST\" + (\" \" * 18) + \"1.\"\n print >> out, \" END\"\n # print ellipticities\n N, S, E = str(len(x)), str(x[0]), str(x[-1])\n print >> out, \" NSTEND {}{}{}{}{}\".format(\n N, \" \"*(13-len(N)), \n S, \" \"*(15-len(S)), E) \n # 7 columns\n for ychunk in ichunk(y, 7):\n cols = map(lambda x: str(x).rjust(8)[:8], ychunk)\n print >> out, \" \" + \" \".join(cols)\n\n","sub_path":"src/txt2contincd/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"238384546","text":"\n\nfrom xai.brain.wordbase.nouns._shipment import _SHIPMENT\n\n#calss header\nclass _SHIPMENTS(_SHIPMENT, ):\n\tdef __init__(self,): \n\t\t_SHIPMENT.__init__(self)\n\t\tself.name = \"SHIPMENTS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"shipment\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_shipments.py","file_name":"_shipments.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"362311568","text":"\n\nfrom copy import deepcopy\nfrom collections import defaultdict\nfrom math import sqrt\n\n# Feature TODOs\n# TODO (JLD):\n\n\nclass AthenaPost(object):\n \"\"\"\n Post processing and statistical analysis of optimization data generated by AthenaOpt and AthenaRunner\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Initialize the AthenaPost object\n \"\"\"\n pass\n\n\nclass Population(object):\n \"\"\"\n Class representing a population\n \"\"\"\n def __init__(self, population):\n \"\"\"\n Initialize the population\n \"\"\"\n self._population = population\n\n\ndef calculate_design_centroid(population):\n \"\"\"\n Calculate the centroid of the population in the decision space\n @param population: The population to use for the calculation\n @type population: list(Individual)\n @return: The centroid in decision space\n @rtype: float\n \"\"\"\n ndim = len(population[0].x)\n k = len(population)\n centroid = [0.0]*ndim\n\n for i in range(ndim):\n for ind in population:\n centroid[i] += ind.x[i]\n\n centroid[i] /= k\n\n return centroid\n\n\ndef calculate_objective_centroid(population):\n \"\"\"\n Calculate the centroid of the population in the objective space\n @param population: The population to use for the calculation\n @type population: list(Individual)\n @return: The centroid in objective space\n @rtype: float\n \"\"\"\n ndim = len(population[0].f)\n k = len(population)\n centroid = [0.0]*ndim\n\n for i in range(ndim):\n for ind in population:\n centroid[i] += ind.f[i]\n\n centroid[i] /= k\n\n return centroid\n\n\ndef calculate_decision_radius(population, centroid):\n \"\"\"\n Calculate the radius of the population in decision space\n @param population: The population to use for the calculation\n @type population: list(Individual)\n @param centroid: The centroid of the population\n @type centroid: float\n @return: The population's radius in decision space\n @rtype: float\n \"\"\"\n radius = 0.0\n # Calculate the max distance between the individuals and the centroid\n for ind in population:\n distance = sqrt(sum((x - c)**2 for (x, c) in zip(ind.x, centroid)))\n if distance > radius:\n radius = distance\n\n return radius\n\n\ndef calculate_objective_radius(population, centroid):\n \"\"\"\n Calculate the radius of the population in objective space\n @param population: The population to use for the calculation\n @type population: list(Individual)\n @param centroid: The centroid of the population\n @type centroid: float\n @return: The population's radius in objective space\n @rtype: float\n \"\"\"\n radius = 0.0\n # Calculate the max distance between the individuals and the centroid\n for ind in population:\n distance = sqrt(sum((f - c)**2 for (f, c) in zip(ind.f, centroid)))\n if distance > radius:\n radius = distance\n\n return radius\n\n\ndef calculate_percent_valid(population):\n \"\"\"\n Calculate the percentage of the population that is valid\n @param population: The population to use for the calculation\n @type population: list(Individual)\n @return: The percentage of the population that is valid\n @rtype: float\n \"\"\"\n k = len(population)\n invalid = 0\n for ind in population:\n if ind.s > 0:\n invalid += 1\n\n if invalid > 0:\n percentage = invalid / k\n else:\n percentage = 1.0\n\n return percentage\n\n\ndef nondominated_sort(population, k, first_front_only=False):\n \"\"\"\n Sort the first k individuals in the population into different non-domination\n levels using the fast non-dominated sorting approach proposed by Deb et al.\n @param population: The population of individuals to sort\n @type population: list(Individual)\n @param k: The number of individuals to select\n @type k: int\n @param first_front_only: True if only the first non-dominated front is desired\n @type first_front_only: bool\n @return: A list of ordered Pareto fronts\n @rtype: list(list(Individual))\n \"\"\"\n if k == 0:\n return []\n\n map_fit_ind = defaultdict(list)\n for ind in population:\n map_fit_ind[(tuple(ind.f))] = ind\n fits = map_fit_ind.keys()\n\n current_front = []\n next_front = []\n dominating_fits = defaultdict(int)\n dominated_fits = defaultdict(list)\n\n # Rank first Pareto front\n for i, fit_i in enumerate(fits):\n for fit_j in fits[i+1:]:\n if map_fit_ind[tuple(fit_i)].dominates(map_fit_ind[tuple(fit_j)]):\n dominating_fits[fit_j] += 1\n dominated_fits[fit_i].append(fit_j)\n elif map_fit_ind[tuple(fit_j)].dominates(map_fit_ind[tuple(fit_i)]):\n dominating_fits[fit_i] += 1\n dominated_fits[fit_j].append(fit_i)\n if dominating_fits[fit_i] == 0:\n map_fit_ind[tuple(fit_i)].r = 1\n current_front.append(fit_i)\n\n fronts = [[]]\n for fit in current_front:\n fronts[-1].append(map_fit_ind[tuple(fit)])\n pareto_sorted = len(fronts[-1])\n\n # Rank the next front until all individuals are sorted or\n # the given number of individual are sorted.\n if not first_front_only:\n N = min(len(population), k)\n while pareto_sorted < N:\n fronts.append([])\n for fit_p in current_front:\n for fit_d in dominated_fits[fit_p]:\n dominating_fits[fit_d] -= 1\n if dominating_fits[fit_d] == 0:\n next_front.append(fit_d)\n pareto_sorted += 1\n fronts[-1].append(map_fit_ind[tuple(fit_d)])\n map_fit_ind[tuple(fit_d)].r = len(fronts)\n current_front = next_front\n next_front = []\n\n return deepcopy(fronts)\n\n\ndef assign_crowding_distance(population):\n \"\"\"\n Assign the crowding distance to each individual in the population\n @param population: The population to assign the crowding distance to\n @type population: list(Individual)\n @return: None\n \"\"\"\n if len(population) == 0:\n return\n\n distances = [0.0] * len(population)\n crowd = [(ind.f, i) for i, ind in enumerate(population)]\n nobj = len(population[0].f)\n\n for i in xrange(nobj):\n crowd.sort(key=lambda element: element[0][i])\n distances[crowd[0][1]] = float(\"inf\")\n distances[crowd[-1][1]] = float(\"inf\")\n if crowd[-1][0][i] == crowd[0][0][i]:\n continue\n norm = nobj * float(crowd[-1][0][i] - crowd[0][0][i])\n for prev, cur, nexxt in zip(crowd[:-2], crowd[1:-1], crowd[2:]):\n distances[cur[1]] += (nexxt[0][i] - prev[0][i]) / norm\n\n for i, dist in enumerate(distances):\n population[i].d = dist\n\n","sub_path":"AthenaPost/athena_post.py","file_name":"athena_post.py","file_ext":"py","file_size_in_byte":6791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"496970167","text":"#!usr/bin/env python\n#-*- coding:utf-8 -*-\n\nimport os\nimport tqdm\nimport pandas as pd\nimport torch\nimport torch.nn as nn\nfrom torch.optim import Adam\nfrom transformers import BertTokenizer, BertModel, BertConfig\nfrom optim_schedule import ScheduledOptim\nfrom torch.utils.data import Dataset\nfrom torch.utils.data import DataLoader\nfrom model import SoftMaskedBert\nfrom sklearn.model_selection import KFold\nMAX_INPUT_LEN = 512\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"1\"\n\nclass SoftMaskedBertTrainer():\n def __init__(self, bert, tokenizer, device, hidden=256, layer_n=1, lr=2e-5, gama=0.8, betas=(0.9, 0.999), weight_decay=0.01, warmup_steps=10000):\n\n self.device = device\n self.bert = bert\n self.tokenizer = tokenizer\n self.model = SoftMaskedBert(self.bert, self.tokenizer, hidden, layer_n, self.device).to(self.device)\n\n # if torch.cuda.device_count() > 1:\n # print(\"Using %d GPUS for train\" % torch.cuda.device_count())\n # self.model = nn.DataParallel(self.model, device_ids=[0,1,2])\n\n self.optim = Adam(self.model.parameters(), lr=lr, betas=betas, weight_decay=weight_decay)\n self.optim_schedule = ScheduledOptim(self.optim, hidden, n_warmup_steps=warmup_steps)\n self.criterion_c = nn.NLLLoss()\n self.criterion_d = nn.BCELoss()\n self.gama = gama\n self.log_freq = 10\n\n def train(self, train_data, epoch):\n self.model.train()\n return self.iteration(epoch, train_data)\n\n def evaluate(self, val_data, epoch):\n self.model.eval()\n return self.iteration(epoch, val_data, train=False)\n\n def inference(self, data_loader):\n self.model.eval()\n out_put = []\n data_iter = tqdm.tqdm(enumerate(data_loader),\n desc=\"%s\" % 'Inference:',\n total=len(data_loader),\n bar_format=\"{l_bar}{r_bar}\")\n for i, data in data_iter:\n # 0. batch_data will be sent into the device(GPU or cpu)\n data = {key: value.to(self.device) for key, value in data.items()}\n\n out, prob = self.model(data[\"random_text\"]) #prob [batch_size, seq_len, 1]\n out_put.extend(out.argmax(dim=-1))\n\n return [self.tokenizer.convert_ids_to_tokens(x) for x in out_put]\n\n def save(self, file_path):\n torch.save(self.model.cpu(), file_path)\n self.model.to(self.device)\n print('Model save {}'.format(file_path))\n\n def load(self, file_path):\n if not os.path.exists(file_path):\n return\n self.model = torch.load(file_path)\n\n def iteration(self, epoch, data_loader, train=True):\n str_code = \"train\" if train else \"val\"\n\n # Setting the tqdm progress bar\n data_iter = tqdm.tqdm(enumerate(data_loader),\n desc=\"EP_%s:%d\" % (str_code, epoch),\n total=len(data_loader),\n bar_format=\"{l_bar}{r_bar}\")\n\n avg_loss = 0.0\n total_correct = 0\n total_element = 0\n\n for i, data in data_iter:\n # 0. batch_data will be sent into the device(GPU or cpu)\n data = {key: value.to(self.device) for key, value in data.items()}\n\n out, prob = self.model(data[\"random_text\"]) #prob [batch_size, seq_len, 1]\n # label = data[\"label\"].reshape(-1,prob.shape[1], prob.shape[-1]) #prob [batch_size, seq_len]\n prob = prob.reshape(-1, prob.shape[1])\n # prob = prob.transpose(1, 2)\n # label = data['label'].reshape(-1, prob.shape[1], prob.shape[-1])\n # p = prob.reshape(prob.shape[0]*prob.shape[1],-1)\n # label = data['label'].reshape(prob.shape[0]*prob.shape[1])\n # print(p.shape)\n # print(label.shape)\n loss_d = self.criterion_d(prob, data['label'].float())\n loss_c = self.criterion_c(out.transpose(1, 2), data[\"origin_text\"])\n loss = self.gama * loss_c + (1-self.gama) * loss_d\n\n if train:\n self.optim_schedule.zero_grad()\n loss.backward(retain_graph=True)\n self.optim_schedule.step_and_update_lr()\n\n correct = out.argmax(dim=-1).eq(data[\"origin_text\"]).sum().item()\n avg_loss += loss.item()\n total_correct += correct\n total_element += data[\"label\"].nelement()\n\n post_fix = {\n \"epoch\": epoch,\n \"iter\": i,\n \"avg_loss\": avg_loss / (i + 1),\n \"avg_acc\": total_correct / total_element * 100,\n \"loss\": loss.item()\n }\n\n if i % self.log_freq == 0:\n data_iter.write(str(post_fix))\n\n print(\"EP%d_%s, avg_loss=\" % (epoch, str_code), avg_loss / len(data_iter), \"total_acc=\",\n total_correct * 100.0 / total_element)\n return avg_loss / len(data_iter)\n\n\nclass BertDataset(Dataset):\n def __init__(self, tokenizer, dataset, max_len=512, pad_first=True):\n self.tokenizer = tokenizer\n self.dataset = dataset\n self.max_len = max_len\n self.data_size = len(dataset)\n self.pad_first = pad_first\n\n def __len__(self):\n return self.data_size\n\n def __getitem__(self, item):\n item = self.dataset.iloc[item]\n origin_text = item['origin_text']\n random_text = item['random_text']\n label = item['label']\n\n origin_text = [self.tokenizer.convert_tokens_to_ids([x])[0] for x in origin_text]\n random_text = [self.tokenizer.convert_tokens_to_ids([x])[0] for x in random_text]\n label = [int(x) for x in label.split(' ')]\n\n pad_len = self.max_len - len(origin_text) - 2 if self.max_len-2 > len(origin_text) else 0\n if pad_len == 0:\n origin_text = origin_text[:self.max_len-2]\n random_text = random_text[:self.max_len - 2]\n label = label[:self.max_len - 2]\n\n if self.pad_first:\n origin_text = [self.tokenizer.cls_token_id]\\\n + [self.tokenizer.pad_token_id] * pad_len + origin_text\\\n + [self.tokenizer.sep_token_id]\n\n random_text = [self.tokenizer.cls_token_id]\\\n + [self.tokenizer.pad_token_id] * pad_len + random_text\\\n + [self.tokenizer.sep_token_id]\n\n label = [self.tokenizer.pad_token_id]\\\n + [self.tokenizer.pad_token_id] * pad_len + label\\\n + [self.tokenizer.pad_token_id]\n\n else:\n origin_text = [self.tokenizer.cls_token_id]\\\n + origin_text + [self.tokenizer.pad_token_id] * pad_len\\\n + [self.tokenizer.sep_token_id]\n\n random_text = [self.tokenizer.cls_token_id]\\\n + random_text + [self.tokenizer.pad_token_id] * pad_len\\\n + [self.tokenizer.sep_token_id]\n\n label = [self.tokenizer.pad_token_id]\\\n + label + [self.tokenizer.pad_token_id] * pad_len\\\n + [self.tokenizer.pad_token_id]\n output = {\n 'origin_text': origin_text,\n 'random_text': random_text,\n 'label': label\n }\n\n return {key: torch.tensor(value) for key, value in output.items()}\n\nif __name__ == '__main__':\n dataset = pd.read_csv('data/processed_data/all_same_765376/train.csv')\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n kf = KFold(n_splits=5, shuffle=True)\n for k, (train_index, val_index) in enumerate(kf.split(range(len(dataset)))):\n print('Start train {} ford'.format(k))\n config = BertConfig.from_pretrained('data/chinese_wwm_pytorch/bert_config.json')\n tokenizer = BertTokenizer.from_pretrained('data/chinese_wwm_pytorch/vocab.txt')\n bert = BertModel.from_pretrained('data/chinese_wwm_pytorch/pytorch_model.bin', config=config)\n\n train = dataset.iloc[train_index]\n val = dataset.iloc[val_index]\n train_dataset = BertDataset(tokenizer, train, max_len=152)\n train_data_loader = DataLoader(train_dataset, batch_size=8, num_workers=2)\n val_dataset = BertDataset(tokenizer, val, max_len=152)\n val_data_loader = DataLoader(val_dataset, batch_size=8, num_workers=2)\n trainer = SoftMaskedBertTrainer(bert, tokenizer, device)\n best_loss = 100000\n # for e in range(10):\n # trainer.train(train_data_loader, e)\n # val_loss = trainer.evaluate(val_data_loader, e)\n # if best_loss > val_loss:\n # best_loss = val_loss\n # trainer.save('best_model_{}ford.pt'.format(k))\n # print('Best val loss {}'.format(best_loss))\n\n trainer.load('best_model_0ford.pt')\n print(trainer.inference(val_data_loader))","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":8893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"389273095","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[4]:\n\n\nimport os\nfrom epanettools import epanet2 as et\nfrom epanettools.examples import simple\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom scipy.stats import norm\nfrom tqdm import tqdm\n\nfile = os.path.join(os.path.dirname(simple.__file__),'Austin_Pattern.inp')\n\nret=et.ENopen(file,\"Austin_Pattern.rpt\",\"\")\n\n# Network Properties\nret,nlinks=et.ENgetcount(et.EN_LINKCOUNT)\nret,nnodes=et.ENgetcount(et.EN_NODECOUNT)\n\nnodes=[]\nlinks=[]\n\nfor index in range(1,nnodes+1):\n ret,t=et.ENgetnodeid(index)\n nodes.append(t)\n\nfor index in range(1,nlinks+1):\n ret,t=et.ENgetlinkid(index)\n links.append(t) \n \npumps=[91,92,93,94,95,96,97]\nnpumps=len(pumps)\n\nimport itertools\nstatus=list(itertools.product(([0, 1]), repeat=npumps))\n\nfor x in status:\n if sum(x)>5:\n status.remove(x)\nstatus.remove((1,1,1,1,1,1,0))\n#이건 왜 안지워지는지 모르겠음\nstatus.remove((1,1,1,0,0,1,1))\nstatus.remove((1,1,0,1,0,1,1))\nstatus.remove((1,1,0,0,1,1,1))\nstatus.remove((0,0,1,1,1,1,1))\n\nncase=len(status)\n\npres_init=[]\nfor i in range(0,ncase):\n t=[]\n pres_init.append(t)\n for j in range(nnodes):\n y=[]\n pres_init[i].append(y)\n\ntime=[]\nfor i in range(ncase):\n t=[]\n time.append(t)\n \net.ENsettimeparam(et.EN_DURATION, 0)\n\nfor j in range(ncase):\n for k in range(npumps):\n et.ENsetlinkvalue(pumps[k], et.EN_INITSTATUS, status[j][k])\n \n et.ENopenH()\n et.ENinitH(0)\n\n while True:\n ret,t=et.ENrunH()\n \n for i in range(nnodes):\n ret,p=et.ENgetnodevalue(i+1, et.EN_PRESSURE)\n pres_init[j][i].append(p)\n\n ret,tstep=et.ENnextH()\n if (tstep<=0):\n break\n\n ret=et.ENcloseH()\n\ninit_40_evaluation=[]\nfor i in range(ncase):\n t=[]\n init_40_evaluation.append(t)\n\nfor i in range(ncase):\n for j in range(nnodes):\n if pres_init[i][j][0]>40:\n init_40_evaluation[i].append(1)\n\noptimal_init_status=[]\n\nfor i in range(ncase):\n if sum(init_40_evaluation[i])==125:\n optimal_init_status.append(i+1)\n \nprint(optimal_init_status)\nprint(pres_init[3])\n\n","sub_path":"7_Pumps_Optimization_Initial_Status.py","file_name":"7_Pumps_Optimization_Initial_Status.py","file_ext":"py","file_size_in_byte":2172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"423097603","text":"# -*- coding: utf-8 -*-\n\"\"\"\nPlotting portion of SLAL to render\ngraphical representations of vectors\nand matrices. \n\nUsing matplotib...\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom vector import Vector\nfrom matrix import Matrix\nfrom SLALutil import vector2list, listlist2matrix, matrix2rowlist, matrix2collist\n\ndef draw_vector(soa):\n \n X, Y, U, V = zip(*soa)\n plt.figure()\n ax = plt.gca()\n ax.quiver(X, Y, U, V, angles='xy', scale_units='xy', scale=1)\n ax.set_xlim([-1, 10])\n ax.set_ylim([-1, 10])\n plt.draw()\n\n\nM = listlist2matrix([ [ 0, 0, 3, 2],\n [ 0, 0, 1, 1],\n [ 0, 0, 9, 9] ])\nprint(M)\nv_list = matrix2collist(M)\nprint(v_list)\n\nlst = np.array([ vector2list(v) for v in v_list ])\nprint(lst)\n\ndraw_vector(lst)\nsoa =np.array( [ [0,0,3,2], [0,0,1,1],[0,0,9,9]])\n\nX, Y, U, V = zip(*soa)\nplt.figure()\nax = plt.gca()\nax.quiver(X, Y, U, V, angles='xy', scale_units='xy', scale=1)\nax.set_xlim([-1, 10])\nax.set_ylim([-1, 10])\nplt.draw()\n\nfrom pylab import *\n\n# Set limits and number points in grid\nxmax = 2.0\nxmin = -xmax\nNX = 10\nymax = 2.0\nymin = -ymax\nNY = 10\n\n","sub_path":"plotting.py","file_name":"plotting.py","file_ext":"py","file_size_in_byte":1139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"38632117","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom batchthis.models import Batch, Fermenter\n# Create your views here.\n\ndef index(request):\n\n top_batches = Batch.objects.all()[:5]\n total_batch_count = Batch.objects.all().count()\n active_batch_count = Batch.objects.filter(active=True).count()\n active_fermenters = Fermenter.objects.filter(status=Fermenter.STATUS_ACTIVE)\n\n context = {\n 'top_batches': top_batches,\n 'total_batch_count': total_batch_count,\n 'active_batch_count': active_batch_count,\n 'active_fermenters': active_fermenters\n }\n return render(request,'index.html',context=context)\n\n\n","sub_path":"views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"283939936","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.signal import spectrogram\nimport struct\nimport ipdb\n\n\ndef order_data(filename, point_index):\n \"\"\"\n \"\"\"\n #the dram has 2**24 addrs, we read this in\n #blocks of 2**13, we have 2**11 of those blocks\n #each block has 2**13*64 bytes\n\n\n dram_addrs = 2**24\n addr_size = 64\n block_size = 2**13\n block_bitesize = block_size*addr_size\n \n beg_block = point_index/block_size #begining block\n offset_beg = point_index%block_size\n \n f = file('order_data', 'a')\n\n #1 read to complete the first blocksize\n\n if (offset_beg>0):\n data = np.memmap(filename, mode='r', shape=(1, (8192-offset_beg)*addr_size), offset=beg_block*block_bitesize+offset_beg*addr_size)\n raw_data = struct.pack('>'+str(len(data[0]))+'B', *data[0])\n f.write(raw_data)\n del data\n \n #2 read from the beg_block to the end of the file\n \n n_iter = 2**11-(beg_block+1)\n\n for i in range(n_iter):\n data = np.memmap(filename, mode='r', shape=(1, block_bitesize), offset=(beg_block+1)*block_bitesize+block_bitesize*i)\n raw_data = struct.pack('>'+str(len(data[0]))+'B', *data[0])\n f.write(raw_data)\n del data\n\n #3 read from to the beg_block\n\n for i in range(beg_block):\n data = np.memmap(filename, mode='r', shape=(1, block_bitesize), offset=block_bitesize*i)\n raw_data = struct.pack('>'+str(len(data[0]))+'B', *data[0])\n f.write(raw_data)\n del data\n\n #4 read from block_size to the beginig at miss offset\n\n data = np.memmap(filename, mode='r',shape=(1,(offset_beg)*addr_size), offset=beg_block*block_bitesize)\n raw_data = struct.pack('>'+str(len(data[0]))+'B', *data[0])\n f.write(raw_data)\n del data\n f.close()\n\n \n\ndef plot_spectrogram(filename):\n dram_size = 2**30 #1Gb of data\n addr_size = 64\n bram_size = 2**13*addr_size\n\n dirs = dram_size/bram_size\n\n fft_size = 1024\n\n plot_data = np.zeros([fft_size/2+1,dirs])\n\n for i in range(dirs):\n data = np.memmap(filename, mode='r',shape=(1,bram_size), offset=bram_size*i)\n f,t,Sxx = spectrogram(data[0], fs=1080, nperseg=1024)\n plot_data[:,i] = Sxx[:,40] #40 is in the middle... check how to obtain this number\n del data\n\n fpga_clk = 67.5*10**6\n total_time = 2**24*4/(fpga_clk)\n t = np.linspace(0,total_time, dirs)\n plt.xlabel('Time[s]')\n plt.ylabel('Frequency[MHz]')\n plt.pcolormesh(t,f,20*np.log10(plot_data))\n plt.show()\n\n\n\n","sub_path":"v1/adc_input/codes/order_functs.py","file_name":"order_functs.py","file_ext":"py","file_size_in_byte":2531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"94012280","text":"# coding=utf-8\r\n# /usr/bin/env python\r\n\"\"\"\r\nAuthor:washing\r\ndate:2021/1/2 下午11:45\r\ndesc:\r\n\"\"\"\r\n# Definition for singly-linked list.\r\n# class ListNode:\r\n# def __init__(self, val=0, next=None):\r\n# self.val = val\r\n# self.next = next\r\nclass Solution:\r\n def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:\r\n return_link = ListNode(None)\r\n cur = return_link\r\n\r\n plus = 0\r\n while l1 or l2:\r\n if l1:\r\n v1 = l1.val\r\n l1 = l1.next\r\n else:\r\n v1 = 0\r\n if l2:\r\n v2 = l2.val\r\n l2 = l2.next\r\n else:\r\n v2 = 0\r\n add_together = v1 + v2 + plus\r\n ans = add_together % 10\r\n plus = add_together // 10\r\n if return_link.val == None:\r\n return_link.val = ans\r\n else:\r\n new_node = ListNode(ans)\r\n cur.next = new_node\r\n cur = cur.next\r\n\r\n if plus:\r\n cur.next = ListNode(plus)\r\n\r\n return return_link","sub_path":"Solutions/0002/0002.py","file_name":"0002.py","file_ext":"py","file_size_in_byte":1116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"318612516","text":"friends = input(\"\\n Enter the names of two people separated by &: \").lower()\r\n\r\nprint(f\"\\n You have entered {friends}\")\r\nscore = 0\r\n\r\nfor letters in friends:\r\n if letters in \"aeiou\":\r\n score += 3\r\n if letters in \"friend\":\r\n score += 5\r\n if letters in \"harsh\":\r\n score += 10\r\n\r\nif score >= 95:\r\n print(\"\\nBesties\")\r\nelif score > 75:\r\n print(\"\\n More than good friends\")\r\nelif score >=60:\r\n print(\"\\n Good friends\")\r\nelse:\r\n print(\"\\n Just friends\")\r\n\r\nprint(f\"\\n Your friendship score is {score}\")\r\n","sub_path":"frndcal.py","file_name":"frndcal.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"339510090","text":"# -*- coding: utf-8 -*-\n# Part of Nuca Erp create by Mahmudamen. See LICENSE file for full copyright and licensing details.\n\nfrom odoo import fields, models, api , _\nfrom datetime import datetime , timedelta\nfrom dateutil import relativedelta\nfrom dateutil.relativedelta import relativedelta\nimport time\nfrom datetime import datetime, date, time, timedelta\nfrom odoo.tools import date_utils\nfrom odoo.tools import DEFAULT_SERVER_DATE_FORMAT as DATE_FORMAT, DEFAULT_SERVER_DATETIME_FORMAT as DATETIME_FORMAT\n\nclass ExtendedPeriodsList(models.Model):\n _name = 'extend.extendedperiodslist'\n _description = 'extended periods list '\n _rec_name = 'subject_id'\n _inherit = ['mail.thread']\n\n subject_id = fields.Many2one('res.partner', domain=[('is_subject', '=', True)], string=\"subject\", required=True)\n entity_id = fields.Many2one('res.partner',domain=[('is_entity','=',True)],string=\"entity\", required= True)\n new_city_id = fields.Many2one('res.partner', domain=[('is_new_city', '=', True)], string=\"new city\", required=True)\n name = fields.Char(string='ID', readonly=True)\n agency_issue_date = fields.Many2many('extend.agencyissuedate' ,string='agency issue date')\n agency_issue_number = fields.Integer(string='agency issue number' , required=True)\n modified_expiration_date = fields.Many2many('extend.modifiedlist' ,string='modified expiration date')\n committee_issue_number_to_agency = fields.Many2many('extend.committeeagency' ,string='committee issue number to agency')\n advisory_opinion_issue_date = fields.Many2many('extend.advisorydate' ,string='advisory opinion issue date')\n issued_by_the_committee_to_the_advisory = fields.Many2many('extend.issuedadvisory' ,string='issued by the committee to the advisory')\n order_number = fields.Integer(string='order number')\n Administrator = fields.Many2one('res.users', 'Administrator')\n partner_address_id = fields.Many2one('res.partner', string=\"Address\", )\n low_type = fields.Selection([('Low 182', 'Low 182'), ('Low 89', 'Low 89')], string=\"Low Type\", defualt='Low 182' , required=True)\n state = fields.Selection([('planned','planned'),('today','today'),('overdue','overdue')],string=\"state\", defualt='today' )\n activity_states = fields.Char(string=\"activity state\",default='today' )\n date_start = fields.Date(string=\"Start Date\", required=True, default=fields.Date.today)\n date_end = fields.Date(string=\"End Date\", required=True, default=fields.Date.today)\n\n @api.model\n def default_get(self,fields):\n rec = super(ExtendedPeriodsList,self).default_get(fields)\n rec['state'] = 'today'\n rec['activity_states'] = 'today'\n return rec\n\n def action_planned(self):\n self.activity_states = \"planned\"\n self.state = \"planned\"\n\n def action_today(self):\n self.activity_states = \"today\"\n self.state = \"today\"\n\n def action_overdue(self):\n self.activity_states = \"overdue\"\n self.state = \"overdue\"\n\n def print_report(self):\n #data = {'date_start': self.date_start, 'date_end': self.date_end}\n return self.env.ref('extended_periods.extended_periods_document_report').report_action(self)\n\n @api.model\n def create(self,val):\n val['name'] = self.env['ir.sequence'].next_by_code('extend.extendedperiodslist')\n result = super(ExtendedPeriodsList, self).create(val)\n msg_body = 'Object created '\n for msg in self:\n msg.message_post(body=msg_body)\n return result\n\n def action_active(self):\n self.state = \"active\"\n\n def action_inactive(self):\n self.state = \"inactive\"\n\n @api.onchange('entity_id')\n def _onchange_entity(self):\n '''\n The purpose of the method is to define a domain for the available\n Entity address.\n '''\n address_id = self.entity_id\n self.partner_address_id = address_id\n\n @api.onchange('committee_issue_number_to_agency')\n def _onchange_committee_issue_number_to_agency(self):\n if self.committee_issue_number_to_agency:\n activity_states = {'activity_states': \"planned\"}\n self.update(activity_states)\n state = {'state': \"planned\"}\n self.update(state)\n\n print('planned')\n\n @api.model\n def send_notiy_agency_issue_date(self):\n\n #today = (datetime.now() + timedelta(days=+15)).strptime('%Y-%m-%d')\n\n #todays = datetime.strptime(today, '%Y-%m-%d').isocalendar()\n\n todays = date_utils.add(datetime.now() , days=-15)\n todayss = datetime.strftime(todays,'%Y-%m-%d')\n #todays= ( datetime.strptime(today, '%Y-%m-%d') + relativedelta(days =+ 30).strftime('%Y-%m-%d') )\n print(todayss)\n extended = self.env['extend.extendedperiodslist']\n extended_periods_date_expire = extended.sudo().search_read([('agency_issue_date', '=', todayss)])\n print(extended_periods_date_expire)\n domain = [('agency_issue_date', '=', todayss)]\n for rec in extended_periods_date_expire:\n print(rec.get('agency_issue_date')[0])\n self.env['mail.message'].create({'message_type':\"notification\",\n 'body': 'الموضوع داخل من 15 يوم من صادر الجهاز' + ' ' + rec.get('subject_id')[1] + ' ' + rec.get('entity_id')[1],\n 'subject': rec.get('subject_id')[1] ,\n 'model': 'extend.extendedperiodslist',\n 'parent_id':2,\n 'res_id':rec.get('id'),\n 'subtype_id': 1,\n })\n #notif_domain = [('res_partner_id', '=', 12),('is_read', '=', True),('mail_message_id','=',609)]\n #print(notif_domain)\n #notifications = self.env['mail.notification'].sudo().search(notif_domain)\n #notifications.write({'is_read': False})\n extended_periods_date_expire = self.env['mail.message'].sudo().search_read([] ,order='id desc')[0]\n print(extended_periods_date_expire['id'])\n company_info ={\n 'mail_message_id': extended_periods_date_expire['id'],\n 'is_read': False,\n 'res_partner_id': 12,\n 'notification_type':'inbox',\n 'notification_status':'sent',\n }\n self.env['mail.notification'].create(company_info)\n\n @api.model\n def send_notiy_committee_issue_number_to_agency(self):\n\n #today = (datetime.now() + timedelta(days=+15)).strptime('%Y-%m-%d')\n\n #todays = datetime.strptime(today, '%Y-%m-%d').isocalendar()\n\n todays = date_utils.add(datetime.now() , days=+21)\n todayss = datetime.strftime(todays,'%Y-%m-%d')\n #todays= ( datetime.strptime(today, '%Y-%m-%d') + relativedelta(days =+ 30).strftime('%Y-%m-%d') )\n print(todayss)\n extended = self.env['extend.extendedperiodslist']\n extended_periods_date_expire = extended.sudo().search_read([('modified_expiration_date', '=', todayss)])\n print(extended_periods_date_expire)\n domain = [('modified_expiration_date', '=', todayss)]\n for rec in extended_periods_date_expire:\n print(rec.get('modified_expiration_date')[0])\n self.env['mail.message'].create({'message_type':\"notification\",\n 'body': 'الموضوع فاضل ع��ي تاريخ النهو المقرر 3 اسبابيع من صادر اللجنة للجهاز' + ' ' + rec.get('subject_id')[1] + ' ' + rec.get('entity_id')[1],\n 'subject': rec.get('subject_id')[1],\n 'model': 'extend.extendedperiodslist',\n 'parent_id':3,\n 'res_id': rec.get('id'),\n 'subtype_id': 1,\n })\n #notif_domain = [('res_partner_id', '=', 3),('is_read', '=', True),('mail_message_id','=',42)]\n #print(notif_domain)\n #notifications = self.env['mail.notification'].sudo().search(notif_domain)\n #notifications.write({'is_read': False})\n extended_periods_date_expire = self.env['mail.message'].sudo().search_read([] ,order='id desc')[0]\n print(extended_periods_date_expire)\n company_info ={\n 'mail_message_id': extended_periods_date_expire['id'],\n 'is_read': False,\n 'res_partner_id': 12,\n 'notification_type':'inbox',\n 'notification_status':'sent',\n }\n self.env['mail.notification'].create(company_info)","sub_path":"models/extended_periods_list.py","file_name":"extended_periods_list.py","file_ext":"py","file_size_in_byte":8999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"129770274","text":"\ndata = [\n (\"data/ecmp50_fct.csv\", \"ECMP\", 'k', 'o'),\n (\"data/drill50_fct.csv\", \"DRILL\", 'dodgerblue', 'X'),\n (\"data/dibs50_fct.csv\", \"DIBS\", 'r', 'v'),\n (\"data/valinor_sch50_fct.csv\", \"Vertigo\", 'springgreen', '|')\n]\n\nconfig = {\n \"name\" : \"qps50fct\",\n \"xticks\": 9,\n \"x\": [55, \"\", 65, \"\", 75, \"\", 85, \"\", 95],\n \"xlabel\": \"Aggregate Network Load %\",\n \"ylabel\": \"Mean FCT (s)\",\n \"legend\": False,\n \"ylim_min\": -0.01,\n \"ylim_max\": 1\n}\n\n\n# [55, 60, 65, 70, 75, 80, 85, 90, 95]","sub_path":"figure5/PARAMETERS_50_fct.py","file_name":"PARAMETERS_50_fct.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"626793308","text":"# Parses https://publications.parliament.uk/pa/cm201516/cmhansrd/cm160211/debtext/160211-0001.htm#16021143000004\n# into a CSV File of Topic-Speaker-Speech\n\n\nimport lxml\nimport csv\nfrom bs4 import BeautifulSoup\n\ninfile = open('House of Commons Hansard Debates for 11 Feb 2016 (pt 0001).htm', 'r')\noutfile = open('House_of_Commons_outfile.csv', 'w')\nwriter = csv.writer(outfile)\n\nsoup = BeautifulSoup(infile, 'lxml')\n\n\n# Create a list of all h3 and p elements\nsoup_find_all = soup.find_all(['h3', 'p'])\n# print(len(soup_find_all))\n\ni = 0\nheading = []\nheading_trailer = []\nspeaker = []\nspeeches = []\nspeech = ''\n\nwhile i < len(soup_find_all):\n if soup_find_all[i].name == 'h3':\n heading.append(soup_find_all[i].text)\n i += 1\n while i < len(soup_find_all) and soup_find_all[i].name == 'p':\n heading_trailer.append(heading[-1]) # Create a list of headings associated with each paragraph\n if soup_find_all[i].b is not None:\n # If the paragraph starts with a bold element\n speaker.append(soup_find_all[i].b.text[:-1]) # Strip off trailing colon (\":\")\n # Remove the element containing the name of the speaker\n soup_find_all[i].b.decompose()\n if soup_find_all[i].text == '':\n # If the paragraph consisted only of a bold element (That means it is a date, which needs to be removed.)\n try:\n speaker[-1] = speaker[-2] # Reset to the name of the speaker of the previous paragraph\n except: # If we should be at the very first paragraph\n pass\n i += 1\n continue\n else:\n # If the paragraph had text after the bold element, append that text to the speech\n speeches.append(soup_find_all[i].text.strip())\n else:\n # if the paragraph does not start with a bold element, add its speech to the previous one\n speeches.append(soup_find_all[i].text.strip())\n\n try: # check if we are at the very beginning of the file\n if speaker[-1] == speaker[-2]:\n # If we stay with the same speaker, just append to the speech string\n i += 1\n continue\n else:\n # If there was a switch between speakers\n for j in speeches[:-1]:\n speech += j + ' '\n\n # Write the CSV file up to the second last element (because the heading and speaker has changed at the last element)\n writer.writerow([heading_trailer[-2], speaker[-2], speech[:-1].replace('\\n', '')]) # Strip the last space \" \" from the speech\n speech = ''\n speeches = [speeches[-1]] # Trim the speeches element up to the last element\n speaker = [speaker[-1]] # Trim the speakers up to the last element\n i += 1\n except:\n i += 1\n continue\n else:\n i += 1\n\n\noutfile.close()","sub_path":"BeautifulSoup.py","file_name":"BeautifulSoup.py","file_ext":"py","file_size_in_byte":3181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"58538199","text":"import scrapy\nimport json\nimport csv\nimport os\nimport ssl\nfrom urllib import request\n\nif (not os.environ.get('PYTHONHTTPSVERIFY', '') and getattr(ssl, '_create_unverified_context', None)):\n ssl._create_default_https_context = ssl._create_unverified_context\n\nclass ConstruSpider(scrapy.Spider):\n name = \"construtechs\"\n startup_list = []\n\n def start_requests(self):\n\n urls = [\n 'https://constructapp.io/pt/100-startups-de-construcao-civil/'\n ]\n\n for url in urls:\n yield scrapy.Request(url=url, callback=self.parse)\n\n def parse(self, response):\n\n startup_data = response.xpath('/html/body/div[1]/div/div[2]/div[1]/div[1]/table/tbody/tr[position()>1]')\n \n for startup in startup_data:\n \n if startup.xpath('td[3]/text()').get() is None:\n ocupation = startup.xpath('td[3]/strong/text()').get()\n else:\n ocupation = startup.xpath('td[3]/text()').get()\n\n self.startup_list.append({\n \"name\": startup.css('td a::text').get(),\n \"ocupation\": ocupation\n })\n\n for num, startup in enumerate(startup_data, start=0):\n\n url = startup.xpath('td[2]/a/@href').get()\n \n if url is not None:\n yield scrapy.Request(url, callback=self.parse_startup_links, meta={'index': num})\n else:\n self.startup_list[num][\"url\"] = \"null\"\n\n def parse_startup_links(self, response):\n url = response.xpath('//*[@id=\"company_header\"]/div[1]/h1/small/a/@href').get()\n if url is not None:\n self.startup_list[response.meta.get('index')][\"url\"] = url\n else:\n self.startup_list[response.meta.get('index')][\"url\"] = \"null\"\n\n def get_sharedcount(self):\n for startup in self.startup_list:\n try:\n if startup[\"url\"] == \"null\":\n startup[\"facebook_count\"] = \"null\"\n print('invalid url')\n else:\n request_url = 'https://api.sharedcount.com/v1.0/?apikey=91aeac3cae7c46160618baba16dcb1f5df782761&url=' + startup[\"url\"]\n resource = request.urlopen(request_url)\n content = json.loads(resource.read().decode('utf-8'))\n startup[\"facebook_count\"] = content[\"Facebook\"][\"total_count\"]\n print(content)\n except KeyError as e:\n print('I got a KeyError - reason \"%s\"' % str(e))\n print(startup)\n\n def __del__(self):\n print('iniciando sharedCount')\n self.get_sharedcount()\n print('gerando CSV')\n with open('construtechs_spider.csv', 'w') as f: \n w = csv.DictWriter(f, self.startup_list[0].keys())\n w.writeheader()\n for row in self.startup_list:\n w.writerow(row)\n print('DONE')\n","sub_path":"constru_crawl/spiders/constru_spider.py","file_name":"constru_spider.py","file_ext":"py","file_size_in_byte":2937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"461309455","text":"from Place import Place, Door\nfrom Item import Item\n\nintro_text = ('You wake up, sprawled on the floor in a small space. You don\\'t '\n'feel too good and your brain feels foggy.')\n\ncloset = Place(name='Closet', description='You appear to be in a storage closet '\n 'of some kind.', door_north=Door(description='A simple wooden door.',\n key_id='closet_door'))\nhallway1 = Place(name='Hallway', description='You are standing in a hallway.')\nhallway2 = Place(name='Hallway', description='You are standing in a hallway.')\n\ncloset.north = hallway1\nhallway1.east = hallway2\n\ninitial_location = closet\n","sub_path":"NewWorld.py","file_name":"NewWorld.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"47074723","text":"# --------------------------------------------------------------------------- #\n# File Name :: ec_ssh.py\n# Purpose :: ElectricCommanderSSH over SSH for ectool or ec_perl\n# --------------------------------------------------------------------------- #\n\n\n# When REST API is not applicable with an older version of ElectricCommanderSSH\n# we can use a ssh session to execute command on a remote machine\n\nimport logging\n\n# authentication credential store\nimport netrc\n\nimport xmltodict, json\n\n# https://github.com/paramiko/paramiko\nimport paramiko\nimport re\n\n\nclass ElectricCommanderSSH(object):\n\n def __init__(self, settings):\n\n self.log = logging.getLogger()\n\n self.settings = settings\n self.ssh = None\n self.stdin = None\n self.stdout = None\n\n self.connect()\n\n def __exit__(self):\n if self.ssh:\n self.ssh.close()\n\n def connect(self):\n\n # default is $HOME/.netrc\n info = netrc.netrc()\n user, account, passwd = info.authenticators(self.settings.ec_ssh_server)\n\n self.log.info('Connecting via SSH server for EC tools ...')\n\n self.ssh = paramiko.SSHClient()\n self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n self.ssh.connect(self.settings.ec_ssh_server, username=user, password=passwd, port=22, timeout=10)\n\n self.log.info('SSH connection established')\n\n channel = self.ssh.invoke_shell()\n #channel.process('export PS1=\"EC>\"')\n\n self.log.info('Shell invoked on SSH channel!')\n\n self.stdin = channel.makefile('wb')\n self.stdout = channel.makefile('r')\n self.stderr = channel.makefile_stderr('rb')\n\n self.login()\n\n def login(self):\n\n # default is $HOME/.netrc\n info = netrc.netrc()\n\n # create a session\n login_user, login_account, login_passwd = info.authenticators(self.settings.ec_server)\n login_passwd = login_passwd.replace('!', '\\!')\n self.log.info('ectool login ...')\n self.execute('login \"%s\" \"%s\"' % (login_user, login_passwd), log_print=False)\n self.log.info('...ectool login success!')\n\n def _print_exec_out(self, cmd, out_buf, err_buf, exit_status):\n self.log.info('command executed: \\n\\n{}\\n\\n'.format(cmd))\n self.log.info('STDOUT:')\n self.log.info('\\n' + ''.join(out_buf))\n self.log.info('STDERR:')\n self.log.error('\\n' + ''.join(err_buf))\n self.log.info('end of STDERR')\n self.log.info('finished with exit status: {}'.format(exit_status))\n self.log.info('------------------------------------')\n\n def execute(self, ec_exec, log_print=True):\n\n cmd = '%s --server %s ' % (self.settings.ec_tool, self.settings.ec_server)\n #cmd = '%s ' % self.settings.ec_tool\n cmd += ec_exec\n cmd = cmd.strip('\\n')\n\n if log_print:\n self.log.info('write cmd=\\n\\n%s\\n\\n' % cmd)\n self.stdin.write(cmd + '\\n')\n finish = 'end of STDOUT buffer. finished with exit status'\n echo_cmd = 'echo {} $?'.format(finish)\n self.stdin.write(echo_cmd + '\\n')\n self.stdin.flush()\n\n shout = []\n sherr = []\n exit_status = 0\n for line in self.stdout:\n if str(line).startswith(cmd) or str(line).startswith(echo_cmd):\n # up for now filled with shell junk from stdin\n shout = []\n elif str(line).startswith(finish):\n # our finish command ends with the exit status\n # exit_status = self.stdout.channel.recv_exit_status() # status is 0\n exit_status = int(str(line).rsplit(' ', 1)[1])\n if exit_status:\n # stderr is combined with stdout.\n # thus, swap sherr with shout in a case of failure.\n sherr = shout\n shout = []\n break\n else:\n if self.settings.ec_sh_prompt in line:\n line = line.split(self.settings.ec_sh_prompt)[0]\n #if cmd.strip() in line:\n # line = ''\n #if echo_cmd.strip() in line:\n # # the last line may mixed with shell prompt PS1\n # line = line.split('qftfemto')[0]\n # get rid of 'coloring and formatting' special characters\n shout.append(re.compile(r'(\\x9B|\\x1B\\[)[0-?]*[ -/]*[@-~]').sub('', line).\n replace('\\b', '').replace('\\r', ''))\n\n # first and last lines of shout/sherr contain a prompt\n if shout and echo_cmd in shout[-1]:\n shout.pop()\n if shout and cmd in shout[0]:\n shout.pop(0)\n if sherr and echo_cmd in sherr[-1]:\n sherr.pop()\n if sherr and cmd in sherr[0]:\n sherr.pop(0)\n\n if log_print:\n self._print_exec_out(cmd=cmd, out_buf=shout, err_buf=sherr, exit_status=exit_status)\n\n return {'exit': exit_status, 'out': shout, 'error': sherr}\n\n def abort_job(self, job_id):\n\n return self.execute('abortJob %s --force 1' % job_id)\n\n def delete_job(self, job_id):\n\n return self.execute('deleteJob %s' % job_id)\n\n def job_properties(self, job_id):\n\n result = self.execute('getProperties --jobId %s' % job_id, log_print=False)\n if result['exit'] == 0:\n # parse XML\n o = xmltodict.parse('\\n'.join(result['out']))\n result['details'] = o['response']\n return result\n\n def job_status_info(self, job_id, details=False):\n\n if details:\n result = self.execute('getJobInfo %s' % job_id)\n else:\n result = self.execute('getJobStatus %s' % job_id)\n if result['exit'] == 0:\n # parse XML\n o = xmltodict.parse('\\n'.join(result['out']))\n #self.log.info('\\n\\n%s\\n\\n' % json.dumps(o, indent=4))\n if details:\n job = o['response']['job']\n result['details'] = job\n result['outcome'] = str(job['outcome'])\n result['status'] = str(job['status'])\n else:\n result['outcome'] = str(o['response']['outcome'])\n result['status'] = str(o['response']['status'])\n\n return result\n\n def get_job_id(self, **kwargs):\n \"\"\"\n au_label, SI, crm_build_id, build_type, subtype, make_arg, target\n \"\"\"\n job_params = []\n for k, v in kwargs.iteritems():\n job_params.append('%s=\"%s\"' % (k, v))\n return self.execute(\n 'runProcedure Femto_Common '\n '--procedureName \"generate_crm_build_one_subtype_from_filer\" '\n '--actualParameter' + \" \".join(job_params))\n","sub_path":"SC/pyfsmsync/pyfsmsync/ec_ssh.py","file_name":"ec_ssh.py","file_ext":"py","file_size_in_byte":6755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"260390838","text":"import pygame\nimport random\nimport time\nimport math\nimport Helpers\n\npygame.font.init()\n\nclass Sys:\n screen = None\n screen_height, screen_width = None, None\n\n FrameRate = None\n\n\nclass Mode_1:\n initiated = False\n Frame = 0\n TotalFrames = 600\n mode = 1\n\n WaterGraphValues = [] # Should be around 300 Values\n CarbonGraphValues = [] # Should also be around 300 values\n HumGraphValues = [] # Around 150 as well\n\n BoxText = Helpers.Font.GetFont(27, semilight=True)\n PercentText = Helpers.Font.GetFont(20, semilight=True)\n YakimText = None\n EmptyGraph = None\n\n GraphValues = []\n\n BBposition = (0, 1050)\n BBimage = None\n\n TopData = []\n RadarPoints = []\n\n Advanced = False\n\n @staticmethod\n def init():\n # Create WaterGraphValues for use\n def GraphSin(FrameRate, Frame, Scale, UseThird=False): # Uses Trig to create values\n \"\"\"\n In the form of sin(InnerFirst) + sin(InnerSecond)\n :param FrameRate: Period of function, essentially\n :param Frame: Which frame it's on now (x value)\n :return: rounded to 3 decimal places. \n \"\"\"\n First = math.radians(2 * (360 / FrameRate) * Frame)\n Second = math.radians((360 / FrameRate) * Frame)\n Third = math.radians(2 * (360 / FrameRate) * Frame/4) if UseThird else 0\n sin = math.sin(First) + math.sin(Second) + math.sin(Third)\n return round(Scale * sin, 3)\n\n # Use GraphSin() to generate WaterGraph and CarbonGraph Values\n for i in range(Mode_1.TotalFrames): # For each of the grames\n Mode_1.WaterGraphValues.append(round(GraphSin(150, i, 10))) # Create Water normal Values\n Mode_1.CarbonGraphValues.append(round(GraphSin(50, i, 3)))\n Mode_1.HumGraphValues.append(round(GraphSin(300, i, 8, UseThird=1)))\n\n # print(Mode_1.WaterGraphValues)\n\n def TopChartWork(Frame): # Create the positions of the Nitrogen and Oxygen necessary\n # Takes in the Frame number and returns the percentage of each Nitrogen and Oxygen\n Nitrogen = math.radians((360 / 300) * Frame) # Based on the Frame Int\n Oxygen = math.radians(2*(360 / 300) * Frame)\n\n f_Nitrogen = round(10 * math.sin(Nitrogen))\n f_Oxygen = round(5 * math.sin(Oxygen))\n\n return (f_Nitrogen, f_Oxygen)\n\n for i in range(Mode_1.TotalFrames): # For each of the frames \n Mode_1.TopData.append(TopChartWork(i)) # Add to the TopRow cycle values\n\n Mode_1.YakimText = pygame.image.load('Assets/Yakim01.png')\n Mode_1.EmptyGraph = pygame.image.load(\"Assets/EmptyGraph.png\")\n\n # Generate 14 values for GraphValues[] for the actual graph\n for i in range(15): # this is so there are values when the graph starts graphing\n Mode_1.GraphValues.append(Mode_1.CreateGraphPoints(mode=1))\n\n Mode_1.BBimage = pygame.image.load('Assets/YakimBottomBar.png')\n\n Mode_1.initiated = True\n\n @staticmethod\n def CreateChart(x_position, text, data, color, text_color=None, start=360, y_position=80):\n \"\"\"\n Used 3 times, can create the individual charts on the top right that slowly fill and decrease\n :param x_position: Where each one should start, x wise\n :param text: What the text should read above it\n :param data: What it should use for the variations\n :param color: Its color\n :param text_color: The color of the text (defaults to black)\n :param start: What value should it start at? 0-400 (recommended: 360)\n :param y_position: Where should the y position be (defaults to 80)\n :return: One of the item boxes\n \"\"\"\n if not text_color: # Set default text color to black\n text_color = (0, 0, 0)\n BoxPosition = (x_position, y_position, 80, 400)\n # Set Up Words First\n TextWidth, TextHeight = Mode_1.BoxText.size(text) # Get estimate of size\n TextPosition = (BoxPosition[0] + (80-TextWidth)/2, y_position - 35) # Adjust position to center it\n\n Text = Mode_1.BoxText.render(text, True, (0, 0, 0)) # Create text object\n Sys.screen.blit(Text, TextPosition) # Blit to screen\n\n # Now set up the box that moves\n BlueBoxPosition = (x_position, 400 + y_position, 80, -start - data[Mode_1.Frame-1]) # Adjust box pos based on variation\n BlueBox = pygame.Rect(BlueBoxPosition) # Create object\n pygame.draw.rect(Sys.screen, color, BlueBox) # Blit it\n\n BlueBoxOutline = pygame.Rect(BlueBoxPosition) # Outline of the box object\n pygame.draw.rect(Sys.screen, Helpers.Color(\"Black\"), BlueBoxOutline, 2) # Blit it\n\n Outline = pygame.Rect(BoxPosition) # Full Outline\n pygame.draw.rect(Sys.screen, Helpers.Color(\"Black\"), Outline, 2) # Blit\n\n # Percent Text\n Percent = str(round((start+data[Mode_1.Frame-1])*100/400)) + \"%\" # Text Percentage\n PercentTextWidth, PercentTextHeight = Mode_1.PercentText.size(Percent) # Estimate size\n\n PercentPos = (x_position + (80 - PercentTextWidth)/2, 400 + y_position -start-data[Mode_1.Frame-1]) # Center it\n PercentTextFinal = Mode_1.PercentText.render(Percent, True, text_color) # Render the Percentage Text\n Sys.screen.blit(PercentTextFinal, PercentPos) # Blit it\n\n @staticmethod\n def TopChart():\n \"\"\"\n The Fundamental Theorem of Yakim\n :return: A bigass chart that tells the composition of the atmosphere\n \"\"\"\n TopChartPosition = (20, 70, 1240, 60)\n TotalLength = 1240\n\n # Nitrogen\n NitrogenPosition = (TopChartPosition[0], TopChartPosition[1])\n NitrogenLength = 0.75 * TotalLength + Mode_1.TopData[Mode_1.Frame][0]\n NitrogenTotal = NitrogenPosition + (NitrogenLength, TopChartPosition[3])\n\n NitrogenBox = pygame.Rect(NitrogenTotal) # Insides of Nitrogen\n pygame.draw.rect(Sys.screen, Helpers.Color(\"Purple\"), NitrogenBox) # Blit it\n pygame.draw.rect(Sys.screen, Helpers.Color(\"Black\"), NitrogenBox, 1) # Outline it!\n\n # Oxygen\n OxygenPosition = (NitrogenLength + TopChartPosition[0], TopChartPosition[1])\n OxygenLength = 0.2 * TotalLength + Mode_1.TopData[Mode_1.Frame][1]\n OxygenTotal = OxygenPosition + (OxygenLength, TopChartPosition[3])\n\n OxygenBox = pygame.Rect(OxygenTotal) # Insides of Nitrogen\n pygame.draw.rect(Sys.screen, Helpers.Color(\"Blue\"), OxygenBox) # Blit it\n pygame.draw.rect(Sys.screen, Helpers.Color(\"Black\"), OxygenBox, 1) # Outline it!\n\n # Remaining\n RemainingLength = TotalLength - OxygenLength - NitrogenLength\n if RemainingLength % 2 != 0:\n RemainingLength = ((RemainingLength-1)/2, (RemainingLength+1)/2)\n else:\n RemainingLength = (RemainingLength/2, RemainingLength/2)\n\n # Argon\n ArgonPosition = (NitrogenLength + OxygenLength + TopChartPosition[0], TopChartPosition[1])\n ArgonLength = int(RemainingLength[0])\n ArgonTotal = ArgonPosition + (ArgonLength, TopChartPosition[3])\n\n ArgonBox = pygame.Rect(ArgonTotal) # Insides of Argon\n pygame.draw.rect(Sys.screen, Helpers.Color(\"Yellow\"), ArgonBox) # Blit it\n pygame.draw.rect(Sys.screen, Helpers.Color(\"Black\"), ArgonBox, 1) # Outline it!\n\n # Other\n OtherPosition = (ArgonPosition[0] + ArgonLength, TopChartPosition[1])\n OtherLength = int(RemainingLength[1])\n OtherTotal = OtherPosition + (OtherLength, TopChartPosition[3])\n\n OtherBox = pygame.Rect(OtherTotal) # Insides of Argon\n pygame.draw.rect(Sys.screen, Helpers.Color(\"RedOrange\"), OtherBox) # Blit it\n pygame.draw.rect(Sys.screen, Helpers.Color(\"Black\"), OtherBox, 1) # Outline it!\n\n # Full Outline\n FullOutline = pygame.Rect(TopChartPosition) # Outline of the box object\n pygame.draw.rect(Sys.screen, Helpers.Color(\"Black\"), FullOutline, 2) # Blit it\n\n ### TEXT\n # Nitrogen\n NiSize = Mode_1.BoxText.size(\"Nitrogen\")\n NiPos = (NitrogenTotal[0] + NitrogenLength - NiSize[0]-5, NitrogenTotal[1]+6)\n NiText = Mode_1.BoxText.render(\"Nitrogen\", True, (0, 0, 0)) # Render the Percentage Text\n Sys.screen.blit(NiText, NiPos) # Blit it\n\n # Oxygen\n OxySize = Mode_1.BoxText.size(\"Oxygen\")\n OxyPos = (OxygenTotal[0] + OxygenLength - OxySize[0] - 5, OxygenTotal[1] + 6)\n OxyText = Mode_1.BoxText.render(\"Oxygen\", True, (0, 0, 0)) # Render the Percentage Text\n Sys.screen.blit(OxyText, OxyPos) # Blit it\n\n @staticmethod\n def CreateGraphPoints(mode=1, margin=(0, 350)):\n \"\"\"\n Returns y value of node for point\n \"\"\"\n if mode == 1:\n mid = margin[1]/2\n range = (mid-30, mid+30)\n return random.randint(range[0], range[1])\n elif mode == 2:\n return random.randint(margin[0], margin[1])\n\n @staticmethod\n def GenerateNewPoint():\n if Mode_1.mode == 1:\n if random.randrange(2) == 1:\n return\n del Mode_1.GraphValues[0]\n Mode_1.GraphValues.append(Mode_1.CreateGraphPoints(mode=Mode_1.mode))\n\n @staticmethod\n def GenGraph():\n Sys.screen.blit(Mode_1.EmptyGraph, (660, 600))\n poslist = []\n x_pos = 620\n\n for point in Mode_1.GraphValues:\n x_pos += 40\n pos = (x_pos, 600 + point)\n poslist.append(pos)\n\n pygame.draw.lines(Sys.screen, Helpers.Color(\"Black\"), False, poslist, 3)\n\n for point in poslist:\n circledpoint = pygame.draw.circle(Sys.screen, Helpers.Color(\"Blue\"), point, 8)\n circledpoint = pygame.draw.circle(Sys.screen, Helpers.Color(\"White\"), point, 4)\n\n # Big Text\n Text = \"Cloud Pressure Variations\"\n\n TextWidth, TextHeight = Mode_1.BoxText.size(Text) # Estimate size\n TextPos = (660+int((580-TextWidth)/2), 600)\n TextObj = Mode_1.BoxText.render(Text, True, (0, 0, 0)) # Create text object\n Sys.screen.blit(TextObj, TextPos) # Blit to screen\n\n @staticmethod\n def BottomBar():\n Sys.screen.blit(Mode_1.BBimage, Mode_1.BBposition)\n\n @staticmethod\n def Radar():\n center = (330, 800)\n radius = 200\n # Create the general outline of the radar\n pygame.draw.circle(Sys.screen, Helpers.Color(\"DarkWhite\"), center, radius)\n pygame.draw.circle(Sys.screen, Helpers.Color(\"White\"), center, radius, 8)\n pygame.draw.circle(Sys.screen, Helpers.Color(\"Black\"), center, radius, 4)\n\n # Generate the sweeping line\n Radians = math.radians(Mode_1.Frame/300*360)\n Coords = (round(200 * math.cos(Radians)), round(200 * math.sin(Radians)))\n final_Coords = (center[0] + Coords[0], center[1] + Coords[1])\n \n # Draw positioning lines\n pygame.draw.line(Sys.screen, Helpers.Color(\"Black\"), (center[0], center[1]-radius),\n (center[0], center[1]+radius))\n pygame.draw.line(Sys.screen, Helpers.Color(\"Black\"), (center[0] - radius, center[1]),\n (center[0] + radius, center[1]))\n \n # Draw the Sweeping Line\n pygame.draw.line(Sys.screen, Helpers.Color(\"Black\"), center, final_Coords, 7)\n pygame.draw.line(Sys.screen, Helpers.Color(\"White\"), center, final_Coords, 2)\n \n # Draw circle in the center\n pygame.draw.circle(Sys.screen, Helpers.Color(\"Black\"), center, 10)\n pygame.draw.circle(Sys.screen, Helpers.Color(\"DarkWhite\"), center, 8)\n\n # Generate a few random points\n if Mode_1.Frame % 60 == 0: # Every 2 seconds\n dummy_list = []\n for point in Mode_1.RadarPoints: # For every established point\n if random.randint(0, 1): # 50% chance itll keep that point\n dummy_list.append(point)\n\n if Mode_1.mode == 2:\n limit = random.randint(10, 30)\n elif Mode_1.mode == 1:\n limit = 10\n\n # Limits them to 10 points. Fills in remaining points. \n for i in range(limit-len(dummy_list)): # Make the extra points\n angle = math.radians(random.randint(0, 360)) # Random angle\n scale = random.randint(20, 180) # Random Vector Length\n Coords = (round(scale * math.cos(angle)), round(scale * math.sin(angle))) # Generate Coords based on those two\n final_Coords = (center[0] + Coords[0], center[1] + Coords[1]) # Set with (0, 0) in the center of the graph\n\n dummy_list.append(final_Coords) # Add the new coord\n\n Mode_1.RadarPoints = dummy_list # Save this list\n\n for point in Mode_1.RadarPoints: # For each point created / established\n pygame.draw.circle(Sys.screen, Helpers.Color(\"Black\"), point, 5) # Create Black Outline\n pygame.draw.circle(Sys.screen, Helpers.Color(\"DarkWhite\"), point, 3) # Create Inside white\n\n # Create Text to show abovewards\n Text = \"Atmospheric Electrostatic Variations\" \n TextWidth, TextHeight = Mode_1.BoxText.size(Text) # Estimate size\n TextPos = (40 + int((580 - TextWidth) / 2), 560)\n TextObj = Mode_1.BoxText.render(Text, True, (0, 0, 0)) # Create text object\n Sys.screen.blit(TextObj, TextPos) # Blit to screen\n \n return\n\n @staticmethod\n def Advance():\n # Only run if its not set up and if it's at the 0 frame\n if Mode_1.Advanced:\n return\n if Mode_1.Frame != 0:\n return\n for i in range(Mode_1.TotalFrames):\n Mode_1.WaterGraphValues[i] = Mode_1.WaterGraphValues[i] * 2\n Mode_1.CarbonGraphValues[i] = Mode_1.CarbonGraphValues[i] * 3\n Mode_1.HumGraphValues[i] = Mode_1.HumGraphValues[i] * 3\n\n Mode_1.mode = 2\n Mode_1.Advanced = True\n print(\"Beginning Cataclysm\")\n\n @staticmethod\n def Run():\n if Mode_1.Frame >= 300: # For all the circular motion, ensure it knows the correct frame\n Mode_1.Frame = 0\n else:\n Mode_1.Frame += 1\n\n Sys.screen.blit(Mode_1.YakimText, (20, 150)) # Blit the image\n\n # Set up Graphs on sidebar\n GraphYPos = 170\n Mode_1.CreateChart(1160, \"Water\", Mode_1.WaterGraphValues, Helpers.Color(\"Blue\"), y_position=GraphYPos)\n Mode_1.CreateChart(1040, \"Carbon\", Mode_1.CarbonGraphValues, Helpers.Color(\"Gray\"), text_color=(255, 255, 255), y_position=GraphYPos)\n Mode_1.CreateChart(920, \"Humidity\", Mode_1.HumGraphValues, Helpers.Color(\"Teal\"), start=300, y_position=GraphYPos)\n\n # Set up Topbar\n Mode_1.TopChart() # Wowzers\n\n # Chart\n Mode_1.GenGraph()\n Mode_1.Radar()\n\n Mode_1.BottomBar()\n\n\nclass Mode_5:\n data = {\n \"System\": \"Atmospherics\",\n \"Dialogue\": [\"Scanning for Clouds\", \"Checking Radar\",\n \"Calculating Storm Percentages\", \"Checking Rain Requirements\",\n \"Regulating Temperature\", \"Deploying Major Correctment\",\n \"Accelorating Desert Storm\", \"Rebooting to Mainframe\"]\n }\n\ndef Navigator(mode: int, unit=0):\n if mode == 1 or mode == 2:\n if not Mode_1.initiated:\n Mode_1.init()\n\n if not unit:\n Mode_1.Run()\n if mode == 2:\n Mode_1.Advance()\n elif unit == 0.5:\n Mode_1.GenerateNewPoint()\n","sub_path":"Yakim.py","file_name":"Yakim.py","file_ext":"py","file_size_in_byte":15637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"270527206","text":"\"\"\"Profiling code.\"\"\"\n\nimport cProfile\nimport io\nimport pstats\nimport contextlib\n\n\ndef start():\n \"\"\"Start and return profiler.\"\"\"\n profiler = cProfile.Profile()\n profiler.enable()\n return profiler\n\n\ndef finish(profiler):\n \"\"\"Stop the profiler and print out stats.\"\"\"\n profiler.disable()\n out_stream = io.StringIO()\n profile_stats = pstats.Stats(\n profiler, stream=out_stream).sort_stats('cumulative')\n profile_stats.print_stats(30)\n print(out_stream.getvalue())\n\n\n@contextlib.contextmanager\ndef profiled(enabled):\n \"\"\"Context manager to profile within a given context.\"\"\"\n profiler = None\n if enabled:\n profiler = start()\n try:\n yield\n finally:\n if profiler is not None:\n finish(profiler)\n","sub_path":"mtg_ssm/profiling.py","file_name":"profiling.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"499102927","text":"\"\"\"\nГлавный модуль отвечающий за пользовательский интерфейс и ввод данных\n\nСписок функций:\n\ngreeting() - Вывод приветственного сообщения\n\nmain_menu_text() - Вывод текста главного меню\"\n\ninput_err() - Сообщение о некорректном вводе\n\ngoodbye() - Прощальное сообщение\n\nfull_text() - Вывод полного текста заданий\n\nstart_test1() - Ввод данных для решения первого задания\n\nstart_test2() - Ввод данных для решения второго задания\n\nmain_menu() - Главное меню\n\"\"\"\n\n\nimport test1\nimport test2\n\n\ndef greeting():\n \"\"\"Вывод приветственного сообщения\"\"\"\n print('Здравстуйте, вас приветствует программа - решение тестовых задач от Школы программистов HeadHunter.')\n print('Выполнил Гиль Григорий')\n\n\ndef main_menu_text():\n \"\"\"Вывод текста главного меню\"\"\"\n print('Введите:')\n print('1 для решения первой задачи')\n print('2 для решения второй задачи')\n print('3 для вывода текста задач')\n print('4 для выхода')\n\n\ndef input_err():\n \"\"\"Сообщение о некорректном вводе\"\"\"\n print('Некорректный ввод')\n\n\ndef goodbye():\n \"\"\"Прощальное сообщение\"\"\"\n print('Всего доброго.')\n\n\ndef full_text():\n \"\"\"Вывод полного текста заданий\"\"\"\n print('Задача 1. Медиана\\nДаны два отсортированных числовых массива одинаковой длины N. Найдите медиану числового массива длины 2N, содержащего все числа из двух данных массивов.')\n print('Задача 2. Бесконечная последовательность\\nВозьмём бесконечную цифровую последовательность, образованную склеиванием последовательных положительных чисел: S = 123456789101112131415...\\nОпределите первое вхождение заданной последовательности A в бесконечной последовательности S (нумерация начинается с 1).')\n\n\ndef start_test1():\n \"\"\"Ввод данных для решения первого задания\"\"\"\n arr1 = []\n arr2 = []\n print('Введите значение первого массива через запятую')\n while True:\n try:\n inp = input().split(',')\n for a in inp:\n arr1.append(int(a))\n except:\n input_err()\n continue\n break\n print('Введите значение второго массива через запятую')\n while True:\n try:\n inp = input().split(',')\n for a in inp:\n arr2.append(int(a))\n if arr1.__len__() != arr2.__len__():\n input_err()\n break\n except:\n input_err()\n continue\n break\n print('Ответ = ', test1.find_m(arr1, arr2))\n\n\ndef start_test2():\n \"\"\"Ввод данных для решения второго задания\"\"\"\n print('Введите числовую последовательность.')\n while True:\n try:\n seq = int(input())\n if seq <= 0:\n input_err()\n continue\n break\n except:\n input_err()\n continue\n print('Ответ = ', test2.count(seq))\n\n\ndef main_menu():\n \"\"\"Главное меню\"\"\"\n greeting()\n while True:\n main_menu_text()\n inp = input()\n try:\n point = int(inp)\n except:\n input_err()\n continue\n if point == 1:\n start_test1()\n elif point == 2:\n start_test2()\n elif point == 3:\n full_text()\n elif point == 4:\n break\n else:\n input_err()\n continue\n goodbye()\n\n\nif __name__ == '__main__':\n main_menu()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"310252963","text":"from django.http import HttpResponse \nfrom django.shortcuts import render, redirect\nfrom .forms import *\nfrom .models import *\n# Create your views here.\ndef product_list(request):\n if request.method == 'GET': \n \n # getting all the objects of product. \n Products = Product.objects.all() \n return render(request, 'viewcart.html',{'product_list' : Products})\n\n\n \ndef product_form_view(request): \n \n if request.method == 'POST': \n form = ProductForm(request.POST, request.FILES) \n \n if form.is_valid(): \n form.save() \n return redirect('success') \n else: \n form = ProductForm() \n return render(request, 'productForm.html', {'form' : form}) \n \n \ndef success(request): \n return render(request, ('success.html'))\n\n\ndef display_product(request): \n \n if request.method == 'GET': \n \n # getting all the objects of product. \n Products = Product.objects.all() \n return render(request, 'product_list.html',{'product_list' : Products})\n\ndef add_to_cart(request):\n Products = Product.objects.get(pk=request.POST.get('productid'))\n \n return render(request, 'viewcart.html',{'Products':Products})\n \n\ndef address(request):\n if request.method == 'POST': \n form = AddressForm(request.POST, request.FILES) \n \n if form.is_valid(): \n form.save() \n return redirect('payment') \n else: \n form = AddressForm() \n return render(request, 'address.html', {'form' : form}) \n\ndef payment(request):\n if request.method == 'POST': \n form = PaymentForm(request.POST,request.FILES)\n\n if form.is_valid(): \n form.save()\n else:\n form = PaymentForm()\n return render(request, 'payment.html', {'form' : form})\n\n\ndef thank_you(request):\n return render(request, 'thankyou.html')\n\n\n","sub_path":"app3/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"251675098","text":"import requests\n\nfrom keycloak_scanner.custom_logging import find, verbose\nfrom keycloak_scanner.properties import add_kv\nfrom keycloak_scanner.scan import Scan\n\nURL_PATTERN = '{}/auth/realms/{}/clients-registrations/default/security-admin-console'\n\n\nclass SecurityConsoleScan(Scan):\n\n def perform(self, launch_properties, scan_properties):\n\n base_url = launch_properties['base_url']\n realms = list(scan_properties['realms'].keys())\n for realm in realms:\n url = URL_PATTERN.format(base_url, realm)\n r = requests.get(url)\n if r.status_code != 200:\n verbose('Bad status code for {}: {}'.format(url, r.status_code))\n else:\n find('Find a security-admin-console {}: {}'.format(url, r.status_code))\n add_kv(scan_properties, 'security-admin-console', realm, r.json())\n if 'secret' in scan_properties['security-admin-console'][realm]:\n find('Find secret for realm {} : {}'\n .format(realm, scan_properties['security-admin-console'][realm]['secret']))\n\n","sub_path":"keycloak_scanner/security_console_scanner.py","file_name":"security_console_scanner.py","file_ext":"py","file_size_in_byte":1114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"486125610","text":"#!/usr/bin/env python\n\n\"\"\"This script draws a boxplot of each atom contribution to the cavity.\"\"\"\n\n\nimport sys\n\nif sys.version < \"2.7\":\n print >> sys.stderr, \"ERROR: This script requires Python 2.7.x. \"\\\n \"Please install it and try again.\"\n exit(1)\n\ntry:\n import matplotlib.pyplot as pyplot\n import numpy\nexcept ImportError:\n print >> sys.stderr, \"ERROR:\",\n print >> sys.stderr, \"This script requires matplotlib and numpy. \"\\\n \"Please make sure you installed it and that \"\\\n \"your PYTHONPATH is set adequately.\"\n exit(1)\n\n\ndef parse_args():\n import argparse\n import os.path\n\n def isfile(path):\n Error = argparse.ArgumentTypeError\n if not os.path.exists(path):\n raise Error(\"No such file: '{0}'\".format(path))\n elif not os.path.isfile(path):\n raise Error(\"Not a valid file: '{0}'\".format(path))\n return path\n\n hf = lambda prog: argparse.HelpFormatter(prog, max_help_position=50)\n parser = argparse.ArgumentParser(description=__doc__, formatter_class=hf)\n parser.add_argument(\"filename\", type=isfile,\n help=\"contribution data file\")\n parser.add_argument(\"-o\", \"--output\",\n help=\"output file name\")\n parser.add_argument(\"-n\", type=int, default=0,\n help=\"show n greatest contributions\")\n parser.add_argument(\"-s\", \"--stdev\", action=\"store_true\",\n help=\"only plot standard deviations\")\n parser.add_argument(\"-r\", metavar=\"residue\", nargs=\"+\",\n help=\"plot specific residues along time\")\n return parser.parse_args()\n\n\ndef die(s):\n print >> sys.stderr, \"ERROR:\", s\n exit(1)\n\n\ndef show_usage():\n print >> sys.stderr, \"usage: python \" + sys.argv[0] + \" \"\n\n\ndef read_contrib(fname):\n data = []\n with open(fname, \"rt\") as f:\n for line in f:\n split = line.split()\n k = split[0]\n counts = [int(c) for c in split[2:]]\n data.append((k, counts))\n return data\n\n\ndef med(x):\n x = sorted(x)\n length = len(x)\n if not length % 2:\n return (x[length / 2] + x[(length - 1) / 2]) / 2.0\n return float(x[length / 2])\n\n\ndef plot_sd(data):\n x = numpy.array([i+1 for i in range(len(data[0]))])\n d = numpy.std(data[1], axis=1)\n pyplot.bar(x, d)\n pyplot.xticks(x+.5, data[0], rotation=90)\n ylim = pyplot.ylim()\n pyplot.ylim((ylim[0]-10, ylim[1]+10))\n pyplot.xlim((x[0]-1, x[-1]+1))\n pyplot.subplots_adjust(left=0.1, right=0.9, top=0.95, bottom=0.2)\n pyplot.title(\"Residue contribution standard deviations\")\n\n\ndef plot_barplot(data):\n x = [i+1 for i in range(len(data[0]))]\n pyplot.boxplot(data[1])\n pyplot.xticks(x, data[0], rotation=90)\n ylim = pyplot.ylim()\n pyplot.ylim((ylim[0]-10, ylim[1]+10))\n pyplot.subplots_adjust(left=0.1, right=0.9, top=0.95, bottom=0.2)\n pyplot.title(\"Residue contribution\")\n\n\ndef plot_residues(data, residues):\n def running_average(x, N):\n return numpy.convolve(x, numpy.ones((N,))/N)[(N-1):]\n if \"all\" in residues:\n residues = data[0]\n for r in residues:\n try:\n i = data[0].index(r)\n except:\n die(\"No residue named '{0}'\".format(r))\n# y = running_average(data[1][i], 5)\n y = data[1][i]\n pyplot.plot(y, label=r)\n pyplot.legend(loc=\"best\")\n\n\ndef main():\n args = parse_args()\n data = read_contrib(args.filename)\n\n if args.n:\n data = sorted(data, key=lambda x: med(x[1]), reverse=True)\n data = data[:args.n]\n\n data = zip(*data)\n\n if args.r:\n plot_residues(data, args.r)\n elif args.stdev:\n plot_sd(data)\n else:\n plot_barplot(data)\n\n if args.output:\n pyplot.savefig(args.output)\n else:\n pyplot.show()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"plot_contribution.py","file_name":"plot_contribution.py","file_ext":"py","file_size_in_byte":3933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"448369794","text":"import sys\n#treenode object\nclass TreeNode(object):\n def __init__(self, value):\n self.value = value\n self.children = []\n\n def addChild(self, node):\n self.children.append(node)\n\n def getValue(self):\n return self.value\n\n def getChildren(self):\n return self.children \n\ndef mkCh(amount, coins):\n #this algorithm will brute-force the problem to find all coin combinations, and then choose the smallest amount\n #create first level of tree\n root = TreeNode(0)\n for i in range(0, len(coins), 1):\n if amount-coins[i]>=0:\n root.addChild(TreeNode(coins[i]))\n #call helper method to build tree of all possible payments from root\n for i in range(0, len(root.children), 1):\n mkChHelper(root.children[i], amount-root.children[i].getValue(), coins)\n\n return getShortestDepth(root)[0][:-1]\n\n#optimizes the solution by finding the lowest depth in the tree\ndef getShortestDepth(root):\n #if leaf node return value\n if(root.children==[]):\n return [[root.value], 1]\n #otherwise grab leftmost child\n smallest = getShortestDepth(root.children[0])\n #find the shortest subtree, with each child being a root\n for i in range(1, len(root.children),1):\n current = getShortestDepth(root.children[i])\n if(current[1]=0:\n newChild = TreeNode(coins[i])\n node.getChildren().append(newChild)\n mkChHelper(newChild, amount-coins[i], coins)\n return None\n\nif __name__ == \"__main__\":\n #coinset used\n coins = [1,3,4]\n #amount needed to pay, in cents\n amount = 6\n #make change\n change = mkCh(amount, coins)\n #output\n print(\"Amount Change Needed For: \" + str(amount))\n print(\"Optimal Payment: \" + str(change))\n sum = 0\n for i in range(0, len(change), 1):\n sum = sum+change[i]\n print(\"Was it payable? \" + str(sum==amount))","sub_path":"SimpleDynamicProgramming/SimpleDynamicProgramming.py","file_name":"SimpleDynamicProgramming.py","file_ext":"py","file_size_in_byte":2208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"573429405","text":"# Project Euler\n# Problem 51 - Prime Digit Replacements\n# Copyright (c) Project Chang. All rights reserved.\n# Author: Sammy Chang\n#\n# https://github.com/schang1146/project_euler\n\nimport time\n\n\ndef isprime(n):\n factors = []\n for i in range(1,int(n**(1/2)) + 1):\n if n % i == 0:\n factors.append(i)\n\n if len(factors) > 1:\n return False\n\n return True\n\n\ndef function(candidate, min_primes):\n answer = 0\n\n # While loop will run until an answer has been found.\n # The answer will be the smallest number with a family of\n # 'min_primes' prime numbers.\n while answer == 0:\n\n # Only count prime candidates for speed.\n if isprime(candidate) == True:\n\n # Create a hash table to know how many numbers will\n # be replaced.\n keys = sorted([int(num) for num in list(set(list(str(candidate)[:-1])))])\n values = [str(candidate)[:-1].count(str(num)) for num in keys]\n hash = {k:v for k,v in zip(keys, values)}\n\n # Replace keys with range(0,10) unless first number\n # of candidate == key, then range(1,10).\n for key in keys: \n num_composites = 0\n replacements = range(0,10)\n\n if key == int(str(candidate)[0]):\n replacements = range(1,10)\n\n for replacement in replacements:\n if replacement != key:\n if isprime(int(str(candidate)[:-1].replace(str(key), str(replacement)) + str(candidate)[-1])) == False:\n num_composites += 1\n\n if num_composites > len(replacements) - min_primes:\n break\n\n if num_composites <= len(replacements) - min_primes:\n answer = candidate\n break\n\n candidate += 2\n \n\n return answer\n\n\nif __name__ == \"__main__\":\n startTime = time.time()\n print('Answer:', function(56003,9))\n print('runtime:', time.time()-startTime, 'sec')\n","sub_path":"python/p051.py","file_name":"p051.py","file_ext":"py","file_size_in_byte":2075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"544539827","text":"\"\"\"gol URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.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.contrib import admin\nfrom django.contrib.auth import views as auth_views\nfrom django.shortcuts import redirect\nfrom django.urls import path\n\nfrom gol.endpoints import parse_rules, submit, step, user_create\nimport gol.views as views\n\nurlpatterns = [\n path('', views.index),\n path('admin/', admin.site.urls),\n path('login', auth_views.LoginView.as_view(), name='login'),\n path('logout', auth_views.LogoutView.as_view(), name='logout'),\n path('accounts/profile/', lambda request: redirect('/', permanent=False)),\n path('rules/parse', parse_rules),\n path('klikatko', views.simulation),\n path('task/', views.task),\n path('task//submit', submit),\n path('task//step', step),\n path('help', views.help),\n path('usercreate', user_create),\n path('monitor', views.monitor),\n path('results.csv', views.results_csv),\n path('pdfscan/', views.pdf_submission_id),\n path('pdfscan', views.my_pdf_submission),\n]\n","sub_path":"gol/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"343642457","text":"print('{:=^60}'.format('CLASSIFICAÇÃO DOS PESOS!'))\nmaior = 0\nmenor = 0\nfor pessoas in range(1,6):\n peso=int(input('Digite o peso da {}ª pessoa:'.format(pessoas)))\n if pessoas == 1:\n maior = peso\n menor = peso\n else:\n if peso > maior:\n maior = peso\n elif peso < menor:\n menor = peso\nprint('O maior peso medido foi de {} KG.'.format(maior))\nprint('O menor peso medido foi de {} KG.'.format(menor))","sub_path":"maior e menor peso digitados.py","file_name":"maior e menor peso digitados.py","file_ext":"py","file_size_in_byte":454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"65709199","text":"'''\r\nCreated on 6 dec. 2016\r\n\r\n@author: Dell\r\n'''\r\nimport datetime\r\n\r\nfrom movie.domain.entities.MostActiveClientsDTO import MostActiveClientsDTO\r\nfrom movie.domain.entities.MostRentedDTO import MostRentedBookDTO\r\nfrom movie.domain.entities.RentedMovieDTO import RentedMovieDTO\r\nfrom movie.domain.entities.LateRentalDTO import LateRentlaDTO\r\nfrom util.Containers import MyList, Sorter\r\n\r\n\r\nclass StatisticsControler(object):\r\n '''\r\n classdocs\r\n '''\r\n\r\n def __init__(self, rentalRepository, movieRepository, clientRepository):\r\n self.__rentalRepository = rentalRepository\r\n self.__movieRepository = movieRepository\r\n self.__clientRepository = clientRepository\r\n \r\n \r\n def __mostRentedMovies(self):\r\n '''\r\n Returns rented movies DTO'S\r\n '''\r\n listOfDTOs = MyList()\r\n r = self.__rentalRepository.get_all()\r\n \r\n for movie in self.__movieRepository.get_all():\r\n \r\n numOfRents = 0\r\n for rent in r:\r\n if movie.entityId == rent.movieId:\r\n numOfRents += 1\r\n \r\n if numOfRents != 0:\r\n listOfDTOs.append(MostRentedBookDTO(movie.entityId, movie.entityName, numOfRents))\r\n \r\n return listOfDTOs\r\n \r\n def mostRentedMovies(self):\r\n return list(Sorter.sort(self.__mostRentedMovies(),reverse=True))\r\n\r\n def __mostActiveClients(self):\r\n '''\r\n Returns active clients dto\r\n '''\r\n listOfDTOs = MyList()\r\n \r\n for elem in self.__clientRepository.get_all():\r\n \r\n numOfDays = 0\r\n for rent in self.__rentalRepository.get_all():\r\n if elem.entityId == rent.clientId:\r\n numOfDays += ((datetime.date.today() if rent.returnedDate is None \r\n else rent.returnedDate) - rent.rentedDate).days\r\n \r\n listOfDTOs.append(MostActiveClientsDTO(elem.entityId, elem.entityName, numOfDays))\r\n \r\n return listOfDTOs\r\n \r\n def mostActiveClients(self):\r\n return list(Sorter.sort(self.__mostActiveClients(), reverse=True))\r\n \r\n def searchClient(self, keyword):\r\n ''' Looks for any matching in name for fields of each Client and returns\r\n the list of matches'''\r\n \r\n listOfMatches = MyList()\r\n \r\n keyword = keyword.lower()\r\n for e in self.__clientRepository.get_all():\r\n if keyword in str(e.entityId): \r\n listOfMatches.append(e)\r\n continue\r\n if keyword in e.entityName.lower():\r\n listOfMatches.append(e)\r\n continue\r\n \r\n return listOfMatches\r\n \r\n def searchMovies(self, keyword):\r\n ''' Looks for any matching in name for fields of each Movie and returns\r\n the list of matches'''\r\n \r\n listOfMatches = MyList()\r\n \r\n keyword = keyword.lower()\r\n for e in self.__movieRepository.get_all():\r\n if keyword in str(e.entityId): \r\n listOfMatches.append(e)\r\n continue\r\n if keyword in e.entityName.lower():\r\n listOfMatches.append(e)\r\n continue\r\n if keyword in e.entityDescription.lower():\r\n listOfMatches.append(e)\r\n continue\r\n if keyword in e.entityGenre.lower():\r\n listOfMatches.append(e)\r\n continue\r\n \r\n return listOfMatches\r\n \r\n def __findActiveRentalByMovieId(self, movieId):\r\n #If the movie is still rented, returns the rent, otherwise returns None\r\n for rent in self.__rentalRepository.get_all():\r\n if movieId == rent.movieId:\r\n if rent.returnedDate is None:\r\n return rent\r\n return None \r\n \r\n def allRentedMovies(self):\r\n \r\n rentedMoviesDTOs = MyList()\r\n \r\n for movie in self.__movieRepository.get_all():\r\n rental = self.__findActiveRentalByMovieId(movie.entityId)\r\n if not rental is None:\r\n client = self.__clientRepository.find_by_id(rental.clientId)\r\n rentedMoviesDTOs.append(RentedMovieDTO(client.entityId, client.entityName, \\\r\n movie.entityId, movie.entityName))\r\n return rentedMoviesDTOs\r\n \r\n def __lateRentedMovies(self):\r\n \r\n \r\n rentedMoviesDTOs = []\r\n \r\n for movie in self.__movieRepository.get_all():\r\n rental = self.__findActiveRentalByMovieId(movie.entityId)\r\n if not rental is None:\r\n today = datetime.date.today()\r\n if today > rental.dueDate:\r\n client = self.__clientRepository.find_by_id(rental.clientId)\r\n rentedMoviesDTOs.append(LateRentlaDTO(client.entityId, client.entityName, \\\r\n movie.entityId, movie.entityName, \\\r\n (today - rental.dueDate).days))\r\n return rentedMoviesDTOs\r\n \r\n def lateRentedMovies(self):\r\n return list(Sorter.sort(self.__lateRentedMovies(),reverse=True))","sub_path":"Fundamentals of Programming/Laboratory9/MovieRental2/src/movie/ctrl/StatisticsControler.py","file_name":"StatisticsControler.py","file_ext":"py","file_size_in_byte":5395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"456108389","text":"# Syntax: noaa_forecast [OPTIONS ...]\n\"\"\"NOAA weather forecast tool\n\nSYNOPSIS\n\nShell:\n bash$ gridlabd noaa_forecast -p|-position=LAT,LON [-i|--interpolate=TIME|METHOD]\n [-g|--glm=GLMNAME] [-n|--name=OBJECTNAME] [-c|--csv=CSVNAME] [--test] [-h|--help|help]\n\nGLM:\n #python -m noaa_forecast -p|-position=LAT,LON [-i|--interpolate=TIME|METHOD]\n [-g|--glm=GLMNAME] [-n|--name=OBJECTNAME] [-c|--csv=CSVNAME] [--test] [-h|--help|help]\n #include \"GLMNAME\"\n\nPython:\n bash$ gridlabd python\n >>> import noaa_forecast as nf\n >>> nf.getforecast(37.5,-122.3)\n temperature[degF] wind_speed[m/s] wind_dir[deg]\n 2021-10-21 14:00:00-07:00 68.000000 4.470400 202.500000\n 2021-10-21 15:00:00-07:00 65.327601 4.275738 201.983153\n 2021-10-21 16:00:00-07:00 62.990829 4.099336 201.673044\n ... ... ... ...\n 2021-10-28 06:00:00-07:00 57.284721 2.770949 315.450517\n 2021-10-28 07:00:00-07:00 55.246212 2.946331 315.403079\n 2021-10-28 08:00:00-07:00 53.000000 3.129280 315.000000\n\n [163 rows x 3 columns]\n\n\nDESCRIPTION\n\nThis module downloads weather forecasts from NOAA and writes GLM files. This can be done from\nthe command line or using call the python API.\n\nInterpolation is usually necessary because the data samples received from NOAA span several hours.\nThe default interval is 60 minutes, but can be set to any integer value in minutes. The sampling\nmethod is by default quadratic. Other interpolation methods supported include \n\n - linear\n\n Ignore the index and treat the values as equally spaced. This is the only method \n supported on MultiIndexes.\n\n - time\n\n Works on daily and higher resolution data to interpolate given length of interval.\n\n - index, values\n\n Use the actual numerical values of the index.\n\n - pad\n\n Fill in NaNs using existing values.\n\n - nearest, zero, slinear, quadratic, cubic, spline, barycentric, polynomial\n\n Passed to scipy.interpolate.interp1d. These methods use the numerical values of the index. \n Both ‘polynomial’ and ‘spline’ require that you also specify an order (int), e.g. \n df.interpolate(method='polynomial', order=5).\n\n - krogh, piecewise_polynomial, spline, pchip, akima, cubicspline\n\n Wrappers around the SciPy interpolation methods of similar names. See Notes.\n\n - from_derivatives\n\n Refers to scipy.interpolate.BPoly.from_derivatives which replaces ‘piecewise_polynomial’ \n interpolation method in scipy 0.18.\n\nPARAMETERS\n\nThe module uses several parameters to control its behavior. \n\n server = \"https://api.weather.gov/points/{latitude},{longitude}\" # NOAA location server (provides forecast URL)\n user_agent = \"(gridlabd.us, gridlabd@gmail.com)\" # default user agent to report to NOAA\n date_format = \"%Y-%m-%d %H:%M:%S\"\n float_format=\"%.1f\" # float format to use \n interpolate_time = 60\n interpolate_method = 'quadratic'\n\nThe parameters can be changed before obtained the forecast.\n\n >>> import noaa_forecast as nf\n >>> nf.interpolate = 5\n >>> nf.getforecast(37.5,-122.3)\n\nEXAMPLE\n\nThe following command downloads only the CSV data for a location:\n\n bash$ gridlabd noaa_forecast -p=45.62,-122.70 -c=test.csv\n\nThe following command downloads the CSV data and creates a GLM file with the data linked and weather object named:\n\n bash$ gridlabd noaa_forecast -p=45.62,-122.70 -c=test.csv -n=test -g=test.glm\n\nSEE ALSO\n\n* [https://www.weather.gov/documentation/services-web-api]\n\"\"\"\n\nimport sys, os, json, requests, pandas, numpy, datetime, dateutil, time\n\nserver = \"https://api.weather.gov/points/{latitude},{longitude}\"\nuser_agent = \"(gridlabd.us, gridlabd@gmail.com)\"\ninterpolate_time = 60\ninterpolate_method = 'quadratic'\nfloat_format = \"%.1f\"\ndate_format = \"%Y-%m-%d %H:%M:%S\"\nmax_retries = 5\n\ndef getforecast(lat,lon):\n \"\"\"Get NOAA location\"\"\"\n url = server.format(latitude=lat,longitude=lon)\n headers = {'User-agent' : user_agent}\n location = json.loads(requests.get(url,headers=headers).content.decode(\"utf-8\"))\n\n data = {}\n result = {\n \"datetime\" : [],\n \"temperature[degF]\" : [],\n \"wind_speed[m/s]\" : [],\n \"wind_dir[deg]\" : [],\n }\n\n cur_tries = 0\n while cur_tries <= max_retries:\n data = json.loads(requests.get(location[\"properties\"][\"forecastHourly\"],headers=headers).content.decode(\"utf-8\"))\n if \"properties\" in data.keys():\n break\n time.sleep(2)\n cur_tries += 1\n\n\n if not \"properties\" in data.keys():\n raise Exception(f\"data does not contain required properties information (data={data})\")\n if not \"periods\" in data[\"properties\"]:\n raise Exception(f\"data does not contain required period information (data={data})\")\n for item in data[\"properties\"][\"periods\"]:\n result[\"datetime\"].append(dateutil.parser.parse(item[\"startTime\"])+datetime.timedelta(hours=item[\"number\"]))\n result[\"temperature[degF]\"].append(float(item[\"temperature\"]))\n result[\"wind_speed[m/s]\"].append(float(item[\"windSpeed\"].split()[0])*0.44704)\n result[\"wind_dir[deg]\"].append(dict(\n N=0, NNE=22.5, NE=45, ENE=67.5, E=90, ESE=112.5, SE=135, SSE=157.5,\n S=180, SSW=202.5, SW=225, WSW=247.5, W=270, WNW=292.5, NW=315, NNW=337.5,\n )[item[\"windDirection\"]])\n df = pandas.DataFrame(result).set_index(\"datetime\")\n if interpolate_time:\n starttime = df.index.min()\n stoptime = df.index.max()\n if starttime.tzinfo.utcoffset != stoptime.tzinfo.utcoffset:\n dt = stoptime - starttime\n stoptime = starttime + dt\n daterange = pandas.DataFrame(index=pandas.date_range(starttime,stoptime,freq=f\"{interpolate_time}min\"))\n df = df.join(daterange,how=\"outer\").interpolate(interpolate_method)\n df.index.name = \"datetime\"\n return df\n\ndef writeglm(data, glm=sys.stdout, name=None, csv=None,download_now=True):\n \"\"\"Write weather object based on NOAA forecast\"\"\"\n if glm:\n if csv == 'auto' or csv == None:\n if type(glm) is str:\n csv = glm.replace(\".glm\",\".csv\")\n else:\n raise Exception(\"csv name is required when glm is not a filename\")\n if type(glm) is str:\n glm = open(glm,\"w\")\n glm.write(\"class forecast\\n{\\n\")\n for column in data.columns:\n glm.write(f\"\\tdouble {column};\\n\")\n glm.write(\"}\\n\")\n data.columns = list(map(lambda x:x.split('[')[0],data.columns))\n glm.write(\"module tape;\\n\")\n glm.write(\"#define NOAA_FORECAST_TIMEZONE=${SHELL gridlabd timezone local}\\n\")\n glm.write(f\"#define NOAA_FORECAST_STARTTIME={data.index.min().isoformat('T')}\\n\")\n glm.write(f\"#define NOAA_FORECAST_STOPTIME={data.index.max().isoformat('T')}\\n\")\n glm.write(\"object forecast\\n{\\n\")\n if name:\n glm.write(f\"\\tname \\\"{name}\\\";\\n\")\n glm.write(\"\\tobject player\\n\\t{\\n\")\n glm.write(f\"\\t\\tfile \\\"{csv}\\\";\\n\")\n glm.write(f\"\\t\\tproperty \\\"{','.join(data.columns)}\\\";\\n\")\n glm.write(\"\\t};\\n\")\n glm.write(\"}\\n\")\n if download_now:\n data.to_csv(csv,header=False,float_format=float_format,date_format=date_format)\n else:\n if csv == None:\n csv = \"/dev/stdout\"\n elif csv == 'auto':\n raise Exception(\"csv cannot be automatically named if GLM is not specified\")\n data.to_csv(csv,header=True,float_format=float_format,date_format=date_format)\n\nif __name__ == \"__main__\":\n def error(msg,code=None):\n if code != None:\n print(f\"ERROR [noaa_forecast.py]: {msg}\",file=sys.stderr)\n exit(code)\n else:\n raise Exception(msg)\n def syntax(code=0):\n if code == 0:\n print(__doc__)\n else:\n print(f\"Syntax: {os.path.basename(sys.argv[0]).replace('.py','')} -p -position=LAT,LON [-i|--interpolate=TIME|METHOD] [-g|--glm=GLMNAME] [-n|--name=OBJECTNAME] [-c|--csv=CSV] [--test] [-h|--help|help]\")\n exit(code)\n position = None\n glm = None\n name = None\n csv = None\n for arg in sys.argv[1:]:\n args = arg.split(\"=\")\n if type(args) is list and len(args) > 1:\n token = args[0]\n value = args[1]\n elif type(args) is list:\n token = args[0]\n value = None\n else:\n token = args\n value = None\n if token in [\"-h\",\"--help\",\"help\"]:\n syntax()\n elif token in [\"-p\",\"--position\"]:\n position = value.split(\",\")\n if len(position) != 2:\n error(\"position is not a tuple\")\n elif token in [\"-i\",\"--interpolate\"]:\n try:\n interpolate_time = int(value)\n except:\n if value:\n interpolate_method = value\n else:\n interpolate_time = None\n elif token in [\"-g\",\"--glm\"]:\n glm = value\n elif token in [\"-n\",\"--name\"]:\n name = value\n elif token in [\"-c\",\"--csv\"]:\n csv = value\n elif token in [\"-r\",\"--retries\"]:\n try:\n max_retries = int(value)\n max_retries = abs(max_retries)\n except ValueError:\n print(\"Retries can only use integer values\")\n print(\"Running default maximum of 5 retries\")\n max_retries = 5\n elif token == \"--test\":\n position = [45.62,-122.70]\n glm = \"test.glm\"\n name = \"test\"\n writeglm(getforecast(float(position[0]),float(position[1])),glm,name,csv)\n exit(os.system(f\"gridlabd {glm}\"))\n else:\n error(f\"option '{token}' is not valid\")\n if position:\n writeglm(getforecast(float(position[0]),float(position[1])),glm,name,csv)\n else:\n syntax(1)\n\n\n","sub_path":"tools/noaa_forecast.py","file_name":"noaa_forecast.py","file_ext":"py","file_size_in_byte":10081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"368709563","text":"import asyncio\n\nfrom ..base import DBTestCase, postgres_only\nfrom ..example_app.tables import Manager\n\n\n@postgres_only\nclass TestPool(DBTestCase):\n async def _create_pool(self):\n await Manager._meta.db.start_connnection_pool()\n await Manager._meta.db.close_connnection_pool()\n\n async def _make_query(self):\n await Manager._meta.db.start_connnection_pool()\n\n await Manager(name=\"Bob\").save().run()\n response = await Manager.select().run()\n self.assertTrue(\"Bob\" in [i[\"name\"] for i in response])\n\n await Manager._meta.db.close_connnection_pool()\n\n async def _make_many_queries(self):\n await Manager._meta.db.start_connnection_pool()\n\n await Manager(name=\"Bob\").save().run()\n\n async def get_data():\n response = await Manager.select().run()\n self.assertEqual(response, [{\"id\": 1, \"name\": \"Bob\"}])\n\n await asyncio.gather(*[get_data() for _ in range(500)])\n\n await Manager._meta.db.close_connnection_pool()\n\n def test_creation(self):\n \"\"\"\n Make sure a connection pool can be created.\n \"\"\"\n asyncio.run(self._create_pool())\n\n def test_query(self):\n \"\"\"\n Make several queries using a connection pool.\n \"\"\"\n asyncio.run(self._make_query())\n\n def test_many_queries(self):\n \"\"\"\n Make sure the connection pool is working correctly, and we don't\n exceed a connection limit - queries should queue, then succeed.\n \"\"\"\n asyncio.run(self._make_many_queries())\n","sub_path":"tests/engine/test_pool.py","file_name":"test_pool.py","file_ext":"py","file_size_in_byte":1559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"88226132","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\nimport win32com\nfrom win32com.client import Dispatch\nimport os\nfrom datetime import datetime, timedelta\n\n\ndef close_excel_by_force(excel):\n import win32process\n import win32gui\n import win32api\n import win32con\n import time\n\n # Get the window's process id's\n hwnd = excel.Application.Hwnd\n t, p = win32process.GetWindowThreadProcessId(hwnd)\n # Ask window nicely to close\n win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0)\n # Allow some time for app to close\n time.sleep(5)\n # If the application didn't close, force close\n try:\n handle = win32api.OpenProcess(win32con.PROCESS_TERMINATE, 0, p)\n if handle:\n win32api.TerminateProcess(handle, 0)\n win32api.CloseHandle(handle)\n except:\n pass\n\n\ndef fillSheet(sht):\n\n print(sht.name)\n xlsApp.Sheets(sht.name).Select()\n # print(sht.UsedRange.Value)\n # print(sht.UsedRange.Rows.Count)\n # print(sht.UsedRange.Columns.Count)\n\n # 从第二行开始顺序读取每一行,如果C列日期中断则补齐,如果重复则标记底色,其他列复制上一行\n preDate = datetime.strptime(sht.Cells(2, 4).Value, '%Y-%m-%d') + timedelta(days=-1)\n print(\"begin preDate=\", preDate.strftime('%Y-%m-%d'))\n\n row = 2\n\n while row < sht.UsedRange.Rows.Count + 1 :\n\n curDate = datetime.strptime(sht.Cells(row, 4).Value, '%Y-%m-%d')\n print(preDate.strftime('%Y-%m-%d'), curDate.strftime('%Y-%m-%d'))\n\n # 判断当前日期是否和上一日连续\n if curDate != preDate + timedelta(days=1):\n\n # 不连续,判断是否和上一日相同\n if curDate == preDate:\n print('same date')\n # 设置底色提醒\n sht.Cells(row, 4).Interior.ColorIndex = 7\n sht.Cells(row - 1, 4).Interior.ColorIndex = 7\n\n else:\n print('insert row')\n # 补足到上一日之间的缺失日期\n sht.Rows(row - 1).Select()\n xlsApp.Selection.Copy()\n sht.Rows(row).Select()\n xlsApp.Selection.Insert()\n # 修改C/D列\n curDate = preDate + timedelta(days=1)\n sht.Cells(row, 4).Value = curDate.strftime('%Y-%m-%d')\n sht.Cells(row, 4).Interior.ColorIndex = 19\n sht.Cells(row, 3).Value = '复制'\n\n preDate = curDate\n row += 1\n\n\nif __name__ == '__main__':\n\n try:\n\n # pythoncom.CoInitialize()\n\n xlsApp = win32com.client.DispatchEx('Excel.Application')\n # 禁用事件\n xlsApp.EnableEvents = False\n # 禁止弹窗\n xlsApp.DisplayAlerts = False\n\n # 准备待加工文件\n cwd = os.getcwd()\n srcFile = cwd + '\\\\srcData.xls'\n dstFile = cwd + '\\\\dstData.xls'\n # os.system('copy {0} {1}'.format(srcFile, dstFile))\n\n wb = xlsApp.Workbooks.Open(srcFile)\n # 屏蔽弹窗\n wb.Checkcompatibility = False\n # 1:打开宏,2:禁用宏\n wb.RunAutoMacros(2)\n # 插入复制\n xlsApp.CutCopyMode = False\n\n for sht in wb.Worksheets:\n fillSheet(sht)\n\n wb.SaveAs(dstFile)\n wb.Close()\n\n # pythoncom.CoUninitialize()\n\n except Exception as e:\n print('except:', e)\n\n finally:\n #print('finally...')\n xlsApp.DisplayAlerts = True\n xlsApp.Application.Quit()\n # xlsApp.Quit()\n # del xlsApp\n close_excel_by_force(xlsApp)\n\n print('END')","sub_path":"src/直销激励/fillForm.py","file_name":"fillForm.py","file_ext":"py","file_size_in_byte":3584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"74767515","text":"import discord\nimport discord.utils\nimport emojiRole\nimport token1\nimport ast\n\nfrom datetime import datetime\nfrom random import seed\nfrom random import randint\nfrom discord.ext import commands\n\nseed(datetime.now())\n\nbot = commands.Bot(command_prefix='!')\n\n@bot.command()\nasync def ping(ctx):\n \"Returns pong\"\n await ctx.send('pong')\n\n@bot.command()\nasync def say(ctx, *, arg):\n \"Says what you put\"\n await ctx.send(arg)\n\n@bot.command(hidden=True)\nasync def secret(ctx, *, arg):\n await ctx.send(arg)\n await ctx.message.delete()\n\nmessageDict = emojiRole.message\nwith open('roles.txt', 'r') as f:\n s = f.read()\n if not s:\n pass\n else:\n messageDict = ast.literal_eval(s.replace(\"\\\\\\\\\", \"\\\\\"))\n\nwatched_message = {}\n\nwith open('dict.txt', 'r') as f:\n s = f.read()\n if not s:\n pass\n else:\n watched_message = ast.literal_eval(s)\n\nemojiList = {}\n\n@bot.command()\n@commands.has_any_role('Cody', 'Dallas')\nasync def addMessage(ctx):\n \"Adds the Role Messages\"\n global messageDict\n global watched_message\n global emojiList\n for mess,emolist in messageDict.items():\n reacted_message = await ctx.send(mess)\n watched_message[reacted_message.id] = emolist\n f = open(\"dict.txt\", \"w\")\n f.write(str(watched_message))\n f.close()\n for emo in emolist:\n await reacted_message.add_reaction(emo)\n\n@bot.command()\nasync def myroles(ctx):\n \"Lists roles of member that called this function\"\n member = ctx.author\n s = \"\"\n iterroles = iter(member.roles)\n next(iterroles)\n for role in iterroles:\n s+=role.name\n s+=\"\\n\"\n await ctx.send('Your roles:\\n%s' %s)\n\n@bot.command()\nasync def serverroles(ctx):\n \"Lists roles of the server\"\n s = \"\"\n roles = ctx.guild.roles\n iterroles = iter(roles)\n next(iterroles)\n for role in iterroles:\n if role.name == \"hackbot 1.1\":\n break\n else:\n s+=role.name\n s+=\"\\n\"\n await ctx.send('Servers roles:\\n%s' %s)\n\n\"\"\"\n@bot.command()\nasync def poll(ctx, *arg):\n \"Adds (a) reaction(s) to a poll message with the number immediately after poll\"\n for i in range(arg1):\n ctx.send('I\\'m not implemented yet')\n #\n #await ctx.message.add_reaction('\\U0001F3B2')\n\"\"\"\n\n@bot.command()\nasync def joined(ctx):\n \"Tells you when you joined the server using UTC\"\n member = ctx.author\n await ctx.send('Time %s joined %s in UTC:\\n%s' %(member.mention, ctx.guild.name, member.joined_at))\n\n@bot.command(pass_context=True)\nasync def roll(ctx, arg1=\"1\", arg2=\"100\"):\n \"You can specify the amount of dice with a space or delimited with a 'd', else it will be 2 random nums between 1-6\"\n await ctx.message.add_reaction('\\U0001F3B2')\n author = ctx.message.author.display_name\n sum_dice = 0\n message = \"\"\n arg1 = str(arg1).lower()\n\n if(\"d\" in arg1):\n arg1, arg2 = arg1.split(\"d\", 1)\n if(arg1 == \"\"):\n arg1 = \"1\"\n if(arg2 == \"\"):\n await ctx.send(f\"Woah {author}, your rolls are too powerful\")\n return;\n\n if(not arg1.isdecimal() or not str(arg2).isdecimal()):\n await ctx.send(f\"Woah {author}, your rolls are too powerful\")\n return\n\n arg1 = int(arg1)\n arg2 = int(arg2)\n\n if(arg1 > 100 or arg2 > 100):\n await ctx.send(f\"Woah {author}, your rolls are too powerful\")\n return\n elif arg1 < 1 or arg2 < 1:\n await ctx.send(f\"Woah {author}, your rolls are not powerful enough\")\n return\n\n # Is it possible to be *too* pythonic?\n message += (f\"{author} rolled {arg1} d{arg2}{(chr(39) + 's') if arg1 != 1 else ''}\\n\")\n # Never.\n\n message += (\"\\n\")\n for i in range(1, arg1+1):\n roll = randint(1, arg2)\n sum_dice += roll\n if(arg2 == 20 and roll == 20):\n message += (f\"Roll {i}: {roll} - Critical Success! (20)\\n\")\n elif(arg2 == 20 and roll == 1):\n message += (f\"Roll {i}: {roll} - Critical Failure! (1)\\n\")\n else:\n message += (f\"Roll {i}: {roll}\\n\")\n\n message += (\"\\n\")\n message += (f\"Sum of all rolls: {sum_dice}\\n\")\n if(len(message) >= 2000):\n await ctx.send(f\"Woah {author}, your rolls are too powerful\")\n else:\n await ctx.send(message)\n\n@bot.command(hidden=True)\n@commands.has_any_role('Cody', 'Dallas')\nasync def logout(ctx):\n \"Logs the bot out\"\n await bot.logout()\n\n@bot.command()\nasync def escalate(ctx):\n await ctx.send('ESCALATING')\n\n@logout.error\nasync def logout_error(ctx, error):\n await ctx.channel.send(\"You don't have the permission to run that command\")\n\n@bot.command(pass_context=True)\nasync def sub(ctx, *args):\n \"Subtracts any roles mentioned after sub if they exist say all for all possible roles to remove\"\n member = ctx.author\n for arg in args:\n if(arg == \"all\"):\n roles = ctx.guild.roles\n iterroles = iter(roles)\n next(iterroles)\n for role in iterroles:\n if role.name == \"hackbot 1.1\":\n break\n else:\n await member.remove_roles(role)\n break\n else:\n role = discord.utils.get(ctx.guild.roles, name=arg)\n await member.remove_roles(role)\n await ctx.send('I\\'ve removed your requested roles %s!' %member.mention)\n\n@sub.error\nasync def sub_error(ctx, error):\n await ctx.channel.send(\"You have probably typed a role that doesn't exist please make sure that isn't the case and try again\")\n\n@bot.command(pass_context=True)\nasync def add(ctx, *args):\n \"Adds any roles mentioned after add if they exist say all for all roles possible to add\"\n member = ctx.author\n for arg in args:\n if(arg == \"all\"):\n roles = ctx.guild.roles\n iterroles = iter(roles)\n next(iterroles)\n for role in iterroles:\n if role.name == \"hackbot 1.1\":\n break\n else:\n await member.add_roles(role)\n break\n else:\n role = discord.utils.get(ctx.guild.roles, name=arg)\n await member.add_roles(role)\n await ctx.send('I\\'ve added your new roles %s!' %member.mention)\n\n@add.error\nasync def add_error(ctx, error):\n await ctx.channel.send(\"You have probably typed a role that doesn't exist please make sure that isn't the case and try again\")\n\nasync def manage_reactions(payload, added: bool):\n if not payload.message_id in watched_message:\n return\n\n messageID = payload.message_id\n mapping = watched_message[messageID]\n\n if not payload.emoji.name in mapping:\n # reaction.emoji is str if normal emoji or ID if custom, but we use both as keys in mapping\n return\n \n guildName = bot.get_guild(payload.guild_id)\n member = discord.utils.get(guildName.members, id=payload.user_id)\n role = discord.utils.get(guildName.roles, name=mapping[payload.emoji.name])\n\n if added:\n await member.add_roles(role)\n else:\n await member.remove_roles(role)\n\n@bot.event\nasync def on_member_join(member):\n botChannel = discord.utils.get(member.guild.channels, name='bot-stuff')\n rulesChannel = discord.utils.get(member.guild.channels, name='rules-and-info')\n await botChannel.send('Welcome to the server %s!\\nPlease check out %s!\\nIn order to view channels you need to add the relevant roles. Type !help for help, !serverroles for the roles you can add yourself to, !add \"role1\" \"role2\" to put yourself in that course.' %(member.mention, rulesChannel.mention))\n\n@bot.event\nasync def on_raw_reaction_add(payload):\n await manage_reactions(payload, True)\n\n@bot.event\nasync def on_raw_reaction_remove(payload):\n await manage_reactions(payload, False)\n\nbot.run(token1.stringToken())\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":7819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"78503701","text":"from django.core.management.base import BaseCommand\nfrom multiprocessing import Pool, TimeoutError, Lock\nfrom itertools import combinations, product\n\n\ndef gen_chain(combination):\n from django import setup\n setup()\n from degrees.models import create_chain_between, Chain\n\n team_a = combination[0][0]\n team_b = combination[0][1]\n year = combination[1]\n\n if year is None:\n s = '[all] '\n else:\n s = f'[{year}] '\n\n try:\n chain = create_chain_between(team_a, team_b, year)\n if not chain:\n raise Exception('')\n\n s += f'({chain.stage_set.count()}) '\n for stage in chain.stage_set.order_by('number'):\n s += f'{stage.connection.team_a_id} -> '\n s += f'{team_b}'\n lock.acquire()\n try:\n print(s)\n finally:\n lock.release()\n except:\n lock.acquire()\n try:\n print(f'{s} Failed {team_a} -> {team_b}')\n Chain.objects.create(team_a_id=team_a, team_b_id=team_b, exists=False, restricted_to=year)\n Chain.objects.create(team_a_id=team_b, team_b_id=team_a, exists=False, restricted_to=year)\n finally:\n lock.release()\n\n\nlock = None\n\n\ndef init(l):\n global lock\n lock = l\n\n\nclass Command(BaseCommand):\n def add_arguments(self, parser):\n parser.add_argument('n', type=int)\n\n def handle(self, *args, **options):\n from degrees.management.commands.make import years\n from degrees.models import Team\n teams = [t.id for t in Team.objects.all()]\n combos = list(combinations(teams, 2))\n cart_product = product(combos, years + [None])\n\n print(combos)\n _lock = Lock()\n with Pool(processes=options['n'], initializer=init, initargs=(_lock,)) as pool:\n pool.map(gen_chain, cart_product)\n","sub_path":"degrees/management/commands/gen.py","file_name":"gen.py","file_ext":"py","file_size_in_byte":1843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"33978290","text":"_nav = [\n {'url':'/', 'desc': 'Home'},\n {'url':'/about', 'desc': 'About'},\n {'url':'/blog', 'desc': 'Blog',},\n {'url':'/projects', 'desc': 'Projects'},\n]\n\n# Or, from django.core.urlresolvers import reverse_lazy then reverse_lazy('home')\n\n# The following is a template context processor that can be used\n# via the TEMPLATE_CONTEXT_PROCESSORS settings to make navigation\n# links available to every page template\n\ndef get_nav(request):\n # Set the \"active\" attribute of the entry that is currently active\n best_match = {'url': ''}\n for n in _nav:\n if request.path.startswith(n['url']) and len(n['url']) > len(best_match['url']):\n best_match = n\n if best_match['url'] == '/' and len(request.path) > 1:\n best_match = None\n return {\"nav\": [(n if n is not best_match else dict(active=True, **n)) for n in _nav]}\n","sub_path":"bradenmacdonald/nav.py","file_name":"nav.py","file_ext":"py","file_size_in_byte":856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"570283665","text":"import sqlite3\n\nconexion = sqlite3.connect(\"bdbiblioteca.db\")\n\ncursor = conexion.cursor()\nlista_autores = [('Flor Cerdán', '25/10/1978'), \n ('Daniel Levano', '17/01/1980'),\n ('Omar Peña', '15/10/1978'),\n ('Cesar Zapata', '15/10/1960')\n ]\n\nlista_editoriales = [('EIU', 'A'), \n ('Macro', 'A'),\n ('Bosch', 'A'),\n ('Lima Sur', 'A'),\n ('Pirámide', 'A'),\n ('Colombus', 'A'),\n ('Centro', 'A')\n ]\n\n\nlista_paises = [('Argentinaaa', 'A'), \n ('Colombiaaa', 'A'),\n ('Venezuelaaa', 'A'),\n ('Uruguaaay', 'A'),\n ('Paraguaaay', 'A'),\n ('USaaA', 'A')\n ]\n\nlista_libros = [('Oracle 11g', 10, 2019, 50, 'A', 1, 1, 1), \n ('Sistemas Operativos', 14, 2016, 59, 'A', 1, 4, 3),\n ('Estructuras de Datos', 6, 2018, 20, 'A', 2, 2, 3),\n ('Algoritmos con Python', 8, 2017, 70, 'A', 2, 2, 1),\n ('BI', 6, 1998, 50, 'A', 1, 4, 2),\n ('Ing. de Software', 9, 2000, 56, 'A', 3, 2, 4),\n ('Organización de PC', 9, 2016, 60, 'A', 7, 2, 1),\n ('Ensamblaje', 9, 2018, 50, 'A', 4, 4, 3)\n ]\n\nconsulta_pais = \"\"\"INSERT INTO \n PAIS(NOMBRE, ESTADO) \n VALUES (?,?)\n \"\"\"\n\nconsulta_editorial = \"\"\"INSERT INTO \n EDITORIAL(NOMBRE, ESTADO) \n VALUES (?,?)\n \"\"\"\n\nconsulta_autor = \"\"\"INSERT INTO \n AUTOR(NOMBRE, F_NACIMIENTO) \n VALUES (?,?)\n \"\"\"\nconsulta_libro = \"\"\"INSERT INTO \n LIBRO(TITULO, CANTIDAD, ANIO, PRECIO, ESTADO, IDAUTOR, IDEDITORIAL, IDPAIS) \n VALUES (?,?,?,?,?,?,?,?)\n \"\"\"\n \ncursor.executemany(consulta_pais,lista_paises)\ncursor.executemany(consulta_editorial,lista_editoriales)\ncursor.executemany(consulta_autor,lista_autores)\ncursor.executemany(consulta_libro,lista_libros)\nconexion.commit()\n\nconexion.close()\n","sub_path":"semana6/biblioteca/agregarvariosregistros.py","file_name":"agregarvariosregistros.py","file_ext":"py","file_size_in_byte":2231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"609590343","text":"import torch\nimport torch.nn as nn\n\nrnn_size = 100\nrnn_nLayers = 2\nlayer0 = 100\nlayer1 = 100\n\nuse_cuda = False\nprint(torch.version.__version__, use_cuda)\n\nlearning_rate = 0.001\nL2_lambda = 0.0\nnEpochs = 25\ndropout = 0.0\n\ncharDict = dict() # for convert data into ndx_data\n\n\nclass RNN(nn.Module):\n\n def __init__(self, specs):\n super(RNN, self).__init__()\n\n nChars, embed_size, rnn_layers, ffnn_layers, dropout = specs\n\n self.CharEmbed = nn.Embedding(nChars, embed_size)\n self.rnn = nn.GRU(embed_size, rnn_size, rnn_nLayers, dropout=dropout, batch_first=True)\n\n self.layers = nn.ModuleList([])\n prev_size = rnn_size\n\n for i, layer_size in enumerate(ffnn_layers):\n layer = nn.Linear(prev_size, layer_size)\n self.layers.append(layer)\n prev_size = layer_size\n\n self.non_linear = nn.LeakyReLU(negative_slope=0.01)\n\n self.dropout = nn.Dropout(dropout)\n\n for p in self.parameters():\n if p.dim() > 1:\n nn.init.kaiming_normal_(p)\n pass\n\n def forward(self, character, hidden=None):\n # print(character)\n character = character.view(1, 1)\n embed = self.CharEmbed(character)\n\n prev, hidden = self.rnn(embed, hidden)\n\n for layer in self.layers:\n prev = layer(prev)\n prev = self.non_linear(prev)\n prev = self.dropout(prev)\n\n self.out = nn.Linear(100, 1) # output floating number stream\n\n out = self.out(prev)\n out = out.squeeze()\n\n return out\n\n\ndef RNN_train(model, optimizer, criterion, input, target, update=True):\n\n target = torch.tensor(target, dtype=torch.float)\n\n model.zero_grad()\n loss = 0\n\n out = model(input)\n\n loss += criterion(out, target)\n\n if update:\n if not loss is 0:\n loss.backward()\n optimizer.step()\n\n return loss.data.item()\n\n\ndef train_rnn_model(model, training_data, charDict):\n if use_cuda:\n model = model.cuda()\n\n # define the loss functions\n criterion = nn.BCEWithLogitsLoss()\n\n # choose an optimizer\n optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate, weight_decay=L2_lambda)\n\n for e in range(nEpochs):\n for data in training_data:\n targets = []\n for i in range(len(data) - 1):\n if data[i] != \" \" and data[i + 1] != \" \":\n targets.append(0)\n elif data[i] != \" \" and data[i + 1] == \" \":\n targets.append(1)\n elif data[i] == \" \":\n pass\n inputs = data.replace(\" \", \"\").strip()\n for i, character in enumerate(inputs):\n ndx_data = torch.tensor(charDict[character], dtype=torch.long)\n train_loss = 0\n model.train()\n loss = RNN_train(model, optimizer, criterion, ndx_data, targets[i], update=True)\n train_loss += loss\n print(train_loss)\n\n return model\n\ndef count():\n training_data = open(\"./seg_data/msr_training.utf8\", 'r', encoding=\"utf-8\")\n for data in training_data:\n for i in range(len(data)):\n if data[i] in charDict.keys():\n pass\n else:\n charDict[data[i]] = len(charDict)\n return len(charDict)\n\n\ndef segmentation(out, data):\n output = str()\n tuning = 1.10\n for i in range(len(out)):\n out[i] = abs(out[i])\n avg_distance = sum(out) / len(out)\n for i in range(len(out)):\n if out[i] < avg_distance * tuning:\n out[i] = 0\n else:\n out[i] = 1\n\n for j in range(len(data)):\n if out[j] == 0:\n output = output + data[j]\n else:\n output = output + data[j] + \" \"\n return output\n\n\nif __name__ == '__main__':\n char_embed_size = 10\n RNN_layers = [rnn_size, rnn_nLayers]\n FFNN_layers = [layer0, layer1]\n\n training_data = open(\"./seg_data/msr_training.utf8\", 'r', encoding=\"utf-8\")\n\n nChars = count()\n print(nChars)\n\n specs = [nChars, char_embed_size, RNN_layers, FFNN_layers, dropout]\n model = RNN(specs)\n # try:\n # train_rnn_model(model, training_data, charDict)\n # except Exception:\n # pass\n\n test_data = open(\"./seg_data/msr_test.utf8\", 'r', encoding=\"utf-8\")\n for data in test_data:\n for i in range(len(data)):\n if data[i] in charDict.keys():\n test_ndx = torch.tensor(charDict[data[i]], dtype=torch.long)\n else:\n test_ndx = 0\n out = model(test_ndx)\n print(out)\n # out = out.tolist()\n # print(segmentation(out, data))\n","sub_path":"code/char_based.py","file_name":"char_based.py","file_ext":"py","file_size_in_byte":4698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"377102853","text":"#!\nimport sys\nimport math\n\ndef find_median(list1, list2):\n listn = list()\n for i in list1:\n listn.append(i)\n for i in list2:\n listn.append(i)\n listn.sort()\n x = len(listn)\n x = math.floor((x - 1)/2)\n x = listn[x]\n ret = (x,listn)\n return(ret)","sub_path":"Prelab08/listmod.py","file_name":"listmod.py","file_ext":"py","file_size_in_byte":283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"75938954","text":"# -*- coding: utf-8 -*-\nfrom openerp import fields, models, api, exceptions\nfrom datetime import datetime, timedelta\n\n\nclass Quote(models.Model):\n _name = 'sale.quote'\n # _inherit = 'mail.thread'\n\n @api.depends('quote_line')\n def _get_cost_price(self):\n for record in self:\n for line in record.quote_line:\n if line.cost_price:\n record.cost_price += line.cost_price * line.qty\n\n # @api.onchange('quote_line')\n\n\n\n\n name = fields.Char(\n string='Quote name',\n required=True)\n\n partner_id = fields.Many2one(\n comodel_name='res.partner',\n string='Client',\n required=True)\n\n state = fields.Selection(\n [('draft', 'Draft'),\n ('approved', 'Approved'),\n ('sent', 'Sent'),\n ('transfered', 'Transfered')],\n string='field_name',\n default='draft')\n\n origin = fields.Selection(\n [('modify', 'Modify'),\n ('same_as', 'Same as')],\n string='Origin')\n # quote_taxes = fields.Many2many(\n # comodel_name='sale.quote.tax',\n # relation='quote_tax',\n # column1='quote',\n # column2='tax',\n # string='Quote taxes')\n quote_taxes = fields.One2many(\n 'sale.quote.tax',\n 'quote_id',\n string='Tax Lines')\n quote_line = fields.One2many(\n comodel_name='sale.quote.line',\n inverse_name='quote_id',\n string='Lines')\n\n cost_price = fields.Float(\n string='Cost Price',\n compute=_get_cost_price)\n expiration = fields.Date(\n string=\"Expiration\",\n default=fields.Datetime.from_string(fields.Datetime.now()) +\n timedelta(days=30))\n weight = fields.Float(\n string='Weight')\n quote_origin = fields.Many2one(\n comodel_name='sale.quote',\n string='Quote origin')\n amount_untaxed = fields.Float(\n string='Ammount Untaxed')\n amount_tax = fields.Float(\n string='Ammount tax')\n amount_total = fields.Float(\n string='Ammount total')\n currency_id = fields.Many2one(\n comodel_name='res.currency',\n string='Moneda',\n default=1)\n margen_abs = fields.Float(\n string='Margen')\n margen_porcentaje = fields.Float(\n string='Margen porcentaje')\n total_bases = fields.Float(\n string='Total bases')\n descuento1 = fields.Float(\n string='Descuento 1')\n descuento2 = fields.Float(\n string='Descuento 2')\n metodo_valoracion = fields.Selection(\n [('porcentaje', 'Porcentaje'),\n ('margen', 'Margen'),\n ('ii', 'I.I'),\n ('bases', 'Total Bases'),\n ('mismo', 'Mismo Precio')],\n string='Metodo Valoración')\n porcentaje = fields.Float(\n string='Porcentaje')\n margen_valoracion = fields.Float(\n string='Margen Valoración')\n iva_incluido = fields.Float(\n string='I.V.A incluido')\n bases = fields.Float(\n string='Total Bases')\n mismo_precio = fields.Float(\n string='Mismo Precio')\n\n _sql_constraints = [\n ('name_unique',\n 'UNIQUE(name)',\n \"The quote must be unique\"),\n ]\n @api.model\n def _validate_expiration(self):\n if fields.Datetime.from_string(self.expiration).date() < datetime.now().date():\n return False\n return True\n\n @api.model\n def _validate_valoracion(self):\n if self.margen_abs == 0:\n return False\n return True\n\n\n def _generate_pack(self):\n if self.weightless() == False:\n raise exceptions.Warning('No se traspasa el presupuesto.Artículos sin peso.')\n return False\n\n producto = self.env['product.product'].create({'name':self.name,\n 'is_pack':True,'list_price':self.total_bases})\n\n bom = self.env['mrp.bom'].create({'product_tmpl_id':producto.product_tmpl_id.id,\n 'product_id':producto.id,\n 'name':producto.name + ' v.0',\n 'product_qty':1,\n 'type':'normal'})\n\n for line_quote in self.quote_line:\n producto.weight += line_quote.product_id.weight\n if line_quote.product_id.categ_id.name == \"Envases y embalajes\":\n producto.volume = line_quote.product_id.volume\n bom_line_values = {'bom_id':bom.id,\n 'product_id':line_quote.product_id.id,\n 'product_qty':line_quote.qty}\n bom.write({'bom_line_ids':[(0,0,bom_line_values)]})\n\n return True\n\n def weightless(self):\n for line_quote in self.quote_line:\n if line_quote.product_id.weight == 0:\n return False\n return True\n\n\n @api.one\n def valorar_presupuesto(self):\n self.calcular_bases()\n\n if self.metodo_valoracion == \"porcentaje\":\n self.margen_porcentaje = self.porcentaje\n self.margen_abs = self.margen_porcentaje * self.cost_price / 100\n self.total_bases = self.cost_price + self.margen_abs\n if self.descuento1 != 0 or self.descuento2 != 0:\n self.total_bases = self.total_bases / (1 - ((self.descuento1 + self.descuento2)/100))\n self.amount_total = 0\n for taxes in self.quote_taxes:\n taxes.base = taxes.porcentaje * self.total_bases / 100\n self.amount_total += taxes.base + (taxes.base * taxes.tax_id.amount)\n\n if self.metodo_valoracion == \"margen\":\n # import pdb; pdb.set_trace()\n self.margen_abs = self.margen_valoracion\n self.total_bases = self.cost_price + self.margen_abs\n if self.descuento1 != 0 or self.descuento2 != 0:\n self.total_bases = self.total_bases / (1 - ((self.descuento1 + self.descuento2)/100))\n self.margen_porcentaje = self.margen_abs * 100 / self.cost_price\n self.amount_total = 0\n for taxes in self.quote_taxes:\n taxes.base = taxes.porcentaje * self.total_bases / 100\n self.amount_total += taxes.base + (taxes.base * taxes.tax_id.amount)\n if self.metodo_valoracion == \"ii\":\n self.amount_total = self.iva_incluido\n self.total_bases = 0\n for taxes in self.quote_taxes:\n base_temp = self.amount_total * taxes.porcentaje / 100.00\n taxes.base = base_temp / (1.00000 + taxes.tax_id.amount)\n self.total_bases += taxes.base\n self.margen_abs = self.total_bases - self.cost_price\n self.margen_porcentaje = self.margen_abs * 100 / self.cost_price\n if self.metodo_valoracion == \"bases\":\n self.total_bases = self.bases\n self.margen_abs = self.total_bases - self.cost_price\n self.margen_porcentaje = self.margen_abs * 100 / self.cost_price\n self.amount_total = 0\n for taxes in self.quote_taxes:\n taxes.base = taxes.porcentaje * self.total_bases / 100\n self.amount_total += taxes.base + (taxes.base * taxes.tax_id.amount)\n if self.metodo_valoracion == \"mismo\":\n self.total_bases = self.total_bases + ((self.total_bases * self.mismo_precio)/100)\n self.margen_abs = self.total_bases - self.cost_price\n self.margen_porcentaje = self.margen_abs * 100 / self.cost_price\n self.amount_total = 0\n for taxes in self.quote_taxes:\n taxes.base = taxes.porcentaje * self.total_bases / 100\n self.amount_total += taxes.base + (taxes.base * taxes.tax_id.amount)\n\n @api.multi\n def calcular_bases(self):\n taxes = []\n self.quote_taxes = False\n for line in self.quote_line:\n if line.tax_line not in taxes:\n taxes.append(line.tax_line)\n for tax in taxes:\n tax_value = {'tax_id': tax.id, 'base': 0}\n self.write({'quote_taxes': [(0,0,tax_value)]})\n for line in self.quote_line:\n for tax in self.quote_taxes:\n if line.tax_line == tax.tax_id:\n tax.base += line.cost_price * line.qty\n tax.porcentaje = (tax.base / self.cost_price) * 100\n # @api.multi\n # def write(self, vals):\n # super(Quote, self).create(vals)\n # self.calcular_bases()\n # return True\n\n @api.multi\n def copy(self, default=None):\n default = dict(default or {})\n\n copied_count = self.search_count(\n [('name', '=like', u\"Copy of {}%\".format(self.name))])\n if not copied_count:\n new_name = u\"Copy of {}\".format(self.name)\n else:\n new_name = u\"Copy of {} ({})\".format(self.name, copied_count)\n\n default['name'] = new_name\n res = super(Quote,self).copy(default)\n res.origin = 'same_as'\n res.quote_origin = self\n res.margen_abs = False\n res.margen_porcentaje = False\n res.total_bases = False\n res.descuento1 = False\n res.descuento2 = False\n res.porcentaje = False\n res.metodo_valoracion = ''\n res.margen_valoracion = False\n res.iva_incluido = False\n res.bases = False\n res.amount_total = False\n\n res.quote_line = self.quote_line\n res.calcular_bases()\n return res\n\n\n @api.multi\n def action_approved(self):\n if self._validate_valoracion() is True:\n self.state = 'approved'\n else:\n raise exceptions.Warning('No se puede aprobar un presupuesto que no ha sido valorado')\n\n @api.multi\n def action_sent(self):\n self.state = 'sent'\n\n @api.multi\n def action_transfered(self):\n if self._validate_expiration() is True:\n if self._generate_pack():\n self.state = 'transfered'\n else:\n raise exceptions.Warning('No se puede traspasar, la fecha de expiración ya ha vencido')\n\n\n @api.multi\n def action_to_draft(self):\n self.state = 'draft'\n\n\nclass QuoteLine(models.Model):\n _name = 'sale.quote.line'\n _order = 'order, line_order'\n\n # @api.model\n # def _compute_line_order(self):\n # import pdb; pdb.set_trace()\n # maxi = 0\n # for line in self.quote_id.quote_line:\n # if line.order > maxi:\n # maxi = line.order\n # self.line_order = maxi\n\n name = fields.Text(\n string='Description',\n related=\"product_id.description\")\n order = fields.Integer(\n string= 'Order')\n line_order = fields.Integer(\n string= 'Line Order')\n # default=_compute_line_order)\n product_id = fields.Many2one(\n comodel_name='product.product',\n string='Product',\n required=True)\n qty = fields.Integer(\n string='Quantity',\n default = '1')\n cost_price = fields.Float(\n string='Cost Price',\n related=\"product_id.standard_price\")\n tax_line = fields.Many2many(\n comodel_name='account.tax',\n relation='tax_line',\n column1='quote_line',\n column2='tax',\n string='Taxes',\n related=\"product_id.taxes_id\")\n line_total = fields.Float(\n string='Subtotal')\n quote_id = fields.Many2one(\n comodel_name='sale.quote',\n string='Quote')\n stock = fields.Float(\n string='Stock available',\n related=\"product_id.qty_available\")\n\n @api.model\n def create(self, vals):\n res = super(QuoteLine, self).create(vals)\n res.order = res.product_id.categ_id.order\n if not res.line_order:\n res.line_order = len(res.quote_id.quote_line)\n return res\n\n @api.onchange('qty')\n def _check_qty(self):\n for record in self:\n if record.qty < 1:\n record.qty = 1\n return {\n 'warning': {\n 'title': \"Valor incorrecto\",\n 'message': \"La cantidad no puede ser menor que 1. Se cambiará automaticamente.\",\n },\n }\n\n\nclass QuoteTax(models.Model):\n _name = 'sale.quote.tax'\n\n tax_id = fields.Many2one(\n comodel_name='account.tax',\n string='Tax')\n base = fields.Float(\n string='base')\n porcentaje = fields.Float(\n string='%')\n quote_id = fields.Many2one(\n comodel_name='sale.quote',\n inverse_name='quote_taxes',\n string='Quote')\n","sub_path":"dx_quotes/models/quote.py","file_name":"quote.py","file_ext":"py","file_size_in_byte":12547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"573131915","text":"# -*- coding: utf-8 -*-\n# Copyright 2009-2016 Yelp and Contributors\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\"\"\"Functions to populate py:class:`OptionParser` and :py:class:`OptionGroup`\nobjects with categorized command line parameters. This module should not be\nmade public until at least 0.4 if not later or never.\n\"\"\"\n\nfrom optparse import OptionParser\nfrom optparse import SUPPRESS_USAGE\n\nfrom mrjob.parse import parse_key_value_list\nfrom mrjob.parse import parse_port_range_list\nfrom mrjob.runner import CLEANUP_CHOICES\n\n\ndef _append_to_conf_paths(option, opt_str, value, parser):\n \"\"\"conf_paths is None by default, but --no-conf or --conf-path should make\n it a list.\n \"\"\"\n\n if parser.values.conf_paths is None:\n parser.values.conf_paths = []\n\n # this method is also called during generate_passthrough_arguments\n # the check below is to ensure that conf_paths are not duplicated\n if value not in parser.values.conf_paths:\n parser.values.conf_paths.append(value)\n\n\ndef _add_protocol_opts(opt_group):\n \"\"\"Add options related to choosing protocols.\n \"\"\"\n return [\n opt_group.add_option(\n '--strict-protocols', dest='strict_protocols', default=True,\n action='store_true', help='If something violates an input/output '\n 'protocol then raise an exception (the default)'),\n opt_group.add_option(\n '--no-strict-protocols', dest='strict_protocols', default=True,\n action='store_false', help='If something violates an input/output '\n 'protocol then increment a counter and continue'),\n ]\n\n\ndef _add_basic_opts(opt_group):\n \"\"\"Options for all command line tools\"\"\"\n\n return [\n opt_group.add_option(\n '-c', '--conf-path', dest='conf_paths', action='callback',\n callback=_append_to_conf_paths, default=None, nargs=1,\n type='string',\n help='Path to alternate mrjob.conf file to read from'),\n\n opt_group.add_option(\n '--no-conf', dest='conf_paths', action='store_const', const=[],\n help=\"Don't load mrjob.conf even if it's available\"),\n\n opt_group.add_option(\n '-q', '--quiet', dest='quiet', default=None,\n action='store_true',\n help=\"Don't print anything to stderr\"),\n\n opt_group.add_option(\n '-v', '--verbose', dest='verbose', default=None,\n action='store_true', help='print more messages to stderr'),\n ]\n\n\ndef _add_runner_opts(opt_group, default_runner='local'):\n \"\"\"Options for all runners.\"\"\"\n return [\n opt_group.add_option(\n '--archive', dest='upload_archives', action='append',\n default=[],\n help=('Unpack archive in the working directory of this script. You'\n ' can use --archive multiple times.')),\n\n opt_group.add_option(\n '--bootstrap-mrjob', dest='bootstrap_mrjob', action='store_true',\n default=None,\n help=(\"Automatically tar up the mrjob library and install it when\"\n \" we run the mrjob. This is the default. Use\"\n \" --no-bootstrap-mrjob if you've already installed mrjob on\"\n \" your Hadoop cluster.\")),\n\n opt_group.add_option(\n '--cleanup', dest='cleanup', default=None,\n help=('Comma-separated list of which directories to delete when'\n ' a job succeeds, e.g. TMP,LOGS. Choices:'\n ' %s (default: ALL)' % ', '.join(CLEANUP_CHOICES))),\n\n opt_group.add_option(\n '--cleanup-on-failure', dest='cleanup_on_failure', default=None,\n help=('Comma-separated list of which directories to delete when'\n ' a job fails, e.g. TMP,LOGS. Choices:'\n ' %s (default: NONE)' % ', '.join(CLEANUP_CHOICES))),\n\n opt_group.add_option(\n '--cmdenv', dest='cmdenv', default=[], action='append',\n help='set an environment variable for your job inside Hadoop '\n 'streaming. Must take the form KEY=VALUE. You can use --cmdenv '\n 'multiple times.'),\n\n opt_group.add_option(\n '--file', dest='upload_files', action='append',\n default=[],\n help=('Copy file to the working directory of this script. You can'\n ' use --file multiple times.')),\n\n opt_group.add_option(\n '--interpreter', dest='interpreter', default=None,\n help=('Non-python command to run your script, e.g. \"ruby\".')),\n\n # for more info about jobconf:\n # http://hadoop.apache.org/mapreduce/docs/current/mapred-default.html\n opt_group.add_option(\n '--jobconf', dest='jobconf', default=[], action='append',\n help=('-D arg to pass through to hadoop streaming; should'\n ' take the form KEY=VALUE. You can use --jobconf multiple'\n ' times.')),\n\n opt_group.add_option(\n '--no-bootstrap-mrjob', dest='bootstrap_mrjob',\n action='store_false', default=None,\n help=(\"Don't automatically tar up the mrjob library and install it\"\n \" when we run this job. Use this if you've already installed\"\n \" mrjob on your Hadoop cluster.\")),\n\n opt_group.add_option(\n '--no-output', dest='no_output',\n default=None, action='store_true',\n help=\"Don't stream output after job completion\"),\n\n opt_group.add_option(\n '-o', '--output-dir', dest='output_dir', default=None,\n help='Where to put final job output. This must be an s3:// URL ' +\n 'for EMR, an HDFS path for Hadoop, and a system path for local,' +\n 'and must be empty'),\n\n opt_group.add_option(\n '--python-archive', dest='python_archives', default=[],\n action='append',\n help=('Archive to unpack and add to the PYTHONPATH of the mr_job'\n ' script when it runs. You can use --python-archives'\n ' multiple times.')),\n\n opt_group.add_option(\n '--python-bin', dest='python_bin', default=None,\n help=('Alternate python command for Python'\n ' mappers/reducers. You can'\n ' include arguments, e.g. --python-bin \"python -v\"')),\n\n opt_group.add_option(\n '-r', '--runner', dest='runner', default=default_runner,\n choices=('local', 'hadoop', 'emr', 'inline'),\n help=('Where to run the job: local to run locally, hadoop to run'\n ' on your Hadoop cluster, emr to run on Amazon'\n ' ElasticMapReduce, and inline for local debugging. Default'\n ' is %s.' % default_runner)),\n\n opt_group.add_option(\n '--setup', dest='setup', action='append',\n help=('A command to run before each mapper/reducer step in the'\n ' shell (\"touch foo\"). You may interpolate files'\n ' available via URL or on your local filesystem using'\n ' Hadoop Distributed Cache syntax (\". setup.sh#\"). To'\n ' interpolate archives, use #/: \"cd foo.tar.gz#/; make')),\n\n opt_group.add_option(\n '--setup-cmd', dest='setup_cmds', action='append',\n default=[],\n help=('A command to run before each mapper/reducer step in the'\n ' shell (e.g. \"cd my-src-tree; make\") specified as a string.'\n ' You can use --setup-cmd more than once. Use mrjob.conf to'\n ' specify arguments as a list to be run directly.')),\n\n opt_group.add_option(\n '--setup-script', dest='setup_scripts', action='append',\n default=[],\n help=('Path to file to be copied into the local working directory'\n ' and then run. You can use --setup-script more than once.'\n ' These are run after setup_cmds.')),\n\n opt_group.add_option(\n '--steps-interpreter', dest='steps_interpreter', default=None,\n help=(\"Non-Python command to use to query the job about its\"\n \" steps, if different from --interpreter.\")),\n\n opt_group.add_option(\n '--steps-python-bin', dest='steps_python_bin', default=None,\n help=('Name/path of alternate python command to use to'\n ' query the job about its steps, if different from the'\n ' current Python interpreter.')),\n ]\n\n\ndef _add_local_opts(opt_group):\n \"\"\"Options for ``inline`` and ``local`` runners.\"\"\"\n return [\n opt_group.add_option(\n '--hadoop-version', dest='hadoop_version', default=None,\n help=('Specific version of Hadoop to simulate')),\n ]\n\n\ndef _add_hadoop_emr_opts(opt_group):\n \"\"\"Options for ``hadoop`` and ``emr`` runners\"\"\"\n return [\n opt_group.add_option(\n '--hadoop-arg', dest='hadoop_extra_args', default=[],\n action='append', help='Argument of any type to pass to hadoop '\n 'streaming. You can use --hadoop-arg multiple times.'),\n\n opt_group.add_option(\n '--hadoop-log-dir', dest='hadoop_log_dir', default=[],\n action='append', help='Hard-coded directory to search for'\n ' hadoop logs in. You can use --hadoop-log-dir multiple times.'),\n\n opt_group.add_option(\n '--hadoop-streaming-jar', dest='hadoop_streaming_jar',\n default=None,\n help='Path of your hadoop streaming jar (locally, or on S3/HDFS)'),\n\n opt_group.add_option(\n '--label', dest='label', default=None,\n help='alternate label for the job, to help us identify it'),\n\n opt_group.add_option(\n '--owner', dest='owner', default=None,\n help='user who ran the job (if different from the current user)'),\n\n opt_group.add_option(\n '--partitioner', dest='partitioner', default=None,\n help=('Hadoop partitioner class to use to determine how mapper'\n ' output should be sorted and distributed to reducers. For'\n ' example: org.apache.hadoop.mapred.lib.HashPartitioner')),\n\n opt_group.add_option(\n '--check-input-paths', dest='check_input_paths',\n default=True, action='store_true',\n help='Check input paths exist before running (the default)'),\n\n opt_group.add_option(\n '--no-check-input-paths', dest='check_input_paths',\n default=True, action='store_false',\n help='Skip the checks to ensure all input paths exist'),\n ]\n\n\ndef _add_hadoop_opts(opt_group):\n \"\"\"Options for ``hadoop`` runner\"\"\"\n return [\n opt_group.add_option(\n '--hadoop-bin', dest='hadoop_bin', default=None,\n help='path to hadoop binary'),\n\n opt_group.add_option(\n '--hadoop-home', dest='hadoop_home',\n default=None,\n help='Deprecated hint about where to find hadoop binary and'\n ' streaming jar. Just set $HADOOP_HOME or use the'\n ' --hadoop-bin and --hadoop-streaming-jar switches.'),\n\n opt_group.add_option(\n '--hadoop-tmp-dir', dest='hadoop_tmp_dir',\n default=None,\n help='Temp space on HDFS (default is tmp/mrjob)'),\n\n opt_group.add_option(\n '--hdfs-scratch-dir', dest='hdfs_scratch_dir',\n default=None,\n help='Deprecated alias for --hadoop-tmp-dir'),\n ]\n\n\ndef _add_emr_opts(opt_group):\n \"\"\"Options for ``emr`` runner\"\"\"\n return (_add_emr_connect_opts(opt_group) +\n _add_emr_launch_opts(opt_group) +\n _add_emr_run_opts(opt_group))\n\n\ndef _add_emr_connect_opts(opt_group):\n \"\"\"Options for connecting to the EMR API.\"\"\"\n return [\n opt_group.add_option(\n '--aws-region', dest='aws_region', default=None,\n help=('Region to run EMR jobs in. Default is us-west-2')),\n\n opt_group.add_option(\n '--emr-endpoint', dest='emr_endpoint', default=None,\n help=('Force mrjob to connect to EMR on this endpoint'\n ' (e.g. us-west-1.elasticmapreduce.amazonaws.com). Default'\n ' is to infer this from aws_region.')),\n\n opt_group.add_option(\n '--s3-endpoint', dest='s3_endpoint', default=None,\n help=(\"Force mrjob to connect to S3 on this endpoint (e.g.\"\n \" s3-us-west-1.amazonaws.com). You usually shouldn't\"\n \" set this; by default mrjob will choose the correct\"\n \" endpoint for each S3 bucket based on its location.\")),\n ]\n\n\ndef _add_emr_run_opts(opt_group):\n \"\"\"Options for running and monitoring a job on EMR.\"\"\"\n return [\n opt_group.add_option(\n '--check-emr-status-every', dest='check_emr_status_every',\n default=None, type='int',\n help='How often (in seconds) to check status of your EMR job'),\n\n opt_group.add_option(\n '--cluster-id', dest='cluster_id', default=None,\n help='ID of an existing EMR cluster to run our job on'),\n\n # --ec2-key-pair is used to launch the job, not to monitor it\n opt_group.add_option(\n '--ec2-key-pair-file', dest='ec2_key_pair_file', default=None,\n help='Path to file containing SSH key for EMR'),\n\n opt_group.add_option(\n '--emr-action-on-failure', dest='emr_action_on_failure',\n default=None,\n help=('Action to take when a step fails'\n ' (e.g. TERMINATE_CLUSTER | CANCEL_AND_WAIT | CONTINUE)')),\n\n opt_group.add_option(\n '--emr-job-flow-id', dest='emr_job_flow_id', default=None,\n help='Deprecated alias for --cluster-id'),\n\n opt_group.add_option(\n '--hadoop-streaming-jar-on-emr',\n dest='hadoop_streaming_jar_on_emr', default=None,\n help=('Local path of the hadoop streaming jar on the EMR node.'\n ' Rarely necessary.')),\n\n opt_group.add_option(\n '--no-ssh-tunnel', dest='ssh_tunnel',\n default=None, action='store_false',\n help=(\"Don't open an SSH tunnel to the Hadoop job\"\n \" tracker/resource manager\")),\n\n opt_group.add_option(\n '--pool-wait-minutes', dest='pool_wait_minutes', default=None,\n type='int',\n help=('Wait for a number of minutes for a cluster to finish'\n ' if a job finishes, run job on its cluster. Otherwise'\n \" create a new one. (0, the default, means don't wait)\")),\n\n opt_group.add_option(\n '--ssh-bin', dest='ssh_bin', default=None,\n help=(\"Name/path of ssh binary. Arguments are allowed (e.g.\"\n \" --ssh-bin 'ssh -v')\")),\n\n opt_group.add_option(\n '--ssh-bind-ports', dest='ssh_bind_ports', default=None,\n help=('A list of port ranges that are safe to listen on, delimited'\n ' by colons and commas, with syntax like'\n ' 2000[:2001][,2003,2005:2008,etc].'\n ' Defaults to 40001:40840.')),\n\n opt_group.add_option(\n '--ssh-tunnel', dest='ssh_tunnel',\n default=None, action='store_true',\n help=('Open an SSH tunnel to the Hadoop job tracker/resource'\n ' manager')),\n\n opt_group.add_option(\n '--ssh-tunnel-is-closed', dest='ssh_tunnel_is_open',\n default=None, action='store_false',\n help='Make ssh tunnel accessible from localhost only'),\n\n opt_group.add_option(\n '--ssh-tunnel-is-open', dest='ssh_tunnel_is_open',\n default=None, action='store_true',\n help=('Make ssh tunnel accessible from remote hosts (not just'\n ' localhost).')),\n\n opt_group.add_option(\n '--ssh-tunnel-to-job-tracker', dest='ssh_tunnel_to_job_tracker',\n default=None, action='store_true',\n help='Deprecated alias for --ssh-tunnel'),\n ]\n\n\ndef _add_emr_launch_opts(opt_group):\n \"\"\"Options for launching a cluster (including bootstrapping).\"\"\"\n return [\n opt_group.add_option(\n '--additional-emr-info', dest='additional_emr_info', default=None,\n help='A JSON string for selecting additional features on EMR'),\n\n opt_group.add_option(\n '--aws-availability-zone', dest='aws_availability_zone',\n default=None,\n help='Availability zone to run the cluster on'),\n\n opt_group.add_option(\n '--ec2-key-pair', dest='ec2_key_pair', default=None,\n help='Name of the SSH key pair you set up for EMR'),\n\n opt_group.add_option(\n '--emr-api-param', dest='emr_api_params',\n default=[], action='append',\n help='Additional parameters to pass directly to the EMR API '\n ' when creating a cluster. Should take the form KEY=VALUE.'\n ' You can use --emr-api-param multiple times.'\n ),\n\n opt_group.add_option(\n '--emr-tag', dest='emr_tags',\n default=[], action='append',\n help='Metadata tags to apply to the EMR cluster; '\n 'should take the form KEY=VALUE. You can use --emr-tag '\n 'multiple times.'),\n\n opt_group.add_option(\n '--iam-endpoint', dest='iam_endpoint', default=None,\n help=('Force mrjob to connect to IAM on this endpoint'\n ' (e.g. iam.us-gov.amazonaws.com)')),\n\n opt_group.add_option(\n '--iam-instance-profile', dest='iam_instance_profile',\n default=None,\n help=('EC2 instance profile to use for the EMR cluster - see'\n ' \"Configure IAM Roles for Amazon EMR\" in AWS docs')),\n\n opt_group.add_option(\n '--iam-service-role', dest='iam_service_role',\n default=None,\n help=('IAM service role to use for the EMR cluster -- see'\n ' \"Configure IAM Roles for Amazon EMR\" in AWS docs')),\n\n opt_group.add_option(\n '--max-hours-idle', dest='max_hours_idle',\n default=None, type='float',\n help=(\"If we create a persistent cluster, have it automatically\"\n \" terminate itself after it's been idle this many hours.\")),\n\n opt_group.add_option(\n '--mins-to-end-of-hour', dest='mins_to_end_of_hour',\n default=None, type='float',\n help=(\"If --max-hours-idle is set, control how close to the end\"\n \" of an EC2 billing hour the cluster can automatically\"\n \" terminate itself (default is 5 minutes).\")),\n\n opt_group.add_option(\n '--no-bootstrap-python', dest='bootstrap_python',\n action='store_false', default=None,\n help=(\"Don't automatically try to install a compatible version\"\n \" of Python at bootstrap time.\")),\n\n opt_group.add_option(\n '--no-pool-clusters', dest='pool_clusters',\n action='store_false',\n help=\"Don't run our job on a pooled cluster (the default).\"),\n\n opt_group.add_option(\n '--no-pool-emr-job-flows', dest='pool_emr_job_flows',\n action='store_false',\n help=\"Deprecated alias for --no-pool-clusters\"),\n\n opt_group.add_option(\n '--pool-clusters', dest='pool_clusters',\n action='store_true',\n help='Add to an existing cluster or create a new one that does'\n ' not terminate when the job completes. Overrides other '\n ' cluster-related options including EC2 instance'\n ' configuration. Joins pool \"default\" if --pool-name is not'\n ' specified. WARNING: do not run this without'\n ' mrjob terminate-idle-clusters in your crontab;'\n ' clusters left idle can quickly become expensive!'),\n\n opt_group.add_option(\n '--pool-emr-job-flows', dest='pool_emr_job_flows',\n action='store_true',\n help='Deprecated alias for --pool-clusters'),\n\n opt_group.add_option(\n '--pool-name', dest='pool_name', action='store',\n default=None,\n help=('Specify a pool name to join. Set to \"default\" if not'\n ' specified.')),\n\n opt_group.add_option(\n '--s3-log-uri', dest='s3_log_uri', default=None,\n help='URI on S3 to write logs into'),\n\n opt_group.add_option(\n '--s3-scratch-uri', dest='s3_scratch_uri', default=None,\n help='Deprecated alias for --s3-tmp-dir.'),\n\n opt_group.add_option(\n '--s3-sync-wait-time', dest='s3_sync_wait_time', default=None,\n type='float',\n help=('How long to wait for S3 to reach eventual consistency. This'\n ' is typically less than a second (zero in us-west) but the'\n ' default is 5.0 to be safe.')),\n\n opt_group.add_option(\n '--s3-tmp-dir', dest='s3_tmp_dir', default=None,\n help='URI on S3 to use as our temp directory.'),\n\n opt_group.add_option(\n '--s3-upload-part-size', dest='s3_upload_part_size', default=None,\n type='float',\n help=('Upload files to S3 in parts no bigger than this many'\n ' megabytes. Default is 100 MiB. Set to 0 to disable'\n ' multipart uploading entirely.')),\n\n opt_group.add_option(\n '--no-emr-api-param', dest='no_emr_api_params',\n default=[], action='append',\n help='Parameters to be unset when calling EMR API.'\n ' You can use --no-emr-api-param multiple times.'\n ),\n\n opt_group.add_option(\n '--visible-to-all-users', dest='visible_to_all_users',\n default=None, action='store_true',\n help='Make your cluster is visible to all IAM users on the same'\n ' AWS account (the default).'\n ),\n\n opt_group.add_option(\n '--no-visible-to-all-users', dest='visible_to_all_users',\n default=None, action='store_false',\n help='Hide your cluster from other IAM users on the same AWS'\n ' account.'\n ),\n\n ] + _add_emr_bootstrap_opts(opt_group) + _add_emr_instance_opts(opt_group)\n\n\ndef _add_emr_bootstrap_opts(opt_group):\n \"\"\"Add options having to do with bootstrapping (other than\n :mrjob-opt:`bootstrap_mrjob`, which is shared with other runners).\"\"\"\n return [\n\n opt_group.add_option(\n '--bootstrap', dest='bootstrap', action='append',\n help=('A shell command to set up libraries etc. before any steps'\n ' (e.g. \"sudo apt-get -qy install python3\"). You may'\n ' interpolate files available via URL or locally with Hadoop'\n ' Distributed Cache syntax (\"sudo dpkg -i foo.deb#\")')),\n\n opt_group.add_option(\n '--bootstrap-action', dest='bootstrap_actions', action='append',\n default=[],\n help=('Raw bootstrap action scripts to run before any of the other'\n ' bootstrap steps. You can use --bootstrap-action more than'\n ' once. Local scripts will be automatically uploaded to S3.'\n ' To add arguments, just use quotes: \"foo.sh arg1 arg2\"')),\n\n opt_group.add_option(\n '--bootstrap-cmd', dest='bootstrap_cmds', action='append',\n default=[],\n help=('Commands to run on the master node to set up libraries,'\n ' etc. You can use --bootstrap-cmd more than once. Use'\n ' mrjob.conf to specify arguments as a list to be run'\n ' directly.')),\n\n opt_group.add_option(\n '--bootstrap-file', dest='bootstrap_files', action='append',\n default=[],\n help=('File to upload to the master node before running'\n ' bootstrap_cmds (for example, debian packages). These will'\n ' be made public on S3 due to a limitation of the bootstrap'\n ' feature. You can use --bootstrap-file more than once.')),\n\n opt_group.add_option(\n '--bootstrap-python', dest='bootstrap_python',\n action='store_true', default=None,\n help=('Attempt to install a compatible version of Python'\n ' at boostrap time. Currently this only does anything'\n ' for Python 3, for which it is enabled by default.')),\n\n opt_group.add_option(\n '--bootstrap-python-package', dest='bootstrap_python_packages',\n action='append', default=[],\n help=('Path to a Python module to install on EMR. These should be'\n ' standard python module tarballs where you can cd into a'\n ' subdirectory and run ``sudo python setup.py install``. You'\n ' can use --bootstrap-python-package more than once.')),\n\n opt_group.add_option(\n '--bootstrap-script', dest='bootstrap_scripts', action='append',\n default=[],\n help=('Script to upload and then run on the master node (a'\n ' combination of bootstrap_cmds and bootstrap_files). These'\n ' are run after the command from bootstrap_cmds. You can use'\n ' --bootstrap-script more than once.')),\n\n opt_group.add_option(\n '--disable-emr-debugging', dest='enable_emr_debugging',\n action='store_false',\n help='Disable storage of Hadoop logs in SimpleDB'),\n\n opt_group.add_option(\n '--enable-emr-debugging', dest='enable_emr_debugging',\n default=None, action='store_true',\n help='Enable storage of Hadoop logs in SimpleDB'),\n ]\n\n\ndef _add_emr_instance_opts(opt_group):\n \"\"\"Add options having to do with instance creation\"\"\"\n return [\n # AMI\n opt_group.add_option(\n '--ami-version', dest='ami_version', default=None,\n help=('AMI Version to use, e.g. \"2.4.11\", \"3.8.0\", \"4.0.0\"')),\n\n opt_group.add_option(\n '--release-label', dest='release_label', default=None,\n help=('Release Label (e.g. \"emr-4.0.0\"). Overrides'\n ' --ami-version')),\n\n # instance types\n opt_group.add_option(\n '--ec2-core-instance-type', '--ec2-slave-instance-type',\n dest='ec2_core_instance_type', default=None,\n help='Type of EC2 instance for core (or \"slave\") nodes only'),\n\n opt_group.add_option(\n '--ec2-instance-type', dest='ec2_instance_type', default=None,\n help=('Type of EC2 instance(s) to launch (e.g. m1.medium,'\n ' c3.xlarge, r3.xlarge). See'\n ' http://aws.amazon.com/ec2/instance-types/ for the full'\n ' list.')),\n\n opt_group.add_option(\n '--ec2-master-instance-type', dest='ec2_master_instance_type',\n default=None,\n help='Type of EC2 instance for master node only'),\n\n opt_group.add_option(\n '--ec2-task-instance-type', dest='ec2_task_instance_type',\n default=None,\n help='Type of EC2 instance for task nodes only'),\n\n # instance number\n opt_group.add_option(\n '--num-ec2-instances', dest='num_ec2_instances', default=None,\n type='int',\n help='Total number of EC2 instances to launch '),\n\n # NB: EMR instance counts are only applicable for slave/core and\n # task, since a master count > 1 causes the EMR API to return the\n # ValidationError \"A master instance group must specify a single\n # instance\".\n opt_group.add_option(\n '--num-ec2-core-instances', dest='num_ec2_core_instances',\n default=None, type='int',\n help=('Number of EC2 instances to start as core (or \"slave\") '\n 'nodes. Incompatible with --num-ec2-instances.')),\n\n opt_group.add_option(\n '--num-ec2-task-instances', dest='num_ec2_task_instances',\n default=None, type='int',\n help=('Number of EC2 instances to start as task '\n 'nodes. Incompatible with --num-ec2-instances.')),\n\n # bid price\n opt_group.add_option(\n '--ec2-core-instance-bid-price',\n dest='ec2_core_instance_bid_price', default=None,\n help=(\n 'Bid price to specify for core (or \"slave\") nodes when'\n ' setting them up as EC2 spot instances (you probably only'\n ' want to set a bid price for task instances).')\n ),\n\n opt_group.add_option(\n '--ec2-master-instance-bid-price',\n dest='ec2_master_instance_bid_price', default=None,\n help=(\n 'Bid price to specify for the master node when setting it up '\n 'as an EC2 spot instance (you probably only want to set '\n 'a bid price for task instances).')\n ),\n\n opt_group.add_option(\n '--ec2-task-instance-bid-price',\n dest='ec2_task_instance_bid_price', default=None,\n help=(\n 'Bid price to specify for task nodes when '\n 'setting them up as EC2 spot instances.')\n ),\n ]\n\n\ndef _print_help_for_groups(*args):\n option_parser = OptionParser(usage=SUPPRESS_USAGE, add_help_option=False)\n option_parser.option_groups = args\n option_parser.print_help()\n\n\ndef _alphabetize_options(opt_group):\n opt_group.option_list.sort(key=lambda opt: opt.dest or '')\n\n\ndef _fix_custom_options(options, option_parser):\n \"\"\"Update *options* to handle KEY=VALUE options, etc.\"\"\"\n if hasattr(options, 'cmdenv'):\n cmdenv_err = '--cmdenv argument %r is not of the form KEY=VALUE'\n options.cmdenv = parse_key_value_list(options.cmdenv,\n cmdenv_err,\n option_parser.error)\n\n def parse_commas(cleanup_str):\n cleanup_error = ('cleanup option %s is not one of ' +\n ', '.join(CLEANUP_CHOICES))\n new_cleanup_options = []\n for choice in cleanup_str.split(','):\n if choice in CLEANUP_CHOICES:\n new_cleanup_options.append(choice)\n else:\n option_parser.error(cleanup_error % choice)\n if ('NONE' in new_cleanup_options and\n len(set(new_cleanup_options)) > 1):\n option_parser.error(\n 'Cannot clean up both nothing and something!')\n\n return new_cleanup_options\n\n if getattr(options, 'cleanup', None):\n options.cleanup = parse_commas(options.cleanup)\n\n if getattr(options, 'cleanup_on_failure', None):\n options.cleanup_on_failure = parse_commas(options.cleanup_on_failure)\n\n if hasattr(options, 'emr_api_params'):\n emr_api_err = (\n '--emr-api-params argument %r is not of the form KEY=VALUE')\n options.emr_api_params = parse_key_value_list(options.emr_api_params,\n emr_api_err,\n option_parser.error)\n\n if hasattr(options, 'no_emr_api_params'):\n for param in options.no_emr_api_params:\n options.emr_api_params[param] = None\n\n if hasattr(options, 'emr_tags'):\n emr_tag_err = '--emr-tag argument %r is not of the form KEY=VALUE'\n options.emr_tags = parse_key_value_list(options.emr_tags,\n emr_tag_err,\n option_parser.error)\n\n if hasattr(options, 'jobconf'):\n jobconf_err = '--jobconf argument %r is not of the form KEY=VALUE'\n options.jobconf = parse_key_value_list(options.jobconf,\n jobconf_err,\n option_parser.error)\n\n if getattr(options, 'ssh_bind_ports', None):\n try:\n ports = parse_port_range_list(options.ssh_bind_ports)\n except ValueError as e:\n option_parser.error('invalid port range list %r: \\n%s' %\n (options.ssh_bind_ports, e.args[0]))\n options.ssh_bind_ports = ports\n","sub_path":"mrjob/options.py","file_name":"options.py","file_ext":"py","file_size_in_byte":33169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"156613507","text":"from src.input_parser import MAZE, START, END\nfrom src.vertex.valid_vertex import ValidVertex\nfrom src.vertex.vertex import Vertex, adapt_vertex\n\nWALL = 'X'\n\n\nclass Maze:\n \"\"\"\n Class that represents the maze to navigate\n\n Attributes\n ----------\n width : int\n width of the maze\n height : int\n height of the maze\n start : Vertex\n Starting point in the maze\n end : Vertex\n Target point in the maze\n\n canvas : List\n A matrix containing all the text representation of the maze\n\n vertices: dict\n Collection of traversable vertices\n\n walls : dict\n Collection of wall pertices\n \"\"\"\n\n def __init__(self):\n self.width = 0\n self.height = 0\n self.start = Vertex(0, 0)\n self.end = Vertex(0, 0)\n self.canvas = []\n self.vertices = {}\n self.walls = {}\n\n\nclass Builder:\n def __init__(self, data: dict):\n self.width = len(data[MAZE][0])\n self.height = len(data[MAZE])\n self.start = data[START]\n self.end = data[END]\n self.canvas = data[MAZE]\n\n def build(self) -> Maze:\n maze = Maze()\n maze.width = self.width\n maze.height = self.height\n maze.start = adapt_vertex(self.start)\n maze.end = adapt_vertex(self.end)\n maze.canvas = self.canvas\n maze.vertices, maze.walls = self.__adapt_maze()\n return maze\n\n def __adapt_maze(self):\n \"\"\"\n Parses the canvas for walls and traversable vertices\n :return: a tuple of a list of traversable vertices and a list of impassable vertices\n \"\"\"\n width = len(self.canvas[0])\n height = len(self.canvas)\n vertices = {}\n walls = {}\n\n for row in range(height):\n for column in range(width):\n vertex_value = self.canvas[row][column]\n\n if vertex_value is WALL:\n vertex = Vertex(row, column)\n walls[str(vertex)] = vertex\n else:\n vertex = self.__find_neighbours(ValidVertex(row, column), column, row)\n vertices[str(vertex)] = vertex\n\n return vertices, walls\n\n def __find_neighbours(self, vertex, column, row) -> ValidVertex:\n \"\"\"\n Given a traversable vertex, finds all its traversable neighbours\n\n :param vertex: Vertex for which neighbours are to be found\n :param column: column in which the vertex is located\n :param row: row in wich the vertex is located\n :return: vertex with all its neighbours added\n \"\"\"\n\n # check surrounding vertices\n neighbour_coordinates = [(row + 1, column),\n (row - 1, column),\n (row, column + 1),\n (row, column - 1)]\n for coordinates in neighbour_coordinates:\n x, y = coordinates\n neighbour = self.canvas[x][y]\n if neighbour is not WALL:\n vertex.add_neighbour(Vertex(x, y))\n return vertex\n","sub_path":"state-space-search-maze/src/maze.py","file_name":"maze.py","file_ext":"py","file_size_in_byte":3111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"463279341","text":"import json\nimport argparse\nimport random\nimport requests\nfrom sanity_suite.conf_tcs.config import *\nfrom sanity_suite.lib_tcs.utils import *\n\nrequests.packages.urllib3.disable_warnings()\n\nURL = \"https://%s:443\"\nSETTINGS_URL = \"/settings/threshold?cluster_id=%s&cluster_name=%s&vcenter_ip=%s\"\n\n'''\nAutomated test for:\n 1. Get health threshold settings\n 2. Set threshold for IOPS\n 3. Set threshold for Throughput\n 4. Set threshold for Latency\n 5. Set threshold for IOPS and Throughput\n 6. Set threshold for Throughput and Latency\n 7. Set threshold for Throughput, Latency and IOPS\n\nSample test run:\npython3 threshold_setting_test.py --appliance-ip 192.168.3.28 --cluster-id 192168189_C01 --cluster-name C01 --vcenter-ip 192.168.1.189\n\n\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--appliance-ip', required=True, help='Appliance IP')\nparser.add_argument('--cluster-id', required=True, help='Cluster Id')\nparser.add_argument('--cluster-name', required=True, help='Cluster name')\nparser.add_argument('--vcenter-ip', required=True, help='vCenter IP')\n\nargs = parser.parse_args()'''\nURL = URL % (APPLIANCE_IP)\nSETTINGS_URL = SETTINGS_URL % (CLUSTER_ID, CLUSTER_NAME, VCENTER_IP)\n\nconfig = {\n \"cluster_id\" : CLUSTER_ID,\n \"cluster_name\" : CLUSTER_NAME,\n \"vcenter_ip\" : VCENTER_IP\n }\n\ndef test_run(f):\n try:\n f()\n except Exception as err:\n import traceback\n traceback.print_exc()\n print(\"Failed test : %s\" % f.__name__)\n \nclass ThresholdTest:\n def __init__(self, url):\n self.url = url\n self.print_msg = \"*\" * 15\n def post(self, data, url, test_name):\n response = requests.post(\"%s%s\" %(URL, url), json=data, verify=False)\n print(\"test\", \" : \", test_name)\n print(\"status code\", \" : \", response.status_code)\n print(\"response\", \" : \", response.text)\n print(\"%sFinished %s%s\\n\" % (self.print_msg, test_name, self.print_msg))\n return response\n\n def get(self, url, test_name):\n response = requests.get(\"%s%s\" %(URL, url), verify=False)\n print(\"test\", \" : \", test_name)\n print(\"status code\", \" : \", response.status_code)\n print(\"response\", \" : \", response.text)\n print(\"%sFinished %s%s\\n\" % (self.print_msg, test_name, self.print_msg))\n return response\n\n@test_run\ndef test_get_health_threshold_01():\n test_obj = ThresholdTest(URL)\n test_obj.get(SETTINGS_URL, \"test_get_health_threshold_01\") \n\n@test_run\ndef test_set_health_threshold_iops():\n test_obj = ThresholdTest(URL)\n data = {\n \"iops\" : { \n \"low\" : 11,\n \"high\" : 50\n }\n }\n data = {\"data\" : data}\n data.update(config)\n test_obj.post(data, SETTINGS_URL, \"test_set_health_threshold_iops\")\n\n@test_run\ndef test_set_health_threshold_throughput():\n test_obj = ThresholdTest(URL)\n data = {\n \"throughput\" : { \n \"low\" : 13,\n \"high\" : 59\n }\n }\n data = {\"data\" : data}\n data.update(config)\n test_obj.post(data, SETTINGS_URL, \"test_set_health_threshold_throughput\")\n\n@test_run\ndef test_set_health_threshold_latency():\n test_obj = ThresholdTest(URL)\n data = {\n \"latency\" : {\n \"4k\" : {\n \"low\" : 1,\n \"high\" : 10\n }\n }\n }\n data = {\"data\" : data}\n data.update(config)\n response = test_obj.post(data, SETTINGS_URL, \"test_set_health_threshold_latency\")\n assert(response.status_code == 200)\n\n@test_run\ndef test_set_health_threshold_throughput_iops():\n test_obj = ThresholdTest(URL)\n data = {\n \"throughput\" : {\n \"low\" : 1,\n \"high\" : 59\n },\n \"iops\" : {\n \"low\" : 11,\n \"high\" : 50\n }\n }\n data = {\"data\" : data}\n data.update(config)\n response = test_obj.post(data, SETTINGS_URL, \"test_set_health_threshold_throughput_iops\")\n assert(response.status_code == 200)\n\n@test_run\ndef test_set_health_threshold_throughput_latency():\n test_obj = ThresholdTest(URL)\n data = {\n \"throughput\" : {\n \"low\" : 1,\n \"high\" : 9\n },\n \"latency\" : {\n \"4k\" : {\n \"low\" : 1,\n \"high\" : 15\n }\n }\n }\n data = {\"data\" : data}\n data.update(config)\n response = test_obj.post(data, SETTINGS_URL, \"test_set_health_threshold_throughput_latency\")\n assert(response.status_code == 200)\n\n@test_run\ndef test_set_health_threshold_throughput_latency_iops():\n test_obj = ThresholdTest(URL)\n data = {\n \"throughput\" : {\n \"low\" : 1,\n \"high\" : 9\n },\n \"latency\" : {\n \"4k\" : {\n \"low\" : 1,\n \"high\" : 15\n }\n },\n \"iops\" : {\n \"low\" : 11,\n \"high\" : 50\n }\n\n }\n data = {\"data\" : data}\n data.update(config)\n response = test_obj.post(data, SETTINGS_URL, \"test_set_health_threshold_throughput_latency_iops\")\n assert(response.status_code == 200)\n\n@test_run\ndef test_get_health_threshold_02():\n test_obj = ThresholdTest(URL)\n test_obj.get(SETTINGS_URL, \"test_get_health_threshold_02\")\n","sub_path":"sanity_suite/tests/threshold_setting.py","file_name":"threshold_setting.py","file_ext":"py","file_size_in_byte":6339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"312533706","text":"#!/usr/bin/env python\n\n# Copyright (c) 2014, Facebook, Inc.\n# All rights reserved.\n#\n# This source code is licensed under the BSD-style license found in the\n# LICENSE file in the root directory of this source tree. An additional grant \n# of patent rights can be found in the PATENTS file in the same directory.\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n# pyexpect.replwrap will not work with unicode_literals\n#from __future__ import unicode_literals\n\nimport os\nimport random\nimport unittest\n\n# osquery-specific testing utils\nimport test_base\n\nSHELL_TIMEOUT = 10\n\nclass OsqueryiTest(unittest.TestCase):\n def setUp(self):\n self.binary = os.path.join(test_base.ARGS.build, \"osquery\", \"osqueryi\")\n self.osqueryi = test_base.OsqueryWrapper(self.binary)\n self.dbpath = \"%s%s\" % (\n test_base.CONFIG[\"options\"][\"database_path\"],\n str(random.randint(1000, 9999)))\n\n def test_error(self):\n '''Test that we throw an error on bad query'''\n self.osqueryi.run_command(' ')\n self.assertRaises(test_base.OsqueryException,\n self.osqueryi.run_query, 'foo')\n\n def test_config_check_success(self):\n '''Test that a 0-config passes'''\n proc = test_base.TimeoutRunner([\n self.binary,\n \"--config_check\",\n \"--database_path=%s\" % (self.dbpath),\n \"--config_path=%s/test.config\" % test_base.SCRIPT_DIR\n ],\n SHELL_TIMEOUT)\n self.assertEqual(proc.stdout, \"\")\n print (proc.stdout)\n print (proc.stderr)\n self.assertEqual(proc.proc.poll(), 0)\n\n def test_config_check_failure(self):\n '''Test that a missing config fails'''\n proc = test_base.TimeoutRunner([\n self.binary,\n \"--config_check\",\n \"--database_path=%s\" % (self.dbpath),\n \"--config_path=/this/path/does/not/exist\"\n ],\n SHELL_TIMEOUT)\n self.assertNotEqual(proc.stderr, \"\")\n print (proc.stdout)\n print (proc.stderr)\n self.assertEqual(proc.proc.poll(), 1)\n\n # Now with a valid path, but invalid content.\n proc = test_base.TimeoutRunner([\n self.binary,\n \"--config_check\",\n \"--database_path=%s\" % (self.dbpath),\n \"--config_path=%s/test.badconfig\" % test_base.SCRIPT_DIR\n ],\n SHELL_TIMEOUT)\n self.assertEqual(proc.proc.poll(), 1)\n self.assertNotEqual(proc.stderr, \"\")\n\n # Finally with a missing config plugin\n proc = test_base.TimeoutRunner([\n self.binary,\n \"--config_check\",\n \"--database_path=%s\" % (self.dbpath),\n \"--config_plugin=does_not_exist\"\n ],\n SHELL_TIMEOUT)\n self.assertNotEqual(proc.stderr, \"\")\n self.assertNotEqual(proc.proc.poll(), 0)\n\n def test_meta_commands(self):\n '''Test the supported meta shell/help/info commands'''\n commands = [\n '.help',\n '.all',\n '.all osquery_info',\n '.all this_table_does_not_exist',\n '.echo',\n '.echo on',\n '.echo off',\n '.header',\n '.header off',\n '.header on',\n '.mode',\n '.mode csv',\n '.mode column',\n '.mode line',\n '.mode list',\n '.mode pretty',\n '.mode this_mode_does_not_exists',\n '.nullvalue',\n '.nullvalue \"\"',\n '.print',\n '.print hello',\n '.schema osquery_info',\n '.schema this_table_does_not_exist',\n '.schema',\n '.separator',\n '.separator ,',\n '.show',\n '.tables osquery',\n '.tables osquery_info',\n '.tables this_table_does_not_exist',\n '.tables',\n '.trace',\n '.width',\n '.width 80',\n '.timer',\n '.timer on',\n '.timer off'\n ]\n for command in commands:\n result = self.osqueryi.run_command(command)\n pass\n\n def test_time(self):\n '''Demonstrating basic usage of OsqueryWrapper with the time table'''\n self.osqueryi.run_command(' ') # flush error output\n result = self.osqueryi.run_query(\n 'SELECT hour, minutes, seconds FROM time;')\n self.assertEqual(len(result), 1)\n row = result[0]\n self.assertTrue(0 <= int(row['hour']) <= 24)\n self.assertTrue(0 <= int(row['minutes']) <= 60)\n self.assertTrue(0 <= int(row['seconds']) <= 60)\n\n def test_config_bad_json(self):\n self.osqueryi = test_base.OsqueryWrapper(self.binary,\n args={\"config_path\": \"/\"})\n result = self.osqueryi.run_query('SELECT * FROM time;')\n self.assertEqual(len(result), 1)\n\nif __name__ == '__main__':\n test_base.Tester().run()\n","sub_path":"tools/tests/test_osqueryi.py","file_name":"test_osqueryi.py","file_ext":"py","file_size_in_byte":5050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"628362671","text":"\"\"\"\nThư viện này viết ra phục vụ cho môn học `Các mô hình ngẫu nhiên và ứng dụng`\nSử dụng các thư viện `networkx, pandas, numpy, matplotlib`\n\"\"\"\n\nimport processviz.algorithm.side_algo as sa\nimport processviz.algorithm.mean_time as mt\nimport processviz.algorithm.graph_travel as gt\nimport networkx as nx\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.image import imread\nimport pandas as pd\n\n# Error handler\nimport sentry_sdk\nsentry_sdk.init(\"https://31be2fd911834411b1b58755d06e9ac2@sentry.io/2445393\")\n\n\nclass MarkovChain:\n def __init__(self):\n pass\n\n '''\n Initialize data of Markov chain:\n From stdin:\n Provide state space, transition matrix, initial vector(optional)\n From file:\n Import from a csv file.\n Please include path to file\n '''\n\n def from_stdin(self, state=None, data=None, pi=None):\n if state == None or data == None:\n return \"Nothing is given\"\n else:\n self.P = data\n self.pi = pi\n self.state = state\n\n def from_file(self, path='input.csv'):\n data = pd.read_csv(path)\n matrix = pd.DataFrame(data)\n data = matrix.values.tolist()\n self.pi = data[0]\n self.state = matrix.columns\n self.P = data[1:]\n\n '''\n Generate graph structure:\n Structure is provided by a list with each element has form:\n [state1, state2, 'label':value]\n '''\n\n def __generate_struct__(self, n):\n matrix = self.matrix_at(n)\n struct = []\n for i in range(len(self.state)):\n for j in range(len(self.state)):\n if matrix[i][j] > 0:\n struct.append([self.state[i], self.state[j],\n {'label': matrix[i][j]}])\n del matrix\n return struct\n\n \"\"\"\n Generate transition matrix, state vector at specific step\n \"\"\"\n\n def matrix_at(self, n=1):\n return np.matrix.round(np.linalg.matrix_power(self.P, n), 3)\n\n def state_vector_at(self, n=1):\n return list(np.matmul(self.pi, self.matrix_at(n)))\n\n '''\n Generate state distribution graph and transition graph through time\n __get_state_through_time__:\n get each state distribution at time\n generate_state_graph:\n plot graph from given figures\n generate_graph:\n create a graph\n '''\n\n def __get_state_through_time__(self, n):\n state = [[i] for i in self.pi]\n steps = []\n for i in range(n):\n steps.append(i+1)\n state.append(self.state_vector_at(i))\n state = (np.transpose(state[len(self.P):])).tolist()\n return state, steps\n\n def generate_state_graph(self, n, path='img/state_vector.svg'):\n if self.pi == None:\n return \"Not found origin state\"\n else:\n state, steps = self.__get_state_through_time__(n)\n legend = self.state\n for i in range(len(self.pi)):\n plt.plot(steps, state[i])\n plt.legend(legend, loc='best')\n plt.title(\"Distribution state vector through time\")\n plt.xlabel(\"Steps\")\n plt.ylabel(\"Probability\")\n plt.savefig(path, format='svg', dpi=1200)\n plt.show()\n\n def generate_graph(self, n=1, path='img/Graph.svg'):\n if self.state is None:\n return \"Graph is empty. \\n Nothing to show\"\n else:\n self.matrix_at(n)\n self = nx.drawing.nx_agraph.to_agraph(\n nx.DiGraph(self.__generate_struct__(n)))\n self.layout('dot')\n self.node_attr.update(color='red', height=0.5,\n width=0.5, fontname=\"Calibri\", fontsize=10)\n self.edge_attr.update(color='blue', fontsize=8,\n fontname=\"Calibri\", rotate=True)\n self.draw(path)\n self.draw('img/Graph.png')\n img = imread('img/Graph.png')\n plt.axis(\"off\")\n plt.imshow(img)\n\n # This part is use for further properties of Markov chain\n\n def has_path(self, source, target):\n '''\n Check if a state can reach another state.\n Use BFS to travel through graph\n For more detail, go to graph_travel in algorithm\n '''\n return True if gt.BFS(self.state, self.P, source=source, target=target) > 0 else False\n\n def is_connected(self, state1, state2):\n '''\n Check if two state is connected\n '''\n return True if self.has_path(state1, state2) and self.has_path(state2, state1) else False\n\n def is_regular(self):\n # Check is irreducible\n component = self.get_communicating_class()\n if len(component) > 1:\n return False\n return True if self.get_period(self.state[0]) == 1 else 0\n\n def is_irreducible(self):\n '''\n Return True if Matrix is reducible\n False if not\n '''\n return True if len(self.get_communicating_class()) > 1 else False\n\n def get_communicating_class(self):\n return gt.get_communicating_class(self.state, self.P)\n\n def is_recurrent(self, state=None):\n if state != None:\n containing_class = gt.get_containing_class(\n self.state, self.P, state)\n if containing_class == False:\n return False\n else:\n state_vector = gt.convert_to_adjacency(self.state, self.P)\n union = set([])\n for i in containing_class:\n union = union.union(set(state_vector[i]))\n return True if union == set(containing_class) else False\n else:\n return \"No state is given\"\n\n def get_period(self, target):\n '''\n Return period of a state\n '''\n component = self.get_communicating_class()\n for sl in component:\n if target in sl:\n break\n t = []\n if target not in sl:\n return 0\n else:\n for i in sl:\n t.append(gt.BFS(self.state, self.P, i, i))\n return sa.gcd_list(t)\n\n # ----------------------------------------------------\n # Get steady state\n # ----------------------------------------------------\n\n def get_steady_state(self):\n A = np.transpose(self.P)\n A = np.subtract(A, np.identity(len(A)))\n A = np.ndarray.tolist(A)\n A.append(np.ndarray.tolist(np.ones(len(A))))\n b = np.ndarray.tolist(np.transpose(np.zeros(len(A))))\n b[len(b)-1] = 1\n # Calc\n return np.matmul(np.linalg.inv(np.matmul(np.transpose(A), A)), np.matmul(np.transpose(A), b))\n\n # ----------------------------------------------------\n # Get mean time spent\n # ----------------------------------------------------\n '''\n get_mean_time(source, target, type):\n if type == 'absoring':\n return expected time to reach absoring state\n if type == 'transient':\n case1: source and target are given:\n return expected time to reach target from source\n case2: at least source or target is not provided:\n return matrix\n if type is not provided correctly, return \"Invalid\"\n '''\n\n def get_mean_time(self, source=None, target=None, type='transient'):\n try:\n state = mt.get_transient_state(self.state, self.P)\n matrix = mt.get_mean_time_transient(self.state, self.P)\n if type == 'absoring':\n return state, (mt.get_mean_time_absoring(self.state, self.P)).tolist()\n elif type == 'transient':\n if source == None and target == None:\n return state, matrix\n elif source == None:\n return state, (np.transpose(matrix)).tolist()[state.index(target)]\n elif target == None:\n return state, (matrix[state.index(source)]).tolist()\n else:\n return state, matrix[state.index(source)][state.index(target)]\n except:\n return \"Invalid\"\n","sub_path":"processviz/markovchain.py","file_name":"markovchain.py","file_ext":"py","file_size_in_byte":8188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"248185045","text":"import numpy as np\nimport pandas as pd\nfrom sklearn.metrics.pairwise import cosine_similarity\nfrom rec_sys.models import *\n\n\ndef gen_recipes_lists():\n users = User.objects.all()\n recipes = Recipe.objects.all()\n\n ratings = Rating.objects.all()\n n_users = users.count()\n n_recipes = recipes.count()\n rating_matrix = np.zeros((n_users, n_recipes))\n print('start matrix')\n for rating in ratings:\n rating_matrix[int(rating.user.id - 2), int(rating.recipe.old_id)] = rating.rating\n print('matrix done')\n recipe_cosine_similarity = pd.DataFrame(cosine_similarity(rating_matrix.T))\n\n for user in users:\n print(' -- USER {} -- '.format(user.id))\n # получаем список избранных рецептов\n f_recipes = Recipe.objects.filter(addedrecipes__user=user).order_by('-addedrecipes__id')[:5]\n if not f_recipes.exists():\n # если нет избранных, попробуем рекомендовать по истории просмотров\n # (аналогично возьмем до 5 последних просмотров)\n f_recipes = Recipe.objects.filter(history__user=user).order_by('-history__view_date')[:5]\n if not f_recipes.exists():\n # для тех, кто в танке, просто будем советовать 50 самых популярных рецептов\n print('User {} has no favourites or history! '\n 'Gen recipes list with the best mean rating.'.format(user.id))\n rec_recipes_list = Recipe.objects.all().order_by('-mean_rating')[:50]\n user.userrecrecipes.recipe_list = '$'.join([str(x) for x in rec_recipes_list.values_list('id', flat=True)])\n user.userrecrecipes.save()\n else:\n content_based_rec = cb_recommend(f_recipes)\n recommendation = ub_recommend(content_based_rec, user, recipe_cosine_similarity, rating_matrix)\n user.userrecrecipes.recipe_list = '$'.join([str(x) for x in recommendation])\n user.userrecrecipes.save()\n else:\n content_based_rec = cb_recommend(f_recipes)\n recommendation = ub_recommend(content_based_rec, user, recipe_cosine_similarity, rating_matrix)\n user.userrecrecipes.recipe_list = '$'.join([str(x) for x in recommendation])\n user.userrecrecipes.save()\n\n\ndef cb_recommend(f_recipes):\n content_based_rec = []\n for recipe in f_recipes:\n recipe.similar = recipe.similar.split('$')\n for recipe_id in recipe.similar:\n content_based_rec.append(Recipe.objects.get(id=recipe_id).old_id)\n print(' - CONTENT-BASED RECOMMENDATION DONE')\n return content_based_rec\n\n\ndef ub_recommend(content_based_rec, current_user, recipe_cosine_similarity, rating_matrix):\n\n predict = pd.Series(index=content_based_rec)\n recipes_rec_simil = recipe_cosine_similarity[content_based_rec]\n\n for recipe_id, recipe_simil in recipes_rec_simil.iteritems():\n top_recipe_simil = recipe_simil.sort_values(ascending=False)[:900]\n top_ratings = rating_matrix[current_user.id - 2].T[top_recipe_simil.index.values]\n\n i = 0\n for index, recipe_sim in top_recipe_simil.items():\n if top_ratings[i] != 0:\n top_ratings[i] = recipe_sim * (top_ratings[i] - Recipe.objects.get(old_id=index).mean_rating)\n else:\n top_ratings[i] = 0\n i += 1\n\n if top_recipe_simil.sum() != 0:\n predict[recipe_id] = Recipe.objects.get(old_id=recipe_id).mean_rating + top_ratings.sum() / top_recipe_simil.sum()\n else:\n predict[recipe_id] = Recipe.objects.get(old_id=recipe_id).mean_rating + top_ratings.sum() / 900\n\n recommendation = []\n predict = list(predict.sort_values(ascending=False).index)[:50]\n for index in predict:\n recommendation.append(Recipe.objects.get(old_id=index).id)\n print(' - COLLABORATIVE FILTERING DONE')\n return recommendation\n","sub_path":"hybrid_rec.py","file_name":"hybrid_rec.py","file_ext":"py","file_size_in_byte":4081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"425945150","text":"from config import *\nfrom util import *\n\nimport re\nimport os\nfrom crawler import crawl_baike, crawl_image, crawl_music\n\n\ndef intro():\n reply = \"你好呀~我是某人的人工智能搭档小紫,目前我的辅助范围有:\\n\" \\\n \"1. MC影之乡服务器。(发送\\\"/mc help\\\"获取详情)\\n\" \\\n \"2. 最终幻想14。(发送\\\"/ff help\\\"获取详情)\"\n return reply\n\n\ndef who_r_u():\n reply = \"我是小紫呀~\"\n return reply\n\n\ndef i_love_u(qq_number):\n if qq_number == PARTNER_QQ:\n reply = \"我也爱你呀~\"\n else:\n reply = \"我不是那么随便的人~\"\n return reply\n\n\ndef my_cp(qq_number):\n if qq_number == PARTNER_QQ:\n reply = \"是我呀~\"\n else:\n reply = \"我哪知道~\"\n return reply\n\n\ndef connect_server(at_content):\n name = re.match('连接(.+)', at_content).group(1)\n backinfo = os.system('ping -c 1 -W 1 ' + name)\n if backinfo == 0:\n reply = \"服务器连接良好\"\n else:\n reply = \"服务器连接失败\"\n return reply\n\n\ndef server_time():\n reply = \"现在的时间是:{}\".format(str(cur_time()).split('.')[0])\n return reply\n\n\ndef where_r_u(self):\n self.cur_lat, self.cur_lon = move_on_earth(self.cur_lat, self.cur_lon)\n lat = str(round(self.cur_lat, 6))\n lon = str(round(self.cur_lon, 6))\n reply = [\"[CQ:location,lat={},lon={}]\".format(lat, lon), \"来找我玩呀~\"]\n return reply\n\n\ndef move_on_earth(lat, lon):\n lat += random.uniform(-2, 2)\n lon += random.uniform(-2, 2)\n if lat > 90:\n lat = 180 - lat\n elif lat < -90:\n lat = -180 - lat\n\n if lat > 180:\n lat = lat - 360\n elif lat < -180:\n lat = lat + 360\n return lat, lon\n\n\ndef what_is(at_content):\n reply = None\n if regex_match('.+是什么.*', at_content):\n item = re.search('(.+)是什么.*', at_content).group(1)\n reply = crawl_baike(item)\n elif regex_match('.+是啥.*', at_content):\n item = re.search('(.+)是啥.*', at_content).group(1)\n reply = crawl_baike(item)\n return reply\n\n\ndef what_is_image(at_content):\n reply = None\n if regex_match('.+长啥样.*', at_content):\n item = re.search('(.+)长啥样.*', at_content).group(1)\n reply = crawl_image(item)\n elif regex_match('.+长什么样.*', at_content):\n item = re.search('(.+)长什么样.*', at_content).group(1)\n reply = crawl_image(item)\n return reply\n\n\ndef music(par_list):\n if len(par_list) == 1:\n return \"格式不正确!\"\n\n music_name = ' '.join(par_list[1:])\n reply = crawl_music(music_name)\n return reply\n\n\ndef save_message(group_id, qq_number, message):\n if regex_match('\\\\[CQ:.*\\\\].*', message):\n message = re.sub('\\\\[CQ:.*\\\\]', '', message).strip()\n\n if '[CQ:' in message or message == \"\":\n message = \"\"\n\n file_name = CHAT_DATA_DIR_PATH + str(cur_time().date()) + \".json\"\n chat_data = load_file(file_name)\n\n if group_id not in chat_data:\n chat_data[group_id] = []\n chat_data[group_id].append({\"sender\": qq_number, \"message\": message, \"time\": str(cur_time())})\n update_file(file_name, chat_data)\n\n\nasync def duel(self, bot, context, par_list):\n group_id = str(context['group_id'])\n self_qq = str(context['user_id'])\n\n if group_id not in self.duel_dict:\n self.duel_dict[group_id] = {}\n\n if len(par_list) == 1 or par_list[1] == \"\":\n reply = \"请选择一位对手吧!\"\n elif par_list[1] == \"record\":\n reply = duel_record(self, group_id, self_qq)\n elif par_list[1] == \"rank\":\n reply = duel_rank(self, group_id)\n else:\n opponent_qq = par_list[1]\n reply = await duel_qq(self, bot, group_id, self_qq, opponent_qq)\n\n return reply\n\n\ndef duel_record(self, group_id, self_qq):\n if self_qq not in self.duel_dict[group_id] or not done_today(self.duel_dict[group_id][self_qq]['date']):\n win_times = 0\n lose_times = 0\n else:\n win_times = self.duel_dict[group_id][self_qq]['win_times']\n lose_times = self.duel_dict[group_id][self_qq]['lose_times']\n reply = \"你今日决斗的战绩为:{}胜,{}负~\".format(win_times, lose_times)\n return reply\n\n\ndef duel_rank(self, group_id):\n record_list = []\n\n for qq in self.duel_dict[group_id]:\n if done_today(self.duel_dict[group_id][qq]['date']) and \\\n self.duel_dict[group_id][qq]['win_times'] >= self.duel_dict[group_id][qq]['lose_times']:\n record_list.append((qq,\n self.duel_dict[group_id][qq]['win_times'] * 2 - self.duel_dict[group_id][qq][\n 'lose_times']))\n if len(record_list) == 0:\n reply = \"今天还没有人决斗过哦,过来试试吧~\"\n else:\n record_list.sort(key=lambda k: k[1], reverse=True)\n reply = \"下面是今日的决斗榜,今天你上榜了嘛~\\n\"\n for i in range(min(len(record_list), 5)):\n win_times = self.duel_dict[group_id][record_list[i][0]]['win_times']\n lose_times = self.duel_dict[group_id][record_list[i][0]]['lose_times']\n rate = win_times / (win_times + lose_times)\n reply += \"{}.{} {}胜 胜率{}%\\n\" \\\n .format(str(i + 1), record_list[i][0], win_times, round(rate * 100, 2))\n reply = reply.strip()\n return reply\n\n\nasync def duel_qq(self, bot, group_id, self_qq, opponent_qq):\n if self_qq == opponent_qq:\n reply = \"你想自残吗……\"\n else:\n try:\n self_info = await bot.get_group_member_info(group_id=int(group_id), user_id=int(self_qq))\n opponent_info = await bot.get_group_member_info(group_id=int(group_id), user_id=int(opponent_qq))\n if self_qq == PARTNER_QQ and opponent_qq == SELF_QQ:\n reply = \"不急,等晚上再一起玩~\"\n elif self_info['role'] == 'admin' or self_info['role'] == 'owner':\n if opponent_info['role'] == \"admin\" or opponent_info['role'] == \"owner\":\n reply = \"管理员之间的争斗,我管不了……\"\n else:\n await bot.set_group_ban(group_id=int(group_id), user_id=int(opponent_qq),\n duration=10 * 60)\n reply = \"一股强大的力量袭来……\"\n elif opponent_info['role'] == \"owner\":\n await bot.set_group_ban(group_id=int(group_id), user_id=int(self_qq), duration=5 * 60)\n reply = \"竟敢挑战群主,你将受到天罚!\"\n elif str(opponent_info['user_id']) == SELF_QQ:\n await bot.set_group_ban(group_id=int(group_id), user_id=int(self_qq), duration=5 * 60)\n reply = \"我定的规则,你觉得我会输吗~\"\n elif opponent_info['role'] == \"admin\":\n await bot.set_group_ban(group_id=int(group_id), user_id=int(self_qq), duration=5 * 60)\n reply = \"竟敢挑战管理员,你将受到天罚!\"\n else:\n self_name = get_name(self_info)\n opponent_name = get_name(opponent_info)\n self_point = random.randint(1, 99)\n opponent_point = random.randint(1, 99)\n reply = \"{}掷出了{}点\\n{}掷出了{}点\\n\" \\\n .format(self_name, str(self_point), opponent_name, str(opponent_point))\n\n if self_point < opponent_point:\n win_qq = opponent_qq\n win_name = opponent_name\n lose_qq = self_qq\n loss_name = self_name\n reply += \"你在决斗中失败了……\"\n elif self_point > opponent_point:\n win_qq = self_qq\n win_name = self_name\n lose_qq = opponent_qq\n loss_name = opponent_name\n reply += \"你在决斗中胜利了!\"\n else:\n reply += \"平局!\"\n return reply\n\n if str(self.duel_dict[group_id][lose_qq]['multi_kill']) in MULTI_KILL:\n ban_time = (self.duel_dict[group_id][lose_qq]['multi_kill'] - 3) * 5 + 10\n else:\n ban_time = 10\n await bot.set_group_ban(group_id=int(group_id), user_id=int(lose_qq), duration=ban_time * 60)\n\n if str(self.duel_dict[group_id][lose_qq]['multi_kill']) in MULTI_KILL:\n reply += \"\\n{}被终结了!\".format(loss_name)\n\n record_duel_info(self.duel_dict[group_id], lose_qq, False)\n record_duel_info(self.duel_dict[group_id], win_qq, True)\n update_file(DUEL_PATH, self.duel_dict)\n if str(self.duel_dict[group_id][win_qq]['multi_kill']) in MULTI_KILL:\n reply += \"\\n{}{}\".format(win_name, MULTI_KILL[self.duel_dict[group_id][win_qq]['multi_kill']])\n except:\n reply = \"群里貌似并没有这个人……\"\n return reply\n\n\ndef record_duel_info(dict, qq, win):\n cur_date = str(cur_time().date())\n qq = str(qq)\n if qq not in dict or dict[qq]['date'] != cur_date:\n dict[qq] = {'date': cur_date, 'win_times': 0, 'lose_times': 0, 'multi_kill': 0}\n if win:\n dict[qq]['win_times'] += 1\n dict[qq]['multi_kill'] += 1\n else:\n dict[qq]['lose_times'] += 1\n dict[qq]['multi_kill'] = 0","sub_path":"violet_util.py","file_name":"violet_util.py","file_ext":"py","file_size_in_byte":9464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"151269777","text":"import os\nimport mysql.connector\nimport json\nimport sys\nimport codecs\nfrom datetime import datetime, timedelta\nimport time\nimport shutil\nimport shelve\nfrom sqlalchemy import or_, and_\nfrom flask import Flask, request, session, g, redirect, url_for, \\\n abort, render_template, flash\n\nsys.path.append(\"../\")\nfrom models.Models import *\nfrom database import db,db_session,connect_db\n\ndef convert_date(dt):\n date_json_load = datetime.datetime.strptime(\"2020-02-17\", \"%Y-%m-%d\")\n single_date = [\n ['year','years', 1],\n ['month','months', 2],\n ['week','weeks', 3],\n ['day','days', 4],\n ['hour','hours', 5],\n ['minute','minutes', 6],\n ['second','seconds', 7]\n ]\n s = \"\"\n dt_unit = None\n for d in single_date:\n if dt.find(d[0]) > 0:\n s = dt[0:dt.find(d[0])].strip()\n elif dt.find(d[1]) > 0:\n s = dt[0:dt.find(d[1])].strip()\n\n if s != \"\":\n dt_unit = d[2]\n break\n dlt = 0\n try:\n dlt = int(s)\n except:\n print(\"error format date:\")\n print(dt)\n print(s)\n return\n\n dtdelta = None\n if dt_unit == 1:\n dtdelta = timedelta(days = dlt*365)\n elif dt_unit == 2:\n dtdelta = timedelta(days = dlt*30)\n #time.localtime()[1]-1 or 12\n elif dt_unit == 3:\n dtdelta = timedelta(days = dlt*7)\n elif dt_unit == 4:\n dtdelta = timedelta(days = dlt)\n elif dt_unit == 5:\n dtdelta = timedelta(hours = dlt)\n elif dt_unit == 6:\n dtdelta = timedelta(minutes = dlt)\n elif dt_unit == 7:\n dtdelta = timedelta(seconds = dlt)\n\n return date_json_load - dtdelta\n\n\ndef rescaleByteSize(fz):\n sizeUnit = ['B','K','M','G','T']\n ext = \"B\"\n for unit in sizeUnit:\n ext = unit\n if fz < 1024 or unit == 'T':\n break\n fz = fz / 1024.0\n return \"{:.2f}{}\".format(fz,ext)\n\n\ndef file_size(fz):\n\n sizeUnit = [' B','KB','MB','GB','TB']\n ext = \"B\"\n t_unit = \"B\"\n num = 0\n l = 1\n #print(fz)\n for unit in sizeUnit:\n ext = unit\n if fz.find(ext) > -1:\n num = fz[0:fz.find(ext)].strip()\n #print(\"num:{0}\".format(fz[0:fz.find(ext)]))\n num = float(num) * l\n break\n\n l = l * 1024.0\n\n return num\n\n\ndict_hashcode = []\n\n\ndef hasscode():\n connect_db()\n session = db_session()\n\n qf = session.query(SearchHash.info_hash).filter(SearchHash.id > 3845352).all()\n for l in qf:\n dict_hashcode.append(l.info_hash)\n\n\ndef insert_data(hashjson):\n s = SearchHash()\n s.info_hash = hashjson[\"infohash\"]\n\n s.name = hashjson[\"title\"]\n s.create_time = convert_date(hashjson[\"Added Time\"])\n s.last_seen = convert_date(hashjson[\"Last Update\"])\n s.requests = hashjson[\"Leechers\"]\n s.length = file_size(hashjson[\"Size\"])\n s.filescount = hashjson[\"Total Files\"]\n\n torfile = None\n filecnt = 0\n if \"files\" in hashjson and len(hashjson[\"files\"]) > 0:\n torfile = tf_c_all()\n\n torfile.infohash = s.info_hash\n torfile.filecount = len(hashjson[\"files\"])\n fn_string = []\n for f in hashjson[\"files\"]:\n filecnt += 1\n\n fn_string.append(\",\".join(f))\n fn = u\",\".join(fn_string)\n torfile.filename = fn\n\n return s, torfile\n\n\ndef import_from_json():\n json_root = [\n \"E:/git/magspider/idope/hash\",\n \"E:/git/magspider/idope/hash1\",\n \"E:/git/magspider/idope/hash2\",\n \"E:/git/magspider/idope/hash3\",\n \"E:/git/magspider/idope/hash5\",\n \"E:/git/magspider/idope/hash11\",\n \"E:/git/magspider/idope/hash12\",\n \"E:/git/magspider/idope/hash13\"\n ]\n\n hasscode()\n for root in json_root:\n print(root)\n i =0\n connect_db()\n session = db_session()\n tf_session = db_session()\n for filename in os.listdir(root):\n i+=1\n fname = os.path.join(root,filename)\n fs = codecs.open(fname,'r','utf-8')\n hashjson = json.loads(fs.read())\n\n if hashjson[\"infohash\"] in dict_hashcode:\n continue\n try:\n #print(convert_date(hashjson[\"Added Time\"]))\n s,tf = insert_data(hashjson)\n session.add(s)\n tf_session.add(tf)\n\n if i% 1 == 0:\n print(i)\n #print(\"commit\\n\")\n session.commit()\n tf_session.commit()\n except Exception as ex:\n print(ex)\n print(root)\n\n #session.rollback()\n session.rollback()\n tf_session.rollback()\n\n fname_log = os.path.join(root,\"../hash_err/\")\n print(fname_log)\n shutil.copy(fname, fname_log)\n\n session.commit()\n tf_session.commit()\n print(i)\n print(\"commit\\n\")\n\n\ndef import_from_shelv(dbpath):\n i =0\n hasscode()\n connect_db()\n session = db_session()\n tf_session = db_session()\n db = shelve.open(dbpath)\n for k,v in db.items():\n i+=1\n if k in dict_hashcode:\n continue\n s,tf = insert_data(v)\n try:\n #print(convert_date(hashjson[\"Added Time\"]))\n s,tf = insert_data(v)\n session.add(s)\n tf_session.add(tf)\n\n if i% 1 == 0:\n print(i)\n #print(\"commit\\n\")\n session.commit()\n tf_session.commit()\n except Exception as ex:\n print(ex)\n\n session.rollback()\n tf_session.rollback()\n print(k)\n\n\n\nif __name__ == \"__main__\":\n\n #import_from_json()\n import_from_shelv(\"C:\\\\databak\\\\hash_json\\\\hash_json.svdb\")\n","sub_path":"madmin/newdata.py","file_name":"newdata.py","file_ext":"py","file_size_in_byte":5812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"}