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 = ['
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/| ' + ' | '.join(headers) + ' |
| ' + ' | '.join(values) + ' |
| ' + ' | '.join(values) + ' |
| User Id | '\n\t\tresponse+='User Name | '\n\t\tresponse+='User Mail | '\n\t\tresponse+='User Profile picture | '\n\t\tresponse+='Action | '\n\t\tresponse+='||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| {i[0]} | {i[1]} | {i[2]} | \"\n\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+=' |
| {j} | \"\n\t\t\tresponse+='
|---|
| '\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\tresponse+='
| {j} | \"\n\t\t#\tresponse+='Action | '\n\t\t#\tresponse+='||||
|---|---|---|---|---|---|
| '\n\t\t#response+=' | '\n\t\t#response+=' | '\n\t\t#response+=' | '\n\t\t#response+=' | '\n\t\t#response+=' | '\n\t\t#response+=' |
| Name | Location | District | State | ZIP code |
|---|---|---|---|---|
| {i[1]} | {i[0]} | {i[3]} | {i[2]} | {i[4]} |
cand.0.txt
\n\" + 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'\\' + 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 'Add to advisor preferences
Bio:
' + \\\n '' + strip_tags(prof[10]) + '
' + \\\n 'Academic Interests:
' + \\\n '' + strip_tags(prof[9]) + '
' + \\\n past_papers + \\\n '*Small images (< 1MB) of dimensions 300x400 px work best.
\" + \\\n \"\" + \\\n \"
| NetID: | \" + \\\n \"\" + prof[0] + \" | \" + \\\n \"
| First Name: | \" + \\\n \"\" + prof[1] + \" | \" + \\\n \"
| Last Name: | \" + \\\n \"\" + prof[2] + \" | \" + \\\n \"
| Phone: | \" + \\\n \"\" + prof[5] + \" | \" + \\\n \"
| Email: | \" + \\\n \"\" + prof[4] + \" | \" + \\\n \"
| Title: | \" + \\\n \"\" + prof[3] + \" | \" + \\\n \"
| Website: | \" + \\\n \"\" + prof[6] + \" | \" + \\\n \"
| Rooms: | \" + \\\n \"\" + prof[7] + \" | \" + \\\n \"
| Department: | \" + \\\n \"\" + prof[8] + \" | \" + \\\n \"
| Areas: | \" + \\\n \"\" + prof[9]+ \" | \" + \\\n \"
| Bio: | \" + \\\n \"\" + prof[10] + \" | \" + \\\n \"
| Image File: | \" + \\\n \"\" + prof[11] + \" | \" + \\\n \"
| \" + \" | \" +\\\n \"
*Small images (< 1MB) of dimensions 300x400 px work best.
\" + \\\n \"\" + \\\n \"