diff --git "a/2435.jsonl" "b/2435.jsonl" new file mode 100644--- /dev/null +++ "b/2435.jsonl" @@ -0,0 +1,781 @@ +{"seq_id":"137828818","text":"from procgame import *\n\nclass ParallaxDemo(game.Mode):\n\t\n\tdef __init__(self, game, priority):\n\t\t# Roep de __init__ functie van de superklasse aan om de standaard functionaliteit van een Mode te erven.\n\t\tsuper(ParallaxDemo, self).__init__(game, priority)\n\t\t\n\t\t# We gaan een lijst met parallax lagen definieren, 1 voor elke graphic die we hebben.\n\t\tself.parallax_layers = []\n\t\tself.parallax_layers += [ParallaxLayer(\"workshop_parallax5.dmd\",0.3,\"copy\")]\n\t\tself.parallax_layers += [ParallaxLayer(\"workshop_parallax4.dmd\",0.6,\"alpha\")]\n\t\tself.parallax_layers += [ParallaxLayer(\"workshop_parallax3.dmd\",0.9,\"alpha\")]\n\t\tself.parallax_layers += [ParallaxLayer(\"workshop_parallax2.dmd\",1.8,\"alpha\")]\n\t\tself.parallax_layers += [ParallaxLayer(\"workshop_parallax1.dmd\",2.7,\"alpha\")]\n\t\tself.layer = dmd.layers.GroupedLayer(128,32, self.parallax_layers)\n\t\tself.layer.opaque = True\n\t\t\t\n\t\t\nclass ParallaxLayer(dmd.Layer):\n\n\tdef __init__(self, animation_file, speed, composite_op):\n\t\tsuper(ParallaxLayer, self).__init__()\n\t\t\n\t\t# Van iedere inkomende variabele maken we een gelijknamige property in het ParallaxLayer object.\n\t\t# Op die manier zijn ze steeds bereikbaar in de next_frame() functie. \n\t\tself.frame = dmd.Animation().load(\"dmd/\" + animation_file).frames[0]\n\t\tself.speed = speed\n\t\tself.composite_op = composite_op # Goede \"blending mode\" meegeven.\n\t\tself.x = 0\n\t\t\n\tdef next_frame(self):\n\t\t# Nieuwe layers list aanmaken. \n\t\t# We hebben een list/lijst nodig omdat we soms 2 lagen moeten combineren \n\t\t# om de illusie te wekken dat de afbeeldingen oneindig lang zijn.\n\t\tlayers = []\n\t\t\n\t\t# We gaan de verschuivende laag aanmaken.\n\t\tlayer = dmd.layers.FrameLayer(False,self.frame)\n\t\tlayer.target_x = int(self.x) # Op de goede positie zetten.\n\t\tlayers += [layer] # Toevoegen aan de layers list.\n\t\t\n\t\t# Als de laag helemaal links uit beeld is, brengen we hem terug naar rechts.\n\t\tif self.x < -self.frame.width: \n\t\t\tself.x += self.frame.width\n\t\t\n\t\t# Tijdens de periode dat de rechter rand van de laag in beeld te zien is, \n\t\t# doen we deze aanvullen door dezelfde laag er rechts nog eens naast te plaatsen.\n\t\tif self.x < -self.frame.width + 128:\n\t\t\t# We gaan de tweede hulp-laag aanmaken\n\t\t\tlayer = dmd.layers.FrameLayer(False,self.frame)\n\t\t\t#layer.composite_op = self.composite_op # Goede \"blending mode\" meegeven.\n\t\t\tlayer.target_x = int(self.x) + self.frame.width # Op de goede positie zetten.\n\t\t\tlayers += [layer] # Toevoegen aan de layers list.\n\t\t\n\t\t# De positie updaten voor het volgende frame, a.d.h.v. de speed.\n\t\tself.x -= self.speed\n\t\t\n\t\treturn dmd.layers.GroupedLayer(128,32, layers).next_frame()\n\t","sub_path":"modes/parallax.py","file_name":"parallax.py","file_ext":"py","file_size_in_byte":2597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"6"} +{"seq_id":"321478152","text":"from django.core.exceptions import FieldError\nfrom django.db import models\nfrom django.test import TestCase\n\nfrom .fields import RandomSlugField\n\n\n# Using length=255 to increase chances of getting invalid character in\n# generated slug.\nclass FullSlug(models.Model):\n slug = RandomSlugField(length=255)\n\n\nclass UppercaseSlug(models.Model):\n slug = RandomSlugField(length=255, exclude_lower=True, exclude_digits=True)\n\n\nclass LowercaseSlug(models.Model):\n slug = RandomSlugField(length=255, exclude_upper=True, exclude_digits=True)\n\n\nclass DigitsSlug(models.Model):\n slug = RandomSlugField(length=255, exclude_lower=True, exclude_upper=True)\n\n\nclass NoVowelSlug(models.Model):\n slug = RandomSlugField(length=255, exclude_vowels=True)\n\n\nclass MaxSlugs(models.Model):\n slug = RandomSlugField(length=1, exclude_lower=True, exclude_upper=True)\n\n\nclass RandomSlugTestCase(TestCase):\n def setUp(self):\n self.lower = 'abcdefghijklmnopqrstuvwxyz'\n self.upper = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n self.digits = '0123456789'\n self.vowels = 'aeiouAEIOU'\n\n FullSlug.objects.create()\n LowercaseSlug.objects.create()\n UppercaseSlug.objects.create()\n DigitsSlug.objects.create()\n NoVowelSlug.objects.create()\n for _ in range(10):\n MaxSlugs.objects.create()\n\n def test_slug_length(self):\n '''Test to make sure slug is correct length.'''\n obj = FullSlug.objects.get(pk=1)\n self.assertEqual(len(obj.slug), 255)\n\n def test_slug_charset(self):\n '''Test to make sure slug only contains ascii characters and\n digits.\n '''\n chars = self.upper + self.lower + self.digits\n obj = FullSlug.objects.get(pk=1)\n self.assertTrue(obj.slug.isalnum())\n for char in obj.slug:\n self.assertTrue(char in chars)\n\n def test_slug_is_uppercase(self):\n '''Test to make sure slug only contains uppercase characters.'''\n chars = self.upper\n obj = UppercaseSlug.objects.get(pk=1)\n self.assertTrue(obj.slug.isupper() and obj.slug.isalpha())\n for char in obj.slug:\n self.assertTrue(char in chars)\n\n def test_slug_is_lowercase(self):\n '''Test to make sure slug only contains lowercase characters.'''\n chars = self.lower\n obj = LowercaseSlug.objects.get(pk=1)\n self.assertTrue(obj.slug.islower() and obj.slug.isalpha())\n for char in obj.slug:\n self.assertTrue(char in chars)\n\n def test_slug_is_digits(self):\n '''Test to make sure slug only contains digits.'''\n chars = self.digits\n obj = DigitsSlug.objects.get(pk=1)\n self.assertTrue(obj.slug.isdigit())\n for char in obj.slug:\n self.assertTrue(char in chars)\n\n def test_slug_has_no_vowels(self):\n '''Test to make sure slug contains no vowels.'''\n chars = self.vowels\n obj = NoVowelSlug.objects.get(pk=1)\n self.assertTrue(obj.slug.isalnum())\n for char in obj.slug:\n self.assertFalse(char in chars)\n\n def test_max_slug_limit(self):\n '''Test to make sure slug generation stops when there isn't any\n possible slugs remaining.\n '''\n self.assertRaises(FieldError, MaxSlugs.objects.create)\n\n def test_slugs_are_unique(self):\n '''Test to make sure all slugs generated are unique.'''\n control = MaxSlugs.objects.get(pk=1)\n queryset = MaxSlugs.objects.all().exclude(pk=1)\n for obj in queryset:\n self.assertNotEqual(obj.slug, control.slug)\n","sub_path":"randomslugfield/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":3580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"6"} +{"seq_id":"506240547","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport zmq, json, socket,signal\nimport threading\nimport time\nimport sys\nimport pickle\nclass FaceSubscriber(threading.Thread):\n def __init__(self,addr,pushaddr,yoloq):\n threading.Thread.__init__(self)\n self.context = zmq.Context()\n self.socket = self.context.socket(zmq.SUB)\n self.socket.connect(addr)\n self.socket.setsockopt(zmq.SUBSCRIBE, '')\n self.thread_state = True\n self.poller = zmq.Poller()\n self.poller.register(self.socket, zmq.POLLIN)\n self.yoloq = yoloq\n self.mutex = threading.Lock()\n self.sender = self.context.socket(zmq.PUB)\n self.sender.bind(pushaddr)\n self.sender.send(str(2))\n def stop(self):\n print(\"FaceSubscriber thread stop!\")\n self.thread_state = False\n self.socket.close()\n #signal.alarm(1) #break select method\n\n def run(self):\n i = 0\n while self.thread_state:\n socks = dict(self.poller.poll())\n if socks.get(self.socket) == zmq.POLLIN:\n msg_cli = self.socket.recv()\n\n if(i ==0):\n pickle.dump(msg_cli, open('yolodata', 'wb'))\n i =2\n #recv = json.loads(msg_cli)\n self.yoloq.put(msg_cli)\n self.sender.send(str(2))\n print('yoloq len = %d ###########################'%(self.yoloq.qsize()))\n time.sleep(0.1)\n #print(recv)\n\n\n\n\n\n","sub_path":"reconition_protocol/face_subscriber_protocol.py","file_name":"face_subscriber_protocol.py","file_ext":"py","file_size_in_byte":1512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"6"} +{"seq_id":"209620566","text":"import numpy as np\nimport os\nimport keras\nimport matplotlib.pyplot as plt\nfrom keras.layers import Dense,GlobalAveragePooling2D\nfrom keras.applications.nasnet import NASNetLarge, preprocess_input\nfrom keras.preprocessing import image\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.models import Model\nfrom keras.optimizers import Adam\nfrom keras.models import save_model\nfrom keras.callbacks import ModelCheckpoint\n\nimport pandas as pd \nimport seaborn as sn \nfrom sklearn.metrics import confusion_matrix, classification_report\n\nimport matplotlib.image as mpimg\nfrom PIL import Image\n\n\nPROJECT_ROOT_DIR = os.path.dirname(os.path.abspath(''))\n\nIMAGES_DIR = PROJECT_ROOT_DIR + '/input/stanford-dogs-dataset/images/Images'\nANNOTATIONS_DIR = PROJECT_ROOT_DIR + '/input/stanford-dogs-dataset/annotations/Annotation'\n\nRESULT_PLOTS_DIR = PROJECT_ROOT_DIR + '/plots'\n\n\ndef absolute_path(relative_path):\n return PROJECT_ROOT_DIR + '/' + relative_path\n\ntrain_data_dir = '/content/gdrive/My Drive/dm_image_classification/split/split/train' #absolute_path('split/train')\nvalidation_data_dir = '/content/gdrive/My Drive/dm_image_classification/split/split/val' #absolute_path('split/val')\n\n\nbase_model = NASNetLarge(weights='imagenet', include_top=False)\n\nx=base_model.output\nx=GlobalAveragePooling2D()(x)\nx=Dense(1024,activation='relu')(x) #we add dense layers so that the model can learn more complex functions and classify for better results.\nx=Dense(1024,activation='relu')(x) #dense layer 2\nx=Dense(512,activation='relu')(x) #dense layer 3\npreds=Dense(120,activation='softmax')(x) #final layer with softmax activation\n\nmodel = Model(inputs=base_model.input, outputs=preds)\n# specify the inputs\n# specify the outputs\n# now a model has been created based on our architecture\n\nfor i, layer in enumerate(model.layers):\n print(i, layer.name)\n\nfor layer in base_model.layers:\n layer.trainable = False\n\ntrain_datagen = ImageDataGenerator(\n preprocessing_function=preprocess_input) # included in our dependencies\n\ntrain_generator = train_datagen.flow_from_directory(train_data_dir,\n target_size=(331, 331),\n color_mode='rgb',\n batch_size=32,\n class_mode='categorical',\n shuffle=True)\n\ntest_datagen = ImageDataGenerator(preprocessing_function=preprocess_input)\n\nvalidation_generator = test_datagen.flow_from_directory(\n validation_data_dir,\n target_size=(331, 331),\n color_mode='rgb',\n batch_size=32,\n class_mode='categorical',\n shuffle=False)\n\nmodel.compile(optimizer='Adam', loss='categorical_crossentropy',\n metrics=['accuracy'])\n# Adam optimizer\n# loss function will be categorical cross entropy\n# evaluation metric will be accuracy\n\nstep_size_train = train_generator.n//train_generator.batch_size\nstep_size_validation = validation_generator.n//validation_generator.batch_size\n\n## checkpoints\nfilepath=\"/content/gdrive/My Drive/dm_image_classification/weights-improvement-naslarge-{epoch:02d}.hdf5\"\ncheckpoint = ModelCheckpoint(filepath, monitor='val_loss', verbose=1, save_best_only=False, mode='auto')\ncallbacks_list = [checkpoint]\n\nmodel.fit_generator(generator=train_generator,\n steps_per_epoch=step_size_train,\n validation_data=validation_generator,\n validation_steps=step_size_validation,\n epochs=10,\n callbacks=callbacks_list)\n\nmodel.save_weights(filepath='/content/gdrive/My Drive/dm_image_classification/nasnetlarge.h5')\n############################################### https://www.kaggle.com/devang/transfer-learning-with-keras-and-mobilenet-v2#Confusion-matrix\n# Classification report + confusion matrix \n\nvalidation_generator.reset()\npredictions = model.predict_generator(validation_generator)\nprint(predictions)\nclasses = validation_generator.classes[validation_generator.index_array]\ny = np.argmax(predictions, axis=-1)\nprint(y)\n\nprint('Classification Report')\ncr = classification_report(y_true=validation_generator.classes, y_pred=y)\nprint(cr)\n\nprint('Confusion Matrix')\nplt.clf()\ncm = confusion_matrix(validation_generator.classes, y)\ndf = pd.DataFrame(cm, columns=validation_generator.class_indices)\nplt.figure(figsize=(80,80))\nsn.heatmap(df, annot=True)\nplt.savefig('/content/gdrive/My Drive/dm_image_classification/cm_nasnetlarge.png')","sub_path":"experiments/7_nasnetlarge/classification.py","file_name":"classification.py","file_ext":"py","file_size_in_byte":4555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"6"} +{"seq_id":"394934634","text":"import sys, os\nsys.path.append(\"/\".join(os.path.abspath(__file__).split(\"/\")[0:-2]))\nimport json\nimport random\nfrom newssender import NewsSender\nfrom newsreceiver import NewsReceiver\nfrom databasetools.mongo import MongoCollection\nfrom api import MAX_PACKAGE_SIZE\n\n\n# LA BASELINE N'A PAS ACCES A LA DB ELLE FAIT DES CALLS API ET ENVOIE LA REPONSE VIA DES QUEUES RABBITMQ\n# CES QUEUES SONT TENUES PAR UN SYSTEMINTERFACE QUI A UNE FONCTION/QUEUE\n# EN ENVOI LINTERFACE PUSH DANS UNE QUEUE SPECIFIQUE PAR SYSTEM, EN RECEPTION LINTERFACE TRANSMET AU REQDISPATCHER\n# LE REQDISPATCHER TRANSMET A L'APPLICATION VIA\n\n# Résumé fonctionnement de départ:\n# Inscription du user par API ==> OK\n# API transmet le token user au ReqDispatcher\n# RD inscrit le user à un system random (garder chiffres du nombre de users/systemes)\n# tronche : rd.systems[5].subUser(userid)\n# user pushé par systeminterface sur la queue users du system\n# rd.systems[5].getNews() (ou content ou whatever)\n# demande pushée sur la queue du system\n# Début fonctionnement régulier\n# Itérer sur queue.method.message_count != 0 sur toutes les queues de manière intelligente (eh lol)\n#\n\n\n\n# Résumé fonctionnement régulier APP <=> API <=> RQ <=> SYSTEMINTERFACE <=> SYSTEM:\n# APP_API_CALL arrive sur l'API.\n# Call transmis au reqdispatcher\n# reqdispatcher match usertoken et system responsable ==> OK\n# reqdispatcher.systemsinscrits est une liste d'interfaces systems\n# reqdispatcher.\n\nclass Baseline:\n def __init__(self):\n # sender parameters : def __init__(self, host='localhost', queue_name='news_data_queue'):\n self.name = \"Baseline\"\n self.queues = []\n self.queues.append(NewsSender(queue_name=\"rec_request_\" + self.name))\n self.queues.append(NewsSender(queue_name=\"user_assign_\" + self.name))\n self.queues.append(NewsSender(queue_name=\"news_rec_\" + self.name))\n self.queues.append(NewsSender(queue_name=\"user_data_\" + self.name))\n self.queues.append(NewsSender(queue_name=\"news_request_\" + self.name))\n self.sender = NewsSender()\n self.receiver = NewsReceiver()\n self.articles = []\n\n def getRandomArticles(self, amount=50):\n # make an API call to api.Bulk\n pass\n\nif __name__ == '__main__':\n bs = Baseline()\n print(bs.getRandomArticles())\n\n# Connecter automatiquement la baseline à toutes les queues qui doivent envoyer/recevoir ordres et données, ces queues\n# seront connectées de l'autre côté par l'interface system qui va envoyer via sys.sendContent(content)\n# ou sys.sendUsers(listofusers)(example). 1 FONCTION = 1 queue dans SystemInterface\n","sub_path":"newssourceaggregator/prototypes/baseline.py","file_name":"baseline.py","file_ext":"py","file_size_in_byte":2625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"6"} +{"seq_id":"245292721","text":"from __future__ import print_function\nimport requests\nimport json\nimport base64\nfrom string import Template\nimport argparse\nimport csv\nimport untangle\nimport subprocess\nfrom xml.sax import SAXParseException\n\n__author__ = 'lab'\n\nPDB_UNP_ALIGN_URL = 'http://www.rcsb.org/pdb/rest/das/pdb_uniprot_mapping/alignment?query='\nUNP_FASTA_URL = 'http://www.uniprot.org/uniprot/'\nECOD_FASTA_URL = 'http://prodata.swmed.edu/ecod/complete/sequence?id='\nUNP_FASTA_FILE = \"/tmp/unp.fasta\"\nECOD_FASTA_FILE = \"/tmp/ecod.fasta\"\nSWALIGN_CMD = \"java -jar NWAlign.jar \"\nNEO4J_CREATE_TRAN_URL = \"http://localhost:7474/db/data/transaction/commit\"\nNEO4J_USER_PASS = 'neo4j:Sheshi6'\n\ndef main():\n args = parse_args()\n source = args.ecod_source\n # csv_destination = args.csv_destination\n # destination = args.destination\n csv_reader = csv.DictReader(source, delimiter=\"\\t\")\n domain_unp_mapping = {}\n for row in csv_reader:\n domain_uid = row['Uid']\n domain_id = row['Domain_id']\n chain_ids = get_chain_id(row)\n for chain_id in chain_ids:\n try:\n aligned_uniprot = get_aligned_uniprot(chain_id)\n uniprot_fasta = get_uniprot_fasta(aligned_uniprot)\n domain_fasta = get_domain_fasta(domain_id)\n alignment = get_uniprot_domain_alignment()\n alignment_map = json.loads(alignment);\n if float(alignment_map['sequence_identity']) >= 0.9:\n neo4j_map_ecod2unp(int(domain_uid), aligned_uniprot, alignment_map['matches'])\n else:\n print('ECOD entry '+domain_uid+\" Doesn't match against UNP entry \"+aligned_uniprot+\n \" sequence_identity is: \"+alignment_map['sequence_identity']+\"\\n\")\n except SAXParseException as e:\n print('ECOD entry '+domain_uid+\" raised a SAX exception while matching against UNP entry\\n\")\n print(e)\n except TypeError as e:\n print('ECOD entry '+domain_uid+\" raised a Type error exception while matching against UNP entry\"+aligned_uniprot+\"\\n sequence_identity: \"+str(alignment_map['sequence_identity'])+\"\\n\")\n print(e)\n\ndef parse_args():\n parser = argparse.ArgumentParser(description=\"Import ECOD to pdb and uniprot mapping.\")\n # exclusive_group = parser.add_mutually_exclusive_group(required=True)\n # batch_group = exclusive_group.add_argument_group(\"Batch processing\", \"description\")\n parser.add_argument(\"-ecod_src\", \"--ecod_source\", help=\"Source file with ECOD IDs\", type=file, required=True)\n parser.add_argument(\"-pdb_unp_map\", \"--pdb_unp_mapping\", help=\"Source file with PDB to UNP residue mapping\", type=file, required=True)\n # parser.add_argument(\"-csvdst\", \"--csv_destination\", help=\"CSV mapping file destination\", type=argparse.FileType('w'),\n # required=True)\n # parser.add_argument(\"-dst\", \"--destination\", help=\"Mapping file destination\", type=argparse.FileType('w'),\n # required=True)\n args = parser.parse_args()\n return args\n\ndef get_chain_id(row):\n pdb_id = row['Domain_id'][1:5]\n chain_list = []\n if \".\" == row['Chain_id']:\n for chain_res in row['PDB_residue_range'].split(\",\"):\n chain_list.append(pdb_id+\".\"+chain_res.split(\":\")[0])\n else:\n chain_list.append(pdb_id+\".\"+row['Chain_id'])\n return chain_list\n\ndef get_aligned_uniprot(chain_id):\n obj = untangle.parse(PDB_UNP_ALIGN_URL+chain_id)\n for alignObject in obj.dasalignment.alignment.alignObject:\n if 'UniProt' == alignObject['dbSource']:\n return alignObject['dbAccessionId']\n\ndef get_uniprot_fasta(aligned_uniprot):\n fasta = requests.get(UNP_FASTA_URL+aligned_uniprot+'.fasta').text\n unp_fa = open(UNP_FASTA_FILE, 'w')\n print(fasta, file=unp_fa)\n unp_fa.close()\n\ndef get_domain_fasta(domain_id):\n fasta = requests.get(ECOD_FASTA_URL+domain_id).text\n ecod_fa = open(ECOD_FASTA_FILE, 'w')\n print(fasta, file=ecod_fa)\n ecod_fa.close()\n\ndef get_uniprot_domain_alignment():\n return subprocess.check_output([SWALIGN_CMD+UNP_FASTA_FILE+' '+ECOD_FASTA_FILE, ], shell=True)\n\ndef neo4j_map_ecod2unp(domain_id, aligned_uniprot, matches_list):\n createmappings(domain_id, aligned_uniprot, matches_list, NEO4J_CREATE_TRAN_URL)\n\ndef createmappings(domain_id, aligned_uniprot, matches_list, trans_location):\n unp_statment_template = 'MATCH (d:Domain {uid: $domain_uid})' \\\n ' MERGE (u:UniprotEntry {accession: \"$unp_acc\"})' \\\n ' CREATE UNIQUE (d)-[:MATCHES {uniprot_start: $uniprot_start, uniprot_end: $uniprot_end, ecod_start: $ecod_start, ecod_end: $ecod_end}]->(u)'\n unp_template = Template(unp_statment_template)\n statments_list = []\n\n for match in matches_list:\n unp_statment = unp_template.substitute(domain_uid=domain_id, unp_acc=aligned_uniprot,\n uniprot_start=match['uniprot_start'], uniprot_end=match['uniprot_end'],\n ecod_start=match['ecod_start'], ecod_end=match['ecod_end'])\n statments_list.append({'statement': unp_statment})\n\n statements_dict = {'statements': statments_list}\n\n r = requests.post(trans_location, headers=generateheaders(),data=json.dumps(statements_dict))\n r_obj = json.loads(r.text)\n if r_obj['errors']:\n print(\"Errors occured while mapping ecod \"+domain_id+\" to uniprot \"+aligned_uniprot+\"\\n\")\n print(r_obj['errors'])\n\ndef generateheaders():\n return {'Authorization': base64.b64encode(NEO4J_USER_PASS),\n 'Accept': 'application/json; charset=UTF-8',\n 'Content-Type': 'application/json'}\n\nif __name__ == \"__main__\":\n main()","sub_path":"mapDomains2UNP.py","file_name":"mapDomains2UNP.py","file_ext":"py","file_size_in_byte":5767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"267529434","text":"from pyradioconfig.calculator_model_framework.interfaces.itarget import ITarget\nfrom os.path import join\n\nclass Target_Sim_Sol(ITarget):\n\n _targetName = \"Sim\"\n _description = \"Supports the wired FPGA and other targets of sim PHYs\"\n _store_config_output = True\n _cfg_location = join('target_sim','sol')\n _tag = \"SIM\"\n\n def target_calculate(self, model):\n\n #Always use fixed length in sim results\n model.vars.frame_length_type.value_forced = model.vars.frame_length_type.var_enum.FIXED_LENGTH\n\n #PHY-specific rules (to be replaced globally once we figure out how calculate where they need to apply)\n if model.phy.name == 'PHY_Bluetooth_LE_1M_Viterbi_917M_noDSA':\n\n # template - put correct calls here\n self.FRC_DFLCTRL_DISABLE(model)\n self.FRC_FCD_DISABLE(model)\n self.MODEM_SHAPING_OVERRIDE(model)\n\n elif model.phy.name == 'PHY_Bluetooth_LE_2M_Viterbi_noDSA_fullrate':\n\n # template - put correct calls here\n self.FRC_DFLCTRL_DISABLE(model)\n self.FRC_FCD_DISABLE(model)\n self.MODEM_SHAPING_OVERRIDE(model)\n\n elif model.phy.name == 'PHY_Bluetooth_LE_2M_Viterbi':\n\n # template - put correct calls here\n self.FRC_DFLCTRL_DISABLE(model)\n self.FRC_FCD_DISABLE(model)\n self.MODEM_SHAPING_OVERRIDE(model)\n\n elif model.phy.name == 'PHY_Bluetooth_LE':\n\n # template - put correct calls here\n self.FRC_DFLCTRL_DISABLE(model)\n self.FRC_FCD_DISABLE(model)\n self.MODEM_SHAPING_OVERRIDE(model)\n\n elif model.phy.name == 'PHY_Bluetooth_LE_Viterbi_noDSA_fullrate':\n\n # template - put correct calls here\n self.FRC_DFLCTRL_DISABLE(model)\n self.FRC_FCD_DISABLE(model)\n self.MODEM_SHAPING_OVERRIDE(model)\n\n elif model.phy.name == 'PHY_Bluetooth_LE_Viterbi_noDSA':\n\n # template - put correct calls here\n self.FRC_DFLCTRL_DISABLE(model)\n self.FRC_FCD_DISABLE(model)\n self.MODEM_SHAPING_OVERRIDE(model)\n\n elif model.phy.name == 'PHY_Bluetooth_LE_Viterbi':\n\n # template - put correct calls here\n self.FRC_DFLCTRL_DISABLE(model)\n self.FRC_FCD_DISABLE(model)\n self.MODEM_SHAPING_OVERRIDE(model)\n\n elif model.phy.name == 'PHY_Bluetooth_LongRange_dsa_125kbps':\n\n # template - put correct calls here\n self.FRC_DFLCTRL_DISABLE(model)\n self.FRC_FCD_DISABLE(model)\n self.MODEM_SHAPING_OVERRIDE(model)\n self.FRC_LONGRANGE_OVERRIDE(model)\n\n elif model.phy.name == 'PHY_Bluetooth_LongRange_dsa_500kbps':\n\n # template - put correct calls here\n self.FRC_DFLCTRL_DISABLE(model)\n self.FRC_FCD_DISABLE(model)\n self.MODEM_SHAPING_OVERRIDE(model)\n self.FRC_LONGRANGE_OVERRIDE(model)\n\n elif model.phy.name == 'PHY_Bluetooth_LongRange_NOdsa_125kbps':\n\n # template - put correct calls here\n self.FRC_DFLCTRL_DISABLE(model)\n self.FRC_FCD_DISABLE(model)\n self.MODEM_SHAPING_OVERRIDE(model)\n self.FRC_LONGRANGE_OVERRIDE(model)\n\n elif model.phy.name == 'PHY_Bluetooth_LongRange_NOdsa_500kbps':\n\n # template - put correct calls here\n self.FRC_DFLCTRL_DISABLE(model)\n self.FRC_FCD_DISABLE(model)\n self.MODEM_SHAPING_OVERRIDE(model)\n self.FRC_LONGRANGE_OVERRIDE(model)\n\n elif model.phy.name == 'PHY_IEEE802154_2p4GHz_cohdsa_diversity':\n\n # template - put correct calls here\n self.FRC_DFLCTRL_DISABLE(model)\n self.FRC_FCD_DISABLE(model)\n # self.MODEM_SHAPING_OVERRIDE(model)\n\n elif model.phy.name == 'PHY_IEEE802154_2p4GHz_cohdsa':\n\n # template - put correct calls here\n self.FRC_DFLCTRL_DISABLE(model)\n self.FRC_FCD_DISABLE(model)\n # self.MODEM_SHAPING_OVERRIDE(model)\n\n elif model.phy.name == 'PHY_IEEE802154_2p4GHz_diversity':\n\n # template - put correct calls here\n self.FRC_DFLCTRL_DISABLE(model)\n self.FRC_FCD_DISABLE(model)\n # self.MODEM_SHAPING_OVERRIDE(model)\n\n elif model.phy.name == 'PHY_IEEE802154_2p4GHz':\n\n # template - put correct calls here\n self.FRC_DFLCTRL_DISABLE(model)\n self.FRC_FCD_DISABLE(model)\n # self.MODEM_SHAPING_OVERRIDE(model)\n\n ############################################################################\n\n def FRC_DFLCTRL_DISABLE(self, model):\n # Dynamic frame length is not currently supported in RTL simulations\n model.vars.FRC_DFLCTRL_DFLBITORDER.value_forced = 0\n model.vars.FRC_DFLCTRL_DFLBITS.value_forced = 0\n model.vars.FRC_DFLCTRL_DFLINCLUDECRC.value_forced = 0\n model.vars.FRC_DFLCTRL_DFLMODE.value_forced = 0\n model.vars.FRC_DFLCTRL_DFLOFFSET.value_forced = 0\n model.vars.FRC_DFLCTRL_DFLSHIFT.value_forced = 0\n model.vars.FRC_DFLCTRL_MINLENGTH.value_forced = 0\n\n def FRC_FCD_DISABLE(self, model):\n model.vars.FRC_CTRL_RXFCDMODE.value_forced = 0\n model.vars.FRC_CTRL_TXFCDMODE.value_forced = 0\n model.vars.FRC_FCD0_CALCCRC.value_forced = 0\n model.vars.FRC_FCD0_EXCLUDESUBFRAMEWCNT.value_forced = 0\n model.vars.FRC_FCD0_SKIPWHITE.value_forced = 0\n model.vars.FRC_FCD0_WORDS.value_forced = 255\n model.vars.FRC_FCD1_CALCCRC.value_forced = 0\n model.vars.FRC_FCD1_INCLUDECRC.value_forced = 0\n model.vars.FRC_FCD1_SKIPWHITE.value_forced = 0\n model.vars.FRC_FCD1_WORDS.value_forced = 255\n model.vars.FRC_FCD2_CALCCRC.value_forced = 0\n model.vars.FRC_FCD2_INCLUDECRC.value_forced = 0\n model.vars.FRC_FCD2_SKIPWHITE.value_forced = 0\n model.vars.FRC_FCD2_WORDS.value_forced = 255\n model.vars.FRC_FCD3_BUFFER.value_forced = 0\n model.vars.FRC_FCD3_CALCCRC.value_forced = 0\n model.vars.FRC_FCD3_INCLUDECRC.value_forced = 0\n model.vars.FRC_FCD3_SKIPWHITE.value_forced = 0\n model.vars.FRC_FCD3_WORDS.value_forced = 255\n\n def FRC_LONGRANGE_OVERRIDE(self, model):\n # needed for simulation\n model.vars.FRC_CTRL_RXFCDMODE.value_forced = 2\n model.vars.FRC_CTRL_TXFCDMODE.value_forced = 2\n model.vars.FRC_FCD0_CALCCRC.value_forced = 1\n model.vars.FRC_FCD0_WORDS.value_forced = 3\n # FIXME: Guner: Why?\n model.vars.MODEM_SYNC0_SYNC0.value_forced = 2391391958\n\n def MODEM_SHAPING_OVERRIDE(self, model):\n # always overwrite the calculator shaping filter coefficients with ideal Gaussian filter for BLE PHYs\n model.vars.MODEM_CTRL0_SHAPING.value_forced = 2\n model.vars.MODEM_SHAPING0_COEFF0.value_forced = 4\n model.vars.MODEM_SHAPING0_COEFF1.value_forced = 10\n model.vars.MODEM_SHAPING0_COEFF2.value_forced = 20\n model.vars.MODEM_SHAPING0_COEFF3.value_forced = 34\n model.vars.MODEM_SHAPING1_COEFF4.value_forced = 50\n model.vars.MODEM_SHAPING1_COEFF5.value_forced = 65\n model.vars.MODEM_SHAPING1_COEFF6.value_forced = 74\n model.vars.MODEM_SHAPING1_COEFF7.value_forced = 79\n model.vars.MODEM_SHAPING2_COEFF8.value_forced = 0\n model.vars.MODEM_SHAPING2_COEFF9.value_forced = 0\n model.vars.MODEM_SHAPING2_COEFF10.value_forced = 0\n model.vars.MODEM_SHAPING2_COEFF11.value_forced = 0\n model.vars.MODEM_SHAPING3_COEFF12.value_forced = 0\n model.vars.MODEM_SHAPING3_COEFF13.value_forced = 0\n model.vars.MODEM_SHAPING3_COEFF14.value_forced = 0\n model.vars.MODEM_SHAPING3_COEFF15.value_forced = 0\n model.vars.MODEM_SHAPING4_COEFF16.value_forced = 0\n model.vars.MODEM_SHAPING4_COEFF17.value_forced = 0\n model.vars.MODEM_SHAPING4_COEFF18.value_forced = 0\n model.vars.MODEM_SHAPING4_COEFF19.value_forced = 0\n model.vars.MODEM_SHAPING5_COEFF20.value_forced = 0\n model.vars.MODEM_SHAPING5_COEFF21.value_forced = 0\n model.vars.MODEM_SHAPING5_COEFF22.value_forced = 0\n model.vars.MODEM_SHAPING5_COEFF23.value_forced = 0\n model.vars.MODEM_SHAPING6_COEFF24.value_forced = 0\n model.vars.MODEM_SHAPING6_COEFF25.value_forced = 0\n model.vars.MODEM_SHAPING6_COEFF26.value_forced = 0\n model.vars.MODEM_SHAPING6_COEFF27.value_forced = 0\n model.vars.MODEM_SHAPING7_COEFF28.value_forced = 0\n model.vars.MODEM_SHAPING7_COEFF29.value_forced = 0\n model.vars.MODEM_SHAPING7_COEFF30.value_forced = 0\n model.vars.MODEM_SHAPING7_COEFF31.value_forced = 0\n model.vars.MODEM_SHAPING8_COEFF32.value_forced = 0\n model.vars.MODEM_SHAPING8_COEFF33.value_forced = 0\n model.vars.MODEM_SHAPING8_COEFF34.value_forced = 0\n model.vars.MODEM_SHAPING8_COEFF35.value_forced = 0\n model.vars.MODEM_SHAPING9_COEFF36.value_forced = 0\n model.vars.MODEM_SHAPING9_COEFF37.value_forced = 0\n model.vars.MODEM_SHAPING9_COEFF38.value_forced = 0\n model.vars.MODEM_SHAPING9_COEFF39.value_forced = 0\n model.vars.MODEM_SHAPING10_COEFF40.value_forced = 0\n model.vars.MODEM_SHAPING10_COEFF41.value_forced = 0\n model.vars.MODEM_SHAPING10_COEFF42.value_forced = 0\n model.vars.MODEM_SHAPING10_COEFF43.value_forced = 0\n model.vars.MODEM_SHAPING11_COEFF44.value_forced = 0\n model.vars.MODEM_SHAPING11_COEFF45.value_forced = 0\n model.vars.MODEM_SHAPING11_COEFF46.value_forced = 0\n model.vars.MODEM_SHAPING11_COEFF47.value_forced = 0\n\n def TX_MODE_1(self, model):\n # override Package/pyradioconfig/parts/ocelot/calculators/calc_synth.py output\n # some PHYs are having issue with the TX synth locking in RNM simulation\n\n model.vars.SYNTH_LPFCTRL2TX_CASELTX.value_forced = 1\n model.vars.SYNTH_LPFCTRL2TX_CAVALTX.value_forced = 8\n model.vars.SYNTH_LPFCTRL2TX_CZSELTX.value_forced = 1\n model.vars.SYNTH_LPFCTRL2TX_CZVALTX.value_forced = 70\n model.vars.SYNTH_LPFCTRL2TX_CFBSELTX.value_forced = 0\n model.vars.SYNTH_LPFCTRL2TX_LPFGNDSWENTX.value_forced = 0\n model.vars.SYNTH_LPFCTRL2TX_LPFINCAPTX.value_forced = 2\n model.vars.SYNTH_LPFCTRL2TX_MODESELTX.value_forced = 0\n model.vars.SYNTH_LPFCTRL1TX_OP1BWTX.value_forced = 5\n model.vars.SYNTH_LPFCTRL1TX_OP1COMPTX.value_forced = 13\n # model.vars.SYNTH_LPFCTRL2TX_CALCTX.value_forced = 16\n model.vars.SYNTH_LPFCTRL1TX_RFBVALTX.value_forced = 0\n model.vars.SYNTH_LPFCTRL1TX_RPVALTX.value_forced = 0\n model.vars.SYNTH_LPFCTRL1TX_RZVALTX.value_forced = 3\n model.vars.SYNTH_LPFCTRL2TX_LPFSWENTX.value_forced = 1\n # model.vars.RAC_SYTRIM0_SYCHPCURRTX.value_forced = 4\n model.vars.SYNTH_DSMCTRLTX_REQORDERTX.value_forced = 0\n model.vars.SYNTH_DSMCTRLTX_MASHORDERTX.value_forced = 0\n model.vars.SYNTH_DSMCTRLTX_DEMMODETX.value_forced = 1\n model.vars.SYNTH_DSMCTRLTX_LSBFORCETX.value_forced = 0\n model.vars.SYNTH_DSMCTRLTX_DSMMODETX.value_forced = 0\n model.vars.SYNTH_DSMCTRLTX_DITHERDACTX.value_forced = 3\n model.vars.SYNTH_DSMCTRLTX_DITHERDSMOUTPUTTX.value_forced = 3\n model.vars.SYNTH_DSMCTRLTX_DITHERDSMINPUTTX.value_forced = 1\n # model.vars.RAC_SYMMDCTRL_SYMMDMODETX.value_forced = 2\n model.vars.RAC_SYTRIM1_SYLODIVLDOTRIMNDIOTX.value_forced = 4\n model.vars.RAC_SYTRIM1_SYLODIVLDOTRIMCORETX.value_forced = 3\n model.vars.RAC_VCOCTRL_VCODETAMPLITUDETX.value_forced = 4\n model.vars.RAC_TX_SYCHPBIASTRIMBUFTX.value_forced = 1\n model.vars.RAC_TX_SYPFDCHPLPENTX.value_forced = 0\n model.vars.RAC_TX_SYPFDFPWENTX.value_forced = 0\n model.vars.RAC_SYEN_SYCHPLPENTX.value_forced = 0\n model.vars.RAC_SYTRIM0_SYCHPLEVPSRCTX.value_forced = 7\n model.vars.RAC_SYTRIM0_SYCHPSRCENTX.value_forced = 1\n","sub_path":"platform/radio/efr32_multiphy_configurator/pyradioconfig/parts/sol/targets/Target_Sim.py","file_name":"Target_Sim.py","file_ext":"py","file_size_in_byte":12008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"625002381","text":"from sys import stdin\ndef numero(lista):\n pivote = lista[len(lista)//2]\n listsum= [abs(x-pivote) for x in lista]\n return sum(listsum)\ndef main():\n casos = int(stdin.readline())\n for i in range(casos):\n lista = [int(x) for x in stdin.readline().strip().split()]\n del lista[0]\n lista.sort()\n print(numero(lista))\nmain()\n","sub_path":"ejercicios/Misc/vito.py","file_name":"vito.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"367674807","text":"# Convolutional Neural Network\n\n# Part 1 - Building the CNN\n\n#Importing the Keras libraries and packages\nfrom keras.models import Sequential\nfrom keras.layers import Convolution2D\nfrom keras.layers import MaxPooling2D\nfrom keras.layers import Flatten\nfrom keras.layers import Dense\n\n# Initialising the CNN\nclassifier = Sequential()\n\n# Step 1 - Convolution\nclassifier.add(Convolution2D(filters= 32, kernel_size= (3,3), data_format= \"channels_last\",\n input_shape= (64,64,3), activation= 'relu'))\n\n# Step 2 - Max Pooling\nclassifier.add(MaxPooling2D(pool_size=(2,2), strides= (2,2)))\n\n# Adding a second convolutional layer\nclassifier.add(Convolution2D(filters= 32, kernel_size= (3,3), data_format= \"channels_last\", \n activation= 'relu'))\nclassifier.add(MaxPooling2D(pool_size=(2,2), strides= (2,2)))\n\n# Step 3 - Flattening\nclassifier.add(Flatten())\n\n# Step 4 - Full connection\n\n# Hidden layer\nclassifier.add(Dense(output_dim= 128, activation= 'relu'))\n# Output layer\nclassifier.add(Dense(output_dim= 1, activation= 'sigmoid'))\n\n# Compiling the CNN\nclassifier.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])\n\n# Part 2 - Fitting the CNN to images\nfrom keras.preprocessing.image import ImageDataGenerator\n\ntrain_datagen= ImageDataGenerator(\n rescale= 1./255,\n shear_range= 0.2,\n zoom_range =0.2,\n horizontal_flip=True)\n\ntest_datagen= ImageDataGenerator(rescale=1./255)\n\ntraining_set= train_datagen.flow_from_directory(directory= 'dataset/training_set',\n target_size= (64,64),\n batch_size= 32,\n class_mode= 'binary')\n\ntest_set= test_datagen.flow_from_directory(directory='dataset/test_set',\n target_size= (64,64),\n batch_size= 32,\n class_mode= 'binary')\n\nclassifier.fit_generator(training_set,\n samples_per_epoch= 8000,\n nb_epoch= 20,\n validation_data= test_set,\n nb_val_samples= 2000)\n\n#Part 3 - Make new predictions\n\nimport numpy as np\nfrom keras.preprocessing import image\ntest_image = image.load_img('dataset/single_prediction/cat_or_dog_2.jpg', target_size= (64,64))\ntest_image = image.img_to_array(test_image)\ntest_image = np.expand_dims(test_image, axis=0)\nresult = classifier.predict(test_image)\ntraining_set.class_indices\nif result[0][0] == 1:\n prediction= 'dog'\nelse:\n prediction = 'cat'\n \nprint(\"The image is predicted to be a\", prediction)\n\n\n\n\n\n\n","sub_path":"cnn.py","file_name":"cnn.py","file_ext":"py","file_size_in_byte":2722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"64781638","text":"import re\nimport logging\nfrom model import QuestionType\n\nlogging.basicConfig(level=logging.INFO, filename='logs\\\\info.log')\nlogger_io = logging.getLogger('IO')\nlogger_process = logging.getLogger('process')\n\n\ndef is_empty(string):\n \"\"\"\n This method verifies if the given string is empty\n '' ---> True\n None ---> True\n 'None' ---> True\n \"\"\"\n return string is None or not string.strip() or string == 'None'\n\n\ndef is_empty_with_none(string):\n \"\"\"\n This method verifies if the given string is empty\n '' ---> True\n None ---> True\n \"\"\"\n return string is None or not string.strip()\n\n\ndef format_filename(string):\n filename = string.replace(' ', '_')\n filename = ''.join(c\n .replace('/', '_')\n .replace('(', '')\n .replace(')', '')\n .replace('@', '_')\n .replace('*', '')\n .replace('&', '_')\n .replace('$', '')\n .replace('+', '')\n for c in filename)\n return filename\n\n\ndef replace_ignore(str_val, old, new):\n pattern = re.compile(re.escape(old), re.IGNORECASE)\n return pattern.sub(new, str_val)\n\n\ndef wrap_padding(value):\n return '##' + value + '##'\n\n\ndef str_to_type(type_text):\n type_dict = {\n 'LargeText': QuestionType.LARGE_TEXT,\n 'Checkbox': QuestionType.CHECKBOX,\n 'Radio': QuestionType.RADIO\n }\n return type_dict.get(type_text, QuestionType.LARGE_TEXT)\n\n\ndef join_with_commas(list_, op=lambda x: x):\n with_comma = ', '.join([op(e) for e in list_ if e is not None])\n at_last = with_comma.rsplit(',', 1)\n if len(at_last) > 1:\n with_comma = at_last[0] + ' and' + at_last[1]\n return with_comma\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"480500555","text":"import pip\n\nkREQ_PKG = ['unidecode', 'wikipedia', 'whoosh', 'nltk', 'scikit-learn', 'regex', 'fuzzywuzzy']\n\ndef install(package):\n pip.main(['install', package])\n\nif __name__ == '__main__':\n for ii in kREQ_PKG:\n install(ii)\n\n import nltk\n nltk.download(\"stopwords\")\n nltk.download('punkt')\n","sub_path":"util/install_python_packages.py","file_name":"install_python_packages.py","file_ext":"py","file_size_in_byte":312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"513171817","text":"# find intersections in tree structure\n# create intersection file and format it\n# for d3 force layout \n\n#NOTE: d3.v3 requires inexplicit indexing for links and nodes \n#rather than attaching an explicit id to a node and referencing it\n#in a link. Thus, every node is given an index that is referenced\n#by a link. A node's index is inexplicitly declared by the order\n#in which it is appended into the json file. (i.e, if a node is\n#the second node in the list then its index is 2)\n\nimport json\nfrom itertools import combinations\nimport sys\n\n#Change these values if needed\nCREATE_INTERFILE = True #true or false\nTHRESHOLD = int(sys.argv[2])\nALGORITHM = sys.argv[1]\n\n# files necessary to create intersection file\nNUCLPATH = 'graphIndexed.mtx_'+ALGORITHM+'_NUCLEI' # verticies contain in each node\nJSONPATH = 'graphIndexed.mtx_'+ALGORITHM+'_circle.json' # tree structure\nVERTEXID = 'data/indexDict.json' # original vertex id\n\n# output files\nINTEPATH = 'data/intersections.json' # intersection file\nFORCPATH = 'graphForce.json' # formatted intersection file\n\n#open nucli file and obtain the vertex ids for each node\n#open the index file to obtain real vertex ids\ndef getVertexIds(npath, dpath):\n #ARG: string path\n #RET: dict: key = node id\n # value = array of vertex ids\n\n #open index dictionary file\n with open(dpath) as file:\n json_data = json.load(file)\n file.close()\n\n #open the nucli file and obtain the vertex ids\n #and change the ids to the real one\n #return the new ids\n with open(npath) as file:\n verticies = {}\n lines = file.readlines()\n for line in lines:\n line = line.split(' ')\n index = line[0]\n temp = line[7:-1]\n\n dups = {}\n v = []\n for new_id in temp:\n if new_id not in dups:\n dups.update({new_id:0})\n v.append(json_data[new_id])\n #v.append(new_id)\n\n verticies[index] = v\n file.close()\n\n print(\"\\tVerticies loaded\")\n return verticies\n\n#open circle json file and obtain the tree structure\ndef getTreeStruct(path, threshold):\n #ARG: string path, int\n #RET: json object\n\n #to do\n def filterTree(parent, threshold):\n if 'children' not in parent:\n return\n parent['children'] = filter(lambda x: x['size'] > threshold, parent['children'])\n for child in parent['children']:\n filterTree(child, threshold)\n\n #open circle json file and return the file\n with open(path) as file:\n json_data = json.load(file)\n filterTree(json_data, threshold)\n print(\"\\tThreshold set at {0}\".format(threshold))\n file.close()\n\n print(\"\\tTree loaded\")\n return json_data\n\n#using the nucli, circle, and index file, find the intersections\ndef findIntersections(jpath, npath, dpath, threshold):\n #ARG: string path, string path\n #RET: dict: key = vertex id,\n # value = array of node ids\n\n #get the real vertex ids and tree structure\n verticies = getVertexIds(npath, dpath)\n tree = getTreeStruct(jpath, threshold)\n intersections = {}\n\n #for every node that references the same vertex\n #create #nodes choose 2 (nCk) pairs\n def createLinks(intersections):\n #ARG: dict: key = vertex id,\n # value = array of node ids\n #RET: dict: key = vertex id,\n # value = array of size 2 arrays\n for vertex, nodes in intersections.iteritems():\n comb = combinations(list(nodes.keys()),2)\n intersections[vertex] = list(comb)\n\n return intersections\n\n #remove the verticies that have less than 2 nodes\n def filterIntersections(intersections):\n #ARG: dict\n #RET: dict\n filtered = {}\n for key,value in intersections.iteritems():\n if len(value) > 1:\n filtered.update({key:value})\n return filtered\n\n #traverse down the tree and for every vertex, find the \n #deepest nodes that references it\n #if less than 2 nodes reference a vertex then there is\n #no intersection for that vertex\n def intersectionsHelp(parent):\n\n # if no children return\n if 'children' not in parent:\n return\n\n # for every child\n for child in parent['children']:\n\n # get the verticies contained in child\n child_index = str(child['index'])\n parent_index = str(parent['index'])\n\n if child_index in verticies:\n\n v = verticies[child_index]\n\n # for every vertex id\n for vertex in v:\n\n if vertex not in intersections:\n intersections[vertex] = {}\n\n # remove the parent index that contains vertex\n if parent_index in intersections[vertex]:\n del intersections[vertex][parent_index]\n\n # add child index that ref the vertex id\n intersections[vertex][child_index] = vertex\n\n intersectionsHelp(child)\n\n intersectionsHelp(tree)\n\n #remove the verticies that have less than 2 nodes referencing it\n filtered = filterIntersections(intersections)\n\n print('\\tIntersections found')\n return createLinks(filtered)\n\ndef dumpIntersections(ipath, intersections):\n #ARG: str path, dict\n #RET: nothing\n\n print('\\tCreating intersection file')\n with open(ipath, 'w') as file:\n json.dump(intersections, file, indent=4)\n file.close() \n\ndef forcelayout_format(fpath, intersections):\n #ARG: str path, dict\n #RET: nothing\n\n print('\\tCreating force layout file format')\n graph = {'graph':[],'links':[],'nodes':[],'directed':'false','multigraph':'false'}\n links = {}\n inter_count = {}\n index_to_node = []\n node_to_index = {}\n\n with open(fpath, 'w') as file:\n index = 0\n\n #create a link and attach the device that results in that link\n #count the number of times a node participates in a link\n #create indicies for every node\n for vertex, nodes in intersections.iteritems():\n for a,b in nodes:\n source = a if a >= b else b\n target = a if a < b else b\n if (source, target) in links:\n links[source,target].append(vertex)\n else:\n links.update({(source,target):[vertex]})\n if a not in inter_count:\n inter_count[a] = 1\n index_to_node.append(a)\n node_to_index[a] = index\n index += 1\n else:\n inter_count[a] += 1\n if b not in inter_count:\n inter_count[b] = 1\n index_to_node.append(b)\n node_to_index[b] = index\n index += 1\n #print(index_to_node[index-1],b,index-1)\n else:\n inter_count[b] += 1\n\n #for every node that participates in a link, append it to the graph\n #for every link, append it to the graph\n for i in range(len(index_to_node)):\n n = index_to_node[i]\n size = inter_count[n]\n graph['nodes'].append({'id':n,'size':size,'type':'circle'})\n for a,b in links:\n ai = node_to_index[a]\n bi = node_to_index[b]\n graph['links'].append({'source':ai,'target':bi,'size':len(links[a,b]),'devices':links[a,b]})\n\n json.dump(graph,file,indent=4)\n file.close()\n\ndef main():\n intersections = findIntersections(JSONPATH, NUCLPATH, VERTEXID, THRESHOLD)\n if CREATE_INTERFILE:\n dumpIntersections(INTEPATH, intersections)\n forcelayout_format(FORCPATH,intersections)\n\nif __name__ == '__main__':\n main()","sub_path":"scripts/intersections.py","file_name":"intersections.py","file_ext":"py","file_size_in_byte":7949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"309684447","text":"import sublime\r\nimport sublime_plugin\r\nimport threading\r\nimport subprocess\r\nimport os\r\nimport sys\r\n\r\nclass pulllogCommand(sublime_plugin.ApplicationCommand):\r\n\r\n\tdef __init__(self,):\r\n\t\tsuper(pulllogCommand,self).__init__()\r\n\r\n\tdef is_enable(self):\r\n\t\treturn True\r\n\r\n\tdef run(self,):\r\n\t\tfilename = self.GetCurFilePath()\r\n\t\tself.filename = filename\r\n\t\t# isvisible, key = self.isjlSvn(filename)\r\n\t\tself.pull(\"pet.log\")\r\n\r\n\tdef GetCurFilePath(self,):\r\n\t\tactiveWin = sublime.active_window()\r\n\t\tactiveView = activeWin.active_view()\r\n\t\treturn activeView.file_name()\r\n\r\n\tdef pull(self, path):\r\n\t\ttargetPath = \"/sdcard/Android/data/com.joyluck.pet/files/pet.log\"\r\n\t\t# if not os.path.exits(\"d:/pet.log\"):\r\n\t\t# \tos.path.create\r\n\t\tcmd = 'adb pull %s %s' % (targetPath, \"D:\\\\\")\r\n\t\tprint(cmd)\r\n\t\tself.exec_cmd(cmd)\r\n\r\n\tdef exec_cmd(self,cmd):\r\n\t\t#print('cmd is ',cmd)\r\n\t\tps = subprocess.Popen(cmd)\r\n\t\tres = ps.wait()\r\n\t\tif res>0:\r\n\t\t\tprint('pull error! %s'%res)\r\n\t\telse:\r\n\t\t\tprint('pull success!')\r\n\r\n\tdef isjlSvn(self,path):\r\n\t\tisjl =False\r\n\t\tkey=''\r\n\t\tif not path:\r\n\t\t\treturn isjl,key\r\n\t\tjlpaths = ['trunk\\code',]\r\n\t\tfor one in jlpaths:\r\n\t\t\tif path.find(one)>=0:\r\n\t\t\t\tisjl = True\r\n\t\t\t\tkey = one\r\n\t\t\t\tbreak;\r\n\t\treturn isjl,key\r\n\r\n\tdef is_visible(self):\r\n\t\treturn True\r\n\t\t# curpath = self.getCurFilePath()\r\n\t\t# isvi,key = self.isjlSvn(curpath)\r\n\t\t# return isvi\r\n\r\n\r\n\r\n\r\n","sub_path":"windows/sublime_plugins/watermoon/pulllog.py","file_name":"pulllog.py","file_ext":"py","file_size_in_byte":1357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"587254327","text":"def shortestToChar(s,c):\r\n N = len(s)\r\n left,right,output = [None]*N , [None]*N , [None]*N\r\n temp = float(\"inf\")\r\n for i in range(N):\r\n if(s[i]==c):\r\n temp =0\r\n left[i]=temp\r\n temp+=1\r\n for i in range(N-1,-1,-1):\r\n if(s[i]==c):\r\n temp =0\r\n right[i] = temp\r\n temp+=1\r\n for i in range(N):\r\n output[i] = min(right[i],left[i])\r\n return output\r\ns = input(\"enter the string\")\r\nc =input(\"enter the character\")\r\nprint(shortestToChar(s,c))\r\n","sub_path":"ShortestDisToChar.py","file_name":"ShortestDisToChar.py","file_ext":"py","file_size_in_byte":588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"6"} +{"seq_id":"237605572","text":"from django.conf.urls import patterns, url\nfrom displayStatus import views\n\nurlpatterns = patterns('',\n url(r'^$', views.index, name='index'),\n url(r'^detail/(?P[0-9]{8})/$', views.detail, name='detail'),\n url(r'^register/$', views.register, name='register'),\n url(r'^login/$', views.user_login, name='login'),\n url(r'^restricted/', views.restricted, name='restricted'),\n url(r'^logout/$', views.user_logout, name='logout'),\n)\n","sub_path":"displayStatus/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"6"} +{"seq_id":"276928886","text":"class Solution:\n def CompareWord(str1, str2) -> str:\n\n if len(str1) < len(str2) :\n compare1 = str1\n compare2 = str2\n else:\n compare1 = str2\n compare2 = str1\n\n strTest = \"\"\n for i in range(len(compare1)) :\n if compare1[i] == compare2[i] :\n strTest += compare1[i]\n else:\n break\n\n return strTest\n\n def DivisionList(strs) -> str:\n size = len(strs)\n halfSize = size//2\n strResult = \"\"\n if size > 2 :\n strs1 = list(strs[:halfSize])\n strs2 = list(strs[halfSize:])\n\n strResult = Solution.CompareWord(Solution.DivisionList(strs1), Solution.DivisionList(strs2))\n\n return strResult\n elif size == 2 :\n strResult = Solution.CompareWord(strs[0],strs[1])\n\n return strResult\n elif size == 1 :\n return strs[0]\n else:\n return \"\"\n\n def longestCommonPrefix(self, strs) -> str:\n\n return Solution.DivisionList(strs)\n\n\n\nprint(Solution.longestCommonPrefix(None, [\"flower\",\"flow\",\"flight\"]))\nprint(Solution.longestCommonPrefix(None, [\"dog\",\"racecar\",\"car\"]))","sub_path":"LEETCODE/14. Longest Common Prefix - Python/CodingTest.py","file_name":"CodingTest.py","file_ext":"py","file_size_in_byte":1217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"6"} +{"seq_id":"96756558","text":"# Dependencies\nfrom splinter import Browser\nfrom bs4 import BeautifulSoup\nimport pandas as pd\nimport requests\nimport pymongo\n\ndef init_browser():\n # @NOTE: Replace the path with your actual path to the chromedriver\n executable_path = {\"executable_path\": \"chromedriver.exe\"}\n return Browser(\"chrome\", **executable_path, headless=False)\n\ndef nasa_scrape(browser):\n #Latest Mars News from NASA\n url = 'https://mars.nasa.gov/news/'\n browser.visit(url)\n html=browser.html\n soup=bs(html,\"html.parser\")\n section=soup.find(class_='item_list')\n link=section.find('a')\n href=link['href']\n title=section.find(class_=\"content_title\")\n link=title.find('a')\n #article title\n news_title=link.text.strip()\n #teaser paragraph\n news_p=section.find(class_='article_teaser_body').text.strip()\n return news_title, news_p\n\ndef jpl_scrape(browser):\n #JPL Mars Space feature image\n base_url=\"https://www.jpl.nasa.gov\"\n search_url=\"/spaceimages/?search=&category=Mars\"\n browser.visit(base_url+search_url)\n html=browser.html\n soup=bs(html,\"html.parser\")\n link=soup.find(class_='button fancybox')['data-fancybox-href']\n #featured image link\n featured_image_url=base_url+link\n return featured_image_url\n\ndef table_scrape(browser):\n # Mars space facts table\n url=\"https://space-facts.com/mars/\"\n browser.visit(url)\n tables = pd.read_html(url)[0]\n tables.columns = ['Stat', 'Mars']\n tables.set_index('Stat', inplace=True)\n mars_table=tables.to_html(classes=\"table table-striped\")\n return mars_table\n\ndef hemi_scrape(browser):\n #Hemisphere photos\n base_url=\"https://astrogeology.usgs.gov\"\n search_url=\"/search/results?q=hemisphere+enhanced&k1=target&v1=Mars\"\n browser.visit(base_url+search_url)\n html=browser.html\n soup=bs(html,\"html.parser\")\n body=soup.find('body')\n n=len(body.find_all(class_='item'))\n hemisphere_image_urls=[]\n hem_name=[]\n hem_links=[]\n for x in range(n):\n img_link=soup.find_all(class_='description')[x]('a')[0]['href']\n img_url=base_url+img_link+'.tif'\n \n name=soup.find_all(class_='description')[x]('a')[0]('h3')[0].text.strip()\n dict={'title':name,'img_url':img_url}\n hemisphere_image_urls.append(dict)\n return hemisphere_image_urls\n\ndef scrape():\n browser = init_browser()\n\n (news_title, news_p)=nasa_scrape(browser)\n featured_image_url=jpl_scrape(browser)\n mars_table=table_scrape(browser)\n hemisphere_image_urls=hemi_scrape(browser)\n\n #combine in one dictionary\n mars_data = {\n \"news_title\": news_title,\n \"news_p\": news_p,\n \"feat_image\": featured_image_url,\n \"facts_table\":mars_table,\n \"hemi_images\":hemisphere_image_urls\n }\n\n # Close the browser after scraping\n browser.quit()\n\n # Return results\n return mars_data","sub_path":"scrape_mars.py","file_name":"scrape_mars.py","file_ext":"py","file_size_in_byte":2867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"306408421","text":"# -m 10000\n\nmatrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\n# output [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\nprint(matrix)\n# output 712 bytes in use; 20 refs in use\nmem()\n\ntranspose = [None, None, None]\ni = 0\nwhile i < 3:\n transpose[i] = [0, 0, 0]\n i = i + 1\n\ndel i\n# output [[0, 0, 0], [0, 0, 0], [0, 0, 0]]\nprint(transpose)\n# output 1352 bytes in use; 37 refs in use\nmem()\n\ni = 0\nwhile i < len(matrix):\n row = matrix[i]\n j = 0\n while j < len(matrix):\n transpose[j][i] = row[j]\n j = j + 1\n i = i + 1\n# output [[1, 4, 7], [2, 5, 8], [3, 6, 9]]\nprint(transpose)\n# output 1128 bytes in use; 30 refs in use\nmem()\n\ndel matrix\ndel row\ndel i\ndel j\n# output 712 bytes in use; 20 refs in use\nmem()\n# output [[1, 4, 7], [2, 5, 8], [3, 6, 9]]\nprint(transpose)\n","sub_path":"project05-kweng/tests/transpose.py","file_name":"transpose.py","file_ext":"py","file_size_in_byte":771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"575012208","text":"__author__ = 'julesmichaud'\n__filename__ = 'delta.py.py'\n__date__ = '20/02/20'\n\nimport Jules, Julien, Load\n\na = \"a_example.txt\"\n\nfile1 = open(a)\nvalues, file1 = Load.load(file1)\nb = Jules.tri_2(file1)\nJulien.print_output_file(b, values)","sub_path":"2020/coconut/delta.py","file_name":"delta.py","file_ext":"py","file_size_in_byte":236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"342684318","text":"# ----------\n# User Instructions:\n# \n# Define a function, search() that returns a list\n# in the form of [optimal path length, row, col]. For\n# the grid shown below, your function should output\n# [11, 4, 5].\n#\n# If there is no valid path from the start point\n# to the goal, your function should return the string\n# 'fail'\n# ----------\n\n# Grid format:\n# 0 = Navigable space\n# 1 = Occupied space\n\n\ngrid = [[0, 0, 1, 0, 0, 0],\n [0, 0, 1, 0, 0, 0],\n [0, 0, 0, 0, 1, 0],\n [0, 0, 1, 1, 1, 0],\n [0, 0, 0, 0, 1, 0]]\n\ngrid2 = [[0,0,0],\n [0,1,1],\n [0,0,0]]\n\ngoal2 = [len(grid2)-1, len(grid2[0])-1]\ninit = [0, 0]\ngoal = [len(grid)-1, len(grid[0])-1]\ncost = 1\n\ndelta = [[-1, 0], # go up\n [ 0,-1], # go left\n [ 1, 0], # go down\n [ 0, 1]] # go right\n\ndelta_name = ['^', '<', 'v', '>']\n\n\n\ndef search(grid,init,goal,cost):\n '''\n Try iteratively to move to next level, mark visited2, add to list of next level starting points if \n it's a new node\n '''\n # make visited array initialized to 0, mark 1 when visited\n visited = grid[:]\n visited[:] = [[0] * len(visited[0]) for _ in range(len(visited))]\n #mark init as visited\n visited[0][0] = 1\n print(visited)\n print(\"grid: {}\\n\".format(grid))\n #list of lists of levels\n path = [[init]]\n curr_cell = init\n #try each of curr_level to find possible moves\n curr_level =[]\n #append possible move-to cells to next_level\n next_level = []\n # how many moves to get to goal\n num_moves = 0\n # counters\n i,j,k,l = 0,0,0,0\n #flag to break outer while loop\n get_out = False\n while(get_out==False):\n # set curr_level\n curr_level = [x[:] for x in path[i]]\n print(\"i: {} curr_level: {}\\n\".format(i, curr_level))\n #iterate curr_level to find moves for each cell in curr_level\n #append to next_level\n for j in range(len(curr_level)):\n #iterate level and set each cell to curr_cell\n curr_cell = curr_level[j]\n print(\"j: {} curr_cell: {}\".format(j, curr_cell))\n #check if curr_cell is goal then break inner loop\n if curr_cell == goal:\n get_out = True\n break\n row = curr_cell[0]\n col = curr_cell[1]\n #try up\n if row-1 >=0:\n if grid[row-1][col]!=1 and visited[row-1][col]!=1:\n #append to next level\n next_level.append([row-1, col])\n #mark as visited\n visited[row-1][col]=1\n # try left\n if col-1 >=0:\n if grid[row][col-1]!=1 and visited[row][col-1]!=1:\n #append to next level\n next_level.append([row, col-1])\n #mark as visited\n visited[row][col-1]=1\n # try down\n if row +1 < len(grid):\n if grid[row+1][col]!=1 and visited[row+1][col]!=1:\n #append to next level\n next_level.append([row+1, col])\n #mark as visited\n visited[row+1][col]=1\n # try up\n if col+1 < len(grid[0]):\n if grid[row][col+1]!=1 and visited[row][col+1]!=1:\n #append to next level\n next_level.append([row, col+1])\n #mark as visited\n visited[row][col+1]=1\n # done iterating, append next level to path\n temp = next_level[:]\n path.append(temp)\n print(\"path w/next_level: {}\\n\".format(path))\n # reset next_level\n next_level[:]=[]\n #increment counter\n i +=1\n \n #found curr_cell== goal in curr_level without appending next_level\n #i-1 for num moves since i starts at 0 for init and increments for each level and we found curr_cell==goal\n # in the i'th level\n num_moves = i-1\n # set path to format [optimal path length, row, col]\n path = [num_moves, curr_cell[0], curr_cell[1]]\n \n return path\n\nif __name__ == \"__main__\":\n # test on small 3*3 grid\n #path2 = search(grid2, init, goal2, cost)\n #print(\"found path: \", path2)\n\n # test on main grid\n path = search(grid, init, goal, cost)\n print(\"found path: \", path)\n","sub_path":"searchMaze.py","file_name":"searchMaze.py","file_ext":"py","file_size_in_byte":4331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"647980878","text":"from django.db import models\nfrom django.utils.translation import ugettext_lazy as _\n\n\nclass Post(models.Model):\n id = models.AutoField(primary_key=True)\n title = models.CharField(max_length=255)\n description = models.TextField(null=True, blank=True)\n image = models.ImageField(upload_to=\"post/\",blank=True,null=True)\n date_time = models.DateTimeField(auto_now_add=True)\n\n is_edited = models.BooleanField(default=False)\n class Meta:\n db_table = 'web_post'\n verbose_name = _('Post')\n verbose_name_plural = _('Posts')\n ordering = ('id',)\n \n def __str__(self):\n return self.title","sub_path":"web/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"93174489","text":"# fibonacci = [0,1,1,2,3,5,8,13,21]\n# for i in range(len(fibonacci)):\n# \tprint(i,fibonacci[i])\n# print()\n\n\"\"\" Fibonacci Module \"\"\"\n\n# import doctest\n#\ndef fib(n):\n \"\"\"Calculates the n-th Fibonacci number iteratively\"\"\"\n\n a, b = 0, 1\n for i in range(n):\n a, b = b, a + b\n\n if n == 20:\n a = 42\n return a\n#\n# def fib(n):\n# \"\"\" Iterative Fibonacci Function \"\"\"\n# a, b = 0, 1\n# for i in range(n):\n# a, b = b, a + b\n# if n == 20:\n# a = 42\n# return a\n#\n# if __name__ == \"__main__\":\n# doctest.testmod()\n\n# def fiblist(n):\n# \"\"\" creates a list of Fibonacci numbers up to the n-th generation \"\"\"\n# fib = [0,1]\n# for i in range(1,n):\n# fib += [fib[-1]+fib[-2]]\n# return fib\n","sub_path":"fibonacci.py","file_name":"fibonacci.py","file_ext":"py","file_size_in_byte":756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"427361626","text":"#!/usr/bin/python3\n# file: ctag_hid_GUI_less_Mic_rec_Graph.py\n# recording of location of Motor current (MotorCur.Measur) for internal Microphone.\nfrom binascii import hexlify\nimport sys\nimport argparse\nimport threading\n#from time import perf_counter as timer\nfrom timeit import default_timer as timer\nfrom time import sleep\nfrom queue import Queue\nimport csv_plot\nfrom ctag_hid_log_files_path import *\nimport record_mic\n\n\nfrom multiprocessing import freeze_support\nimport include_dll_path\nimport hid\nimport os\n\nVENDOR_ID = 0x24b3 # Simbionix\nPRODUCT_ID = 0x1005 # Simbionix MSP430 Controller\n# file1 = None\n# open recording log file:\nif not os.path.exists('log'):\n os.makedirs('log')\n# file1 = open(\"C:\\Work\\Python\\CTAG_HID\\src\\log\\clicker_log.txt\",\"w\") \n#file1 = open(\"C:\\Work\\Python\\CTAG_HID\\src\\log\\clicker_log.csv\",\"w\") \n#file2 = open(\"C:\\Work\\Python\\CTAG_HID\\src\\log\\clicker_overSample.csv\",\"w\") \nfile1 = open(FILE1_PATH,\"w\") \nfile2 = open(FILE2_PATH,\"w\") \n\nREAD_SIZE = 64 # The size of the packet\nREAD_TIMEOUT = 2 # 2ms\n\nWRITE_DATA = bytes.fromhex(\"3f3ebb00b127ff00ff00ff00ffffffff000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\")\n\nSLEEP_AMOUNT = 0.002 # Read from HID every 2 milliseconds\nPRINT_TIME = 1.0 # Print every 1 second\n\nSTART_INDEX = 2 + 4 # Ignore the first two bytes, then skip the version (4 bytes)\n#ANALOG_INDEX_LIST = list(range(START_INDEX + 2, START_INDEX + 4 * 2 + 1, 2)) + [START_INDEX + 6 * 2,]\n#2020_09_24 - for recording of clickerRec P5.0 .\nANALOG_INDEX_LIST = list(range(START_INDEX + 2, START_INDEX + 8 * 2 + 1, 2)) \n\nCOUNTER_INDEX = 2 + 22 + 18 # Ignore the first two bytes, then skip XData1 (22 bytes) and OverSample (==XDataSlave1; 18 bytes)\nOVER_SAMPLE_INDEX = 2 + 22\nOVER_SAMPLE_INDEX_LIST = list(range(OVER_SAMPLE_INDEX, OVER_SAMPLE_INDEX + 9 * 2 + 1, 2))\n\nOUTER_HANDLE_CHANNEL1_STYLE = \"OuterHandleChannel1\"\nOUTER_HANDLE_CHANNEL2_STYLE = \"OuterHandleChannel2\"\nINNER_HANDLE_CHANNEL1_STYLE = \"InnerHandleChannel1\"\nINNER_HANDLE_CHANNEL2_STYLE = \"InnerHandleChannel2\"\nCLICKER_STYLE = \"Clicker\"\n\nstyle_names = [\n OUTER_HANDLE_CHANNEL1_STYLE,\n OUTER_HANDLE_CHANNEL2_STYLE,\n INNER_HANDLE_CHANNEL1_STYLE,\n INNER_HANDLE_CHANNEL2_STYLE,\n CLICKER_STYLE\n]\n\nprogressbar_styles = list()\nprogressbars = list()\nisopen = list()\ninner_clicker = list()\nred_handle = list()\nreset_check = list()\ncounter_entry = list()\nprev_clicker_counter = 0\nfrom_zero_clicker_counts = 0\n\nroot = None\n\ndef update_checkbox(checkbox, bool_value):\n if (bool_value):\n checkbox.select()\n else:\n checkbox.deselect()\n\ndef gui_loop(device):\n do_print = True\n print_time = 0.0\n time = timer()\n handle_time = timer()\n write_time_capture = timer()\n skip_write = 0\n prev_counter = 0\n read_cycle_counter = 0\n seconds_counter = 0\n # cnt = None\n # prev_cnt = None\n # value = None\n\n is_first_run = True\n curr_thrd = threading.current_thread()\n while getattr(curr_thrd, \"do_run\", True):\n # Reset the counter\n if (do_print):\n print_time = timer()\n\n # Write to the device (request data; keep alive)\n if (skip_write % 4) == 0:\n skip_write = 0\n device.write(WRITE_DATA)\n write_time = timer() - write_time_capture\n write_time_capture = timer()\n # print(\"write_time: %.10f\" % write_time)\n skip_write += 1\n \n cycle_time = timer() - time\n # print(\"cycle timer: %.10f\" % cycle_time)\n\n # If not enough time has passed, sleep for SLEEP_AMOUNT seconds\n sleep_time = SLEEP_AMOUNT - (cycle_time)\n # print(\"sleep timer: %.10f\" % sleep_time)\n # if sleep_time > 0.001:\n # # if value:\n # # prev_cnt = cnt\n # # cnt = value[COUNTER_INDEX]\n # # if prev_cnt and cnt < prev_cnt:\n # # print(\"Invalid counter\")\n \n # print(\"in sleep: \")\n # # sleep(sleep_time)\n\n # Measure the time\n time = timer()\n # print(\" \")\n\n # Read the packet from the device\n value = device.read(READ_SIZE, timeout=READ_TIMEOUT)\n\n # Signal the microphone recording to start after the first read\n if is_first_run:\n is_first_run = False\n record_mic.start_recording()\n\n # Update the GUI\n if len(value) >= READ_SIZE:\n # save into file:\n analog = [(int(value[i + 1]) << 8) + int(value[i]) for i in ANALOG_INDEX_LIST]\n OverSample = [(int(value[i + 1]) << 8) + int(value[i]) for i in OVER_SAMPLE_INDEX_LIST]\n MotorCur = analog[4] # new, after changing indexes.\n clicker_analog = analog[5]\n clicker_Rec = analog[6]\n batteryLevel = analog[7]\n # Packets Counter\n counter = (int(value[COUNTER_INDEX + 1]) << 8) + int(value[COUNTER_INDEX])\n count_dif = counter - prev_counter \n clicker_counter = (int(value[COUNTER_INDEX+2 + 1]) << 8) + int(value[COUNTER_INDEX+2])\n global prev_clicker_counter\n global from_zero_clicker_counts\n if prev_clicker_counter == 0:\n prev_clicker_counter = clicker_counter\n first_clicker_counter = clicker_counter\n if prev_clicker_counter != clicker_counter:\n from_zero_clicker_counts = clicker_counter-first_clicker_counter\n # print(\"clicker: %d\" % (clicker_counter-first_clicker_counter))\n print(\"clicker: %d\" % (from_zero_clicker_counts))\n prev_clicker_counter = clicker_counter\n \n global file1\n # if count_dif > 1 :\n # L = [ str(counter),\", \", str(clicker_analog), \", \" , str(count_dif), \" <<<<<--- \" ,\"\\n\" ] \n # else:\n # L = [ str(counter),\", \", str(clicker_analog), \", \" , str(count_dif), \"\\n\" ] \n # L = [ str(counter),\", \", str(clicker_analog), \", \" , str(count_dif),\", \" , str(from_zero_clicker_counts), \"\\n\" ] \n # L = [ str(counter),\", \", str(clicker_analog), \", \" , str(clicker_Rec),\", \" , str(from_zero_clicker_counts), \"\\n\" ] \n # L = [ str(counter),\", \", str(clicker_analog), \", \" , str(clicker_sound.get()),\", \" , str(from_zero_clicker_counts), \"\\n\" ] \n # L = [ str(counter),\", \", str(clicker_analog), \", \" , str(from_zero_clicker_counts), \"\\n\" ] \n # record the motor current as infrastructure for internal microphone recording\n L = [ str(counter),\", \", str(MotorCur), \", \" , str(from_zero_clicker_counts), \"\\n\" ] \n \n # add the Data.Master.ADC[5] just before the OverSample elements.\n file2.writelines(L) \n for i in range(0,9):\n # L2 = [ str(counter),\", \", str(OverSample[i]), \", \" , str(count_dif),\", \" , str(from_zero_clicker_counts), \"\\n\" ] \n # L2 = [ str(counter),\", \", str(OverSample[i]), \", \" , str(clicker_Rec),\", \" , str(from_zero_clicker_counts), \"\\n\" ] \n # L2 = [ str(counter),\", \", str(OverSample[i]), \", \" , str(clicker_sound.get()),\", \" , str(from_zero_clicker_counts), \"\\n\" ] \n # L2 = [ str(counter),\", \", str(OverSample[i]), \", \" , str(from_zero_clicker_counts), \"\\n\" ] \n L2 = [ str(counter),\", \", str(MotorCur), \", \" , str(from_zero_clicker_counts), \"\\n\" ] \n file2.writelines(L2) \n file1.writelines(L) \n # handler(value, do_print=do_print)\n # print(\"Received data: %s\" % hexlify(value))\n Handler_Called = (timer() - handle_time)\n read_cycle_counter += 1\n if read_cycle_counter >= 500 :\n seconds_counter += 1\n read_cycle_counter = 0\n print( str(seconds_counter))\n # if Handler_Called > 0.002 :\n # print(\"handler called: %.6f\" % Handler_Called)\n # print(\"time: %.6f\" % time)\n handle_time = timer() \n prev_counter = counter\n\n # Update the do_print flag\n do_print = (timer() - print_time) >= PRINT_TIME\n\n # print(\"gui_loop end\")\n\ndef handler(value, do_print=False):\n if do_print:\n print(\"Received data: %s\" % hexlify(value))\n\n return # do without gui\n digital = (int(value[START_INDEX + 1]) << 8) + int(value[START_INDEX + 0])\n analog = [(int(value[i + 1]) << 8) + int(value[i]) for i in ANALOG_INDEX_LIST]\n # Packets Counter\n counter = (int(value[COUNTER_INDEX + 1]) << 8) + int(value[COUNTER_INDEX])\n\n encoder1 = analog[3]\n encoder2 = analog[0]\n encoder3 = analog[1]\n encoder4 = analog[2]\n clicker_analog = analog[5]\n \n # file1 = open(\"C:\\Work\\Python\\CTAG_HID\\src\\log\\clicker_log.txt\",\"w\") \n global file1\n # L = [ str(clicker_analog), \",\" ,\"\\n\" ] \n # file1.writelines(L) \n\n\n\n\n bool_inner_isopen = bool((digital >> 0) & 0x0001)\n bool_outer_isopen = bool((digital >> 1) & 0x0001)\n bool_clicker = bool((digital >> 2) & 0x0001)\n bool_reset = bool((digital >> 4) & 0x0001)\n bool_red_handle = bool((digital >> 7) & 0x0001)\n int_outer_handle_channel1 = analog[1]\n int_outer_handle_channel2 = analog[2]\n int_inner_handle_channel1 = analog[0]\n int_inner_handle_channel2 = analog[3]\n int_clicker = clicker_analog\n int_counter = counter\n precentage_outer_handle_channel1 = int((int_outer_handle_channel1 / 4096) * 100)\n precentage_outer_handle_channel2 = int((int_outer_handle_channel2 / 4096) * 100)\n precentage_inner_handle_channel1 = int((int_inner_handle_channel1 / 4096) * 100)\n precentage_inner_handle_channel2 = int((int_inner_handle_channel2 / 4096) * 100)\n precentage_clicker = int((int_clicker / 4096) * 100)\n\n progressbar_style_outer_handle_channel1 = progressbar_styles[0]\n progressbar_style_outer_handle_channel2 = progressbar_styles[1]\n progressbar_style_inner_handle_channel1 = progressbar_styles[2]\n progressbar_style_inner_handle_channel2 = progressbar_styles[3]\n progressbar_style_clicker = progressbar_styles[4]\n progressbar_outer_handle_channel1 = progressbars[0]\n progressbar_outer_handle_channel2 = progressbars[1]\n progressbar_inner_handle_channel1 = progressbars[2]\n progressbar_inner_handle_channel2 = progressbars[3]\n progressbar_clicker = progressbars[4]\n checkbox_outer_handle_isopen = isopen[0]\n checkbox_inner_handle_isopen = isopen[1]\n checkbox_inner_clicker = inner_clicker\n checkbox_red_handle = red_handle\n checkbox_reset_check = reset_check\n entry_counter = counter_entry\n\n progressbar_style_outer_handle_channel1.configure(\n OUTER_HANDLE_CHANNEL1_STYLE,\n text=(\"%d\" % int_outer_handle_channel1)\n )\n progressbar_style_outer_handle_channel2.configure(\n OUTER_HANDLE_CHANNEL2_STYLE,\n text=(\"%d\" % int_outer_handle_channel2)\n )\n progressbar_style_inner_handle_channel1.configure(\n INNER_HANDLE_CHANNEL1_STYLE,\n text=(\"%d\" % int_inner_handle_channel1)\n )\n progressbar_style_inner_handle_channel2.configure(\n INNER_HANDLE_CHANNEL2_STYLE,\n text=(\"%d\" % int_inner_handle_channel2)\n )\n progressbar_style_clicker.configure(\n CLICKER_STYLE,\n text=(\"%d\" % int_clicker)\n )\n\n progressbar_outer_handle_channel1[\"value\"] = precentage_outer_handle_channel1\n progressbar_outer_handle_channel2[\"value\"] = precentage_outer_handle_channel2\n progressbar_inner_handle_channel1[\"value\"] = precentage_inner_handle_channel1\n progressbar_inner_handle_channel2[\"value\"] = precentage_inner_handle_channel2\n progressbar_clicker[\"value\"] = precentage_clicker\n\n update_checkbox(checkbox_outer_handle_isopen, bool_outer_isopen)\n update_checkbox(checkbox_inner_handle_isopen, bool_inner_isopen)\n update_checkbox(checkbox_inner_clicker, bool_clicker)\n update_checkbox(checkbox_red_handle, bool_red_handle)\n update_checkbox(checkbox_reset_check, bool_reset)\n\n entry_counter.delete(0, tk.END)\n entry_counter.insert(tk.END, \"%d\" % int_counter)\n\n root.update()\n\nPROGRESS_BAR_LEN = 300\n\ndef my_channel_row(frame, row, label, style):\n ttk.Label(\n frame,\n text=label\n ).grid(\n row=row,\n sticky=tk.W\n )\n\n row += 1\n\n ttk.Label(\n frame,\n text=\"Is Open\"\n ).grid(\n row=row,\n column=0,\n sticky=tk.W\n )\n ttk.Label(\n frame,\n text=\"Channel 1\"\n ).grid(\n row=row,\n column=1\n )\n ttk.Label(\n frame,\n text=\"Channel 2\"\n ).grid(\n row=row,\n column=2\n )\n\n row += 1\n\n w = tk.Checkbutton(\n frame,\n state=tk.DISABLED\n )\n isopen.append(w)\n w.grid(\n row=row,\n column=0\n )\n w = ttk.Progressbar(\n frame,\n orient=tk.HORIZONTAL,\n length=PROGRESS_BAR_LEN,\n style=(\"%sChannel1\" % style)\n )\n progressbars.append(w)\n w.grid(\n row=row,\n column=1\n )\n w = ttk.Progressbar(\n frame,\n orient=tk.HORIZONTAL,\n length=PROGRESS_BAR_LEN,\n style=(\"%sChannel2\" % style)\n )\n progressbars.append(w)\n w.grid(\n row=row,\n column=2\n )\n\n return row + 1\n\ndef my_seperator(frame, row):\n ttk.Separator(\n frame,\n orient=tk.HORIZONTAL\n ).grid(\n pady=10,\n row=row,\n columnspan=3,\n sticky=(tk.W + tk.E)\n )\n return row + 1\n\ndef my_widgets(frame):\n # Add style for labeled progress bar\n for name in style_names:\n style = ttk.Style(\n frame\n )\n progressbar_styles.append(style)\n style.layout(\n name,\n [\n (\n \"%s.trough\" % name,\n {\n \"children\":\n [\n (\n \"%s.pbar\" % name,\n {\"side\": \"left\", \"sticky\": \"ns\"}\n ),\n (\n \"%s.label\" % name,\n {\"sticky\": \"\"}\n )\n ],\n \"sticky\": \"nswe\"\n }\n )\n ]\n )\n style.configure(name, background=\"lime\")\n\n\n # Outer Handle\n row = 0\n row = my_channel_row(\n frame=frame,\n row=row,\n label=\"Outer Handle\",\n style=\"OuterHandle\"\n )\n\n # Seperator\n row = my_seperator(frame, row)\n\n # Inner Handle\n row = my_channel_row(\n frame=frame,\n row=row,\n label=\"Inner Handle\",\n style=\"InnerHandle\"\n )\n\n # Seperator\n row = my_seperator(frame, row)\n\n # Clicker labels\n ttk.Label(\n frame,\n text=\"Inner Clicker\"\n ).grid(\n row=row,\n column=0,\n sticky=tk.W\n )\n ttk.Label(\n frame,\n text=\"Clicker\"\n ).grid(\n row=row,\n column=1\n )\n\n row += 1\n\n # Clicker data\n w = tk.Checkbutton(\n frame,\n state=tk.DISABLED\n )\n global inner_clicker\n inner_clicker = w\n w.grid(\n row=row,\n column=0\n )\n w = ttk.Progressbar(\n frame,\n orient=tk.HORIZONTAL,\n length=PROGRESS_BAR_LEN,\n style=\"Clicker\"\n )\n progressbars.append(w)\n w.grid(\n row=row,\n column=1\n )\n\n row += 1\n\n # Seperator\n row = my_seperator(frame, row)\n\n # Red handle and reset button labels\n ttk.Label(\n frame,\n text=\"Red Handle\"\n ).grid(\n row=row,\n column=0,\n sticky=tk.W\n )\n ttk.Label(\n frame,\n text=\"Reset Button\"\n ).grid(\n row=row,\n column=1\n )\n\n row += 1\n\n # Red handle and reset button data\n w = tk.Checkbutton(\n frame,\n state=tk.DISABLED\n )\n global red_handle\n red_handle = w\n w.grid(\n row=row,\n column=0\n )\n w = tk.Checkbutton(\n frame,\n state=tk.DISABLED\n )\n global reset_check\n reset_check = w\n w.grid(\n row=row,\n column=1\n )\n\n row += 1\n\n # Seperator\n row = my_seperator(frame, row)\n\n # Counter\n ttk.Label(\n frame,\n text=\"Counter\"\n ).grid(\n row=row,\n column=0,\n sticky=tk.E,\n )\n w = ttk.Entry(\n frame,\n width=20,\n # state=tk.DISABLED\n )\n global counter_entry\n counter_entry = w\n w.grid(\n padx=10,\n pady=5,\n row=row,\n column=1,\n columnspan=2,\n sticky=tk.W,\n )\n\ndef init_parser():\n parser = argparse.ArgumentParser(\n description=\"Recording the HID data from C-TAG into CSV files.\\\n MUST HAVE MICROPHONE CONNECTED TO RUN THIS FILE!!!\"\n )\n parser.add_argument(\n \"-v\", \"--vendor\",\n dest=\"vendor_id\",\n metavar=\"VENDOR_ID\",\n type=int,\n nargs=1,\n required=False,\n help=\"connects to the device with the vendor ID\"\n )\n parser.add_argument(\n \"-p\", \"--product\",\n dest=\"product_id\",\n metavar=\"PRODUCT_ID\",\n type=int,\n nargs=1,\n required=False,\n help=\"connects to the device with that product ID\"\n )\n parser.add_argument(\n \"-a\", \"--path\",\n dest=\"path\",\n metavar=\"PATH\",\n type=str,\n nargs=1,\n required=False,\n help=\"connects to the device with the given path\"\n )\n return parser\n\ndef main():\n global VENDOR_ID\n global PRODUCT_ID\n PATH = None\n \n # open recording log file:\n # file1 = open(\"C:\\Work\\Python\\CTAG_HID\\src\\log\\clicker_log.txt\",\"w\") \n\n # Parse the command line arguments\n parser = init_parser()\n args = parser.parse_args(sys.argv[1:])\n\n # Initialize the flags according from the command line arguments\n avail_vid = args.vendor_id != None\n avail_pid = args.product_id != None\n avail_path = args.product_id != None\n id_mode = avail_pid and avail_vid\n path_mode = avail_path\n default_mode = (not avail_vid) and (not avail_pid) and (not avail_path)\n if (path_mode and (avail_pid or avail_vid)):\n print(\"The path argument can't be mixed with the ID arguments\")\n return\n if ((not avail_path) and ((avail_pid and (not avail_vid)) or ((not avail_pid) and avail_vid))):\n print(\"Both the product ID and the vendor ID must be given as arguments\")\n return\n\n if (default_mode):\n print(\"No arguments were given, defaulting to:\")\n print(\"VENDOR_ID = %X\" % VENDOR_ID)\n print(\"PRODUCT_ID = %X\" % PRODUCT_ID)\n id_mode = True\n elif (id_mode):\n VENDOR_ID = args.vendor_id[0]\n PRODUCT_ID = args.product_id[0]\n elif (path_mode):\n PATH = args.path[0]\n else:\n raise NotImplementedError\n\n device = None\n\n try:\n if (id_mode):\n device = hid.Device(vid=VENDOR_ID, pid=PRODUCT_ID)\n elif (path_mode):\n device = hid.Device(path=PATH)\n else:\n raise NotImplementedError\n\n # Initialize the microphone recording\n record_mic.init()\n\n \n # Create thread that calls\n thrd = threading.Thread(target=gui_loop, args=(device,), daemon=True)\n thrd.start()\n\n input()\n\n thrd.do_run = False # Signal the thread to stop\n record_mic.stop() # Signal the microphone recording to stop\n\n thrd.join() # Wait for the thread to stop\n record_mic.join() # Wait for it to stop\n \n except Exception as err:\n print(err)\n sys.exit(1)\n finally:\n global file1\n global file2\n file1.close() #to change file access modes \n file2.close() #to change file access modes \n try:\n if device != None:\n device.close()\n except Exception as err:\n print(err)\n\n csv_plot.main()\n\nif __name__ == \"__main__\":\n freeze_support() # Required for multiprocessing on Windows\n main()","sub_path":"src/ctag_hid_GUI_less_Mic_rec_Graph.py","file_name":"ctag_hid_GUI_less_Mic_rec_Graph.py","file_ext":"py","file_size_in_byte":20128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"431643763","text":"import setuptools\n\n\nclassifiers = [\n f\"Programming Language :: Python :: {version}\"\n for version in [\"3.7\"]\n]\n\n\n# pylint: disable=invalid-name\nextras_require = {\n \"test\": [\n \"codecov>=2.0.15,<3.0.0\",\n \"pytest>=4.6.3,<5.0.0\",\n \"pytest-cov>=2.7.1,<3.0.0\",\n \"pytest-asyncio>=0.10.0,<1.0.0\",\n ],\n \"lint\": [\n \"pylint>=2.3.1,<3.0.0\",\n \"mypy>=0.701,<1.0\",\n ],\n \"dev\": [\n \"tox>=3.13.2,<4.0.0\",\n ],\n}\n\nextras_require[\"dev\"] = extras_require[\"test\"] + extras_require[\"lint\"] + extras_require[\"dev\"]\n\n\nsetuptools.setup(\n name=\"libp2p\",\n description=\"libp2p implementation written in python\",\n version=\"0.0.1\",\n license=\"MIT/APACHE2.0\",\n platforms=[\"unix\", \"linux\", \"osx\"],\n classifiers=classifiers,\n install_requires=[\n \"pycryptodome>=3.8.2,<4.0.0\",\n \"base58>=1.0.3,<2.0.0\",\n \"pymultihash>=0.8.2\",\n \"multiaddr>=0.0.8,<0.1.0\",\n \"rpcudp>=3.0.0,<4.0.0\",\n \"grpcio>=1.21.1,<2.0.0\",\n \"grpcio-tools>=1.21.1,<2.0.0\",\n \"lru-dict>=1.1.6\",\n ],\n extras_require=extras_require,\n packages=setuptools.find_packages(exclude=[\"tests\", \"tests.*\"]),\n zip_safe=False,\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"83602564","text":"import unittest\nfrom unittest import TestCase\n\nfrom supplychainpy.demand import forecast_demand\nfrom supplychainpy.demand.evolutionary_algorithms import OptimiseSmoothingLevelGeneticAlgorithm\nfrom supplychainpy.demand.forecast_demand import Forecast\n\n\nclass TestForecast(TestCase):\n __orders = [1, 3, 5, 67, 4, 65, 242, 50, 48, 24, 34, 20]\n __orders2 = [4, 5, 7, 33, 45, 53, 55, 35, 53, 53, 43, 34]\n __weights = [.3, .5, .2]\n\n def setUp(self):\n self.__orders_ex = [165, 171, 147, 143, 164, 160, 152, 150, 159, 169, 173, 203, 169, 166, 162, 147, 188, 161,\n 162,\n 169,\n 185,\n 188, 200, 229, 189, 218, 185, 199, 210, 193, 211, 208, 216, 218, 264, 304]\n\n def test_moving_average_value_err(self):\n with self.assertRaises(expected_exception=ValueError):\n d = forecast_demand.Forecast(self.__orders)\n d.moving_average_forecast(forecast_length=6, base_forecast=True, start_position=1)\n\n def test_weighted_moving_average_value_err(self):\n with self.assertRaises(expected_exception=ValueError):\n forecast = forecast_demand.Forecast(self.__orders)\n forecast.weighted_moving_average_forecast(weights=self.__weights, average_period=2, forecast_length=3)\n\n def test_weighted_moving_average_list_err(self):\n with self.assertRaises(expected_exception=ValueError):\n forecast = forecast_demand.Forecast(self.__orders)\n forecast.weighted_moving_average_forecast(weights=self.__weights[:2], average_period=2, forecast_length=3)\n\n def test_mean_absolute_deviation(self):\n forecast = forecast_demand.Forecast(self.__orders)\n forecast.weighted_moving_average_forecast(weights=self.__weights, average_period=3, forecast_length=9,\n base_forecast=True, start_position=3)\n k = forecast_demand.Forecast(self.__orders)\n k.moving_average_forecast(forecast_length=9, base_forecast=True, start_position=3, average_period=3)\n result_array = k.mean_absolute_deviation(forecast.weighted_moving_average)\n result_array2 = forecast.mean_absolute_deviation(k.moving_average)\n self.assertNotEqual(result_array, result_array2)\n\n def test_mean_absolute_deviation_(self):\n orders1 = [1, 3, 5, 67, 4, 65, 44, 50, 48, 24, 34, 20]\n orders2 = [1, 3, 5, 67, 4, 65, 44, 50, 48, 24, 34, 20]\n weights = [.5, .3, .2]\n forecast = forecast_demand.Forecast(orders1)\n forecast.weighted_moving_average_forecast(weights=weights, average_period=3, forecast_length=9,\n start_position=3)\n # d.moving_average(forecast_length=3, base_forecast=True, start_position=3)\n # print(d.moving_average_forecast)\n k = forecast_demand.Forecast(orders2)\n k.moving_average_forecast(forecast_length=9, start_position=3, average_period=3)\n result_array = k.mean_absolute_deviation(forecast.weighted_moving_average)\n result_array2 = forecast.mean_absolute_deviation(k.moving_average)\n self.assertEquals(result_array, result_array2)\n\n def test_mean_forecast_error(self):\n pass\n\n def test_mean_aboslute_percentage_error(self):\n pass\n\n def test_optimise(self):\n pass\n\n def test_simple_exponential_smoothing(self):\n total_orders = 0\n for order in self.__orders_ex[:12]:\n total_orders += order\n avg_orders = total_orders / 12\n f = Forecast(self.__orders_ex, avg_orders)\n alpha = [0.2, 0.3, 0.4, 0.5, 0.6]\n s = [i for i in f.simple_exponential_smoothing(*alpha)]\n sum_squared_error = f.sum_squared_errors(s, 0.5)\n self.assertEqual(15346.859449597407, sum_squared_error[0.5])\n\n def test_standard_error(self):\n total_orders = 0\n for order in self.__orders_ex[:12]:\n total_orders += order\n avg_orders = total_orders / 12\n f = Forecast(self.__orders_ex, avg_orders)\n alpha = [0.2, 0.3, 0.4, 0.5, 0.6]\n s = [i for i in f.simple_exponential_smoothing(*alpha)]\n sum_squared_error = f.sum_squared_errors(s, 0.5)\n standard_error = f.standard_error(sum_squared_error, len(self.__orders_ex), 0.5)\n self.assertEqual(20.93995459784777, standard_error)\n\n def test_optimise_smoothing_level_genetic_algorithm(self):\n total_orders = 0\n for order in self.__orders_ex[:12]:\n total_orders += order\n avg_orders = total_orders / 12\n f = Forecast(self.__orders_ex, avg_orders)\n alpha = [0.2, 0.3, 0.4, 0.5, 0.6]\n s = [i for i in f.simple_exponential_smoothing(*alpha)]\n sum_squared_error = f.sum_squared_errors(s, 0.5)\n standard_error = f.standard_error(sum_squared_error, len(self.__orders_ex), 0.5)\n evo_mod = OptimiseSmoothingLevelGeneticAlgorithm(orders=self.__orders_ex, average_order=avg_orders,\n smoothing_level=0.5,\n population_size=10, standard_error=standard_error)\n self.assertGreaterEqual(len(evo_mod.initial_population),10)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/test_Forecast.py","file_name":"test_Forecast.py","file_ext":"py","file_size_in_byte":5311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"477821933","text":"# Author : Dhaval Harish Sharma\n# Red ID : 824654344\n# Assignment 5, Question 1\n# Finding area from a chain code\n\n# Function for finding the area of the region enclosed by the chain code\ndef Area(ChainCode):\n # Initializing the attributes\n x, y = 0, 0\n area = 0\n coord = []\n \n # Loop for finding the coordinates from the chain code\n for direction in ChainCode:\n if direction == 0:\n y += 1\n elif direction == 1:\n x -= 1\n elif direction == 3:\n x += 1\n else:\n y -= 1\n \n if [x, y] not in coord:\n coord.append([x, y])\n \n # Finding the area of the region from the coordinates\n for i in range(len(coord) - 1):\n area += coord[i + 1][0] * coord[i][1] - coord[i][0] * coord[i + 1][1]\n area = area // 2\n \n return area\n\nprint(Area([0, 0, 3, 0, 3, 2, 3, 2, 1, 1, 2, 1]))\nprint(Area([0, 0, 3, 2, 2, 1]))\nprint(Area([0, 0, 0, 3, 3, 0, 3, 0, 3, 2, 2, 2, 1, 1, 2, 1, 2, 1]))","sub_path":"Assignment 5/Question1.py","file_name":"Question1.py","file_ext":"py","file_size_in_byte":1000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"216943043","text":"import math\nprint(\"ingrese\")\nvar = []\nentra = int(input())\nfor n in range(0,entra):\n\tx1,y1,x2,y2,x3,y3 = input().split()\n\tx1,y1,x2,y2,x3,y3 = int(x1),int(y1),int(x2),int(y2),int(x3),int(y3)\n\ta = math.sqrt((abs(x2-x1)**2 + abs(y2-y1)**2))\n\tb = math.sqrt((abs(x3-x2)**2 + abs(y3-y2)**2))\n\tc = math.sqrt((abs(x3-x1)**2 + abs(y3-y1)**2))\n\tare = (1/4)*math.sqrt(4*math.pow(a,2)*math.pow(b,2)-(a**2+b**2-c**2)**2)\n\t#abajo esta la linea que pone el formato de los floats\n\tarer = '{0:.7f}'.format(are).rstrip('0').rstrip('.')\n\tvar.append(arer)\nprint(*var,sep=' ')\n","sub_path":"python/triangheron.py","file_name":"triangheron.py","file_ext":"py","file_size_in_byte":556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"162172929","text":"from sympy import prevprime, nextprime, sqrt\nfrom Crypto.Util.number import inverse, long_to_bytes, bytes_to_long\nfrom Crypto.Util.Padding import pad\nfrom Crypto.Cipher import AES\nimport base64\nimport hashlib\nimport time\nimport pwn\n\ndef factor_int(modulus):\n lol = int(\"%d\" % sqrt(modulus))\n\n next = lol\n nexts = []\n for i in range(10):\n next = nextprime(next)\n nexts.append(next)\n\n prev = lol\n for i in range(10):\n prev = prevprime(prev)\n for next in nexts:\n if prev * next == modulus:\n return (prev, next)\n\n\nremote = pwn.remote('chall3.heroctf.fr', 9000)\nmytime = time.time()\nremote.recvuntil('modulus : ')\nmodulus = int(remote.recvlineS().rstrip())\nremote.recvuntil('input >> ')\nprev, next = factor_int(modulus) \ne = 0x10001\nn = prev*next\nphi = (prev-1)*(next-1)\nd = inverse(e, phi)\nlove = pow(bytes_to_long(hashlib.sha512(b\"the_proof_of_your_love\").digest()), d, n)\nremote.sendline(\"%d\" % love)\nremote.recvuntil('vu.\\n\\n\\t- ')\nline = remote.recvlineS()[2:]\nbase = line[0:line.find(\"'\")]\n\nenc = base64.b64decode(base)\naes = AES.new(pad(b\"None\", AES.block_size), AES.MODE_CBC, pad(long_to_bytes(int(mytime)), AES.block_size))\nprint(aes.decrypt(enc))","sub_path":"2021/heroctf_v3/crypto/yours_truely/solve.py","file_name":"solve.py","file_ext":"py","file_size_in_byte":1231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"4283019","text":"# -*- coding: utf-8 -*-\nfrom datetime import datetime\nfrom calendar import timegm\nfrom flask import url_for, request\nfrom decimal import Decimal, ROUND_HALF_EVEN\nfrom email.utils import formatdate\nfrom werkzeug.utils import cached_property\nfrom urlparse import urlparse, urlunparse\nfrom .exceptions import MarshallingException\nfrom .utils import not_none\n\nfrom .marshal import marshal\n\n\n__all__ = [\"String\", \"FormattedString\", \"Url\", \"DateTime\", \"Float\",\n \"Integer\", \"Arbitrary\", \"Nested\", \"List\", \"Raw\", \"Boolean\",\n \"Fixed\", \"Price\"]\n\nZERO = Decimal()\n\nclass MinMaxMixin(object):\n def __init__(self, *args, **kwargs):\n self.minimum = kwargs.pop('min', None)\n self.maximum = kwargs.pop('max', None)\n super(MinMaxMixin, self).__init__(*args, **kwargs)\n\n def schema(self):\n schema = super(MinMaxMixin, self).schema()\n schema.update(minimum=self.minimum, maximum=self.maximum)\n return schema\n\nclass BaseField(object):\n __schema_type__ = 'string'\n __schema_format__ = None\n __schema_example__ = None\n\n def __init__(self, *args, **kwargs):\n self.attribute = kwargs.pop('attribute', None)\n self.default = kwargs.pop('default', None)\n self.description = kwargs.pop('description', None)\n self.title = kwargs.pop('title', None)\n self.readonly = kwargs.pop('readonly', None)\n self.required = kwargs.pop('required', None)\n self.example = kwargs.pop('example', self.__schema_example__)\n\n def format(self, value):\n \"\"\"Formats a field's value. No-op by default - field classes that\n modify how the value of existing object keys should be presented should\n override this and apply the appropriate formatting.\n\n :param value: The value to format\n :exception MarshallingException: In case of formatting problem\n\n \"\"\"\n raise NotImplementedError()\n\n def output(self, key, obj):\n \"\"\"Pulls the value for the given key from the object, applies the\n field's formatting and returns the result. If the key is not found\n in the object, returns the default value. Field classes that create\n values which do not require the existence of the key in the object\n should override this and return the desired value.\n\n :exception MarshallingException: In case of formatting problem\n \"\"\"\n value = get_value(key if self.attribute is None else self.attribute, obj)\n\n if value is None:\n return self.default\n\n return self.format(value)\n\n @cached_property\n def __schema__(self):\n return not_none(self.schema())\n\n def schema(self):\n return {\n 'type': self.__schema_type__,\n 'format': self.__schema_format__,\n 'title': self.title,\n 'description': self.description,\n 'readOnly': self.readonly,\n 'default': self.default,\n 'example': self.example,\n }\n\n def to_marshallable_type(self):\n \"\"\"Helper for converting an object to a dictionary only if it is not\n dictionary already or an indexable object nor a simple type\"\"\"\n if self is None:\n return None # make it idempotent for None\n\n if hasattr(self, '__getitem__'):\n return self # it is indexable it is ok\n\n if hasattr(self, '__marshallable__'):\n return self.__marshallable__()\n\n return dict(self.__dict__)\n\nclass String(BaseField):\n __schema_type__ = 'string'\n\n def __init__(self, *args, **kwargs):\n self.enum = kwargs.pop('enum', None)\n self.discriminator = kwargs.pop('discriminator', None)\n super(String, self).__init__(*args, **kwargs)\n self.required = self.discriminator or self.required\n\n def schema(self):\n schema = super(String, self).schema()\n schema.update(enum=self.enum)\n if self.enum and schema['example'] is None:\n schema['example'] = self.enum[0]\n return schema\n\n def format(self, value):\n try:\n if value:\n return unicode(value)\n else:\n return None\n except ValueError as ve:\n raise MarshallingException(ve)\n\nclass Integer(MinMaxMixin, BaseField):\n __schema_type__ = 'integer'\n\n def format(self, value):\n try:\n if value is None:\n return self.default\n return int(value)\n except ValueError as ve:\n raise MarshallingException(ve)\n\nclass Float(MinMaxMixin, BaseField):\n __schema_type__ = 'number'\n\n def format(self, value):\n try:\n return float(value)\n except ValueError as ve:\n raise MarshallingException(ve)\n\nclass Fixed(BaseField):\n __schema_type__ = 'number'\n \"\"\"\n A decimal number with a fixed precision.\n \"\"\"\n\n def __init__(self, decimals=5, **kwargs):\n super(Fixed, self).__init__(**kwargs)\n self.precision = Decimal('0.' + '0' * (decimals - 1) + '1')\n\n def format(self, value):\n dvalue = Decimal(value)\n if not dvalue.is_normal() and dvalue != ZERO:\n raise MarshallingException('Invalid Fixed precision number.')\n return unicode(dvalue.quantize(self.precision, rounding=ROUND_HALF_EVEN))\n\nclass Arbitrary(BaseField):\n __schema_type__ = 'number'\n\n def format(self, value):\n return unicode(Decimal(value))\n\nclass Boolean(BaseField):\n __schema_type__ = 'boolean'\n\n def format(self, value):\n return bool(value)\n\nclass DateTime(BaseField):\n \"\"\"\n Return a formatted datetime string in UTC. Supported formats are RFC 822\n and ISO 8601.\n\n See :func:`email.utils.formatdate` for more info on the RFC 822 format.\n\n See :meth:`datetime.datetime.isoformat` for more info on the ISO 8601\n format.\n\n :param dt_format: ``'rfc822'`` or ``'iso8601'``\n :type dt_format: str\n \"\"\"\n __schema_type__ = 'date_time'\n\n def __init__(self, dt_format='rfc822', **kwargs):\n super(DateTime, self).__init__(**kwargs)\n self.dt_format = dt_format\n\n def format(self, value):\n try:\n if self.dt_format == 'rfc822':\n return _rfc822(value)\n elif self.dt_format == 'iso8601':\n return _iso8601(value)\n else:\n raise MarshallingException(\n '不支持的时间格式 %s' % self.dt_format\n )\n except AttributeError as ae:\n raise MarshallingException(ae)\n\nclass Url(BaseField):\n \"\"\"\n A string representation of a Url\n\n :param endpoint: Endpoint name. If endpoint is ``None``,\n ``request.endpoint`` is used instead\n :type endpoint: str\n :param absolute: If ``True``, ensures that the generated urls will have the\n hostname included\n :type absolute: bool\n :param scheme: URL scheme specifier (e.g. ``http``, ``https``)\n :type scheme: str\n \"\"\"\n\n def __init__(self, endpoint=None, absolute=False, scheme=None):\n super(Url, self).__init__()\n self.endpoint = endpoint\n self.absolute = absolute\n self.scheme = scheme\n\n def output(self, key, obj):\n try:\n data = self.to_marshallable_type()\n endpoint = self.endpoint if self.endpoint is not None else request.endpoint\n o = urlparse(url_for(endpoint, _external=self.absolute, **data))\n if self.absolute:\n scheme = self.scheme if self.scheme is not None else o.scheme\n return urlunparse((scheme, o.netloc, o.path, \"\", \"\", \"\"))\n return urlunparse((\"\", \"\", o.path, \"\", \"\", \"\"))\n except TypeError as te:\n raise MarshallingException(te)\n\nclass List(BaseField):\n \"\"\"\n Field for marshalling lists of other fields.\n\n See :ref:`list-field` for more information.\n\n :param cls_or_instance: The field type the list will contain.\n \"\"\"\n\n def __init__(self, cls_or_instance, **kwargs):\n super(List, self).__init__(**kwargs)\n error_msg = (\"The type of the list elements must be a subclass of \"\n \"flask_yuexun.fields.BaseField\")\n if isinstance(cls_or_instance, type):\n if not issubclass(cls_or_instance, BaseField):\n raise MarshallingException(error_msg)\n self.container = cls_or_instance()\n else:\n if not isinstance(cls_or_instance, BaseField):\n raise MarshallingException(error_msg)\n self.container = cls_or_instance\n\n def format(self, value):\n # Convert all instances in typed list to container type\n if isinstance(value, set):\n value = list(value)\n\n return [\n self.container.output(idx,\n val if (isinstance(val, dict)\n or (self.container.attribute\n and hasattr(val, self.container.attribute)))\n and not isinstance(self.container, Nested)\n and not type(self.container) is BaseField\n else value)\n for idx, val in enumerate(value)\n ]\n\n def output(self, key, data):\n value = get_value(key if self.attribute is None else self.attribute, data)\n # we cannot really test for external dict behavior\n if is_indexable_but_not_string(value) and not isinstance(value, dict):\n return self.format(value)\n\n if value is None:\n return self.default\n\n return [marshal(value, self.container.nested)]\n\n def schema(self):\n schema = super(List, self).schema()\n schema['type'] = 'array'\n schema['items'] = self.container.__schema__\n return schema\n\nclass FormattedString(BaseField):\n \"\"\"\n FormattedString is used to interpolate other values from\n the response into this field. The syntax for the source string is\n the same as the string :meth:`~str.format` method from the python\n stdlib.\n\n Ex::\n\n fields = {\n 'name': fields.String,\n 'greeting': fields.FormattedString(\"Hello {name}\")\n }\n data = {\n 'name': 'Doug',\n }\n marshal(data, fields)\n \"\"\"\n\n def __init__(self, src_str):\n \"\"\"\n :param string src_str: the string to format with the other\n values from the response.\n \"\"\"\n super(FormattedString, self).__init__()\n self.src_str = unicode(src_str)\n\n def output(self, key, obj):\n try:\n data = self.to_marshallable_type()\n return self.src_str.format(**data)\n except (TypeError, IndexError) as error:\n raise MarshallingException(error)\n\nclass Nested(BaseField):\n __schema_type__ = None\n\n \"\"\"Allows you to nest one set of fields inside another.\n See :ref:`nested-field` for more information\n\n :param dict nested: The dictionary to nest\n :param bool allow_null: Whether to return None instead of a dictionary\n with null keys, if a nested dictionary has all-null keys\n :param kwargs: If ``default`` keyword argument is present, a nested\n dictionary will be marshaled as its value if nested dictionary is\n all-null keys (e.g. lets you return an empty JSON object instead of\n null)\n \"\"\"\n\n def __init__(self, model, nested, as_list=False, allow_null=False, **kwargs):\n self.nested = nested\n self.model = model\n self.as_list = as_list\n self.allow_null = allow_null\n super(Nested, self).__init__(**kwargs)\n\n def output(self, key, obj):\n value = get_value(key if self.attribute is None else self.attribute, obj)\n if value is None:\n if self.allow_null:\n return None\n elif self.default is not None:\n return self.default\n return marshal(value, self.nested)\n\n def schema(self):\n schema = super(Nested, self).schema()\n ref = '#/definitions/{0}'.format(self.nested.name)\n\n if self.as_list:\n schema['type'] = 'array'\n schema['items'] = {'$ref': ref}\n else:\n schema['$ref'] = ref\n return schema\n\nclass Raw(BaseField):\n __schema_type__ = 'object'\n\n\n\n\n\"\"\"Alias for :class:`~fields.Fixed`\"\"\"\nPrice = Fixed\n\n\ndef _rfc822(dt):\n \"\"\"Turn a datetime object into a formatted date.\n\n Example::\n\n fields._rfc822(datetime(2011, 1, 1)) => \"Sat, 01 Jan 2011 00:00:00 -0000\"\n\n :param dt: The datetime to transform\n :type dt: datetime\n :return: A RFC 822 formatted date string\n \"\"\"\n return formatdate(timegm(dt.utctimetuple()))\n\n\ndef _iso8601(dt):\n \"\"\"Turn a datetime object into an ISO8601 formatted date.\n\n Example::\n\n fields._iso8601(datetime(2012, 1, 1, 0, 0)) => \"2012-01-01T00:00:00\"\n\n :param dt: The datetime to transform\n :type dt: datetime\n :return: A ISO 8601 formatted date string\n \"\"\"\n return dt.isoformat()\n\n\ndef get_value(key, obj, default=None):\n \"\"\"Helper for pulling a keyed value off various types of objects\"\"\"\n if type(key) == int:\n return _get_value_for_key(key, obj, default)\n elif callable(key):\n return key(obj)\n else:\n return _get_value_for_keys(key.split('.'), obj, default)\n\ndef _get_value_for_keys( keys, obj, default):\n if len(keys) == 1:\n return _get_value_for_key(keys[0], obj, default)\n else:\n return _get_value_for_keys(\n keys[1:], _get_value_for_key(keys[0], obj, default), default)\n\ndef _get_value_for_key(key, obj, default):\n if is_indexable_but_not_string(obj):\n try:\n return obj[key]\n except (IndexError, TypeError, KeyError):\n pass\n return getattr(obj, key, default)\n\ndef is_indexable_but_not_string(obj):\n return not hasattr(obj, \"strip\") and hasattr(obj, \"__iter__\")\n","sub_path":"flask_yuexun/fields.py","file_name":"fields.py","file_ext":"py","file_size_in_byte":13947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"358284809","text":"# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\n\nimport logging\nfrom typing import Callable, Dict\n\nimport torch\n\nfrom .infer_mask import AutoMaskInference\nfrom ..utils.attr import get_nested_attr, has_nested_attr, set_nested_attr\n\n_logger = logging.getLogger()\n\n\nclass Replacer:\n def replace_modules(self, model: torch.nn.Module, auto_inferences: Dict[str, AutoMaskInference]):\n raise NotImplementedError()\n\n\nclass DefaultReplacer(Replacer):\n \"\"\"\n This is replacer is used to replace the leaf-module in the model.\n Leaf-module is the ``torch.nn.Module`` that contains no ``torch.nn.Module`` as its attribute.\n\n Parameters\n ----------\n replace_module_func_dict\n A dict of module compression function, {module_type_name: replace_func}.\n The input of replace_func is the original module and its masks, the output is the compressed module,\n (original_module, (input_mask, output_mask, weight_mask)) -> compressed_module.\n\n Here is an exmaple for module type name ``FakeModule`` replace function::\n\n def fake_module_replace(ori_module, masks):\n in_mask, out_mask, weight_mask = masks\n # prune the ori_module to a new smaller module according to the mask\n return new_small_module\n\n replace_module_func_dict = {'FakeModule': fake_module_replace}\n \"\"\"\n def __init__(self, replace_module_func_dict: Dict[str, Callable]):\n self.replace_module_func_dict = replace_module_func_dict\n\n def replace_modules(self, model, auto_inferences: Dict[str, AutoMaskInference]):\n replaced_names = []\n for unique_name, auto_infer in auto_inferences.items():\n if has_nested_attr(model, unique_name):\n module = get_nested_attr(model, unique_name)\n if isinstance(module, torch.nn.Module):\n _logger.debug(\"replace module %s, with class type %s\", unique_name, type(module))\n self.replace_submodule(model, unique_name, auto_infer)\n # prevent secondary replacement\n replaced_names.append(unique_name)\n else:\n # Support replace function in the future\n pass\n for name in replaced_names:\n auto_inferences.pop(name)\n\n def replace_submodule(self, model: torch.nn.Module, unique_name: str, auto_infer: AutoMaskInference):\n module = get_nested_attr(model, unique_name)\n _logger.info(\"replace module (name: %s, op_type: %s)\", unique_name, type(module))\n replace_function = self.replace_module_func_dict.get(type(module).__name__, None)\n if replace_function:\n compressed_module = replace_function(module, auto_infer.get_masks())\n set_nested_attr(model, unique_name, compressed_module)\n","sub_path":"nni/compression/pytorch/speedup/replacer.py","file_name":"replacer.py","file_ext":"py","file_size_in_byte":2861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"325170396","text":"import os\nimport time\nimport fnmatch\n\n\nclass SearchInFile:\n def __init__(self, path, key, filter_list):\n self.path = path\n self.key = key\n self.filter_list = filter_list\n self.file_count = 0\n\n def filter_match(self, file_name):\n for file_filter in self.filter_list:\n if fnmatch.fnmatch(file_name, file_filter):\n return True\n return False\n\n def find_key_in_files(self, root, file_list):\n for file_name in file_list:\n if self.filter_match(file_name):\n self.search_file(os.path.join(root, file_name))\n self.file_count += 1\n\n def search(self):\n print(\"Search '%s' in [%s]...\" % (self.key, self.path))\n print(\"_\" * 80)\n time_begin = time.time()\n for root, dir_list, file_list in os.walk(self.path, followlinks=True):\n self.find_key_in_files(root, file_list)\n\n print(\"_\" * 80)\n print(\"%s files searched in %0.4fsec.\" % (self.file_count, (time.time() - time_begin)))\n\n def search_file(self, file_path):\n with open(file_path, 'r', encoding='utf-8') as f:\n lines = f.readlines()\n for line in lines:\n if self.key in line:\n print('{file_path}: {line}'.format(file_path=file_path, line=line.strip()))\n\n\ndef main():\n path = r\"D:\\python\\scrapy\\fangzhen\"\n filter_list = ['bas*py', '*_w*py']\n key = 'spider'\n search_in_file = SearchInFile(path, key, filter_list)\n search_in_file.search()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"search/search_in_file.py","file_name":"search_in_file.py","file_ext":"py","file_size_in_byte":1562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"297801674","text":"\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n'''\nCreated on Jul 1, 2019\n\n@author: ballance\n'''\n\nfrom portaskela.exec.exec_local_scalar_type import ExecLocalScalarType\nfrom portaskela.pi.function_import_model import FunctionImportModel\nfrom portaskela.pi.function_exec_model import FunctionExecModel\nfrom portaskela.core_types import field_info\nfrom portaskela.core_types.enum_info_type import EnumInfoType\nfrom portaskela.core_types.field_enum_type import FieldEnumType\nfrom portaskela.core_types.field_kind import FieldKind\nfrom portaskela.core_types.field_scalar_type import FieldScalarType\nfrom portaskela.core_types.field_type import FieldType\nfrom portaskela.exec.exec_scope_type import ExecScopeType\nfrom portaskela.expr.expr_literalint_type import ExprLiteralIntType\nfrom portaskela.expr.value import Value, ValueType\n#from portaskela.pi.function_elab_param import FunctionElabParam\n#from portaskela.pi.function_exec_model import FunctionExecModel\n#from portaskela.pi.function_import_model import FunctionImportModel\n\n\nclass FunctionType(ExecScopeType):\n \n def __init__(self, t, fw):\n super().__init__()\n \n self.name = t.__name__\n self.t = t\n self.fw = fw\n self.fid = -1\n # Handle to the containing context (if present)\n self.ctxt_t = None\n self.is_import = False\n self.phase = None\n self.func = None\n self.fi = None\n self.convert_f = []\n self.n_params = -1\n fi = self.t.__code__\n if len(fi.co_varnames) > 0 and fi.co_varnames[0] == \"self\":\n self.param_names = fi.co_varnames[1:fi.co_argcount]\n self.is_global = False\n else:\n self.is_global = True\n self.param_names = fi.co_varnames[0:fi.co_argcount]\n \n self.param_types = self.t.__defaults__\n\n @staticmethod\n def expr2int(e, ctxt):\n val = e.get_value(ctxt)\n return val.val\n \n @staticmethod\n def expr2bit(e, ctxt):\n val = e.get_value(ctxt)\n return val.val\n\n def populate(self):\n if self.param_types != None:\n for p in self.param_types:\n info = p._int_field_info\n fname = info.name\n fid = info.id\n ftype = info.field_type\n \n if ftype == FieldKind.ScalarType:\n self.convert_f.append(FunctionType.expr2int)\n ft = ExecLocalScalarType(p)\n elif ftype == FieldKind.EnumType:\n enum_info = global_type_scope().find_type_by_user_type(p.enum_t)\n if enum_info == None:\n # Register a new type\n enum_info = EnumInfoType(p.enum_t)\n global_type_scope().add_type(enum_info, enum_info.t)\n \n ft = FieldEnumType(fname, fid, enum_info, False)\n elif ftype == FieldKind.ChandleType:\n # TODO: create a ChandleFieldType\n # TODO: ensure field is not null\n ft = FieldType(fname, fid, ftype, p, False)\n elif ftype == FieldKind.StringType:\n # TODO: create a StringFieldType\n # TODO: Need to consider difference if the field is rand\n ft = FieldType(fname, fid, ftype, p, False) \n else:\n raise Exception(\"Type \\\"\" + str(ftype) + \"\\\" not supported as a function parameter\")\n \n self.field_l.append(ft)\n \n self.n_params = len(self.field_l)\n\n def elab(self, o=None):\n \n param_l = []\n if not self.is_global:\n # Context functions require a context to be specified\n param_l.append(o)\n\n if not self.is_import: \n push_ctor_ctxt(CtorCtxt.Exec)\n # This scope holds parameters and local variables.\n # The parameters have already been populated. Executing\n # the function body will populate the local variables\n push_exec_stmt_scope(self)\n \n self.t(*param_l)\n \n pop_exec_stmt_scope()\n pop_ctor_ctxt()\n \n # Need to give names to any local variables\n# fi = self.t.__code__\n# print(\"argcount=\" + str(fi.co_argcount) + \" varnames=\" + str(fi.co_varnames))\n\n def create_frame(self):\n ret = super().create_frame()\n \n ret.is_exec = True\n \n return ret\n \n \n def build_model(self, builder):\n print(\"--> FunctionType::build_model\")\n builder.push_is_exec(True)\n if self.is_import:\n # A subsequent model visitor will link up an external function if appropriate\n ret = FunctionImportModel(self)\n else:\n ret = FunctionExecModel(self)\n builder.push_active_scope(ret)\n \n # Add variables to represent the function parameters\n# for p in self.param_l:\n# pm = p.build_model(builder)\n# print(\"Parameter Model: \" + str(pm))\n# ret.field_l.append(pm)\n \n for stmt_t in self.stmt_l:\n ret.stmt_l.append(stmt_t.build_model(builder))\n builder.pop_active_scope()\n \n builder.pop_is_exec()\n print(\"<-- FunctionType::build_model\")\n \n return ret \n ","sub_path":"src/portaskela/pi/function_type.py","file_name":"function_type.py","file_ext":"py","file_size_in_byte":6288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"42760462","text":"from __future__ import print_function\nimport sys, os, os.path, operator, shutil, glob, json\nimport openface, numpy as np\nfrom collections import defaultdict\nfrom datetime import datetime\nimport sklearn.cluster\nimport math\n\nnp.set_printoptions(linewidth=np.nan)\n\nnet = openface.TorchNeuralNet(model=\"models/openface/nn4.small2.v1.t7\", cuda=True)\n\ndef largestFace(enc_identity, image_file, face_json):\n if image_file in face_json:\n maxWidth = -1\n faceN = -1\n for faceID, faceData in list(face_json[image_file]['faces'].items()):\n faceWidth = faceData['bounds']['right'] - faceData['bounds']['left']\n if faceWidth > maxWidth:\n maxWidth = faceWidth\n faceN = faceID\n if faceN > -1:\n return (enc_identity + '/aligned_faces/' + str(faceN) + '_' + image_file)\n return \"\"\n\ndef findPrimary(enc_identity, identity_data, face_json, face_pos, clusters):\n primary_images = []\n if 'primary_images' in identity_data:\n primary_images = identity_data['primary_images']\n if 'article_image' in identity_data and identity_data['article_image'] not in primary_images:\n primary_images.append(identity_data['article_image'])\n\n primary_images = [face_pos[fn] for fn in map(lambda x : largestFace(enc_identity, x, face_json), primary_images) if fn != \"\"]\n\n maxClus = -1\n maxPrimaries = 0\n if primary_images != []:\n for c_ind,cluster_files in enumerate(clusters):\n cluster_primaries = 0\n for p_img in primary_images:\n if p_img in cluster_files:\n cluster_primaries += 1\n if cluster_primaries > maxPrimaries:\n maxPrimaries = cluster_primaries\n maxClus = c_ind\n return maxClus\n\ndef outlier_removal(cluster, mpd_arr):\n abs_median = np.absolute(mpd_arr - np.median(mpd_arr))\n MAD = np.median(abs_median)\n abs_median /= MAD\n\n outliers = []\n for i,am in enumerate(abs_median):\n if am > 3.0:\n outliers.append(cluster[i])\n print(len(outliers))\n\n for outlier in outliers:\n cluster.remove(outlier)\n return cluster\n\ndef mpd_single(i, cluster, distance_matrix):\n total_dist = 0.0\n for j in cluster:\n total_dist += distance_matrix[i][j]\n return (total_dist / len(cluster))\n\nsubfolders = glob.glob('dataset/A/Al')\n\nfor sf in subfolders:\n face_sf = 'face' + sf[4:]\n if not os.path.exists(face_sf):\n os.makedirs(face_sf)\n\n if not os.path.exists('clusters/' + sf[8:]):\n os.makedirs('clusters/' + sf[8:])\n html_out = open('clusters/' + sf[8:] + '/clusters.html', 'wb', 0)\n\n unknown_clusters = []\n primary_clusters = {}\n\n identities = glob.glob(sf + \"/Alan Tudyk\") + glob.glob(sf + \"/Al Gore\") + glob.glob(sf + \"/Alistair Burt\") + glob.glob(sf + \"/Alexander Walke\") + glob.glob(sf + \"/Ali Khamenei\") + glob.glob(sf + \"/Alexander Krassotkin\") + glob.glob(sf + \"/Alice Cooper\") + glob.glob(sf + \"/Albert II, Prince of Monaco\") + glob.glob(sf + \"/Alphonse Bertillon\") + glob.glob(sf + \"/Ali Larijani\") + glob.glob(sf + \"/Alan Light\") + glob.glob(sf + \"/Alexei Kortnev\")\n\n for identity in identities:\n enc_identity = identity.decode('utf8').encode('utf8')\n print(enc_identity)\n print(datetime.now().time())\n\n face_files = glob.glob(identity + '/aligned_faces/*.[jJ][pP][gG]') + glob.glob(identity + '/aligned_faces/*.[jJ][pP][eE][gG]')\n n = len(face_files)\n if n == 0:\n continue\n embeddings = np.array(map(lambda path : net.forwardPath(path), face_files))\n face_pos = {face_file : i for (i, face_file) in enumerate(face_files)}\n\n faceset_folder = 'face' + enc_identity[4:]\n faceset_faces = faceset_folder + '/faces'\n faceset_aligned = faceset_folder + '/aligned_faces'\n faceset_padded = faceset_folder + '/padded_faces'\n\n if not os.path.isdir(faceset_faces):\n os.makedirs(faceset_faces)\n if not os.path.isdir(faceset_aligned):\n os.makedirs(faceset_aligned)\n if not os.path.isdir(faceset_padded):\n os.makedirs(faceset_padded)\n\n with open(enc_identity + '/faces.json', \"r\") as load_f:\n face_json = json.load(load_f)\n with open(enc_identity + '/image_data.json', \"r\") as load_f:\n image_data_json = json.load(load_f)\n\n G = np.dot(embeddings, embeddings.T)\n R = np.tile(np.diag(np.dot(embeddings, embeddings.T)),(n,1))\n distance_matrix = np.sqrt(R + R.T - 2 * G)\n\n labels = sklearn.cluster.SpectralClustering(n_clusters=2).fit_predict(embeddings)\n clusters = [[] for i in range(0, max(labels) + 1)]\n for i,x in enumerate(labels):\n if x > -1:\n clusters[x].append(i)\n\n if len(clusters) == 0:\n continue\n \n primary_cluster = -1\n if os.path.isfile(enc_identity + '/identity_data.json'):\n with open(enc_identity + '/identity_data.json', \"r\") as load_f:\n identity_data = json.load(load_f)\n primary_cluster = findPrimary(enc_identity, identity_data, face_json, face_pos, clusters)\n mpd_list = [[mpd_single(c, clusters[num], distance_matrix) for c in clusters[num]] for num in (0,1)]\n if primary_cluster == -1:\n primary_cluster = 0 if np.mean(mpd_list[0]) < np.mean(mpd_list[1]) else 1\n clusters[primary_cluster] = outlier_removal(clusters[primary_cluster], np.array(mpd_list[primary_cluster]))\n\n clusters = map(lambda x : list(map(lambda y : face_files[y], x)), clusters)\n\n primary_clusters[faceset_folder] = (map(lambda x : x[len(enc_identity)+15:], clusters[primary_cluster]), np.average(map(lambda x : embeddings[face_pos[x]], clusters[primary_cluster]), axis=0).tolist())\n for i,c in enumerate(clusters):\n if i != primary_cluster and len(c) > 1:\n unknown_clusters.append((enc_identity, map(lambda x : x[len(enc_identity)+15:], c), np.average(map(lambda x : embeddings[face_pos[x]], c), axis=0).tolist()))\n\n print(datetime.now().time())\n\n if os.path.isfile(enc_identity + '/identity_data.json'):\n shutil.copyfile(enc_identity + '/identity_data.json', faceset_folder + '/identity_data.json')\n\n face_json_enc = {}\n image_data_json_enc = {}\n faces_json_cp = {}\n image_data_json_cp = {}\n\n for fn in list(face_json.keys()):\n face_json_enc[fn.encode('utf-8')] = face_json[fn]\n for fn in list(image_data_json['images'].keys()):\n image_data_json_enc[fn.encode('utf-8')] = image_data_json['images'][fn]\n\n for face_path in clusters[primary_cluster]:\n image = face_path[len(enc_identity) + 15 :]\n original = image[image.index('_') + 1:]\n\n shutil.copyfile(enc_identity + '/faces/' + image, faceset_faces + '/' + image)\n shutil.copyfile(enc_identity + '/aligned_faces/' + image, faceset_aligned + '/' + image)\n shutil.copyfile(enc_identity + '/padded_faces/' + image, faceset_padded + '/' + image)\n\n faces_json_cp[image] = face_json_enc[original]['faces'][image[:image.index('_')]]\n faces_json_cp[image]['original'] = original\n\n if original not in image_data_json_cp:\n image_data_json_cp[original] = image_data_json_enc[original]\n del image_data_json_cp[original]['exif']\n del image_data_json_cp[original]['context']\n \n with open(faceset_folder + '/faces.json', 'wb') as faces_out:\n json.dump(faces_json_cp, faces_out)\n with open(faceset_folder + '/image_data.json', 'wb') as image_data_out:\n json.dump(image_data_json_cp, image_data_out)\n\n # print cluster faces to html\n print('

' + enc_identity + '

', file=html_out)\n for i,cluster in enumerate(clusters):\n print('
', file=html_out)\n if i == primary_cluster:\n print(\"primary\", file=html_out)\n for image in cluster:\n data_uri = open(image, 'rb').read().encode('base64').replace('\\n', '')\n print(''.format(data_uri), file=html_out)\n\n html_out.close()\n\n with open('clusters/' + sf[8:] + '/primary_clusters.txt', 'wb', 0) as primary_clusters_out:\n print(primary_clusters, file=primary_clusters_out)\n\n with open('clusters/' + sf[8:] + '/unknown_clusters.txt', 'wb', 0) as unknown_out:\n print(unknown_clusters, file=unknown_out)\n","sub_path":"scripts/clustering/spectral.py","file_name":"spectral.py","file_ext":"py","file_size_in_byte":8592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"324402755","text":"import numpy as np \r\nclass ListaSecContenido:\r\n __items=None\r\n __tope=0\r\n __cant=0\r\n def __init__(self,xcant):\r\n self.__items= np.empty(xcant,dtype=int)\r\n self.__tope=0\r\n self.__cant= xcant\r\n def tope(self):\r\n return self.__tope\r\n def vacia(self):\r\n return self.__tope == 0\r\n def llena(self):\r\n return self.__tope == self.__cant\r\n def insertar(self,elemento):\r\n if not self.llena():\r\n if self.__tope == 0:\r\n self.__items[0]= elemento\r\n self.__tope += 1\r\n else:\r\n i=0\r\n while i < self.__tope and elemento > self.__items[i]:\r\n i+=1\r\n for j in range(self.__tope, i, -1):\r\n self.__items[j]= self.__items[j-1]\r\n self.__items[i]= elemento\r\n self.__tope += 1\r\n else:\r\n print('ERROR:lista llena. No se puede ingresar el numero {}'.format(elemento))\r\n def suprimir(self,posicion):\r\n if not self.vacia():\r\n if (posicion > 0)and(posicion <= self.__tope):\r\n rec=self.__items[posicion - 1]\r\n for i in range(posicion - 1,self.__tope-1):\r\n self.__items[i]=self.__items[i+1]\r\n self.__tope -= 1\r\n return rec\r\n else:\r\n print('ERROR:No existe posicion {} en la lista'.format(posicion))\r\n input('Presione para continuar...')\r\n else:\r\n print('ERROR:La lista esta vacia')\r\n input('Presione para continuar...')\r\n def suprimirContenido(self,elemento):\r\n if self.vacia():\r\n print('ERROR:La lista esta vacia')\r\n input('Presione para continuar...')\r\n else:\r\n i=0\r\n while i 0)and(posicion <= self.__tope):\r\n return self.__items[posicion-1]\r\n else:\r\n print('ERROR:No existe posicion {} en la lista'.format(posicion))\r\n else:\r\n print('ERROR:La lista esta vacia')\r\n def recorrer(self):\r\n for i in range(self.__tope):\r\n print(self.__items[i])\r\n def primerElemento(self):\r\n if self.vacia() == False:\r\n return self.__items[0]\r\n else:\r\n print('ERROR:La lista esta vacia')\r\n input('Presione para continuar...')\r\n def ultimoElemento(self):\r\n if self.vacia() == False:\r\n return self.__items[self.__tope - 1]\r\n else:\r\n print('ERROR:La lista esta vacia')\r\n input('Presione para continuar...')\r\n\r\n","sub_path":"UNIDAD 3/Practica 3/Ejercicio 5/ListaContenido.py","file_name":"ListaContenido.py","file_ext":"py","file_size_in_byte":3463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"498712076","text":"from flask_apispec import use_kwargs as api_spec_use_kwargs\nfrom flask_marshmallow.fields import _rapply, _url_val\nfrom marshmallow import post_load\nfrom marshmallow import fields as ma_fields\nfrom prettytable import PrettyTable\nfrom opsy.flask_extensions import ma\n\n\ndef use_kwargs(schema_cls, schema_kwargs=None, **kwargs):\n\n if schema_kwargs is None:\n schema_kwargs = {}\n\n def factory(request):\n # Respect partial updates for PATCH and GET requests\n partial = getattr(request, 'method', None) in ['PATCH', 'GET']\n # partial = request.method in ['PATCH', 'GET']\n # Add current request to the schema's context\n return schema_cls(\n partial=partial,\n context={'request': request},\n **schema_kwargs\n )\n\n return api_spec_use_kwargs(factory, **kwargs)\n\n\nclass Hyperlinks(ma_fields.Dict):\n # We recreate this from upstream, but inherit from Dict so apispec gets\n # the right type.\n\n _CHECK_ATTRIBUTE = False\n\n def __init__(self, schema, **kwargs):\n self.schema = schema\n ma_fields.Dict.__init__(self, **kwargs)\n\n def _serialize(self, value, attr, obj):\n return _rapply(self.schema, _url_val, key=attr, obj=obj)\n\n\nclass Password(ma.String):\n \"\"\"Field to obscure passwords on serialization.\"\"\"\n\n def _serialize(self, value, attr, obj, **kwargs):\n if value is None:\n return None\n return ''\n\n\n###############################################################################\n# Base schemas\n###############################################################################\n\n\nclass BaseSchema(ma.ModelSchema):\n\n @post_load\n def make_instance(self, data, **kwargs):\n \"\"\"Return deserialized data as a dict, not a model instance.\"\"\"\n return data\n\n def pt_dumps(self, obj, many=None):\n \"\"\"Returns a rendered prettytable representation of the data.\"\"\"\n many = self.many if many is None else bool(many)\n data = self.dump(obj, many=many)\n if many:\n columns = []\n for attr_name, field_obj in self.fields.items():\n if getattr(field_obj, 'load_only', False):\n continue\n columns.append(field_obj.data_key or attr_name)\n table = PrettyTable(columns, align='l')\n for entity in data:\n table.add_row([entity.get(x) for x in columns])\n else:\n table = PrettyTable(['Property', 'Value'], align='l')\n for key, value in data.items():\n table.add_row([key, value])\n return str(table)\n\n def print(self, obj, many=None, json=False):\n if json:\n print(super().dumps(obj, many=many, indent=4))\n else:\n print(self.pt_dumps(obj, many=many))\n","sub_path":"opsy/schema.py","file_name":"schema.py","file_ext":"py","file_size_in_byte":2812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"198567401","text":"from collections import deque\nfrom string import ascii_lowercase\n\ndef word_ladder(start, end, words):\n queue = deque([(start, [start])])\n\n while queue:\n word, path = queue.popleft()\n if word == end:\n return path\n\n for i in range(len(word)):\n for c in ascii_lowercase:\n next_word = word[:i] + c + word[i + 1:]\n if next_word in words:\n words.remove(next_word)\n queue.append([next_word, path + [next_word]])\n\n return None\n\nprint(word_ladder(\"dog\", \"cat\", {\"dot\", \"dop\", \"dat\", \"cat\"}))","sub_path":"src/main/scala/WordLadder2.py","file_name":"WordLadder2.py","file_ext":"py","file_size_in_byte":602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"617795471","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nfrom tensorflow.examples.tutorials.mnist import input_data\n\n# Load MNIST Dataset\nmnist = input_data.read_data_sets(\"MNIST_data/\", one_hot=True)\nx_train = mnist.train.images.reshape([-1,28,28,1])\ny_train = mnist.train.labels\nx_test = mnist.test.images.reshape([-1,28,28,1])\ny_test = mnist.test.labels\n\nw_init = tf.contrib.layers.xavier_initializer()\nb_init = tf.constant_initializer(0.1)\n\ninit_params = {\n \"kernel_initializer\": w_init,\n \"bias_initializer\": b_init,\n}\n\nconv_params = {\n \"strides\": 1,\n \"padding\": 'same',\n \"activation\": tf.nn.relu,\n}\n\npool_params = {\n \"pool_size\": 2,\n \"strides\": 2,\n \"padding\": 'valid'\n}\n\ndef Residual(x):\n h_conv1 = tf.layers.conv2d(x, kernel_size=3, filters=32, **conv_params, **init_params)\n h_conv2 = tf.layers.conv2d(h_conv1, kernel_size=3, filters=32, **conv_params, **init_params)\n h_conv3 = tf.layers.conv2d(h_conv2, kernel_size=3, filters=32, **conv_params, **init_params)\n h_conv3 = h_conv3 + h_conv1\n h_pool3 = tf.layers.max_pooling2d(h_conv3, **pool_params)\n return h_pool3\n\n# Model\ndef ResidualNet(x):\n h_res1 = Residual(x)\n h_res2 = Residual(h_res1)\n h_reshape2 = tf.reshape(h_res2, [-1, 7*7*32])\n y_logit = tf.layers.dense(h_reshape2, 10, **init_params)\n y_prob = tf.nn.softmax(y_logit)\n return y_prob, y_logit\n\n# Placeholder\nx_ = tf.placeholder(tf.float32, shape=[None, 28, 28, 1], name='x')\ny_ = tf.placeholder(tf.float32, shape=[None, 10], name='y')\n\n# Loss and Solver\ny_prob, y_logit = ResidualNet(x_)\nloss = tf.reduce_mean(tf.losses.softmax_cross_entropy(onehot_labels=y_, logits=y_logit))\nsolver = tf.train.AdamOptimizer(1e-3).minimize(loss)\n\n# Evaluation\ncorrect_prediction = tf.equal(tf.argmax(y_prob,1), tf.argmax(y_,1))\nacc = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n\n# Session\nsess = tf.Session()\nsess.run(tf.global_variables_initializer())\n\n# Train\nbatch_size = 64\nfor i in range(5001):\n batch_id = np.random.choice(x_train.shape[0], batch_size)\n x_batch = x_train[batch_id]\n y_batch = y_train[batch_id]\n _ = sess.run(solver, feed_dict={x_: x_batch, y_: y_batch})\n\n if i%100 == 0:\n batch_id = np.random.choice(x_test.shape[0], 512)\n x_test_batch = x_test[batch_id]\n y_test_batch = y_test[batch_id]\n loss_, acc_ = sess.run([loss, acc], feed_dict={x_: x_test_batch, y_: y_test_batch})\n print('Iter', i, 'Loss:', loss_, 'Acc:', acc_)","sub_path":"10_Tensorflow_Residual.py","file_name":"10_Tensorflow_Residual.py","file_ext":"py","file_size_in_byte":2487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"313226231","text":"import glob\r\n# The glob module finds all the pathnames matching a specified pattern according to the rules used by the Unix shell\r\nfrom pathlib import Path\r\n# The final path component, without its suffix\r\n \r\n \r\nmon_chemin = input('Quel est le chemin relatif du répertoire contenant les fichiers csv ?\\n')\r\n#\"./MIB_Files/\"\r\n \r\nmon_alias = input('Alias du fichier py créé (sera ./MaBase_alias.py) ?\\n')\r\n \r\nmon_fic = \"MaBase_%s.py\" % mon_alias\r\n \r\nmes_csv_file = {Path(f).stem:open(f,\"r\") for f in glob.glob(mon_chemin + \"*.csv\")}\r\n \r\nmes_csv = {Path(f).stem:open(f,\"r\").readlines() for f in glob.glob(mon_chemin + \"*.csv\")}\r\n \r\nmon_py = open(mon_fic,\"w+\")\r\n \r\n \r\ndef creer_classes():\r\n for b in mes_csv:\r\n mon_py.write(\"class \" + b[4:-1] + \":\\n\\tdef __init__(self\")\r\n lignes = mes_csv[b]\r\n attributs = lignes[0].split()[0].split(',')\r\n for a in attributs:\r\n mon_py.write(\", \" + a)\r\n mon_py.write(\"):\\n\\t\\t\")\r\n for a in attributs:\r\n mon_py.write(\"self.%s = %s\\n\\t\\t\" % (a,a))\r\n mon_py.write(\"\\n\\n\")\r\n \r\n \r\ndef creer_bases():\r\n for b in mes_csv:\r\n nom = b[4:-1]\r\n mon_py.write(b + \" = { \")\r\n lignes = mes_csv[b]\r\n for index,ligne in enumerate(lignes[1:]):\r\n ligne = ligne.split()[0].split(',')\r\n debut = '' if index == 0 else ', '\r\n mon_py.write(debut + nom + \"(\")\r\n for att in ligne[:-1]:\r\n mon_py.write(\"'\" + att + \"', \")\r\n mon_py.write(\"'\" + ligne[-1] +\"')\")\r\n mon_py.write(\" }\\n\\n\")\r\n \r\n \r\ndef ferme():\r\n for b in mes_csv_file:\r\n mes_csv_file[b].close()\r\n mon_py.close()\r\n \r\n \r\ncreer_classes()\r\ncreer_bases()\r\nferme()\r\n\r\nclass Responsable:\r\n def __init__(self, NoAllee, Nom):\r\n self.NoAllee = NoAllee\r\n self.Nom = Nom\r\n \r\n \r\nclass Miam:\r\n def __init__(self, NomAlien, Aliment):\r\n self.NomAlien = NomAlien\r\n self.Aliment = Aliment\r\n \r\n \r\nclass Agent:\r\n def __init__(self, Nom, Ville):\r\n self.Nom = Nom\r\n self.Ville = Ville\r\n \r\n \r\nclass gardien:\r\n def __init__(self, Nom, NoCabine):\r\n self.Nom = Nom\r\n self.NoCabine = NoCabine\r\n \r\n \r\nclass Alien:\r\n def __init__(self, Nom, Sexe, Planete, NoCabine):\r\n self.Nom = Nom\r\n self.Sexe = Sexe\r\n self.Planete = Planete\r\n self.NoCabine = NoCabine\r\n \r\n \r\nclass Cabine:\r\n def __init__(self, NoCabine, NoAllee):\r\n self.NoCabine = NoCabine\r\n self.NoAllee = NoAllee\r\n \r\n \r\nBaseResponsables = { Responsable('1', 'Seldon'), Responsable('2', 'Pelorat') }\r\n \r\nBaseMiams = { Miam('Zorglub', 'Bortsch'), Miam('Blorx', 'Bortsch'), Miam('Urxiz', 'Zoumise'), Miam('Zbleurdite', 'Bortsch'), Miam('Darneurane', 'Schwanstucke'), Miam('Mulzo', 'Kashpir'), Miam('Zzzzzz', 'Kashpir'), Miam('Arghh', 'Zoumise'), Miam('Joranum', 'Bortsch') }\r\n \r\nBaseAgents = { Agent('Branno', 'Terminus'), Agent('Darell', 'Terminus'), Agent('Demerzel', 'Uco'), Agent('Seldon', 'Terminus'), Agent('Dornick', 'Kalgan'), Agent('Hardin', 'Terminus'), Agent('Trevize', 'Hesperos'), Agent('Pelorat', 'Kalgan'), Agent('Riose', 'Terminus') }\r\n \r\nBasegardiens = { gardien('Branno', '1'), gardien('Darell', '2'), gardien('Demerzel', '3'), gardien('Seldon', '4'), gardien('Dornick', '5'), gardien('Hardin', '6'), gardien('Trevize', '7'), gardien('Pelorat', '8'), gardien('Riose', '9') }\r\n \r\nBaseAliens = { Alien('Zorglub', 'M', 'Trantor', '1'), Alien('Blorx', 'M', 'Euterpe', '2'), Alien('Urxiz', 'M', 'Aurora', '3'), Alien('Zbleurdite', 'F', 'Trantor', '4'), Alien('Darneurane', 'M', 'Trantor', '4'), Alien('Mulzo', 'M', 'Helicon', '6'), Alien('Zzzzzz', 'F', 'Aurora', '7'), Alien('Arghh', 'M', 'Nexon', '8'), Alien('Joranum', 'F', 'Euterpe', '9') }\r\nBaseCabines={ Cabine('1', '1'), Cabine('2', '1'), Cabine('3', '1'), Cabine('4', '1'), Cabine('5','1'), Cabine('6','2'), Cabine('7','2'), Cabine('8','2'), Cabine('9','2')}\r\n","sub_path":"Mabase_MIB.py","file_name":"Mabase_MIB.py","file_ext":"py","file_size_in_byte":4179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"1890350","text":"from django.db import models\nfrom django.utils.timezone import now\n\n# Create your models here.\nclass ExpenseCategory(models.Model):\n cat_name = models.CharField(max_length=50)\n created_at = models.DateTimeField(default=now, editable=True)\n\n class Meta:\n verbose_name = \"ExpenseCategory\"\n verbose_name_plural = \"ExpenseCategorys\"\n\n def __unicode__(self):\n return self.cat_name \n\nclass Expense(models.Model):\n ExpenseCategory = models.ForeignKey(ExpenseCategory,related_name='expense', on_delete=models.DO_NOTHING) \n expense_name = models.CharField(max_length=50)\n expense_amt = models.IntegerField()\n expense_date = models.DateTimeField(default=now, editable=True)\n\n class Meta:\n verbose_name = \"Expense\"\n verbose_name_plural = \"Expenses\"\n\n def __unicode__(self):\n return '%s %s' % (self.expense_name, self.expense_amt) \n\n","sub_path":"lostfiles/expensemanager/expenses/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"293891941","text":"# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.\n# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\" Tokenization classes for LayoutLM model.\"\"\"\nfrom ..bert.tokenizer import BertTokenizer\n\n__all__ = ['LayoutLMTokenizer']\n\n\nclass LayoutLMTokenizer(BertTokenizer):\n \"\"\"\n The usage of LayoutLMTokenizer is the same as\n `BertTokenizer `__.\n For more information regarding those methods, please refer to this superclass.\n \"\"\"\n resource_files_names = {\"vocab_file\": \"vocab.txt\"} # for save_pretrained\n pretrained_resource_files_map = {\n \"vocab_file\": {\n \"layoutlm-base-uncased\":\n \"https://bj.bcebos.com/paddlenlp/models/transformers/layoutlm/layoutlm-base-uncased/vocab.txt\",\n \"layoutlm-large-uncased\":\n \"https://bj.bcebos.com/paddlenlp/models/transformers/layoutlm/layoutlm-large-uncased/vocab.txt\",\n }\n }\n pretrained_init_configuration = {\n \"layoutlm-base-uncased\": {\n \"do_lower_case\": True\n },\n \"layoutlm-large-uncased\": {\n \"do_lower_case\": True\n },\n }\n","sub_path":"ptstructure/vqa/pytorchnlp/transformers/layoutlm/tokenizer.py","file_name":"tokenizer.py","file_ext":"py","file_size_in_byte":1780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"250794107","text":"from flask import redirect, url_for, render_template, request\nfrom flask_login import login_required, current_user\nfrom flask_babel import lazy_gettext as _\n\nfrom ..ext import db\nfrom ..utils.pagination import get_page, get_page_size\nfrom ..utils.message import success\nfrom ..models import Game, Report\nfrom ..report import report_bp\nfrom ..report.forms import GameReportForm, ReportForm\n\n\n@report_bp.route('/game//add', methods=['POST', 'GET'])\n@login_required\ndef report_add_for_game(game_id):\n game = Game.query.get_or_404(game_id)\n form = GameReportForm()\n if form.validate_on_submit():\n form.save(game=game)\n success(_('Thank you for your report'))\n return redirect(url_for('games.games_details', system_id=game.game_system.id, game_id=game.id))\n ctx = dict(game=game, system=game.game_system, form=form)\n return render_template('report/game_report_form.html', **ctx)\n\n\n@report_bp.route('/add', methods=['POST', 'GET'])\n@login_required\ndef add():\n form = ReportForm()\n if form.validate_on_submit():\n form.save()\n success(_('Thank you for your report'))\n return redirect(url_for('report.list'))\n ctx = {\n 'form': form,\n }\n return render_template('report/form.html', **ctx)\n\n\n@report_bp.route('/', methods=['POST', 'GET'])\ndef details(report_id):\n report = Report.query.get_or_404(report_id)\n in_owner_context = current_user.is_authenticated and report.user == current_user\n form = None\n if in_owner_context and request.method == 'POST':\n form = GameReportForm()\n if form.validate_on_submit():\n report = form.save(game=report.game, obj=report)\n success(_('Your report has been updated'))\n return redirect(url_for('report.details', report_id=report.id))\n ctx = dict(report=report, game=report.game, platform=report.platform_version.platform)\n if in_owner_context:\n if form is None:\n form = GameReportForm(obj=report)\n ctx['form'] = form\n return render_template('report/details.html', **ctx)\n\n\n@report_bp.route('')\ndef list():\n page = get_page(request)\n page_size = get_page_size(request, default_size=10)\n query = Report.query.order_by(db.desc(Report.created))\n pagination = query.paginate(page, page_size)\n ctx = {\n 'pagination': pagination,\n }\n return render_template('report/list.html', **ctx)\n","sub_path":"ecpapp/report/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"166327237","text":"#/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport sys\nimport time\nimport random\nimport jieba\nimport pynlpir\nfrom py2neo import Graph, Node, Relationship\n\ndef SynonymReplace(words):\n \"\"\"\n 词向量替换为同义词向量,同义词表存储在neo4j数据库中,词性根节点为\"SynonymRoot\",词节点为\"synonym\"\n \n \"\"\"\n graph = Graph(\"http://localhost:7474/db/data/\", password = \"102422\")\n sv = []\n for word in words:\n word_node = list(graph.find(\"synonym\", \"word\", word, 1))\n if word_node:\n synonym_node = list(graph.find(\"SynonymRoot\", \"name\", word_node[0][\"tag\"], 1))\n synonym_words = synonym_node[0][\"words\"]\n synonym_random = synonym_words[random.randint(0, len(synonym_words)-1)]\n sv.append(synonym_random) \n return sv\n\t\ndef GenerateSynonymousSentence(question, tool = \"jieba\"):\n \"\"\"\n 生成同义句。分词工具可选择jieba或者nlpir,支持其它或者自定义分词工具扩展。\n \t\n \"\"\"\t\n words = []\n if tool == \"jieba\":\t\n words = list(jieba.cut(question))\n elif tool == \"nlpir\":\n pynlpir.open()\n segments = pynlpir.segment(question)\n for segment in segments:\n words.append(segment[0])\n pynlpir.close()\n print(tool + \" cut: \" + \"/\".join(words))\n \n sv = SynonymReplace(words) \n print(tool + \" generate: \" + \"/\".join(sv))\n answer = \"\".join(sv)\n \n return answer\n\nif __name__ == \"__main__\":\n\tprint(\"同义句生成测试......\") \n\tfilename = \"log/GenerateSynonymousSentence_\" + time.strftime(\"%Y-%m-%d-%H-%M\",time.localtime(time.time())) + \".md\"\n\tf = open(filename, \"w\")\n\tf.write(\"标签:测试文档\\n#同义句生成测试:\\n>Enter the GenerateSynonymousSentence mode...\\n\")\n\n\twhile True:\n\t\ttry:\n\t\t\tquestion = input(\"\\n>>\")\n\t\t\tanswer_jieba = GenerateSynonymousSentence(question, tool = \"jieba\")\n\t\t\tanswer_nlpir = GenerateSynonymousSentence(question, tool = \"nlpir\")\n\t\t\tprint(\"answer_jieba: \" + answer_jieba)\n\t\t\tprint(\"answer_nlpir: \" + answer_nlpir)\n\n\t\t\tf.write(\"`>>\" + question + \"`\\n\")\n\t\t\tf.write(\"`answer_jieba: \" + answer_jieba + \"`\\n\")\n\t\t\tf.write(\"`answer_nlpir: \" + answer_nlpir + \"`\\n\")\n\t\texcept KeyboardInterrupt:\n\t\t\tf.close()","sub_path":"ImEverywhere/GenerateSynonymousSentence.py","file_name":"GenerateSynonymousSentence.py","file_ext":"py","file_size_in_byte":2238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"363961307","text":"import git\nimport random\n\nimport tensorflow as tf\nimport numpy as np\nfrom baselines.common.cmd_util import common_arg_parser\nfrom baselines.common import tf_util as U\nfrom baselines import logger\ngfile = tf.gfile\nfrom parasol.experiment import Experiment\n\nimport dr\nfrom datetime import datetime\nimport pickle\nfrom path import Path\n\n\ndef set_global_seeds(i):\n tf.set_random_seed(i)\n np.random.seed(i)\n random.seed(i)\n\n\nclass PPO(Experiment):\n\n def __init__(self, experiment_name, env_params, train_params, **kwargs):\n self.env_params = env_params\n self.train_params = train_params\n super(PPO, self).__init__(experiment_name, **kwargs)\n\n def from_dict(self, params):\n return PPO(params['env'], params['num_timesteps'],\n params['seed'])\n\n def initialize(self, out_dir):\n pass\n\n def to_dict(self):\n repo = git.Repo(search_parent_directories=True)\n sha = repo.head.object.hexsha\n return {\n 'env_params': self.env_params,\n 'train_params': self.train_params,\n 'git_hash': sha\n }\n\n def train(self, env_id, backend, num_timesteps, seed, viz_logdir, stdev=0., mean_scale=1.0,\n collision_detector='bullet'):\n from baselines.ppo1 import mlp_policy, pposgd_simple\n sess = U.make_session(num_cpu=1)\n sess.__enter__()\n def policy_fn(name, ob_space, ac_space):\n return mlp_policy.MlpPolicy(name=name, ob_space=ob_space, ac_space=ac_space,\n hid_size=64, num_hid_layers=2)\n env_dist = dr.dist.Normal(env_id, backend, stdev=stdev, mean_scale=mean_scale)\n env_dist.seed(seed)\n set_global_seeds(seed)\n\n pi, eval_perfs = pposgd_simple.learn(env_dist, collision_detector, policy_fn,\n max_timesteps=num_timesteps,\n timesteps_per_actorbatch=2048,\n clip_param=0.2, entcoeff=0.0,\n optim_epochs=10, optim_stepsize=3e-4, optim_batchsize=64,\n gamma=0.99, lam=0.95, schedule='linear', viz_logdir=viz_logdir\n )\n\n return sess, eval_perfs\n\n def run_experiment(self, out_dir):\n logger.configure()\n\n env_name = self.env_params['env_name']\n backend = self.env_params['backend']\n collision_detector = self.env_params['collision_detector']\n\n num_ts = self.train_params['num_timesteps']\n seed = self.train_params['seed']\n stdev = self.train_params['env_dist_stdev']\n mean_scale = self.train_params['mean_scale']\n\n viz_logdir = 'runs/' + str(self.env_params) + str(self.train_params) + datetime.now().strftime('%b%d_%H-%M-%S')\n\n sess, eval_perfs = self.train(env_name, backend, num_timesteps=num_ts, seed=seed, viz_logdir=viz_logdir,\n collision_detector=collision_detector, stdev=stdev, mean_scale=mean_scale)\n\n # Save data\n saver = tf.train.Saver()\n\n out_dir = Path(out_dir)\n\n saver.save(sess, out_dir / 'tf_sess.ckpt')\n\n with open(out_dir / 'eval_perfs.pkl', 'wb') as f:\n pickle.dump(eval_perfs, f)\n","sub_path":"dr/experiment/ppo.py","file_name":"ppo.py","file_ext":"py","file_size_in_byte":3124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"244065505","text":"import numpy as np\nimport time\nimport matplotlib.pyplot as plt\nfrom itertools import islice\n\n#cache dictionary\nproduct_cache = {}\n\n\n\ndef calculate_energy( p, t, offset, len_p ): # - memoise \n \"\"\"\n Normalisation for 1D slice of N size array of same length of pattern passed.\n norm= sqrt( sum(f[i]^2) * sum(g[m]^2) )\n \n Inputs:\n ----------------\n p Pattern must be non empty and sum-square of its elements precalculated and passed\n\n t Template with similar dimensionality to pattern\n\n offset Offset position in the template/search array\n\n len_p offset for end-of-slice index for the slice of template\n \n Output:\n ----------------\n norm Scalar float of variance for a given slice of the template/search and pattern\n \"\"\"\n g_slice = t[ offset : offset + len_p ] \n norm = np.sqrt( p * ( g_slice**2).sum() ) \n # if norm == 0 :\n # print (\"p=\", p, \"template=\", g_slice, \"offset = \", offset, \"\\n\")\n return norm\n\n\ndef calculate_score( pattern, template, offset):\n \"\"\"\n Correlation for 1D slice of N size template/search array with pattern at given offset. Sum(f[i]*g[i+m])\n \n Inputs:\n ----------------\n pattern Pattern must be non empty and sum-square of its elements precalculated and passed\n\n template Template with similar dimensionality to pattern\n\n offset Offset position in the template/search array\n \n Output:\n ----------------\n score Scalar float of correlation score between pattern and template slice\n \"\"\" \n #not faster \n # slice_template = template[ offset : offset + len(pattern) ]\n # score = np.dot( pattern, slice_template ) \n #Mutltiply and add each element of the pattern and template\n score = 0 \n for i in range(len( pattern )):\n o = i + offset\n #try:\n if template[o] > 0 and pattern[i] > 0:\n if (i,o) not in product_cache:\n product_cache[ (i,o) ] = pattern[ i ] * template[ o ]\n score += product_cache[ (i,o) ] \n #except:\n #print( \"Error line 26\", pattern, template )\n\n return score\n\n\ndef zero_padding( pattern, template ):\n \"\"\"\n Pad 1D template at begining and end of array with pattern length\n \n Inputs:\n ----------------\n pattern Pattern must be non empty and sum-square of its elements precalculated and passed\n\n template Template with similar dimensionality to pattern\n \n Output:\n ----------------\n template_padded Padded template array \n \"\"\" \n #Calculate pad size \n pad = [ 0 ] * ( len( pattern ) - 1 )\n #Pad begining and end of temple -1 for first element\n template_padded = pad + list(template) + pad\n\n return template_padded\n\n\n#function that finds the largest element and its index in an array\ndef find_best_match( score ):\n \"\"\"\n Find max value in 1D array and its index\n \n Inputs:\n ----------------\n score 1D target array\n \n Output:\n ----------------\n max_element Max Element in the array\n\n index Index of largest element \n\n \"\"\" \n s = np.array( score )\n try:\n max_element = np.amax( s )\n except:\n print( \"Line 45 Error\", score )\n index = np.argmax( s )\n\n return max_element, index\n\n\ndef n_corr( pattern, template, debug = False ): #change later to signal 1 and 2 as inputs\n \"\"\"\n Normed cross correlation of two 1D arrays\n \n Inputs:\n ----------------\n pattern Pattern must be non empty \n\n template Template, search space with similar dimensionality to pattern\n \n Output:\n ----------------\n norm_scores Normed cross correlation array\n \"\"\" \n\n #Pad and initalise arrays for calculation \n template_padded = zero_padding( pattern, template )\n corr_len = len( template_padded ) - len( pattern )\n scores = [0] * ( corr_len )\n norm = [0] * ( corr_len ) \n norm_scores = [0] * ( corr_len ) \n #test = [0] * ( len( template ) - len( pattern ) )\n #t_start = time.time()\n \n #Precalculate pattern squared-sum and store, reduces calculation time by half \n pattern_arr = np.array( pattern )\n pattern_sq_sum = ( pattern_arr**2 ).sum() #to use in norm - memoised values to reduce number of computations\n template_pad_arr = np.array( template_padded )\n \n #Find normed cross correlation from convolution of pattern with template array slices\n t_start = time.time()\n for i in range( len( scores ) ):\n t_step = time.time()\n scores[ i ] = calculate_score( pattern, template, i)\n #print( scores )\n #Whenever the cross correlation is zero, the cross correlation is not calculated \n if scores[i]!=0 : \n norm[ i ] = calculate_energy( pattern_sq_sum, template_pad_arr, i, len(pattern))\n norm_scores[i] = scores[ i ]/norm[ i ]\n tn = time.time()\n if debug: print( f'{ i } step time = { tn - t_step} run time = { tn - t_start}')\n \n #print( \"s=\", scores,\"\\n\", \"n=\", norm, \"\\n\")\n\n return norm_scores\n #return norm\n\ndef find_offset(pattern, template, debug = False): \n \"\"\"\n 1D array offset index and value from normed cross correlation \n \n Inputs:\n ----------------\n pattern Pattern must be non empty \n\n template Template, search space with similar dimensionality to pattern\n \n Output:\n ----------------\n (best_score, best_match) Index of offset found from cross correlation\n \"\"\" \n\n norm_corr = n_corr( pattern, template, debug )\n\n best_score, best_match = find_best_match( norm_corr )\n #print( best_match )\n\n #Plot array of cross correlation\n plt.figure()\n plt.plot(norm_corr)\n\n # subtract padding: - (len - 1)\n return best_match - len( pattern ) + 1, best_score \n\n\n\ndef read_file( fileName ):\n \"\"\"\n Read input data file and filters for numerical values \n \n Inputs:\n ----------------\n fileName File path \n \n Output:\n ----------------\n data_list List of read of only numerical data values\n \n References:\n super9super9 bronze badges, et al. \n “Read File from Line 2 or Skip Header Row.” \n Stack Overflow, 1 May 1960, stackoverflow.com/questions/4796764/read-file-from-line-2-or-skip-header-row. \n \"\"\" \n \n data = open( fileName ,\"r\") \n data_list = [float(line.strip() ) for line in islice(data, 1, None)] \n data.close()\n \n return data_list\n\n\n\n#calculate signal offset for files in the local directory that are read into program\n\ndef main():\n\n debug = False\n\n time_start = time.time()\n\n data_1 = read_file( \"MidSemReport\\sensor1Data.txt\" ) \n data_2 = read_file( \"MidSemReport\\sensor2Data.txt\" )\n data_1_len = len(data_1)\n # print( data_1_len, len( data_2 ) )\n sample_period = 1 / 44100\n speed_sound = 333\n #Debugging size \n size = data_1_len \n\n offset, corr_value = find_offset( data_1[:size], data_2[:size], debug )\n\n offset_time = offset*sample_period\n\n sensor_distance = offset * sample_period * speed_sound\n\n t_total = time.time() - time_start\n \n print(\"offset time = \", offset_time, \"offset position =\", offset,\"sensor distance =\", sensor_distance, \"run time = \", t_total )\n \n #plotting\n plt.figure()\n plt.subplot(211) \n plt.plot(data_1[:size])\n plt.subplot(212) \n plt.plot(data_2[:size])\n plt.show() \n\n \n \n \nif __name__ == '__main__':\n \n main()\n\n\n\n\n\n","sub_path":"MidSemReport/signal_offset_spatial.py","file_name":"signal_offset_spatial.py","file_ext":"py","file_size_in_byte":7540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"595322984","text":"##############################################################################\n# \n# Zope Public License (ZPL) Version 1.0\n# -------------------------------------\n# \n# Copyright (c) Digital Creations. All rights reserved.\n# \n# This license has been certified as Open Source(tm).\n# \n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n# \n# 1. Redistributions in source code must retain the above copyright\n# notice, this list of conditions, and the following disclaimer.\n# \n# 2. Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions, and the following disclaimer in\n# the documentation and/or other materials provided with the\n# distribution.\n# \n# 3. Digital Creations requests that attribution be given to Zope\n# in any manner possible. Zope includes a \"Powered by Zope\"\n# button that is installed by default. While it is not a license\n# violation to remove this button, it is requested that the\n# attribution remain. A significant investment has been put\n# into Zope, and this effort will continue if the Zope community\n# continues to grow. This is one way to assure that growth.\n# \n# 4. All advertising materials and documentation mentioning\n# features derived from or use of this software must display\n# the following acknowledgement:\n# \n# \"This product includes software developed by Digital Creations\n# for use in the Z Object Publishing Environment\n# (http://www.zope.org/).\"\n# \n# In the event that the product being advertised includes an\n# intact Zope distribution (with copyright and license included)\n# then this clause is waived.\n# \n# 5. Names associated with Zope or Digital Creations must not be used to\n# endorse or promote products derived from this software without\n# prior written permission from Digital Creations.\n# \n# 6. Modified redistributions of any form whatsoever must retain\n# the following acknowledgment:\n# \n# \"This product includes software developed by Digital Creations\n# for use in the Z Object Publishing Environment\n# (http://www.zope.org/).\"\n# \n# Intact (re-)distributions of any official Zope release do not\n# require an external acknowledgement.\n# \n# 7. Modifications are encouraged but must be packaged separately as\n# patches to official Zope releases. Distributions that do not\n# clearly separate the patches from the original work must be clearly\n# labeled as unofficial distributions. Modifications which do not\n# carry the name Zope may be packaged in any form, as long as they\n# conform to all of the clauses above.\n# \n# \n# Disclaimer\n# \n# THIS SOFTWARE IS PROVIDED BY DIGITAL CREATIONS ``AS IS'' AND ANY\n# EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL DIGITAL CREATIONS OR ITS\n# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n# SUCH DAMAGE.\n# \n# \n# This software consists of contributions made by Digital Creations and\n# many individuals on behalf of Digital Creations. Specific\n# attributions are listed in the accompanying credits file.\n# \n##############################################################################\n'''\nGuard conditions in a web-configurable workflow.\n$Id$\n'''\n__version__='$Revision$'[11:-2]\n\nfrom string import split, strip, join\nfrom cgi import escape\n\nimport Globals\nfrom Globals import DTMLFile, Persistent\nfrom AccessControl import ClassSecurityInfo\n\nfrom Products.CMFCore.CMFCorePermissions import ManagePortal\n\nfrom Expression import Expression, exprNamespace\nfrom utils import _dtmldir\n\n\nclass Guard (Persistent):\n permissions = ()\n roles = ()\n expr = None\n\n security = ClassSecurityInfo()\n security.declareObjectProtected(ManagePortal)\n\n guardForm = DTMLFile('guard', _dtmldir)\n\n def check(self, sm, wf_def, ob):\n '''\n Checks conditions in this guard.\n '''\n pp = self.permissions\n if pp:\n found = 0\n for p in pp:\n if sm.checkPermission(p, ob):\n found = 1\n break\n if not found:\n return 0\n roles = self.roles\n if roles:\n # Require at least one of the given roles.\n found = 0\n u_roles = sm.getUser().getRolesInContext(ob)\n for role in roles:\n if role in u_roles:\n found = 1\n break\n if not found:\n return 0\n expr = self.expr\n if expr is not None:\n md = exprNamespace(ob, wf_def)\n res = expr(md)\n if not res:\n return 0\n return 1\n\n def getSummary(self):\n # Perhaps ought to be in DTML.\n res = []\n if self.permissions:\n res.append('Requires permission:')\n for idx in range(len(self.permissions)):\n p = self.permissions[idx]\n if idx > 0:\n if idx < len(self.permissions) - 1:\n res.append(';')\n else:\n res.append('or')\n res.append('' + escape(p) + '')\n if self.roles:\n if res:\n res.append(', role:')\n else:\n res.append('Requires role:')\n for idx in range(len(self.roles)):\n r = self.roles[idx]\n if idx > 0:\n if idx < len(self.roles) - 1:\n res.append(';')\n else:\n res.append('or')\n res.append('' + escape(r) + '')\n if self.expr is not None:\n if res:\n res.append(', expr:')\n else:\n res.append('Requires expr:')\n res.append('' + escape(self.expr.text) + '')\n return join(res, ' ')\n\n def changeFromProperties(self, props):\n '''\n Returns 1 if changes were specified.\n '''\n if props is None:\n return 0\n res = 0\n s = props.get('guard_permissions', None)\n if s:\n res = 1\n p = map(strip, split(s, ';'))\n self.permissions = tuple(p)\n s = props.get('guard_roles', None)\n if s:\n res = 1\n r = map(strip, split(s, ';'))\n self.roles = tuple(r)\n s = props.get('guard_expr', None)\n if s:\n res = 1\n self.expr = Expression(s)\n return res\n\n def getPermissionsText(self):\n if not self.permissions:\n return ''\n return join(self.permissions, '; ')\n\n def getRolesText(self):\n if not self.roles:\n return ''\n return join(self.roles, '; ')\n\n def getExprText(self):\n if not self.expr:\n return ''\n return str(self.expr.text)\n\nGlobals.InitializeClass(Guard)\n","sub_path":"CMF/tags/CMF-1_1-release/DCWorkflow/Guard.py","file_name":"Guard.py","file_ext":"py","file_size_in_byte":7554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"2886202","text":"from POO.pessoa import Pessoa\n\n\nclass PessoaJuridica(Pessoa):\n\n def __init__(self, razao_social, cnpf):\n self._razao_social = razao_social\n self._cnpj = cnpf\n'''\n def validar_cnpj(cnpf=None):\n is cnpf is not None:\n return True\n\n return False\n'''","sub_path":"PythonSecao1/POO/pessoa_juridica.py","file_name":"pessoa_juridica.py","file_ext":"py","file_size_in_byte":290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"40323692","text":"# -*- coding: utf-8 -*-\n\ndef create_map(rows):\n maze = []\n for row in rows:\n row = row[:-1]\n subarr = []\n for i in row:\n subarr.append(i)\n maze.append(subarr)\n return maze\n\ndef print_map(chart):\n for subarr in chart:\n print (subarr)\n\ndef find_start(chart):\n for y in range(len(chart)):\n row = chart[y]\n for x in range(len(row)):\n if row[x] == 'S':\n return (y, x)\n\ndef make_step(y, x, chart):\n if chart[y][x] == ' ':\n chart[y][x] = '0'\n\ndef find_exit(y, x, chart):\n h = len(chart)\n w = len(chart[0])\n #left\n if x-1 == 0 and chart[y][x-1] == ' ':\n chart[y][x-1] = 'E'\n return chart[y][x-1]\n elif x-1 > 0 and chart[y][x-1] == ' ':\n chart[y][x-1] = '0'\n find_exit(y, x-1, chart)\n #up\n if y-1 == 0 and chart[y-1][x] == ' ':\n chart[y-1][x] = 'E'\n return chart[y-1][x]\n elif y-1 > 0 and chart[y-1][x] == ' ':\n chart[y-1][x] = '0'\n find_exit(y-1, x, chart)\n #right\n if x+1 == w-1 and chart[y][x+1] == ' ':\n chart[y][x+1] = 'E'\n return chart[y][x+1]\n elif x+1 < w - 1 and chart[y][x+1] == ' ':\n chart[y][x+1] = '0'\n find_exit(y, x+1, chart)\n #down\n if y+1 == h-1 and chart[y+1][x] == ' ':\n chart[y+1][x] = 'E'\n return chart[y+1][x]\n elif y+1 < h - 1 and chart[y+1][x] == ' ':\n chart[y+1][x] = '0'\n find_exit(y+1, x, chart)\n\ndef check_exit(chart):\n for u in chart[0]:\n if u == 'E':\n return True\n for d in chart[-1]:\n if d == 'E':\n return True\n for l in chart:\n if l[0] == 'E':\n return True\n for r in chart:\n if r[-1] == 'E':\n return True\n return False\n\nif __name__ == '__main__':\n file = open('../00_text_files/01_labyrinth.txt', 'rt')\n labyrinth = file.readlines()\n file.close()\n maze = create_map(labyrinth)\n start = find_start(maze)\n maze[start[0]][start[1]] = '0'\n find_exit(start[0], start[1], maze)\n print_map(maze)\n print (check_exit(maze))\n","sub_path":"experiments/14_labyrinth_recursion/labyrinth_recursion.py","file_name":"labyrinth_recursion.py","file_ext":"py","file_size_in_byte":2117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"429102024","text":"from zope.interface import implements\n\nfrom feat.common import fiber, defer\n\nfrom feat.interface.observer import *\nfrom feat.interface.serialization import *\n\n\nclass Observer(object):\n '''\n I observe the fiber returned by a callable and remember its result.\n I also expose methods to wait for the fiber to finish, and get its state.\n '''\n implements(IObserver, ISerializable)\n\n def __init__(self, _method, *args, **kwargs):\n\n if not callable(_method):\n raise TypeError(\n \"1st argument of __init__ should be a callable, got %r\" %\n (type(_method), ))\n\n self._method = _method\n self._args = args\n self._kwargs = kwargs\n\n self._result = None\n self._finished = False\n self._failed = False\n\n self._notifier = defer.Notifier()\n\n def initiate(self):\n d = fiber.maybe_fiber(self._method, *self._args, **self._kwargs)\n d.addCallbacks(self._finished_cb, self._failed_cb)\n\n # Unreference everything we don't need anymore\n self._method = None\n self._args = None\n self._kwargs = None\n\n return d\n\n ### IObserver ###\n\n def notify_finish(self):\n if self._failed:\n return fiber.fail(self._result)\n elif self._finished:\n return fiber.succeed(self._result)\n else:\n return fiber.wrap_defer(self._notifier.wait, 'finished')\n\n def active(self):\n return not self._failed and not self._finished\n\n def get_result(self):\n if self.active():\n raise RuntimeError(\n 'Observer.get_result() called on observer which is not done '\n 'yet. Before using this method you should ensure that this '\n 'job is done, by calling .active()')\n return self._result\n\n ### ISerializable ###\n\n type_name = 'fiber-observer'\n\n def snapshot(self):\n return None\n\n def recover(self, snapshot):\n pass\n\n def restored(self):\n pass\n\n ### IRestorator ###\n\n @classmethod\n def prepare(cls):\n return cls.__new__(cls)\n\n ### private ###\n\n def _finished_cb(self, result):\n self._finished = True\n self._result = result\n self._notifier.callback('finished', result)\n return result\n\n def _failed_cb(self, fail):\n self._failed = True\n self._result = fail\n self._notifier.errback('finished', fail)\n fail.raiseException()\n\n def __eq__(self, other):\n return type(self) == type(other) or NotImplemented\n\n def __ne__(self, other):\n if type(self) != type(other):\n return NotImplemented\n else:\n return False\n","sub_path":"src/feat/common/observer.py","file_name":"observer.py","file_ext":"py","file_size_in_byte":2706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"3727026","text":"# -*- coding: utf-8 -*-\n\nfrom importlib import import_module\n\nfrom django.conf.urls import url\nfrom django.contrib import admin\nfrom django.contrib.admin.views.decorators import staff_member_required\nfrom django.core.exceptions import ImproperlyConfigured\nfrom django.utils.decorators import method_decorator\nfrom django.views.generic.base import TemplateView\n\nfrom . import app_settings\n\n\nclass ControlCenter(object):\n def get_urls(self):\n self.dashboards = []\n for index, path in enumerate(app_settings.DASHBOARDS):\n pkg, name = path.rsplit('.', 1)\n klass = getattr(import_module(pkg), name)\n instance = klass(index)\n self.dashboards.append(instance)\n\n if not self.dashboards:\n raise ImproperlyConfigured('No dashboard found in '\n 'settings.CONTROLCENTER_DASHBOARDS.')\n # Limits number to 10\n length = min([len(self.dashboards) - 1, 9])\n values = length and '[0-{}]'.format(length)\n urlpatterns = [\n url(r'^(?P{})/$'.format(values), dashboard_view,\n name='dashboard'),\n ]\n return urlpatterns\n\n @property\n def urls(self):\n # include(arg, namespace=None, app_name=None)\n return self.get_urls(), 'controlcenter', 'controlcenter'\n\ncontrolcenter = ControlCenter()\n\n\nclass DashboardBaseView(TemplateView):\n template_name = 'controlcenter/dashboard.html'\n\n @method_decorator(staff_member_required)\n def dispatch(self, *args, **kwargs):\n return super(DashboardBaseView, self).dispatch(*args, **kwargs)\n\n def get_dashboard(self):\n pk = int(self.kwargs.get('pk'))\n return controlcenter.dashboards[pk]\n\n def get(self, request, *args, **kwargs):\n self.dashboard = self.get_dashboard()\n return super(DashboardBaseView, self).get(request, *args, **kwargs)\n\n def get_context_data(self, **kwargs):\n context = {\n 'title': self.dashboard.title,\n 'dashboard': self.dashboard,\n 'groups': self.dashboard.get_widgets(self.request),\n 'sharp': app_settings.SHARP,\n }\n\n # Admin context\n kwargs.update(admin.site.each_context(self.request))\n kwargs.update(context)\n return super(DashboardBaseView, self).get_context_data(**kwargs)\n\n\nclass DashboardView(DashboardBaseView):\n\n def get_context_data(self, **kwargs):\n context = super(DashboardView, self).get_context_data(**kwargs)\n # add dashboards from settings.CONTROLCENTER_DASHBOARDS to create navigation\n context['dashboards'] = controlcenter.dashboards\n\n return context\n\ndashboard_view = DashboardView.as_view()\n","sub_path":"controlcenter/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"279562139","text":"import os\nimport database\nimport urllib\nimport json_parser\nimport time\nimport logger\nimport requests\nimport zipfile\nimport datetime\nimport sys\nimport visitors\n\nlog = logger.Logger(\"CPSuperstore/logs/24_hr_task.log\")\n\ntry:\n fail = False\n start = time.time()\n\n\n SUPPORT_EMAIL = \"cpsuperstoreinc@gmail.com\"\n BACKUP_SERVER = \"backupserver.pythonanywhere.com\"\n\n log.log(\"Running Initializations\")\n\n path_head = \"/CPSuperstore/\"\n\n\n database_backup_attempts = 5\n\n try:\n CODES = json_parser.parse_json(\"CPSuperstore/security/codes.json\")\n except IOError:\n CODES = json_parser.parse_json(\"security/codes.json\")\n path_head = \"\"\n\n CODES = {\n \"computer\": 2935,\n \"24_hr\": 525462,\n \"code\": 12552456466418112456474,\n \"backup\": 145678131417\n }\n\n if fail is True:\n print(1 / 0)\n\n log.log(\"Ran Initializations Successfully\")\n log.log(\"Clearing All Downloaded Projects\")\n\n database.delete_downloaded_projects(mode=1)\n\n log.log(\"Checked Database For Incomplete Records\")\n log.log(\"Clearing Email Tmp Directory\")\n\n try:\n for item in os.listdir(os.getcwd() + \"/CPSuperstore/tmp\"):\n os.remove(os.getcwd() + \"/CPSuperstore/tmp/\" + item)\n except OSError:\n for item in os.listdir(os.getcwd() + \"/tmp\"):\n try:\n os.remove(os.getcwd() + \"/tmp/\" + item)\n except OSError:\n pass\n\n log.log(\"Cleared Email Tmp Directory\")\n\n log.log(\"Changing Encryption Challenge Message\")\n urllib.urlopen(\"http://cpsuperstore.pythonanywhere.com/bot/new_message/\" + str(CODES[\"code\"]))\n log.log(\"Changed Encryption Challenge Message\")\n\n log.log(\"Cleaning Up Databases\")\n visitors.delete_old_records()\n log.log(\"Cleaned Up Databases\")\n\n log.log(\"Backing Up Databases\")\n log.log(\"Compressing Databases For Backup\")\n\n try:\n path = \"/CPSuperstore/databases/\"\n file_list = os.listdir(os.getcwd() + \"/CPSuperstore/databases\")\n except OSError:\n path = \"/databases/\"\n file_list = os.listdir(os.getcwd() + \"/databases\")\n\n with zipfile.ZipFile('backup.zip', 'w') as myzip:\n for db in file_list:\n if db.endswith(\".db\"):\n myzip.write(os.getcwd() + path + db, db)\n myzip.close()\n\n backup = open('backup.zip', 'rb')\n\n log.log(\"Compressed Databases For Backup\")\n log.log(\"Sending Databases To Backup Server\")\n\n timestamp = datetime.datetime.fromtimestamp(time.time()).strftime('%Y_%m_%d_%H_%M_%S')\n\n data = {\"backup_type\": \"CPSuperstore\"}\n\n for i in range(database_backup_attempts):\n files = {'backup_file': (\"backup_{}.zip\".format(timestamp), backup)}\n\n r = requests.post(\"http://\" + BACKUP_SERVER + \"/send_backup/{}\".format(CODES[\"backup\"]), data=data, files=files)\n\n code = r.status_code\n text = r.text\n\n if code == 200:\n if text == \"True\":\n log.log(\"Databases Were Sucsessfuly Backed Up\")\n break\n else:\n log.log(\"The Request Was Sent Successfully, But The Server Refused The File (Check That The Code Is Correct)\", status=\"WARN\")\n break\n else:\n if i == database_backup_attempts - 1:\n log.log(\"The Request Failed With A Code: {} - {} ({} Attempts Have Been Exceeded)\".format(r.status_code, r.reason, i + 1, database_backup_attempts), status=\"ERROR\")\n else:\n log.log(\"The Request Failed With A Code: {} - {} (Attempt {} Of {})\".format(r.status_code, r.reason, i + 1, database_backup_attempts), status=\"WARN\")\n\n backup.close()\n os.remove(os.getcwd() + \"/backup.zip\")\n\n log.log(\"Task Completed In {} Seconds\".format(round(time.time() - start, 2)))\n\nexcept Exception as ex:\n exc_type, exc_value, exc_traceback = sys.exc_info()\n details = {\n 'filename': exc_traceback.tb_frame.f_code.co_filename,\n 'line': exc_traceback.tb_lineno,\n 'name': exc_traceback.tb_frame.f_code.co_name,\n 'type': exc_type.__name__,\n 'message': exc_value.message\n }\n log.log(\"Exception {} Has Occurred At Line {}. Caused By {}\".format(details['type'], details['line'], details['message']), status=\"FATAL\")\n","sub_path":"24_Hour_task.py","file_name":"24_Hour_task.py","file_ext":"py","file_size_in_byte":4256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"486894919","text":"from utils import *\n\nGET_MP3_URL = re.compile(r'.*(\\.mp3)')\n\ndef get_content_url(episode):\n global urls\n del driver.requests\n driver.get(PODME_URL+\"?episode=\"+episode)\n for request in driver.requests:\n if request.response:\n request_path = request.path\n if GET_MP3_URL.match(str(request_path)):\n print('url found:', request_path)\n urls.append(request_path)\n del driver.requests\n break\n\n\nurls = []\ndriver = establish_connection()\nget_content_url('221266')\nget_content_url('221592')\ndriver.close()\n\n\nprint(urls)","sub_path":"download_pods.py","file_name":"download_pods.py","file_ext":"py","file_size_in_byte":609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"1545143","text":"def twoNumberSum(array, targetSum):\n\tlst = []\n\tfor i in range(len(array)-1):\n\t\tfirstNum = array[i]\n\t\tfor j in range(i+1,len(array)):\n\t\t\tsecondNum = array[j]\n\t\t\tif firstNum + secondNum == targetSum:\n\t\t\t\treturn [firstNum, secondNum]\n\treturn []\n#TC: O(N^2)\n#SC: O(1)\n","sub_path":"AE/two_sum_num_BF.py","file_name":"two_sum_num_BF.py","file_ext":"py","file_size_in_byte":264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"144849178","text":"import output\nimport os\nimport datetime\nimport sqlite3\nimport json\n\n# add logging support\nimport logging\nmod_log = logging.getLogger('airpi.database')\n\nclass Database(output.Output):\n requiredData = [\"dbPath\"]\n optionalData = []\n dbName = None\n\n def __init__(self, data):\n self.log = logging.getLogger('airpi.database')\n self.dbName = os.path.join(data[\"dbPath\"], 'airpi.db')\n\n try:\n conn = sqlite3.connect(self.dbName)\n # create table\n conn.execute(\"CREATE TABLE airpi (timestamp, sensor_data, gps_data)\")\n # save changes\n conn.commit()\n # close the connection\n conn.close()\n except sqlite3.OperationalError as oe:\n if \"already exists\" in oe.message:\n pass\n else:\n self.log.error(\"Database OperationalError Exception: {0} - {1}\".format(oe, self.dbName))\n raise\n except Exception as e:\n self.log.error(\"Database create Exception: {0} - {1}\".format(e, self.dbName))\n raise\n\n def outputData(self, dataPoints):\n arr = []\n sData = lData = None\n\n for i in dataPoints:\n # handle GPS data\n if i[\"type\"] == \"Location\":\n lData = json.dumps(i)\n else:\n arr.append(i)\n\n sData = json.dumps(arr)\n self.log.debug(\"Database input: [{0},{1}]\".format(sData, lData))\n\n try:\n conn = sqlite3.connect(self.dbName)\n # add row to table\n conn.execute(\"insert into airpi values (?, ?, ?)\", (str(datetime.datetime.now()), sData, lData))\n # save changes\n conn.commit()\n # close the connection\n conn.close()\n except Exception as e:\n self.log.error(\"Database insert Exception: {0}\".format(e))\n raise\n else:\n return True\n","sub_path":"outputs/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":1936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"513904742","text":"# -*- coding: utf-8 -*-\nfrom __future__ import print_function\nfrom datetime import datetime\nfrom libs import func\nfrom libs import a\nimport requests\nimport random\nimport json\nimport a\n\n# --------------- Helpers that build all of the responses ----------------------\n\ndef build_speechlet_response(title, output, reprompt_text, should_end_session):\n return {\n 'outputSpeech': {\n 'type': 'PlainText',\n 'text': output\n },\n 'card': {\n 'type': 'Simple',\n 'title': \"SessionSpeechlet - \" + title,\n 'content': \"SessionSpeechlet - \" + output\n },\n 'reprompt': {\n 'outputSpeech': {\n 'type': 'PlainText',\n 'text': reprompt_text\n }\n },\n 'shouldEndSession': should_end_session\n }\n\n\ndef build_response(session_attributes, speechlet_response):\n return {\n 'version': '1.0',\n 'sessionAttributes': session_attributes,\n 'response': speechlet_response\n }\n\n\n# ---------------Original Func-------------------------------------------------\n\n\ndef start_search(intent, session):\n session_attributes = {}\n reprompt_text = None\n\n should_end_session = False\n\n # Alexaから勤務地 c_station を取得する\n if 'value' in intent['slots']['station']:\n c_station = intent['slots']['station']['value']\n else:\n # 喋らせたい文を作成\n speech_output = \"検索条件を指定してもう一度話しかけてください\"\n return build_response(session_attributes, build_speechlet_response(\n title=\"検索条件を指定してください\", output=speech_output, reprompt_text=reprompt_text,\n should_end_session=should_end_session))\n\n # Alexaから値段 cost を取得する\n if 'value' in intent['slots']['cost']:\n cost = intent['slots']['cost']['value']\n search_key = \"価格、\" + cost\n\n else:\n # 喋らせたい文を作成\n speech_output = \"検索条件を指定してもう一度話しかけてください\"\n return build_response(session_attributes, build_speechlet_response(\n title=\"検索条件を指定してください\", output=speech_output, reprompt_text=reprompt_text,\n should_end_session=should_end_session))\n\n # 価格以下の物件をjsonに保存\n rjson = a.scrape_cost(cost)\n num = len(rjson[\"estate\"]);\n\n # 検索結果が見つからなかった\n if num == 0:\n # 喋らせたい文を作成\n speech_output = search_key + \"の条件に当てはまる物件は見つかりませんでした。\"\n return build_response(session_attributes, build_speechlet_response(\n title=\"検索結果が見つかりませんでした\", output=speech_output, reprompt_text=reprompt_text,\n should_end_session=should_end_session))\n\n\n # 喋らせたい文を作成\n speech_output = search_key + \"の条件で検索をしました。条件にあった物件は\" + str(len(rjson[\"estate\"])) + \"件見つかりました。\" \\\n \"検索結果の上位\" + str(min(2, len(rjson[\"estate\"]))) + \"件を読み上げますか?\"\n\n session_attributes = rjson\n session_attributes[\"c_station\"] = c_station\n session_attributes[\"search_key\"] = search_key\n return build_response(session_attributes, build_speechlet_response(\"検索結果\", speech_output, reprompt_text, should_end_session))\n\n\ndef start_speech(intent, session):\n reprompt_text = None\n should_end_session = False\n\n session_attributes = session.get(\"attributes\", {})\n\n # session_attributes 受け渡し\n estate = session_attributes.get('estate', {})\n c_station = session_attributes.get('c_station', {})\n search_key = session_attributes.get('search_key', {})\n\n if not estate or not c_station or not search_key:\n pass\n else:\n f = open(\"station_data.json\", \"r\")\n station_list = json.load(f)\n f.close()\n\n kinmuchi = station_list[c_station]\n\n for i in estate:\n if i[\"station\"] in station_list:\n ns = station_list[i[\"station\"]]\n i[\"distance\"] = func.calcDistance(float(kinmuchi[\"lat\"]), float(kinmuchi[\"lon\"]), float(ns[\"lat\"]), float(ns[\"lon\"]))\n i[\"ride_time\"] = round(i[\"distance\"])\n else:\n i[\"distance\"] = 99999999\n i[\"ride_time\"] = round(i[\"distance\"])\n\n estate = sorted(estate, key=lambda x: x[\"distance\"])\n\n # 喋らせたい文を作成\n #speech_output = search_key + \"の条件で検索をしました。条件にあった物件は\" + str(len(estate)) + \"件見つかりました。\" \\\n #\"検索結果の上位\" + str(min(2, len(estate))) + \"件を読み上げます。\"\n\n speech_output = \"わかりました。読み上げます。\"\n\n for i in range(min(2, len(estate))):\n speech_output += estate[i][\"locate\"] + \"の物件がお勧めです。\" \\\n + \"家賃は\" + estate[i][\"cost\"] + \"円で、\" \\\n + \"最寄り駅は\" + estate[i][\"station\"] + \"です。\" \\\n + \"駅までの時間は徒歩\" + estate[i][\"walking_time\"] + \"分です。\"\n\n return build_response({}, build_speechlet_response(\"検索結果\", speech_output, reprompt_text, should_end_session))\n\ndef push_line(intent, session):\n reprompt_text = None\n should_end_session = False\n\n session_attributes = session.get(\"attributes\", {})\n\n # session_attributes 受け渡し\n estate = session_attributes.get('estate', {})\n c_station = session_attributes.get('c_station', {})\n search_key = session_attributes.get('search_key', {})\n\n if not estate or not c_station or not search_key:\n pass\n else:\n f = open(\"station_data.json\", \"r\")\n station_list = json.load(f)\n f.close()\n\n kinmuchi = station_list[c_station]\n\n for i in estate:\n if i[\"station\"] in station_list:\n ns = station_list[i[\"station\"]]\n i[\"distance\"] = func.calcDistance(float(kinmuchi[\"lat\"]), float(kinmuchi[\"lon\"]), float(ns[\"lat\"]), float(ns[\"lon\"]))\n i[\"ride_time\"] = round(i[\"distance\"])\n else:\n i[\"distance\"] = 99999999\n i[\"ride_time\"] = round(i[\"distance\"])\n\n\n estate = sorted(estate, key=lambda x: x[\"distance\"])\n\n\n speech_output = \"\"\n for i in range(min(5, len(estate))):\n speech_output += estate[i][\"locate\"] + \"の物件がお勧めです。\" \\\n + \"家賃は\" + estate[i][\"cost\"] + \"円で、\" \\\n + \"最寄り駅は\" + estate[i][\"station\"] + \"です。\" \\\n + \"駅までの徒歩時間は\" + estate[i][\"walking_time\"] + \"分です。\"\n\n\n url = \"https://notify-api.line.me/api/notify\"\n token = \"wZaT6o8agvmGV6SAMDb7VJaMgKEALN9ZCHUy2Q5dvnA\"\n headers = {\"Authorization\" : \"Bearer \"+ token}\n\n # Messageをトークへpushする\n message_head = search_key + \"円の条件で検索をしました。検索結果の上位5件をお伝えします!\"\n message_contents = speech_output\n payload_head = {\"message\" : message_head}\n payload_contents = {\"message\" : message_contents}\n r = requests.post(url ,headers = headers ,params=payload_head)\n r = requests.post(url ,headers = headers ,params=payload_contents)\n\n\n speech_output = \"Lineにメッセージを送信しました。\"\n return build_response({}, build_speechlet_response(\"検索結果\", speech_output, reprompt_text, should_end_session))\n\n# --------------- Functions that control the skill's behavior ------------------\n\ndef get_welcome_response():\n\n session_attributes = {}\n card_title = \"検索するよ\"\n speech_output = \"こんにちは。物件検索スキルです。勤務地は東京駅で家賃は五万円くらいの物件を探して。という風に勤務地と一つ条件を指定して話しかけてください。追加で指定できる条件は、家賃の目安、間取りから指定できます。\"\n\n # If the user either does not reply to the welcome message or says something\n # that is not understood, they will be prompted again with this text.\n reprompt_text = \"please prompt\"\n should_end_session = False\n return build_response(session_attributes, build_speechlet_response(\n card_title, speech_output, reprompt_text, should_end_session))\n\n\ndef handle_session_end_request():\n card_title = \"終了\"\n r = requests.get(\"http://weather.livedoor.com/forecast/webservice/json/v1?city=130010\")\n rjson = r.json()\n\n speech_output = \"検索を終了します。\" \\\n + [\"forecasts\"][1][\"dateLabel\"] + \"の天気は\" + rjson[\"forecasts\"][1][\"telop\"] + \"だよ。\" \\\n + \"また使ってね。\"\n # Setting this to true ends the session and exits the skill.\n should_end_session = True\n return build_response({}, build_speechlet_response(\n card_title, speech_output, None, should_end_session))\n\n\n# --------------- Events ------------------\n\ndef on_session_started(session_started_request, session):\n\n print(\"on_session_started requestId=\" + session_started_request['requestId']\n + \", sessionId=\" + session['sessionId'])\n\n\ndef on_launch(launch_request, session):\n\n print(\"on_launch requestId=\" + launch_request['requestId'] +\n \", sessionId=\" + session['sessionId'])\n # 起動時に分岐させたい場合は、ここに条件文をかく\n # 今回は固定で返却\n return get_welcome_response()\n\n\ndef on_intent(intent_request, session):\n\n print(\"on_intent requestId=\" + intent_request['requestId'] +\n \", sessionId=\" + session['sessionId'])\n\n intent = intent_request['intent']\n intent_name = intent_request['intent']['name']\n\n # 物件を検索するインテント\n if intent_name == \"EstateSearchIntent\":\n return start_search(intent, session)\n # start_searchで検索した結果をAlexaが発話するインテント\n elif intent_name == \"AMAZON.YesIntent\":\n return start_speech(intent, session)\n # start_searchで検索した結果をLineNotifyにPushするインテント\n elif intent_name == \"AMAZON.NoIntent\":\n return push_line(intent, session)\n # 終了インテント(Amazon default)\n elif intent_name == \"AMAZON.CancelIntent\" or intent_name == \"AMAZON.StopIntent\":\n return handle_session_end_request()\n # 一致しない場合は例外を投げる\n else:\n raise ValueError(\"Invalid intent\")\n\n\ndef on_session_ended(session_ended_request, session):\n\n print(\"on_session_ended requestId=\" + session_ended_request['requestId'] +\n \", sessionId=\" + session['sessionId'])\n\n\n#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -#\ndef lambda_handler(event, context):\n\n print(\"event.session.application.applicationId=\" +\n event['session']['application']['applicationId'])\n\n\n # セッションを開始する場所\n if event['session']['new']:\n on_session_started({'requestId': event['request']['requestId']},\n event['session'])\n # 最初の条件分岐\n # 1. 起動リクエスト\n if event['request']['type'] == \"LaunchRequest\":\n return on_launch(event['request'], event['session'])\n # 2. インテントリクエスト(Developerで作成したやつ)\n elif event['request']['type'] == \"IntentRequest\":\n return on_intent(event['request'], event['session'])\n # 3. 終了リクエスト\n elif event['request']['type'] == \"SessionEndedRequest\":\n return on_session_ended(event['request'], event['session'])\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":11537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"39013928","text":"from google.appengine.ext import db\nfrom handlers.handler import Handler\nfrom utilities import Utils\n\n\nclass PostDetailsHandler(Handler):\n \"\"\"\n This class represents request handler for the main post page.\n It checks whether the specified post's id is valid or not.\n If it's valid it renders its content\n (subject, content, owner, likes, comments).\n It can handle two post requests (comment and like).\n \"\"\"\n def get(self, post_id):\n key = db.Key.from_path('Post', int(post_id), parent=Utils.blog_key())\n post = db.get(key)\n\n # Check if the post id is valid\n if not post:\n self.error(404)\n return\n\n self.render(\"post-details.html\", post=post,\n user=self.user, comments=post.comment_post)\n","sub_path":"p3-daily-blog/handlers/postdetails.py","file_name":"postdetails.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"200588706","text":"from unittest.mock import Mock\nfrom model_bakery import baker\nfrom datetime import timedelta, date\n\nfrom django.conf import settings\nfrom django.test import TestCase\nfrom django.utils import timezone\n\nfrom sponsors import use_cases\nfrom sponsors.notifications import *\nfrom sponsors.models import Sponsorship, Contract\n\n\nclass CreateSponsorshipApplicationUseCaseTests(TestCase):\n def setUp(self):\n self.notifications = [Mock(), Mock()]\n self.use_case = use_cases.CreateSponsorshipApplicationUseCase(\n self.notifications\n )\n self.user = baker.make(settings.AUTH_USER_MODEL)\n self.sponsor = baker.make(\"sponsors.Sponsor\")\n self.benefits = baker.make(\"sponsors.SponsorshipBenefit\", _quantity=5)\n self.package = baker.make(\"sponsors.SponsorshipPackage\")\n\n def test_create_new_sponsorship_using_benefits_and_package(self):\n sponsorship = self.use_case.execute(\n self.user, self.sponsor, self.benefits, self.package\n )\n\n self.assertTrue(sponsorship.pk)\n self.assertEqual(len(self.benefits), sponsorship.benefits.count())\n self.assertTrue(sponsorship.level_name)\n\n def test_send_notifications_using_sponsorship(self):\n sponsorship = self.use_case.execute(\n self.user, self.sponsor, self.benefits, self.package\n )\n\n for n in self.notifications:\n n.notify.assert_called_once_with(request=None, sponsorship=sponsorship)\n\n def test_build_use_case_with_correct_notifications(self):\n uc = use_cases.CreateSponsorshipApplicationUseCase.build()\n\n self.assertEqual(len(uc.notifications), 2)\n self.assertIsInstance(uc.notifications[0], AppliedSponsorshipNotificationToPSF)\n self.assertIsInstance(\n uc.notifications[1], AppliedSponsorshipNotificationToSponsors\n )\n\n\nclass RejectSponsorshipApplicationUseCaseTests(TestCase):\n def setUp(self):\n self.notifications = [Mock(), Mock()]\n self.use_case = use_cases.RejectSponsorshipApplicationUseCase(\n self.notifications\n )\n self.user = baker.make(settings.AUTH_USER_MODEL)\n self.sponsorship = baker.make(Sponsorship)\n\n def test_update_sponsorship_as_rejected(self):\n self.use_case.execute(self.sponsorship)\n self.sponsorship.refresh_from_db()\n\n today = timezone.now().date()\n self.assertEqual(self.sponsorship.rejected_on, today)\n self.assertEqual(self.sponsorship.status, Sponsorship.REJECTED)\n\n def test_send_notifications_using_sponsorship(self):\n self.use_case.execute(self.sponsorship)\n\n for n in self.notifications:\n n.notify.assert_called_once_with(request=None, sponsorship=self.sponsorship)\n\n def test_build_use_case_with_correct_notifications(self):\n uc = use_cases.RejectSponsorshipApplicationUseCase.build()\n\n self.assertEqual(len(uc.notifications), 2)\n self.assertIsInstance(uc.notifications[0], RejectedSponsorshipNotificationToPSF)\n self.assertIsInstance(\n uc.notifications[1], RejectedSponsorshipNotificationToSponsors\n )\n\n\nclass ApproveSponsorshipApplicationUseCaseTests(TestCase):\n def setUp(self):\n self.notifications = [Mock(), Mock()]\n self.use_case = use_cases.ApproveSponsorshipApplicationUseCase(\n self.notifications\n )\n self.user = baker.make(settings.AUTH_USER_MODEL)\n self.sponsorship = baker.make(Sponsorship, _fill_optional=\"sponsor\")\n\n today = date.today()\n self.data = {\n \"sponsorship_fee\": 100,\n \"level_name\": \"level\",\n \"start_date\": today,\n \"end_date\": today + timedelta(days=10),\n }\n\n def test_update_sponsorship_as_approved_and_create_contract(self):\n self.use_case.execute(self.sponsorship, **self.data)\n self.sponsorship.refresh_from_db()\n\n today = timezone.now().date()\n self.assertEqual(self.sponsorship.approved_on, today)\n self.assertEqual(self.sponsorship.status, Sponsorship.APPROVED)\n self.assertTrue(self.sponsorship.contract.pk)\n self.assertTrue(self.sponsorship.start_date)\n self.assertTrue(self.sponsorship.end_date)\n self.assertEqual(self.sponsorship.sponsorship_fee, 100)\n self.assertEqual(self.sponsorship.level_name, \"level\")\n\n def test_send_notifications_using_sponsorship(self):\n self.use_case.execute(self.sponsorship, **self.data)\n\n for n in self.notifications:\n n.notify.assert_called_once_with(\n request=None,\n sponsorship=self.sponsorship,\n contract=self.sponsorship.contract,\n )\n\n def test_build_use_case_without_notificationss(self):\n uc = use_cases.ApproveSponsorshipApplicationUseCase.build()\n self.assertEqual(len(uc.notifications), 1)\n self.assertIsInstance(uc.notifications[0], SponsorshipApprovalLogger)\n\n\nclass SendContractUseCaseTests(TestCase):\n def setUp(self):\n self.notifications = [Mock(), Mock()]\n self.use_case = use_cases.SendContractUseCase(self.notifications)\n self.user = baker.make(settings.AUTH_USER_MODEL)\n self.contract = baker.make_recipe(\"sponsors.tests.empty_contract\")\n\n def test_send_and_update_contract_with_document(self):\n self.use_case.execute(self.contract)\n self.contract.refresh_from_db()\n\n self.assertTrue(self.contract.document.name)\n self.assertTrue(self.contract.awaiting_signature)\n for n in self.notifications:\n n.notify.assert_called_once_with(\n request=None,\n contract=self.contract,\n )\n\n def test_build_use_case_without_notificationss(self):\n uc = use_cases.SendContractUseCase.build()\n self.assertEqual(len(uc.notifications), 2)\n self.assertIsInstance(uc.notifications[0], ContractNotificationToPSF)\n self.assertIsInstance(\n uc.notifications[1], SentContractLogger\n )\n\n\nclass ExecuteContractUseCaseTests(TestCase):\n def setUp(self):\n self.notifications = [Mock()]\n self.use_case = use_cases.ExecuteContractUseCase(self.notifications)\n self.user = baker.make(settings.AUTH_USER_MODEL)\n self.contract = baker.make_recipe(\"sponsors.tests.empty_contract\", status=Contract.AWAITING_SIGNATURE)\n\n def test_execute_and_update_database_object(self):\n self.use_case.execute(self.contract)\n self.contract.refresh_from_db()\n self.assertEqual(self.contract.status, Contract.EXECUTED)\n\n def test_build_use_case_without_notificationss(self):\n uc = use_cases.ExecuteContractUseCase.build()\n self.assertEqual(len(uc.notifications), 1)\n self.assertIsInstance(\n uc.notifications[0], ExecutedContractLogger\n )\n\n\nclass NullifyContractUseCaseTests(TestCase):\n def setUp(self):\n self.notifications = [Mock()]\n self.use_case = use_cases.NullifyContractUseCase(self.notifications)\n self.user = baker.make(settings.AUTH_USER_MODEL)\n self.contract = baker.make_recipe(\"sponsors.tests.empty_contract\", status=Contract.AWAITING_SIGNATURE)\n\n def test_nullify_and_update_database_object(self):\n self.use_case.execute(self.contract)\n self.contract.refresh_from_db()\n self.assertEqual(self.contract.status, Contract.NULLIFIED)\n\n def test_build_use_case_without_notificationss(self):\n uc = use_cases.NullifyContractUseCase.build()\n self.assertEqual(len(uc.notifications), 1)\n self.assertIsInstance(\n uc.notifications[0], NullifiedContractLogger\n )\n","sub_path":"sponsors/tests/test_use_cases.py","file_name":"test_use_cases.py","file_ext":"py","file_size_in_byte":7677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"240118759","text":"# -*- coding: utf-8 -*-\nimport scrapy\nimport re\nimport json\nfrom locations.items import GeojsonPointItem\n\n\nclass McDonaldsEGSpider(scrapy.Spider):\n\n name = \"mcdonalds_eg\"\n item_attributes = { 'brand': \"McDonald's\" }\n allowed_domains = [\"www.mcdonalds.eg\"]\n start_urls = (\n 'http://www.mcdonalds.eg/ar/stores/page/228',\n )\n\n def normalize_time(self, time_str, flag=False):\n match = re.search(r'([0-9]{1,2}):([0-9]{1,2})', time_str)\n h, m = match.groups()\n\n return '%02d:%02d' % (\n int(h) + 12 if flag and int(h) < 13 else int(h),\n int(m),\n )\n\n def store_hours(self, response):\n response = '
' + response\n selector = scrapy.Selector(text=response)\n opening_hours = selector.xpath('//*[@id=\"mapInfo\"]/div/span[4]/text()').extract_first()\n if not opening_hours:\n return None\n opening_hours = opening_hours.strip()\n match = re.search(r' ([0-9]{1,2}:[0-9]{1,2}).*([0-9]{1,2}:[0-9]{1,2})', opening_hours)\n if not match:\n return None\n start, end = match.groups()\n start = self.normalize_time(start)\n end = self.normalize_time(end, True)\n\n return 'Mo-Fr {}-{}'.format(start, end)\n\n def parse_data(self, response):\n response = '
' + response\n selector = scrapy.Selector(text=response)\n name = selector.xpath('//h2[@class=\"store-title\"]/b/text()').extract_first().strip()\n address = selector.xpath('//*[@id=\"mapInfo\"]/div/span[1]/text()').extract_first().strip()\n phone = selector.xpath('//span[@class=\"store-tel\"]/text()').extract_first()\n phone = phone.strip() if phone else ''\n return name, address, phone\n\n def parse(self, response):\n match = re.search(r'var locS = (\\[.*\\])\\;', response.body_as_unicode())\n results = json.loads(match.groups()[0])\n index = 0\n for data in results:\n data = data.replace(\"''\", '\"\"')\n try:\n store = json.loads(data)\n except Exception as e:\n continue\n\n name, address, phone = self.parse_data(store[0])\n \n properties = {\n 'ref': index,\n 'addr_full': address,\n 'phone': phone,\n 'name': name,\n 'lat': store[1],\n 'lon': store[2],\n }\n\n opening_hours = self.store_hours(store[0])\n if opening_hours:\n properties['opening_hours'] = opening_hours\n index = index + 1\n yield GeojsonPointItem(**properties)\n\n","sub_path":"locations/spiders/mcdonalds_eg.py","file_name":"mcdonalds_eg.py","file_ext":"py","file_size_in_byte":2712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"629247622","text":"import torch\nimport torchvision.models as models\nimport torch.nn as nn\nfrom torch.autograd import Variable\nimport torch.nn.functional as F\nfrom torch.nn import Parameter\nimport numpy as np\n\n\n\nclass CosLinear(nn.Module):\n def __init__(self, in_features, out_features, m = 0.35):\n super(CosLinear, self).__init__()\n self.in_features = in_features\n self.out_features = out_features\n self.weight = Parameter(torch.Tensor(in_features,out_features) )\n self.weight.data.uniform_(-1, 1).renorm_(2,1,1e-5).mul_(1e5)\n self.m = m\n\n def forward(self, input):\n x = input # size=(B,F) F is feature len\n w = self.weight # size=(F,Classnum) F=in_features Classnum=out_features\n\n ww = w.renorm(2,1,1e-5).mul(1e5)\n xlen = x.pow(2).sum(1).pow(0.5) # size=B\n wlen = ww.pow(2).sum(0).pow(0.5) # size=Classnum\n\n cos_theta = x.mm(ww) # size=(B,Classnum)\n cos_theta = cos_theta / torch.clamp(xlen.view(-1,1) * wlen.view(1,-1), min=1e-8 )\n cos_theta = cos_theta.clamp(-1,1)\n\n # IMPLEMENT phi_theta\n phi_theta = cos_theta - self.m\n \n output = (cos_theta,phi_theta)\n return output\n\n\n\n\nclass SphereLinear(nn.Module):\n def __init__(self, in_features, out_features, m = 4 ):\n super(SphereLinear, self).__init__()\n self.in_features = in_features\n self.out_features = out_features\n self.weight = Parameter(torch.Tensor(in_features,out_features))\n self.weight.data.uniform_(-1, 1).renorm_(2,1,1e-5).mul_(1e5)\n self.m = m\n self.mlambda = [\n lambda x: x**0,\n lambda x: x**1,\n lambda x: 2*x**2-1,\n lambda x: 4*x**3-3*x,\n lambda x: 8*x**4-8*x**2+1,\n lambda x: 16*x**5-20*x**3+5*x\n ]\n\n def forward(self, input):\n x = input # size=(B,F) F is feature len\n w = self.weight # size=(F,Classnum) F=in_features Classnum=out_features\n\n ww = w.renorm(2,1,1e-5).mul(1e5)\n xlen = x.pow(2).sum(1).pow(0.5) # size=B\n wlen = ww.pow(2).sum(0).pow(0.5) # size=Classnum\n\n cos_theta = x.mm(ww) # size=(B,Classnum)\n cos_theta = cos_theta / torch.clamp(xlen.view(-1,1) * wlen.view(1,-1), min=1e-8)\n cos_theta = cos_theta.clamp(-1,1)\n\n # IMPLEMENT phi_theta\n \n theta = Variable(torch.acos(cos_theta.data))\n k = torch.floor(theta/(3.14/self.m))\n cos_mtheta = self.mlambda[self.m](cos_theta)\n \n phi_theta = ((-1)**k)*cos_mtheta - 2*k\n cos_theta = cos_theta * xlen.view(-1,1)\n phi_theta = phi_theta * xlen.view(-1,1)\n\n output = (cos_theta,phi_theta)\n return output\n\n\n\n\nclass GenreNet(torch.nn.Module):\n def __init__(self,embed_type):\n super(GenreNet, self).__init__()\n \n self.net = models.resnet50(pretrained=True)\n \n # turn off gradients\n # for param in self.net.parameters():\n # param.requires_grad = False\n\n # self.new_fc = nn.Sequential(*list(self.net.fc.children())[:-1] + [nn.Linear(2048, 10)])\n # self.net.fc = self.new_fc\n self.new_fc = nn.Sequential(*list(self.net.fc.children())[:-1])\n self.net.fc = self.new_fc\n\n self.embedding_layer = nn.Sequential(*list([torch.nn.Linear(2048,128),\n torch.nn.Linear(128,32)]))\n \n if embed_type == 'sphere':\n self.classifier = SphereLinear(in_features = 32,\n out_features = 10)\n elif embed_type == 'cos':\n self.classifier = CosLinear(in_features = 32,\n out_features = 10)\n else:\n self.classifier = torch.nn.Linear(32,10)\n\n\n def forward(self,x):\n embedding = self.embedding_layer(self.net(x))\n return embedding, self.classifier(embedding)\n\n","sub_path":"network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":3742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"289177752","text":"from django.core.cache import cache\r\n\r\n\r\nclass ZxMiddleware(object):\r\n\r\n def __init__(self, get_response):\r\n self.get_response = get_response\r\n # One-time configuration and initialization.\r\n\r\n def __call__(self, request):\r\n if 'HTTP_X_FORWARDED_FOR' in request.META:\r\n ip = request.META['HTTP_X_FORWARDED_FOR']\r\n else:\r\n ip = request.META['REMOTE_ADDR']\r\n online_ips = cache.get(\"online_ips\", [ip])\r\n response = self.get_response(request)\r\n if ip not in online_ips:\r\n online_ips.append(ip)\r\n cache.set(\"online_ips\", online_ips, 1*60)\r\n return response\r\n","sub_path":"shadowflow/middle.py","file_name":"middle.py","file_ext":"py","file_size_in_byte":655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"305693008","text":"#!/usr/bin/env python3.6\n# -*- coding: utf-8 -*-\n\"\"\"\nWebscrapes websites to get definitions for given abbreviations.\n\n===\n\nMIT License\n\nCopyright (c) 2018 Neko404NotFound\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\nLIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\nOF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\nWITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\"\"\"\nfrom urllib import parse\n\nimport bs4\nimport discord\n\nfrom discomaton import book\nfrom neko2.shared import alg, commands, traits\n\n\ndef gen_url_acronymn_finder(terms):\n terms = parse.quote(terms)\n return (\n 'https://www.acronymfinder.com/~/search/af.aspx?string=exact&Acronym='\n + terms\n )\n\n\nclass AbbrevCog(traits.CogTraits):\n async def fail(self, ctx, query):\n return await ctx.send(f'No results for `{query}`...', delete_after=10)\n\n @commands.command(\n brief='Looks up definitions for the given abbreviations.',\n aliases=['ab'])\n async def abbrev(self, ctx, *, query):\n url = gen_url_acronymn_finder(query)\n\n http = await self.acquire_http()\n\n async with http.get(url) as resp:\n resp.raise_for_status()\n html = await resp.text()\n\n soup = bs4.BeautifulSoup(html)\n\n result_tags = soup.find_all(\n name='td',\n attrs={'class': 'result-list__body__rank'})\n\n if not result_tags:\n return await self.fail(ctx, query)\n\n # Convert to tuples of abbreviation and definition.\n pairs = []\n\n for tag in result_tags:\n abbrev = tag.text\n defn = tag.find_next_sibling(\n name='td',\n attrs={'class': 'result-list__body__meaning'})\n\n definition = defn.text if defn else None\n if definition:\n pairs.append((abbrev, defn))\n\n if not pairs:\n return await self.fail(ctx, query)\n\n embeds = []\n\n def new_embed():\n embeds.append(discord.Embed(title=query,\n description='',\n colour=alg.rand_colour()))\n\n new_embed()\n\n for i, (abbrev, definition) in enumerate(pairs):\n if i and i % 6:\n new_embed()\n\n embeds[-1].description += f'**{abbrev}**\\n\\t{definition}\\n\\n'\n\n booklet = book.EmbedBooklet(pages=embeds, ctx=ctx)\n booklet.start()\n\n\ndef setup(bot):\n bot.add_cog(AbbrevCog())\n","sub_path":"neko2/cogs/abbrev.py","file_name":"abbrev.py","file_ext":"py","file_size_in_byte":3293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"232360992","text":"import datetime\n\nfrom django.contrib.auth import login, authenticate\nfrom django.contrib.auth.forms import AuthenticationForm\nfrom django.core.paginator import Paginator, EmptyPage, InvalidPage\nfrom django.db.models import Q\nfrom django.http import HttpResponseRedirect, HttpResponseNotAllowed, HttpResponse\nfrom django.shortcuts import render, redirect, get_object_or_404\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.views.generic import ListView, DetailView\nfrom requests import Response\nfrom rest_framework import generics, viewsets, permissions\n\nfrom Scribd.decorators import allowed_users, authentificated_user\nfrom Scribd.forms import (\n EbookForm,\n RegisterForm,\n TicketForm,\n ProfileForm,\n UploadFileForm,\n FollowForm,\n ProfileFormProvider,\n Subscription,\n CancelSubscription,\n UpgradeAccountForm,\n UpdatePayment,\n CreateInForum,\n CreateInDiscussion,\n CreateInDiscussionTicket,\n ReviewForm,\n)\nfrom Scribd.models import ViewedEbooks, Review, Discussion, DiscussionTickets\nfrom Scribd.permissions import EditBookPermissions\nfrom Scribd.serializers import *\nfrom .user_models import User, userProfile, providerProfile\n\n##################################\n####### VISTA MAINPAGE ###########\n##################################\n\n\ndef base(request):\n return render(request, \"scribd/base.html\")\n\n\ndef index(request):\n ebooks = Ebook.objects.all().order_by(\"id\")\n paginator = Paginator(ebooks, 3)\n try:\n page = int(request.GET.get(\"page\", \"1\"))\n except:\n page = 1\n try:\n posts = paginator.page(page)\n except (EmptyPage, InvalidPage):\n posts = paginator.page(paginator.num_pages)\n # Get the index of the current page\n index = posts.number - 1 # edited to something easier without index\n # This value is maximum index of your pages, so the last page - 1\n max_index = len(paginator.page_range)\n # You want a range of 7, so lets calculate where to slice the list\n start_index = index - 3 if index >= 3 else 0\n end_index = index + 3 if index <= max_index - 3 else max_index\n # Get our new page range. In the latest versions of Django page_range returns\n # an iterator. Thus pass it to list, to make our slice possible again.\n page_range = list(paginator.page_range)[start_index:end_index]\n promoted = True\n context = {\n \"ebooks\": posts,\n \"promoted\": promoted,\n \"page_range\": page_range,\n \"viewedebooks\": _check_session(request),\n }\n return render(request, \"scribd/mainpage.html\", context)\n\n\ndef _check_session(request):\n if \"viewedebooks\" not in request.session:\n viewedebooks = ViewedEbooks()\n viewedebooks.save()\n request.session[\"viewedebooks\"] = viewedebooks.id_vr\n else:\n viewedebooks = ViewedEbooks.objects.get(\n id_vr=request.session[\"viewedebooks\"])\n return viewedebooks\n\n\nclass ebookMainView(ListView):\n model = Ebook\n template_name = \"scribd/mainpage.html\"\n\n\ndef ebooks(request, search=\"\"):\n # Priorizamos busqueda categoria\n if request.method == \"GET\":\n dictionary = request.GET.dict()\n query = dictionary.get(\"search\")\n print(query)\n if query:\n ebooks = Ebook.objects.filter(\n Q(ebook_number__icontains=query)\n | Q(title__icontains=query)\n | Q(autor__icontains=query)\n | Q(description__icontains=query)\n | Q(is_promot__icontains=query)\n | Q(size__icontains=query)\n | Q(category__icontains=query)\n | Q(media_type__icontains=query)\n | Q(featured_photo__icontains=query)\n | Q(file__icontains=query))\n else:\n ebooks = Ebook.objects.all()\n\n else:\n ebooks = Ebook.objects.all()\n\n context = {\n \"search\": query,\n \"ebooks\": ebooks,\n \"viewedebooks\": _check_session(request),\n }\n\n return render(request, \"scribd/mainpage.html\", context)\n\n\n# TODO\ndef ebook_create_view(request):\n instance2 = providerProfile.objects.get(user=request.user)\n if request.method == \"POST\":\n form = EbookForm(request.POST, request.FILES)\n if form.is_valid():\n ebook = Ebook.objects.create(\n ebook_number=form.cleaned_data.get(\"ebook_number\"),\n title=form.cleaned_data.get(\"title\"),\n autor=form.cleaned_data.get(\"autor\"),\n description=form.cleaned_data.get(\"description\"),\n size=form.cleaned_data.get(\"size\"),\n media_type=form.cleaned_data.get(\"media_type\"),\n featured_photo=form.cleaned_data.get(\"featured_photo\"),\n category=form.cleaned_data.get(\"category\"),\n publisher=instance2,\n file=form.cleaned_data.get(\"file\")\n )\n ebook.save()\n return redirect(\"index\")\n else:\n form = EbookForm()\n books = []\n for book in Ebook.objects.all():\n if book.publisher is not None:\n if str(book.publisher.publisher) == instance2.publisher:\n books.append(book)\n return render(\n request,\n \"scribd/providers_homepage.html\",\n {\n \"book_form\": form,\n \"provider_instance\": instance2,\n \"books\": books\n },\n )\n\n\n##################################\n####### VISTA REVIEW #############\n##################################\n\n##################################\n####### VISTA LOGIN ##############\n##################################\n\n\ndef login_create_view(request,\n backend=\"django.contrib.auth.backends.ModelBackend\"):\n if request.method == \"POST\":\n login_form = AuthenticationForm(None, data=request.POST)\n username = request.POST[\"username\"]\n password = request.POST[\"password\"]\n user = authenticate(request, username=username, password=password)\n\n if user is not None:\n login(request, user, backend)\n request.session[\"login\"] = True\n return redirect(\"index\")\n else:\n request.session[\"login\"] = False\n return redirect(\"index\")\n\n else:\n login_form = AuthenticationForm()\n\n return render(request, \"scribd/mainpage.html\", {\"login_form\": login_form})\n\n\n##################################\n####### VISTA REGISTRO ###########\n##################################\n\n\ndef signup_create_view(request,\n backend=\"django.contrib.auth.backends.ModelBackend\"):\n if request.method == \"POST\":\n signup_form = RegisterForm(request.POST, request.FILES)\n user = None\n if signup_form.is_valid():\n user = User.objects.create_user(\n email=signup_form.cleaned_data.get(\"email\"),\n username=signup_form.cleaned_data.get(\"username\"),\n first_name=signup_form.cleaned_data.get(\"first_name\"),\n last_name=signup_form.cleaned_data.get(\"last_name\"),\n password=signup_form.cleaned_data.get(\"password1\"),\n )\n\n userprofile = userProfile.objects.create(user=user)\n userprofile.subs_type = \"Free trial\"\n userprofile.nbooks_by_subs = 10\n userprofile.save()\n\n login(request, user, backend)\n\n return redirect(\"index\")\n\n else:\n\n context = {\n \"register_form\": signup_form,\n }\n return render(request, \"registration/signup.html\", context)\n\n else:\n signup_form = RegisterForm()\n context = {\n \"register_form\": signup_form,\n }\n return render(request, \"registration/signup.html\", context)\n\n\n@csrf_exempt\ndef update_session(request):\n if not request.is_ajax() or not request.method == \"POST\":\n return HttpResponseNotAllowed([\"POST\"])\n\n request.session[\"login\"] = None\n return HttpResponse(\"ok\")\n\n\n##################################\n####### VISTA PROFILE ###########\n##################################\n\n\ndef edit_profile_page_provider(request):\n if request.method == \"POST\":\n form = ProfileFormProvider(request.POST,\n request.FILES,\n instance=request.user)\n if form.is_valid():\n form.save()\n return redirect(\"index\")\n else:\n form = ProfileFormProvider(instance=request.user)\n context = {\"form\": form}\n return render(request, \"forms/edit_provider_profile.html\", context)\n\n\ndef edit_profile_page(request, username):\n if request.method == \"POST\":\n form = ProfileForm(request.POST,\n request.FILES,\n instance=request.user.user_profile)\n if form.is_valid():\n form.save()\n return redirect(\"userprofilepage\", username=username)\n else:\n form = ProfileForm(instance=request.user.user_profile)\n context = {\"form\": form}\n return render(request, \"forms/edit_user_profile_v2.html\", context)\n\n\nclass user_profile_page(DetailView):\n template_name = \"scribd/user_profile_page.html\"\n model = userProfile\n\n def get_object(self):\n UserName = self.kwargs.get(\"username\")\n return get_object_or_404(User, username=UserName)\n\n def get_context_data(self, **kwargs):\n context = super(user_profile_page, self).get_context_data(**kwargs)\n current_time = datetime.datetime.now()\n user = self.get_object()\n substract = (user.user_profile.nbooks_by_subs -\n user.user_profile.n_books_followed)\n context[\"current_time\"] = current_time\n context[\"substract\"] = substract\n return context\n\n\n@allowed_users(allowed_roles=[\"provider\"])\ndef provider_page(request):\n return render(request, \"scribd/providers_homepage.html\")\n\n\ndef contract_page(request):\n return render(request, \"scribd/contract.html\")\n\n\nclass AccountsViewSet(viewsets.ModelViewSet):\n queryset = User.objects.all().order_by(\"-date_joined\")\n serializer_class = UserSerializer\n\n # permission_classes = permissions.IsAuthenticatedOrReadOnly\n\n def get_queryset(self):\n return User.objects.all().order_by(\"-date_joined\")\n\n\nclass UserList(generics.ListCreateAPIView):\n queryset = User.objects.all().order_by(\"username\")\n serializer_class = UserSerializer\n\n\nclass UserDetail(generics.RetrieveUpdateDestroyAPIView):\n serializer_class = UserSerializer\n queryset = User.objects.all()\n\n def get_object(self):\n UserName = self.kwargs.get(\"username\")\n return get_object_or_404(User, username=UserName)\n\n\n##################################\n####### UPGRADE AND FILES ########\n##################################\n\n\ndef upgrade_account_view(request, username):\n if request.method == \"POST\":\n\n form = UpgradeAccountForm(request.POST,\n instance=request.user.user_profile)\n form_subs = Subscription(request.POST,\n instance=request.user.user_profile)\n user = User.objects.get(username=username)\n prev_state = user.user_profile.subs_type\n if form.is_valid() and form_subs.is_valid():\n form.save()\n form_subs.save()\n user = User.objects.get(username=username)\n\n # If user cancel subscription...\n if user.user_profile.subs_type == \"Free trial\":\n # If has more than 10 books followed we must display the correct value\n if user.user_profile.n_books_followed >= 10:\n user.user_profile.n_books_followed = 10\n user.user_profile.nbooks_by_subs = 10\n\n # if user upgrade to regular but it's the first time then he/she has 50 books to read\n if user.user_profile.subs_type == \"Regular\":\n if user.user_profile.first_upgrade or prev_state == \"Free trial\":\n user.user_profile.first_upgrade = False # html\n user.user_profile.nbooks_by_subs = 50\n # otherwise, we add 20 new books\n else:\n user.user_profile.nbooks_by_subs += 20\n\n # if user upgrade to pro but it's the first time then he/she has 100 books to read\n if user.user_profile.subs_type == \"Pro\":\n if user.user_profile.first_upgrade or prev_state == \"Free trial\":\n user.user_profile.first_upgrade = False # html\n user.user_profile.nbooks_by_subs = 100\n # otherwise, we add 50 new books\n else:\n user.user_profile.nbooks_by_subs += 50\n user.user_profile.expires = datetime.datetime.now(\n ) + datetime.timedelta(weeks=4)\n user.user_profile.save()\n return redirect(\"userprofilepage\", username=username)\n else:\n form = UpgradeAccountForm(instance=request.user.user_profile)\n form_subs = Subscription(instance=request.user.user_profile)\n context = {\n \"form\": form,\n \"current_time\": datetime.datetime.now(),\n \"form_subs\": form_subs,\n }\n\n return render(request, \"forms/upgrade_account.html\", context)\n\n\ndef downgrade_account_view(request, username):\n if request.method == \"POST\":\n user = User.objects.get(username=username)\n if (user.user_profile.subs_type == \"Regular\"\n or user.user_profile.subs_type == \"Pro\"):\n # downgrade to Free trial user\n user.user_profile.subs_type = \"Free trial\"\n user.user_profile.nbooks_by_subs = 10\n # If has more than 10 books followed we must display the correct value\n if user.user_profile.n_books_followed >= 10:\n user.user_profile.n_books_followed = 10\n # If now change the value displayed\n else:\n user.user_profile.n_books_followed = user.user_profile.n_books_followed\n\n user.user_profile.expires = datetime.datetime.now()\n user.user_profile.save()\n return redirect(\"userprofilepage\", username=username)\n else:\n form = CancelSubscription(instance=request.user.user_profile)\n context = {\n \"form\": form,\n }\n return render(request,\n \"forms/cancel_subscription_confirmation_v2.html\",\n context)\n\n\n@authentificated_user\ndef update_payment_details(request, username):\n credit_form = Subscription(request.POST or None, request.FILES)\n if request.method == \"POST\":\n form = UpdatePayment(request.POST, instance=request.user.user_profile)\n if form.is_valid():\n form.save()\n user = User.objects.get(username=username)\n if credit_form.is_valid():\n user.user_profile.card_titular = (\n credit_form.cleaned_data.get(\"card_titular\"), )\n user.user_profile.card_number = (\n credit_form.cleaned_data.get(\"card_number\"), )\n user.user_profile.card_expiration = (\n credit_form.cleaned_data.get(\"card_expiration\"), )\n user.user_profile.card_cvv = credit_form.cleaned_data.get(\n \"card_cvv\")\n\n user.user_profile.save()\n return redirect(\"userprofilepage\", username=username)\n else:\n form = UpgradeAccountForm(instance=request.user.user_profile)\n credit_form = Subscription()\n\n context = {\"form\": form, \"credit_form\": credit_form}\n\n return render(request, \"forms/update_payment.html\", context)\n\n\ndef upload_file(request):\n if request.method == \"POST\":\n form = UploadFileForm(request.POST, request.FILES)\n if form.is_valid():\n instance = form.save(commit=False)\n instance.user = request.user\n instance.user.user_profile.n_uploads += 1\n instance.user.user_profile.save()\n form.save()\n return redirect(\"index\")\n else:\n form = UploadFileForm()\n return render(request, \"forms/upload.html\", {\"upload_file_form\": form})\n\n\ndef follow(request, pk):\n if request.method == \"POST\" and request.user.is_authenticated:\n if \"follow\" in request.POST:\n\n form = FollowForm(request.POST)\n if form.is_valid():\n user = request.user\n\n # always update the value. Controlled in front-end\n\n user.user_profile.n_books_followed += 1\n user.user_profile.save()\n\n instance = Ebook.objects.get(id=pk)\n instance.follower.add(user)\n instance.save()\n next = request.POST.get(\"next\", \"/\")\n return HttpResponseRedirect(next)\n elif \"create_forum\" in request.POST:\n\n forum_form = CreateInForum(request.POST)\n\n if forum_form.is_valid():\n forum = Forum.objects.create(\n ebook=Ebook.objects.get(id=pk),\n user=request.user,\n email=request.user.email,\n topic=forum_form.cleaned_data.get(\"topic\"),\n description=forum_form.cleaned_data.get(\"description\"),\n link=forum_form.cleaned_data.get(\"link\"),\n )\n forum.save()\n next = request.POST.get(\"next\", \"/\")\n return HttpResponseRedirect(next)\n\n elif \"review\" in request.POST:\n\n review_form = ReviewForm(request.POST)\n\n if review_form.is_valid():\n review = Review.objects.create(\n ebook=Ebook.objects.get(id=pk),\n comment=review_form.cleaned_data.get(\"comment\"),\n value_stars=review_form.cleaned_data.get(\"value_stars\"),\n user=request.user,\n )\n review.save()\n\n next = request.POST.get(\"next\", \"/\")\n return HttpResponseRedirect(next)\n else:\n\n next = request.POST.get(\"next\", \"/\")\n return HttpResponseRedirect(next)\n\n else:\n discussion_form = CreateInDiscussion()\n review_form = ReviewForm\n forum_form = CreateInForum()\n form = FollowForm()\n ebook = Ebook.objects.get(id=pk)\n forums = ebook.forum_set.all()\n count = forums.count()\n discussions = []\n for i in forums:\n discussions.append(i.discussion_set.all())\n\n reviews = Review.objects.filter(ebook=ebook)\n if request.user.is_authenticated:\n if (request.user.is_provider or request.user.is_support\n or request.user.is_superuser):\n context = {\n \"form\": form,\n \"ebook\": ebook,\n \"review_form\": review_form,\n \"reviews\": reviews,\n \"discussion_form\": discussion_form,\n \"create_forum\": forum_form,\n \"forums\": ebook.forum_set.all(),\n \"count\": count,\n \"discussions\": discussions,\n }\n else:\n followed = False\n for e in list(request.user.users_key.values()):\n if e[\"id\"] == ebook.id:\n followed = True\n\n context = {\n \"form\":\n form,\n \"substract\":\n request.user.user_profile.nbooks_by_subs -\n request.user.user_profile.n_books_followed,\n \"ebook_followed\":\n followed,\n \"ebook\":\n ebook,\n \"review_form\":\n review_form,\n \"reviews\":\n reviews,\n \"discussion_form\":\n discussion_form,\n \"create_forum\":\n forum_form,\n \"forums\":\n ebook.forum_set.all(),\n \"count\":\n count,\n \"discussions\":\n discussions,\n }\n else:\n context = {\n \"reviews\": reviews,\n \"discussion_form\": discussion_form,\n \"create_forum\": forum_form,\n \"review_form\": review_form,\n \"form\": form,\n \"ebook\": ebook,\n \"forums\": ebook.forum_set.all(),\n \"count\": count,\n \"discussions\": discussions,\n }\n\n return render(request, \"scribd/ebook_details.html\", context)\n\n\ndef ebook_forum(request, book_k, forum_k):\n if request.method == \"POST\" and request.user.is_authenticated:\n discussion_form = CreateInDiscussion(request.POST)\n\n if discussion_form.is_valid():\n discussion = Discussion.objects.create(\n user=request.user,\n forum=Forum.objects.get(id=forum_k),\n discuss=discussion_form.cleaned_data.get(\"discuss\"),\n )\n\n discussion.save()\n next = request.POST.get(\"next\", \"/\")\n return HttpResponseRedirect(next)\n\n else:\n\n discussion_form = CreateInDiscussion()\n forum = Forum.objects.get(id=forum_k)\n discussions = forum.discussion_set.all()\n context = {\n \"forum\": forum,\n \"discussion_form\": discussion_form,\n \"discuss\": discussions,\n }\n\n return render(request, \"scribd/forumdetail.html\", context)\n\n\nclass UploadsViewSet(viewsets.ModelViewSet):\n queryset = UploadedResources.objects.all().order_by(\"id\")\n serializer_class = UploadResourcesSerializer\n\n # permission_classes = permissions.IsAuthenticatedOrReadOnly\n\n def get_queryset(self):\n return UploadedResources.objects.all().order_by(\"id\")\n\n\n##################################\n####### VISTA TICKETS ############\n##################################\n@authentificated_user\nclass ticketListView(ListView):\n model = UserTickets\n template_name = \"scribd/support_page.html\"\n\n\nclass ticketViewSet(viewsets.ModelViewSet):\n queryset = UserTickets.objects.all().order_by(\"id_uTicket\")\n serializer_class = ticketSerializer\n\n def get_queryset(self):\n return UserTickets.objects.all().order_by(\"id\")\n\n\n@authentificated_user\ndef ticketForumView(request, pk):\n if request.method == \"POST\" and request.user.is_authenticated:\n discussion_form = CreateInDiscussionTicket(request.POST)\n\n if discussion_form.is_valid():\n\n discussion = DiscussionTickets.objects.create(\n user=User.objects.get(id=User.objects.get(\n username=request.user.username).id),\n userticket=UserTickets.objects.get(id_uTicket=pk),\n discuss=discussion_form.cleaned_data.get(\"discuss\"),\n )\n\n discussion.save()\n next = request.POST.get(\"next\", \"/\")\n return HttpResponseRedirect(next)\n\n else:\n\n discussion_form = CreateInDiscussionTicket()\n ticket = UserTickets.objects.get(id_uTicket=pk)\n discussions = ticket.discussiontickets_set.all()\n context = {\n \"ticket\": ticket,\n \"discussion_form\": discussion_form,\n \"discuss\": discussions,\n }\n\n return render(request, \"scribd/ticketdetail.html\", context)\n\n\n@authentificated_user\ndef support_page(request):\n if request.method == \"POST\":\n ticket_form = TicketForm(request.POST, request.FILES)\n if ticket_form.is_valid():\n ticket = UserTickets.objects.create(\n ticket_title=ticket_form.cleaned_data.get(\"ticket_title\"),\n ticket_summary=ticket_form.cleaned_data.get(\"ticket_summary\"),\n ticket_user=User.objects.get(username=request.user.username),\n )\n ticket.save()\n\n return redirect(\"support_page\")\n else:\n ticket_form = TicketForm()\n tickets = UserTickets.objects.all()\n context = {\"tickets\": tickets, \"ticket_form\": ticket_form}\n return render(request, \"scribd/support_page.html\", context)\n\n\n##################################\n####### VISTA EBOOK ##############\n##################################\n\n\ndef add_books_form(request):\n return render(request, \"forms/add_book.html\")\n\n\nclass ebookListView(ListView):\n model = Ebook\n template_name = \"scribd/ebooks_list.html\"\n\n\nclass EbookViewSet(viewsets.ModelViewSet):\n queryset = Ebook.objects.all().order_by(\"id\")\n serializer_class = EbookSerializer\n\n # permission_classes = permissions.IsAuthenticatedOrReadOnly\n\n def get_queryset(self):\n return Ebook.objects.all().order_by(\"id\")\n\n\nclass BookUpdateView(generics.RetrieveUpdateAPIView):\n permission_classes = (\n permissions.IsAuthenticatedOrReadOnly,\n EditBookPermissions,\n ) # NOT WORKING\n queryset = Ebook.objects.all()\n serializer_class = EbookSerializer\n template_name = \"scribd/ebook_change.html\"\n form_class = EbookForm\n\n def patch(self, request, *args, **kwargs):\n instance = self.get_object()\n instance.title = request.data.get(\"title\")\n instance.autor = request.data.get(\"autor\")\n instance.description = request.data.get(\"description\")\n instance.is_promot = request.data.get(\"is_promot\")\n instance.featured_photo = request.data.get(\"featured_photo\")\n instance.category = request.data.get(\"category\")\n instance.media_type = request.data.get(\"media_type\")\n instance.count_downloads = request.data.get(\"count_downloads\")\n instance.file = request.data.get(\"file\")\n instance.save()\n\n serializer = EbookSerializer(data=request.data)\n serializer.is_valid(raise_exception=True)\n self.perform_update(serializer)\n\n return Response(serializer.data)\n\n\n@allowed_users(allowed_roles=[\"support\"])\ndef change_ebook(request, pk):\n instance = Ebook.objects.get(pk=pk)\n form = EbookForm(request.POST or None, instance=instance)\n if form.is_valid():\n form.save()\n return redirect(\"index\")\n return render(request, \"scribd/ebook_change.html\", {\"form\": form})\n\n\n##################################\n####### VISTA FORUM ##############\n##################################\n\n\nclass ForumViewSet(viewsets.ModelViewSet):\n queryset = Forum.objects.all().order_by(\"date_created\")\n serializer_class = ForumSerializer\n\n # permission_classes = permissions.IsAuthenticatedOrReadOnly\n\n def get_queryset(self):\n return User.objects.all().order_by(\"date_created\")\n\n\n##################################\n####### 404/500/403/400 ##############\n##################################\n\n\ndef error404(request, exception):\n return render(request, \"scribd/404.html\", {})\n\n\ndef error500(request, exception=None):\n return render(request, \"scribd/500.html\", {})\n\n\n\"\"\"def custom_permission_denied_view(request, exception=None):\n return render(request, \"scribd/403.html\", {})\n\ndef custom_bad_request_view(request, exception=None):\n return render(request, \"scribd/400.html\", {})\"\"\"\n","sub_path":"Scribd/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":27232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"429289901","text":"# -*- coding: utf-8 -*-\n'''\nCreated on 28 oct. 2021\n\n@author: Alfon\n'''\nimport csv\nfrom parsers import *\nfrom collections import namedtuple\nPropiedad = namedtuple('Propiedad', 'distrito barrio tipo_construcción tipo_impuesto bloque lote uso_propiedad direccion codigo_postal unidades_residenciales unidades_comerciales unidades_totales superficie_usable superficie_total año_construccion tipo_impuesto_venta tipo_vivienda_venta precio_venta fecha_venta reventa')\n\ndef lee_propiedades(fichero):\n registros = []\n with open (fichero, encoding ='utf-8') as f:\n \n lector = csv.reader(f,delimiter=';')\n next(lector)\n \n for linea in lector:\n distrito = int(linea[0])\n barrio = linea[1]\n tipo_construcción = linea[2]\n tipo_impuesto = linea[3]\n bloque = int(linea[4])\n lote = int(linea[5])\n uso_propiedad = linea[6]\n direccion = linea[7]\n codigo_postal = int(linea[8])\n unidades_residenciales = int(linea[9])\n unidades_comerciales = int(linea[10])\n unidades_totales = int(linea[11])\n superficie_usable = parsear_int(linea[12])\n superficie_total = parsear_int(linea[13])\n año_construccion = int(linea[14])\n tipo_impuesto_venta = linea[15]\n tipo_propiedad_venta = linea[16]\n precio_venta = parsear_int(linea[17])\n fecha_venta = parsear_fecha(linea[18])\n reventa = parsear_booleano(linea[19])\n \n tupla = Propiedad(distrito, barrio, tipo_construcción, tipo_impuesto, bloque, lote, uso_propiedad, direccion, codigo_postal, unidades_residenciales, unidades_comerciales, unidades_totales, superficie_usable, superficie_total, año_construccion, tipo_impuesto_venta, tipo_propiedad_venta, precio_venta, fecha_venta, reventa)\n registros.append(tupla)\n \n return registros","sub_path":"src/ventas.py","file_name":"ventas.py","file_ext":"py","file_size_in_byte":1957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"215914323","text":"#!/usr/bin/env python3\n\nimport socket, time\nfrom _thread import *\n\nhost_start = 2\nhost_end = 22\nhost_except = [5]\nPORT = 65432 # The port used by the server\nexpected_size = 200000\nn_packets = 5\ndone = 0\ndef multi_threaded_client(host,port):\n global done\n with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:\n s.connect((host,port))\n s.sendall(b'Hello, world')\n sum = 0\n while(sum < expected_size):\n data = s.recv(1024)\n sum+=len(data)\n done += 1\nfor i in range(host_start,host_end+1):\n if(i in host_except):\n continue\n num_except = 0 \n for j in host_except:\n if(j <= i):\n num_except += 1\n N = i - host_start + 1 - num_except\n print('N = {}'.format(N))\n start = time.time()\n for k in range(n_packets):\n done = 0\n for j in range(host_start,i+1):\n if(j in host_except):\n continue\n host = '192.168.2.' + str(j)\n start_new_thread(multi_threaded_client,(host,PORT))\n while(done != N):\n continue\n end = time.time()\n print('Latency: {} sec\\nGoodput: {} Mbps'.format(end-start, expected_size*n_packets*8*(10**(-6))*N/(end-start)))\n","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":1235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"583223537","text":"\"\"\"\n读取Excel的方法\n\"\"\"\n\nimport os\nfrom testFile.getpathInfo import * # 自己定义的内部类,该类返回项目的绝对路径\n# 调用读Excel的第三方库xlrd\nfrom xlrd import open_workbook\n\n\n#拿到项目所在的绝对路径\npath = get_path(__file__)\n\nclass readExcel():\n def get_xls(self,xls_name,sheet_name): # xls_name填写用例的Excel名称 sheet_name该Excel的sheet名称\n cls = []\n # 获取用例文件路径\n xlsPath = os.path.join(path,'case',xls_name)\n file = open_workbook(xlsPath) #打开用例Excel\n sheet = file.sheet_by_name(sheet_name) #获得打开Excel的sheet\n # 获取这个sheet内容函数\n nrows = sheet.nrows\n for i in range(nrows):\n if sheet .row_values(i)[1] != u'case_name':\n # 如果这个Excel的这个sheet的第i行的第一列不等于case_name那么我们把这行的数据添加到cls[]\n cls.append(sheet.row_values(i))\n return cls\n\nif __name__ == '__main__': # 我们执行该文件测试一下是否可以正确获取Excel中的值\n print(readExcel().get_xls('userCase.xlsx','login'))","sub_path":"babTest/testFile/readExcel.py","file_name":"readExcel.py","file_ext":"py","file_size_in_byte":1150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"475519994","text":"import os\nimport django\nimport json\nimport unittest\nos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')\ndjango.setup()\nimport get_sched2 as schedule_return\n\n\n\n#UNIT TESTING\n\nfrom users.models import MyUser, my_stations\n\nclass TestSchedule(unittest.TestCase):\n ret = schedule_return.get_times('testing')\n data = json.loads(ret)\n\n def test_call(self):\n #check it returns a string object to be parsed\n self.assertTrue(type(self.ret) == str)\n\n def test_non_existing(self):\n #test for a stop that does not exist\n #returns an array (loaded above) with 7 fields saying does not exist\n field_count = 0\n for i in range(0, len(self.data)):\n ## our data has 7 chosen fields\n field_count += 1\n #self.assertTrue(ob_len == 1)\n self.assertTrue(field_count == 7)\n\n def test_existing(self):\n ## this is time dependant\n ret = schedule_return.get_times(['8220DB004432'])\n data = json.loads(ret)\n fields = []\n stop = []\n for i in range(0, len(data)):\n fields.append(data[i].items())\n break\n print(fields)\n self.assertTrue(0==0)\nif __name__ == '__main__':\n unittest.main()","sub_path":"favourites/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"103594369","text":"\"\"\"\nCreated on July 31, 2020\nUpdated on May 18, 2021\n\nmodel: DeepFM: A Factorization-Machine based Neural Network for CTR Prediction\n\n@author: Ziyao Geng(zggzy1996@163.com)\n\"\"\"\n\nimport tensorflow as tf\nfrom tensorflow.keras import Model\nfrom tensorflow.keras.regularizers import l2\nfrom tensorflow.keras.layers import Embedding, Dropout, Dense, Input, Layer\n\nfrom modules import *\n\n\nclass DeepFM(Model):\n\tdef __init__(self, feature_columns, hidden_units=(200, 200, 200), dnn_dropout=0.,\n\t\t\t\t activation='relu', fm_w_reg=1e-6, embed_reg=1e-6):\n\t\t\"\"\"\n\t\tDeepFM\n\t\t:param feature_columns: A list. a list containing dense and sparse column feature information.\n\t\t:param hidden_units: A list. A list of dnn hidden units.\n\t\t:param dnn_dropout: A scalar. Dropout of dnn.\n\t\t:param activation: A string. Activation function of dnn.\n\t\t:param fm_w_reg: A scalar. The regularizer of w in fm.\n\t\t:param embed_reg: A scalar. The regularizer of embedding.\n\t\t\"\"\"\n\t\tsuper(DeepFM, self).__init__()\n\t\tself.dense_feature_columns, self.sparse_feature_columns = feature_columns\n\t\tself.embed_layers = {\n\t\t\t'embed_' + str(i): Embedding(input_dim=feat['feat_num'],\n\t\t\t\t\t\t\t\t\t\t input_length=1,\n\t\t\t\t\t\t\t\t\t\t output_dim=feat['embed_dim'],\n\t\t\t\t\t\t\t\t\t\t embeddings_initializer='random_normal',\n\t\t\t\t\t\t\t\t\t\t embeddings_regularizer=l2(embed_reg))\n\t\t\tfor i, feat in enumerate(self.sparse_feature_columns)\n\t\t}\n\t\tself.feature_length = sum([feat['feat_num'] for feat in self.sparse_feature_columns])\n\t\tself.embed_dim = self.sparse_feature_columns[0]['embed_dim'] # all sparse features have the same embed_dim\n\t\tself.fm = FM(self.feature_length, fm_w_reg)\n\t\tself.dnn = DNN(hidden_units, activation, dnn_dropout)\n\t\tself.dense = Dense(1, activation=None)\n\n\tdef call(self, inputs, **kwargs):\n\t\tdense_inputs, sparse_inputs = inputs\n\t\t# embedding\n\t\tsparse_embed = tf.concat([self.embed_layers['embed_{}'.format(i)](sparse_inputs[:, i])\n for i in range(sparse_inputs.shape[1])], axis=-1) # (batch_size, embed_dim * fields)\n\t\t# wide\n\t\twide_inputs = {'sparse_inputs': sparse_inputs,\n\t\t\t\t\t 'embed_inputs': tf.reshape(sparse_embed, shape=(-1, sparse_inputs.shape[1], self.embed_dim))}\n\t\twide_outputs = self.fm(wide_inputs) # (batch_size, 1)\n\t\t# deep\n\t\tif len(self.dense_feature_columns) > 0:\n\t\t\tstack = tf.concat([dense_inputs, sparse_embed], axis=-1)\n\t\telse:\n\t\t\tstack = sparse_embed\n\t\tdeep_outputs = self.dnn(stack)\n\t\tdeep_outputs = self.dense(deep_outputs) # (batch_size, 1)\n\t\t# outputs\n\t\toutputs = tf.nn.sigmoid(tf.add(wide_outputs, deep_outputs))\n\t\treturn outputs\n\n\tdef summary(self):\n\t\tdense_inputs = Input(shape=(len(self.dense_feature_columns),), dtype=tf.float32)\n\t\tsparse_inputs = Input(shape=(len(self.sparse_feature_columns),), dtype=tf.int32)\n\t\tModel(inputs=[dense_inputs, sparse_inputs], outputs=self.call([dense_inputs, sparse_inputs])).summary()\n","sub_path":"DeepFM/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"403075336","text":"#!/usr/bin/env python\n\n# Copyright (C) 2006-2011 Open Data (\"Open Data\" refers to\n# one or more of the following companies: Open Data Partners LLC,\n# Open Data Research LLC, or Open Data Capital LLC.)\n#\n# This file is part of Augustus.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport itertools as it\nfrom base import corelib, EquivUnary, Test, as_any_array, as_num_array\nsubtract = corelib.subtract\nsort = corelib.sort\narange = corelib.arange\ncumsum = corelib.cumsum\ngroupby = it.groupby\nizip = it.izip\ntakewhile = it.takewhile\ndropwhile = it.dropwhile\n\n\n########################################################################\n\nclass DictMap(EquivUnary):\n '''apply dictionary mapping to each element in array, retaining unmatched values\n\n >>> func = DictMap()\n >>> mapping = {1:100,2:200,3:300,'a':'aaa','b':'bbb'}\n >>> assert func([1,3,6,7,'a',9],mapping=mapping).tolist() == [100,300,6,7,'aaa',9]\n\n '''\n name = 'dict_map'\n ranking = ('naive_comp', 'naive_loop',)\n\n tests = (\n Test([1,3,6,7,7,9],mapping={1:100,2:200,3:300}) == [100,300,6,7,7,9],\n Test([1,3,6,7,'a',9],mapping={'1':100,'a':'aaa','3':300}) == [100,300,6,7,'aaa',9],\n )\n\n @staticmethod\n def naive_loop(arg,mapping={}):\n arg = as_any_array(arg)\n out = []\n for value in arg:\n out.append(mapping.get(value,value))\n return as_any_array(out)\n\n @staticmethod\n def naive_comp(arg,mapping={}):\n arg = as_any_array(arg)\n out = [mapping.get(value,value) for value in arg]\n return as_any_array(out)\n\n\n########################################################################\n\nclass DictMapDefault(EquivUnary):\n '''apply dictionary mapping to each element in array, using default for unmatched\n\n >>> func = DictMapDefault()\n >>> mapping = {1:100,2:200,3:300,'a':'aaa','b':'bbb'}\n >>> assert func([1,3,6,7,'a',9],mapping=mapping).tolist() == [100,300,6,7,'aaa',9]\n\n '''\n name = 'dict_map_default'\n ranking = ('naive_comp', 'naive_loop',)\n\n tests = (\n Test([1,3,6,7,7,9],mapping={1:100,2:200,3:300}) == [100,300,0,0,0,0],\n Test([1,3,6,7,'a',9],mapping={'1':100,'a':'aaa','3':300}) == ['100','300','0','0','aaa','0'],\n )\n\n @staticmethod\n def naive_loop(arg,mapping={},default=0):\n arg = as_any_array(arg)\n out = []\n for value in arg:\n out.append(mapping.get(value,default))\n return as_any_array(out)\n\n @staticmethod\n def naive_comp(arg,mapping={},default=0):\n arg = as_any_array(arg)\n out = [mapping.get(value,default) for value in arg]\n return as_any_array(out)\n\n\n########################################################################\n\nclass FuncMap(EquivUnary):\n '''apply function to each element in array\n\n >>> func = FuncMap()\n >>> mapping = {1:100,2:200,3:300,'a':'aaa','b':'bbb'}\n >>> assert func([1,3,6,7,7,9],func=mapping.get).tolist() == [100,300,6,7,7,9]\n\n '''\n name = 'func_map'\n ranking = ('naive_comp', 'naive_loop',)\n\n tests = (\n Test([1,3,6,7,7,9],func={1:100,2:200,3:300,6:6,7:7,9:9}.get) == [100,300,6,7,7,9],\n )\n\n @staticmethod\n def _default_func(arg): return arg\n\n @staticmethod\n def naive_loop(arg,func=None):\n func = func or FuncMap._default_func\n arg = as_any_array(arg)\n out = []\n for value in arg:\n out.append(func(value))\n return as_any_array(out)\n\n @staticmethod\n def naive_comp(arg,func=None):\n func = func or FuncMap._default_func\n arg = as_any_array(arg)\n out = [func(value) for value in arg]\n return as_any_array(out)\n\n\n########################################################################\n\nclass GetShift(EquivUnary):\n '''get value of other column shifted by some offset\n (typically useful for previous value (or arbitrary offset into column)\n\n >>> func = GetShift()\n >>> assert func([1,3,6,7,7,9],filler=99).tolist() == [3,6,7,7,9,99]\n\n '''\n name = 'get_shift'\n ranking = ('smart','fast', 'naive_comp', 'naive_loop',)\n\n tests = (\n Test([0]) == [0],\n Test([1,3,6,7,7,9]) == [0,1,3,6,7,7],\n Test([1,3,6,7,7,9],offset=3) == [0,0,0,1,3,6,],\n Test([1,3,6,7,7,9],offset=-2) == [6,7,7,9,0,0],\n Test([1,3,6,7,7,9],filler=99) == [99,1,3,6,7,7],\n )\n\n @staticmethod\n def naive_loop(arg,offset=1,filler=0,out=None):\n arg = as_num_array(arg)\n if not out:\n out = arg.new()\n if offset < 0:\n cut = len(arg)+offset\n for i in xrange(cut):\n out[i] = arg[i-offset]\n for i in xrange(cut,len(arg)):\n out[i] = filler\n else:\n cut = offset\n for i in xrange(cut):\n out[i] = filler\n for i in xrange(cut,len(arg)):\n out[i] = arg[i-offset]\n return out\n\n @staticmethod\n def naive_comp(arg,offset=1,filler=0,out=None):\n arg = as_num_array(arg)\n if not out:\n out = arg.new()\n if offset < 0:\n cut = len(arg)+offset\n out[:cut] = [arg[i] for i in xrange(-offset,len(arg))]\n out[cut:] = [filler]*(-offset)\n else:\n cut = offset\n out[:cut] = [filler]*(offset)\n out[cut:] = [arg[i] for i in xrange(len(arg)-cut)]\n return out\n\n @staticmethod\n def fast(arg,offset=1,filler=0,out=None):\n arg = as_num_array(arg)\n if offset < 0:\n cut = len(arg)+offset\n out1 = arg[-offset:len(arg)]\n out2 = (-offset)*[filler]\n else:\n cut = offset\n out1 = offset*[filler]\n out2 = arg[:len(arg)-cut]\n if not out:\n out = arg.new()\n out[:cut] = out1\n out[cut:] = out2\n return out\n\n @classmethod\n def smart(self,arg,offset=1,filler=0,out=None):\n if len(arg) < 100:\n return self.naive_loop(arg,offset=offset,filler=filler,out=out)\n return self.fast(arg,offset=offset,filler=filler,out=out)\n\n @staticmethod\n def _check_result(out,arg,**kwargs):\n offset = kwargs.get('offset',1)\n filler = kwargs.get('filler',0)\n if offset < 0:\n cut = len(arg)+offset\n for i in xrange(cut):\n assert out[i] == arg[i-offset]\n for i in xrange(cut,len(arg)):\n assert out[i] == filler\n else:\n cut = offset\n for i in xrange(cut):\n assert out[i] == filler\n for i in xrange(cut,len(arg)):\n assert out[i] == arg[i-offset]\n return True\n\n\n\n########################################################################\n\nclass DeltaPrev(EquivUnary):\n '''difference from previous value\n\n >>> func = DeltaPrev()\n >>> assert func([1,3,6,7,7,9]).tolist() == [0,2,3,1,0,2]\n\n '''\n name = 'delta_prev'\n ranking = ('smart','fast', 'naive_comp', 'naive_loop',)\n\n tests = (\n Test([1,3,6,7,7,9]) == [0,2,3,1,0,2],\n Test([0,3,0,7,0,0]) == [0,3,-3,7,-7,0],\n Test([0]) == [0],\n )\n\n @staticmethod\n def naive_loop(arg,out=None):\n arg = as_num_array(arg)\n if not out:\n out = arg.new()\n out[0] = 0\n for i in xrange(1,len(arg)):\n out[i] = arg[i] - arg[i-1]\n return out\n\n @staticmethod\n def naive_comp(arg,out=None):\n arg = as_num_array(arg)\n if not out:\n out = arg.new()\n out[0] = 0\n out[1:] = [arg[i]-arg[i-1] for i in xrange(1,len(arg))]\n return out\n\n @staticmethod\n def fast(arg,out=None):\n arg = as_num_array(arg)\n if not out:\n out = arg.new()\n out[0] = 0\n subtract(arg[1:],arg[:-1],out[1:])\n return out\n\n @classmethod\n def smart(self,arg,out=None):\n if len(arg) < 10:\n return self.naive_loop(arg,out)\n return self.fast(arg,out)\n\n @staticmethod\n def _check_result(out,arg,**kwargs):\n assert out[0] == 0\n for o,a1,a2 in izip(out[1:],arg[1:],arg[:-1]):\n assert o == a1-a2\n return True\n\n\n\n#################################################################\n\nclass CarryForward(EquivUnary):\n '''fill empty values with previous non-empty value\n\n >>> func = CarryForward().fast\n >>> assert func([0,3,0,0,4,0]).tolist() == [0,3,3,3,4,4]\n\n '''\n name = 'carry_forward'\n ranking = ('naive_loop', 'naive_iter', 'array_idx')\n\n tests = (\n Test([0,3,0,0,4,0]) == [0,3,3,3,4,4],\n Test([0,0,0,0,0,0]) == [0,0,0,0,0,0],\n Test([0,0,0,0,0,5]) == [0,0,0,0,0,5],\n Test([9,0,0,0,0,0]) == [9,9,9,9,9,9],\n )\n\n @staticmethod\n def array_idx(arg,out=None):\n arg = as_num_array(arg)\n if not out:\n out = arg.new()\n idx = arg.nonzero()[0]\n try:\n first = idx[0]\n except IndexError:\n first = len(out)\n out[:first] = 0\n if not len(idx):\n return out\n a,b = it.tee(idx)\n b.next()\n for start,stop in izip(a,b):\n out[start:stop] = arg[start]\n last = idx[-1]\n out[last:] = arg[last]\n return out\n\n @staticmethod\n def naive_iter(arg,out=None):\n arg = as_num_array(arg)\n if not out:\n out = arg.new()\n last = 0\n for i,value in izip(it.count(),arg):\n if value != 0:\n out[i] = last = value\n else:\n out[i] = last\n return out\n\n @staticmethod\n def naive_loop(arg,out=None):\n arg = as_num_array(arg)\n if not out:\n out = arg.new()\n last = 0\n for i in xrange(len(arg)):\n if arg[i] != 0:\n last = arg[i]\n out[i] = last\n return out\n\n########################################################################\n\nclass LookAheadIndex(EquivUnary):\n \"\"\"Given\n 1) a vector of sorted values that may contain duplicates and\n irregular spacing (like event timestamps, for example), and\n 2) a numeric delta to add to the vector (to identify the\n future timestamp some fixed interval away),\n return an index vector into the original data vector such that\n for each current value, the index points to either\n 1) the first occurrence of current value+delta, or\n 2) if the data doesn't contain such value, the first occurrence\n of the lext lower value that does occur in the data.\n\n If delta==0, then the index points to the first/last occurrence of the\n current value in the data.\n\n \"\"\"\n itypes = 'i'\n\n ranking = ('naive_loop',)\n ranking = ('missing1','naive_loop')\n bench_sizes = (1,2,3,4,5,10,20,50,100,200,300,500,1000,5000,\n #10000,\n #50000,\n #100000,\n #500000,\n #1000000,\n )\n\n\n tests = (\n Test([0,0,1,1,1,2,3,5,9],delta=0,first=True)\t== [0,0,2,2,2,5,6,7,8],\n Test([0,0,1,1,1,2,3,5,9],delta=1,first=True)\t== [2,2,5,5,5,6,6,7,8],\n Test([0,0,1,1,1,2,3,5,9],delta=2,first=True)\t== [5,5,6,6,6,6,7,7,8],\n Test([0,0,1,1,1,2,3,5,9],delta=3,first=True)\t== [6,6,6,6,6,7,7,7,8],\n Test([0,0,1,1,1,2,3,5,9],delta=4,first=True)\t== [6,6,7,7,7,7,7,8,8],\n Test([0,0,1,1,1,2,3,5,9],delta=5,first=True)\t== [7,7,7,7,7,7,7,8,8],\n\n Test([0,0,1,1,1,2,3,5,9],delta=0,first=False)\t== [1,1,4,4,4,5,6,7,8],\n Test([0,0,1,1,1,2,3,5,9],delta=1,first=False)\t== [4,4,5,5,5,6,6,7,8],\n Test([0,0,1,1,1,2,3,5,9],delta=2,first=False)\t== [5,5,6,6,6,6,7,7,8],\n Test([0,0,1,1,1,2,3,5,9],delta=3,first=False)\t== [6,6,6,6,6,7,7,7,8],\n Test([0,0,1,1,1,2,3,5,9],delta=4,first=False)\t== [6,6,7,7,7,7,7,8,8],\n Test([0,0,1,1,1,2,3,5,9],delta=5,first=False)\t== [7,7,7,7,7,7,7,8,8],\n\n Test([0,0,1,1,1,2,3,5,9],delta=-0,first=True)\t== [0,0,2,2,2,5,6,7,8],\n Test([0,0,1,1,1,2,3,5,9],delta=-1,first=True)\t== [0,0,0,0,0,2,5,6,7],\n Test([0,0,1,1,1,2,3,5,9],delta=-2,first=True)\t== [0,0,0,0,0,0,2,6,7],\n Test([0,0,1,1,1,2,3,5,9],delta=-3,first=True)\t== [0,0,0,0,0,0,0,5,7],\n Test([0,0,1,1,1,2,3,5,9],delta=-4,first=True)\t== [0,0,0,0,0,0,0,2,7],\n Test([0,0,1,1,1,2,3,5,9],delta=-5,first=True)\t== [0,0,0,0,0,0,0,0,6],\n\n Test([0,0,1,1,1,2,3,5,9],delta=-0,first=False)\t== [1,1,4,4,4,5,6,7,8],\n Test([0,0,1,1,1,2,3,5,9],delta=-1,first=False)\t== [1,1,1,1,1,4,5,6,7],\n Test([0,0,1,1,1,2,3,5,9],delta=-2,first=False)\t== [1,1,1,1,1,1,4,6,7],\n Test([0,0,1,1,1,2,3,5,9],delta=-3,first=False)\t== [1,1,1,1,1,1,1,5,7],\n Test([0,0,1,1,1,2,3,5,9],delta=-4,first=False)\t== [1,1,1,1,1,1,1,4,7],\n Test([0,0,1,1,1,2,3,5,9],delta=-5,first=False)\t== [1,1,1,1,1,1,1,1,6],\n\n Test([0],delta=-1)\t\t\t== [],\n Test([1,5],delta=-3)\t\t== [0,0],\n Test([0])\t\t\t\t== [],\n Test([1,5],delta=3)\t\t\t== [0,1],\n )\n\n def _prep_testdata(self,*args,**kwargs):\n # benchmark for inputs that are already vectors\n # simplification for tests: dep == indep\n return [as_num_array(sorted(arg)) for arg in args]\n\n @staticmethod\n def missing1(arg,delta=1,first=False):\n # build answer lookup mapping each arg value to first index\n run_lens = [(k,len(list(g))) for k,g in groupby(arg)]\n keys = as_num_array([k for k,l in run_lens])\n lens = as_num_array([l for k,l in run_lens])\n ends = cumsum(lens)\n starts = ends - lens\n if first:\n answer = dict(izip(keys,starts))\n else:\n answer = dict(izip(keys,ends-1))\n # identify missing keys\n need = keys + delta\n needset = set(need)\n haveset = set(answer)\n fillset = needset.difference(haveset)\n fill = as_num_array(sorted(fillset))\n #\n minkey,maxkey = arg[0],arg[-1]\n #\n have_iter = iter(keys[-1::-1])\n fill_iter = iter(fill[-1::-1])\n thiskey = maxkey\n thisval = answer[thiskey]\n for fillkey in fill_iter:\n if thiskey >= fillkey:\n try:\n thiskey = dropwhile(lambda x:x>=fillkey,have_iter).next()\n except StopIteration:\n thiskey = minkey\n thisval = answer[thiskey]\n answer[fillkey] = thisval\n out = [answer[val+delta] for val in arg]\n return out\n\n\n @staticmethod\n def naive_loop(arg,delta=1,first=False):\n out = []\n for i,val in enumerate(arg):\n # find answer range\n target = val + delta\n jj = i\n if target > val:\n # look forward\n for j in xrange(i+1,len(arg)):\n if arg[j] > target:\n break\n else:\n j = len(arg)\n jj = j-1\n target = arg[jj]\n elif target < val:\n # look backward\n for j in xrange(i-1,-1,-1):\n if arg[j] <= target:\n break\n else:\n j = 0\n jj = j\n target = arg[jj]\n\n # find first or last answer within range\n if first:\n kk = 0\n for k in xrange(jj,-1,-1):\n if arg[k] != target:\n kk = k+1\n break\n else:\n kk = len(arg)-1\n for k in xrange(jj,len(arg)):\n if arg[k] != target:\n kk = k-1\n break\n out.append(kk)\n return out\n\n########################################################################\n\nif __name__ == \"__main__\":\n from base import tester\n tester.testmod()\n\n########################################################################\n","sub_path":"tags/augustus-0.5.0.0/augustus-scoringengine/augustus/kernel/unitable/veclib/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":14883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"423186768","text":"from boto.mturk.connection import MTurkConnection\nfrom boto.mturk.question import ExternalQuestion\nfrom boto.mturk.qualification import LocaleRequirement\nfrom boto.mturk.qualification import Qualifications, PercentAssignmentsApprovedRequirement, NumberHitsApprovedRequirement, Requirement\nfrom boto.mturk.qualification import *\nimport os.path\nimport datetime\n\ndef create_hit():\n \n# read variables from file \n \n longi_file = open ('longi.txt', 'r')\n longi = longi_file.readlines()\n longi_file.close()\n\n url = longi[0].rstrip('\\n')\n access_key = longi[1].rstrip('\\n')\n secret_access_key = longi[2].rstrip('\\n')\n host = longi[3].rstrip('\\n')\n PercentAssignmentsApproved_yesno = longi[4].rstrip('\\n')\n PercentAssignmentsApproved_value = longi[5].rstrip('\\n')\n Block_past_workers_yesno = longi[6].rstrip('\\n')\n Locale_requirement_yesno = longi[7].rstrip('\\n')\n Locale_requirement_id = longi[8].rstrip('\\n')\n NumberHitsApproved_yesno = longi[9].rstrip('\\n')\n NumberHitsApproved_id = longi[10].rstrip('\\n')\n lifetime = longi[11].rstrip('\\n')\n duration = longi[12].rstrip('\\n')\n max_assignments = longi[13].rstrip('\\n')\n keywords = longi[14].rstrip('\\n')\n title = longi[15].rstrip('\\n')\n description = longi[16].rstrip('\\n')\n payment = longi[17].rstrip('\\n') \n approval_delay = 604800 \n subject = longi[18].rstrip('\\n')\n message = longi[19].rstrip('\\n')\n global path\n path = longi[23].rstrip('\\n')\n start_time = longi[25].rstrip('\\n')\n global reminder_frequency\n reminder_frequency = longi[29].rstrip('\\n')\n global delete_date\n delete_date = longi[30].rstrip('\\n')\n \n# check how many rounds have been completed\n\n global rounds_so_far\n if not os.path.isfile('hit_id_test.txt'):\n rounds_so_far = 0\n hit_ids_file = open('hit_id_test.txt', 'w')\n hit_ids_file.close()\n else:\n hit_ids_file = open('hit_id_test.txt', 'r')\n rounds_so_far = sum(1 for line in hit_ids_file)\n hit_ids_file.close()\n \n# check if researcher has one url, subject & message, or multiple, and load correct one if multiple\n\n if '.txt' in url:\n url_file = open('%s' % url, 'r')\n urls = url_file.readlines()\n url = urls[rounds_so_far]\n url = url.rstrip('\\n')\n url_file.close()\n \n if '.txt' in subject:\n subject_file = open('%s' % subject, 'r')\n subjects = subject_file.readlines()\n subject = subjects[rounds_so_far - 1]\n subject = subject.rstrip('\\n')\n subject_file.close()\n \n if '.txt' in message:\n message_file = open('%s' % message, 'r')\n messages = message_file.readlines()\n message = messages[rounds_so_far - 1]\n message = message.rstrip('\\n')\n message_file.close()\n\n if '.txt' in title:\n title_file = open('%s' % title, 'r')\n titles = title_file.readlines()\n title = titles[rounds_so_far]\n title = title.rstrip('\\n')\n title_file.close()\n \n if '.txt' in description:\n description_file = open('%s' % description, 'r')\n descriptions = description_file.readlines()\n description = descriptions[rounds_so_far]\n description = description.rstrip('\\n')\n description_file.close()\n \n# open Mturk connection\n \n mturk_connect = MTurkConnection(aws_access_key_id = access_key,\n aws_secret_access_key=secret_access_key,\n host=host)\n \n q = ExternalQuestion(external_url=url, frame_height=640)\n \n# set basic qualifications\n \n quals = Qualifications()\n if PercentAssignmentsApproved_yesno.lower() == 'yes':\n quals.add(PercentAssignmentsApprovedRequirement(\"GreaterThanOrEqualTo\", PercentAssignmentsApproved_value))\n if Locale_requirement_yesno.lower() == 'yes':\n quals.add(LocaleRequirement(\"EqualTo\", Locale_requirement_id)) \n if NumberHitsApproved_yesno.lower() == 'yes':\n quals.add(NumberHitsApprovedRequirement(\"GreaterThanOrEqualTo\", NumberHitsApproved_id)) \n \n# if researcher wants to block past workers: \n \n if Block_past_workers_yesno.lower() == 'yes':\n new_qual = False\n \n# if this is the first run:\n\n if rounds_so_far == 0:\n \n# check if a past worker qual already exists from a previous study\n if os.path.isfile('quals.txt'):\n quals_file = open('quals.txt', 'r')\n quals_ids = quals_file.readlines()\n quals_file.close()\n if not quals_ids: \n new_qual = True\n else:\n new_qual = True\n \n# if not, create a new qualification and store its ID in a text file\n\n if new_qual:\n quals_file = open('quals.txt', 'w')\n pastworker_qual = mturk_connect.create_qualification_type(name='past workers', description='this qualification is given to workers who complete any round of my study', status = 'Active')\n Block_past_workers_id = pastworker_qual[0].QualificationTypeId\n quals_file.write(Block_past_workers_id)\n quals_file.write('\\n')\n quals_file.close()\n \n# if a past worker qual already existed, read it in from the text file:\n \n if not new_qual:\n quals_file = open('quals.txt', 'r')\n quals_ids = quals_file.readlines()\n quals_file.close() \n Block_past_workers_id = quals_ids[0].rstrip('\\n')\n if rounds_so_far == 0:\n qual_req = Requirement(qualification_type_id = Block_past_workers_id, comparator = 'DoesNotExist')\n quals.add(qual_req)\n \n# if this is not the first round, ensure that only workers who have completed the previous round are allowed to take this hit:\n\n if rounds_so_far != 0:\n \n# create a qualification necessary to complete the current round, and add its ID to a text file\n \n quals_file = open('quals.txt', 'a')\n name = \"Completed Round \" + str(rounds_so_far)\n qual_description = \"This qualification is given to workers who have completed round \" + str(rounds_so_far) \n current_round_qual = mturk_connect.create_qualification_type(name=name, description=qual_description, status = 'Active')\n current_round_qual_id = current_round_qual[0].QualificationTypeId\n qual_req = Requirement(qualification_type_id = current_round_qual_id, comparator = 'Exists')\n quals.add(qual_req)\n quals_file.write(current_round_qual_id)\n quals_file.write('\\n')\n quals_file.close()\n \n# assign qual to workers who have completed the previous round. Send email inviting them to complete the hit:\n\n previous_round_file = \"workers_round\" + str(rounds_so_far) + \".txt\"\n previous_round = open('%s' % previous_round_file, 'r') \n workerids = previous_round.readlines()\n previous_round.close()\n for x in range (0, len(workerids)):\n workerids[x] = workerids[x].rstrip('\\n') \n for x in range (0, len(workerids)):\n mturk_connect.assign_qualification(current_round_qual_id, workerids[x], send_notification = True)\n send_email = mturk_connect.notify_workers(workerids[x], subject, message)\n \n# define hit \n \n hit_ids_file = open('hit_id_test.txt', 'a') \n create_hit = mturk_connect.create_hit(question=q,\n lifetime=lifetime,\n max_assignments=max_assignments,\n keywords=keywords,\n reward=payment,\n duration=duration,\n approval_delay=approval_delay, \n\t\t\t\t\t\t\t\t\t\ttitle=title,\n description=description,\n qualifications=quals,\n response_groups = 'Minimal') \n# store hit ID to reference later\n \n hit_ids_file.write(create_hit[0].HITId)\n hit_ids_file.write('\\n')\n assert(create_hit.status == True)\n hit_ids_file.close()\n \n \ncreate_hit()\t\nplus30 = datetime.datetime.now() + datetime.timedelta(minutes = 30)\nif plus30.minute < 10:\n minute = \"0\" + str(plus30.minute)\nelse:\n minute = str(plus30.minute)\nif plus30.hour < 10:\n hour = \"0\" + str(plus30.hour)\nelse:\n hour = str(plus30.hour)\nstart_time = hour + \":\" + minute \n\n# schedule a task to approve completed hits every 30 minutes until the experiment is over and all data is deleted.\n\nbatch_create = open ('sched_approve.bat', 'w')\nbatch_create.write('c:\\ncd ')\nbatch_create.write(path)\nbatch_create.write('\\n')\nbatch_create.write(path)\nbatch_create.write('python.exe ')\nbatch_create.write(path)\nbatch_create.write('longi_approve.py')\nbatch_create.close()\nminutes = int(start_time[-2:])\nhours = int (start_time[0:2])\n\nfrom subprocess import call\ndir = \"C:\\windows\\system32\"\ncmdline = \"schtasks /create /TN LONGI_approve /TR \\\"\" + path + \"sched_approve.bat \\\" /SC minute /MO 30 /ST \" + start_time + \" /ED \" + delete_date + \" /ET 23:45 /f\"\nrc = call(cmdline, cwd=dir) \n\n# if this is not the first round, schedule a task to remind previous workers to complete your current hit\n\nif rounds_so_far != 0:\n batch_create = open ('sched_reminder.bat', 'w')\n batch_create.write('c:\\ncd ')\n batch_create.write(path)\n batch_create.write('\\n')\n batch_create.write(path)\n batch_create.write('python.exe ')\n batch_create.write(path)\n batch_create.write('longi_email.py')\n batch_create.close()\n from subprocess import call\n dir = \"C:\\windows\\system32\"\n if '.txt' in reminder_frequency:\n reminder_file = open('%s' % reminder_frequency, 'r')\n total_reminders = sum(1 for line in reminder_file)\n reminder_file.close()\n reminder_file = open('%s' % reminder_frequency, 'r')\n reminders = reminder_file.readlines()\n reminder_file.close()\n for i in range (0, total_reminders):\n reminder = reminders[i]\n reminder = reminder.rstrip('\\n')\n reminder = reminder.split()\n reminder_date = reminder[0]\n reminder_time = reminder[1]\n cmdline = \"schtasks /create /TN LONGI_remind\" + str(i) + \" /TR \\\"\" + path + \"sched_reminder.bat \\\" /SD \" + reminder_date + \" /SC ONCE /ST \" + reminder_time + \" /f\"\n rc = call(cmdline, cwd=dir)\n else:\n reminder_frequency = reminder_frequency.lstrip(' every ')\n number = reminder_frequency[0]\n unit = reminder_frequency.lstrip(' ' + number + ' ')\n unit = unit.rstrip('s')\n if unit == 'day':\n unit = 'daily'\n elif unit == 'hour' or unit == 'week' or unit == 'month':\n unit = unit = unit + 'ly'\n cmdline = \"schtasks /create /TN LONGI_remind /TR \\\"\" + path + \"sched_reminder.bat \\\" /SC \" + unit + \" /MO \" + number + \" /ST \" + start_time + \" /ED \" + delete_date + \"/f\"\n rc = call(cmdline, cwd=dir)\n\n\n","sub_path":"longi.py","file_name":"longi.py","file_ext":"py","file_size_in_byte":11148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"298555685","text":"#Python-ish script for visit to make video\n#Run like \"visit -cli -nowin -s viz2D.py\"\n\n#Can separate and use execfile(\"blah.py\")\nfrom visit_utils import *\nfrom visit_utils.common import lsearch\nimport os\n\n#Species data\nTitStr = \"Electron [100 keV]\"\npStub = \"e.100keV\" #h5p stub\n#TitStr = \"Electrons [1 MeV]\"\n#pStub = \"e.1000keV\" #h5p stub\n\n\n#General file structure\nEqDir = \"~/Work/magnetoloss/eqSlc_HF\" #eqSlc database\n#pDir = \"~/Work/magnetoloss/synth\" #Directory of h5part\npDir = \"~/Work/magnetoloss/debug\" #Directory of h5part\nSess = \"~/Work/lfm2box/visit/lfmtp2D.session\" #Session template\n\n#Videos to do, list of pairs\n#Vids = [(0,0),(2,1)] \n#x = background pseudocolor varID, y = particle varID\n#Vids = [(0,0) , (0,1) , (1,1)]\nVids = [(0,1)]\ntestPic = False\n\npicHeight = 1024\npicWidth = 1200\n#ffmpeg options\nffOpts = \"-vcodec libx264 -pix_fmt yuv420p -vf setpts=2*PTS\"\ndoRender = True\n\n#Pseudocolor background options\ndbzMod = 25; fldebMod = 0.01\npc_Pid = 0 #Plot ID in visit\npc_CMap = \"RdGy\"\npc_Opacity = 0.75\npc_varId = [\"dBz\", \"F_ExBy\"]\npc_varLab = [\"Residual Bz [nT]\",\"ExB Velocity [Y, Re/s]\"]\npc_LabPos = (0.03,0.915)\npc_CMin = [-dbzMod,-fldebMod]\npc_CMax = [ dbzMod, fldebMod]\n\n#Particle plot options\n#Get colormaps from ColorTableNames()\ndaMod = 1.0e-4\npp_Pid = 1 #Plot ID in visit\npp_Size = 4; pp_CMap = \"Cool\"\npp_varId = [\"driftAlign\", \"kev\"]\npp_varLab = [\"Drift Alignment\", \"Particle Energy [keV]\"]\npp_LabPos = (0.03,0.15)\npp_CMin = [-daMod, 50]\npp_CMax = [daMod, 150]\n\n#Contour plot options (set to log)\ndoContour = True\nc_Pid = 3\nc_CMap = \"Summer\"\nc_varId = \"Bmag\"\nc_CBar = [1,1000]\nc_NLev = 8\nc_varLab = \"Field Magnitude [nT]\"\nc_LabPos = (0.7,0.71) #Position of c_varLab\n\n#Construct filenames/directory structure\nSrc0 = EqDir + \"/eqSlc.*.vti database\"\nSrc1 = pDir + \"/\" + pStub + \".h5part\" \nOutdir = \"Vid_\" + pStub\n\n#Setup visit\nShowAllWindows()\nOpenComputeEngine() #Just do it locally\nRestoreSessionWithDifferentSources(Sess, 0, (Src0,Src1))\nOpenDatabase(Src0, 1)\nOpenDatabase(Src1, 1)\n\n#Bring in variables\nexecfile(\"Vars.py\")\n\n#Show what we've got\nDrawPlots()\nNt = GetDatabaseNStates()\nif testPic: #Just draw some pics to test\n\tNt = 1\n\tdoRender = False\n\n#Loop over videos\nNumVids = len(Vids)\nfor v in range(NumVids):\n\tResetView()\n\tpcNum = Vids[v][0]\n\tppNum = Vids[v][1]\n\tpcIDn = pc_varId[pcNum]; ppIDn = pp_varId[ppNum]\n\tStub = pcIDn + \".\" + ppIDn #Stub for filenames\n\t\n\tprint(\"Generating video w/ PC (%s) and PP (%s)\"%(pcIDn,ppIDn))\n\tprint(\"\\tUsing format = %s.0000.png\"%(Stub))\n\tprint(\"\\tGenerating %d pics\"%(Nt))\n\t#Setup plots\n\t# Setup pcolor\n\tSetActivePlots(pc_Pid); pcol = GetPlotOptions()\n\tpcol.colorTableName=pc_CMap; \n\tpcol.opacityType=2; pcol.opacity = pc_Opacity\n\tpcol.min = pc_CMin[pcNum]; pcol.max = pc_CMax[pcNum];\n\tChangeActivePlotsVar(pcIDn)\n\tSetPlotOptions(pcol)\n\n\t# Setup particle plot\n\tSetActivePlots(pp_Pid); scat = GetPlotOptions()\n\tscat.var4 = ppIDn;\n\tscat.pointSizePixels = pp_Size\n\tscat.var4Min = pp_CMin[ppNum]; scat.var4Max = pp_CMax[ppNum]\n\tscat.colorTableName = pp_CMap \n\t#These are forced\n\tscat.var1 = \"xeq\"; scat.var2 = \"yeq\"; scat.var3 = \"default\" ; scat.var3Role = 4\n\tscat.var4MinFlag = 1; scat.var4MaxFlag = 1;\n\tscat.invertColorTable=0\n\tSetPlotOptions(scat)\t\n\t#Some extra threshold options for particle plot\n\topT = GetOperatorOptions(0)\n\topT.listedVarNames = (\"Outside\",\"rEq\")\n\topT.lowerBounds = (-1e8,2)\n\topT.upperBounds = (0.5,1e8)\n\tSetOperatorOptions(opT)\n\n\t#Handle annotation information\n\t#Set title\n\tAnnObjNames = GetAnnotationObjectNames()\n\tGetAnnotationObject('pLab').text = pp_varLab[ppNum]\n\tGetAnnotationObject('pLab').position = pp_LabPos\n\tGetAnnotationObject('bLab').text = pc_varLab[pcNum]\n\tGetAnnotationObject('bLab').position = pc_LabPos\n\n\tGetAnnotationObject('Title').text = TitStr\n\tGetAnnotationObject('cLabel').text = c_varLab\n\n\t#Do an extra contour if you want\n\tif doContour:\n\t\tSetActivePlots(c_Pid)\n\t\tcont = GetPlotOptions()\n\t\tcont.colorTableName = c_CMap\n\t\tcont.min = c_CBar[0]; cont.max = c_CBar[1]\n\t\tcont.contourNLevels = c_NLev\n\t\tChangeActivePlotsVar(c_varId)\n\t\tSetPlotOptions(cont)\n\t\tGetAnnotationObject('cLabel').visible = 1\n\t\tGetAnnotationObject('cLabel').position = c_LabPos\n\t\tif (v == 0):\n\t\t\tHideActivePlots() #Show contour\n\n\tprint(GetAnnotationObjectNames())\n\tprint(GetAnnotationObject('pLab'))\n\t#Generate slices\n\texecfile(\"doVid.py\")\n\n\t#Now render video\n\tif doRender:\n\t\tVidOut = Outdir + \"/\" + pStub + \".\" + Stub + \".mp4\" \n\t\tComS = \"ffmpeg -i %s/%s.%%04d.png \"%(Outdir,Stub) + ffOpts + \" \" + VidOut\n\t\tprint(\"\\t running command: %s\"%(ComS))\n\t\tos.system(ComS)\n\nexit()\n","sub_path":"visit/standalone/viz2D.py","file_name":"viz2D.py","file_ext":"py","file_size_in_byte":4552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"628780618","text":"import sys\nimport praw\n\n\nclass Readit(object):\n\n def __init__(self, sort, sub):\n self.sort = sort\n self.sub = sub\n\n self.redd = praw.Reddit(user_agent=\"Readit: v0.0.1\")\n\n def show_posts(self):\n sort_by = {\n \"hot\": self.display_hot,\n \"top\": self.display_top,\n \"new\": self.display_new,\n \"controversial\": self.display_controversial,\n \"contro\": self.display_controversial,\n \"rising\": self.display_rising,\n }\n if self.sort in sort_by:\n sort_by[self.sort]()\n else:\n print(\"Not a proper sorting method!\")\n\n def display_hot(self):\n self.hot = self.redd.get_subreddit(self.sub).get_hot(limit=10)\n for x in self.hot:\n print(str(x))\n print(str(x.permalink))\n\n def display_top(self):\n self.top = self.redd.get_subreddit(self.sub).get_top(limit=10)\n for x in self.top:\n print(str(x))\n print(str(x.permalink))\n\n def display_new(self):\n self.new = self.redd.get_subreddit(self.sub).get_new(limit=10)\n for x in self.new:\n print(str(x))\n print(str(x.permalink))\n\n def display_controversial(self):\n self.contro = self.redd.get_subreddit(self.sub)\n for x in self.contro.get_controversial(limit=10):\n print(str(x))\n print(str(x.permalink))\n\n def display_rising(self):\n self.rising = self.redd.get_subreddit(self.sub).get_rising(limit=10)\n for x in self.rising:\n print(str(x))\n print(str(x.permalink))\n\n\ndef main():\n poster = Readit(sys.argv[1], sys.argv[2])\n poster.show_posts()\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"232179558","text":"from airflow.hooks.postgres_hook import PostgresHook\nfrom airflow.models import BaseOperator\nfrom airflow.utils.decorators import apply_defaults\n\nclass LoadFactOperator(BaseOperator):\n\n ui_color = '#F98866'\n\n @apply_defaults\n def __init__(self,\n redshift_conn_id = \"\",\n sql = \"\",\n truncate_table = True,\n table= \"\",\n *args, **kwargs):\n\n super(LoadFactOperator, self).__init__(*args, **kwargs)\n \n self.redshift_conn_id = redshift_conn_id\n self.truncate_table = truncate_table\n self.table = table\n self.sql = sql\n\n def execute(self, context):\n\n redshift = PostgresHook(postgres_conn_id=self.redshift_conn_id)\n if self.truncate_table:\n redshift.run(f'INSERT INTO {self.table} {self.sql} WHERE NOT EXISTS (SELECT * FROM {self.table})')\n self.log.info(f'Fact table with data.')\n else:\n redshift.run(f'TRUNCATE songplays')\n self.log.info(f'Fact table {self.table} truncated.')\n\n ","sub_path":"plugins/operators/load_fact.py","file_name":"load_fact.py","file_ext":"py","file_size_in_byte":1079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"317562027","text":"# pylint: disable=invalid-name\n# pylint: disable=missing-docstring\n# pylint: disable=trailing-whitespace\nimport rethinkdb as r\nimport tweepy\nimport time\nfrom datetime import datetime\nimport json\nimport logging\n\nfrom tweepy_conf import init\nfrom convert_time import to_iso8601, date, hour\nfrom db_conf import get_conf\n\n\nlogging.basicConfig(filename='stream.log',level=logging.INFO)\n\nlogging.info(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))\n\n\nrdb_config = get_conf()\napi = init()\nusers = []\n\nclass listener(tweepy.StreamListener):\n\n def on_data(self, data):\n obj = json.loads(data)\n\n if 'delete' in obj:\n return self.on_delete(obj['delete']['status']['id'], obj['delete']['status']['user_id'])\n\n elif 'scrub_geo' in obj:\n return self.on_scrub_geo(obj['scrub_geo']['user_id'], obj['scrub_geo']['up_to_status_id'])\n\n elif 'limit' in obj:\n return self.on_limit(obj['limit']['track'])\n\n elif 'status_withheld' in obj:\n return self.on_status_withheld(obj['status_withheld']['id'], obj['status_withheld']['user_id'], obj['status_withheld']['withheld_in_countries'])\n\n elif 'user_withheld' in obj:\n return self.on_user_withheld(obj['user_withheld']['id'], obj['user_withheld']['withheld_in_countries'])\n\n elif 'disconnect' in obj:\n return self.on_disconnect(obj['disconnect']['code'], obj['disconnect']['stream_name'], obj['disconnect']['reason'])\n\n elif 'warning' in obj:\n return self.on_stall_warning(obj['warning']['code'], obj['warning']['message'], obj['warning']['percent_full'])\n\n elif 'text' in obj:\n return self.on_status(obj)\n else:\n return self.on_unknown(obj)\n\n return True\n\n def on_status(self, status):\n if status['user']['id_str'] in user_ids:\n logging.info(\"New status: %s: %s\", status['user']['screen_name'], status['text'])\n timestamp = to_iso8601(status['created_at'])\n status['created_at'] = timestamp\n with r.connect(**rdb_config) as conn:\n r.table('tweets').insert(status).run(conn)\n\n def on_delete(self, status_id, user_id):\n \"\"\"Called when a delete notice arrives for a status\"\"\"\n logging.info(\"Delete %s received\", status_id)\n return True\n\n def on_scrub_geo(self, user_id, up_to_status_id):\n \"\"\"Called when geolocated data must be stripped for user_id for statuses before up_to_status_id\"\"\"\n logging.warning(\"Scrub_geo received for user %s\", user_id)\n return True\n\n def on_limit(self, track):\n \"\"\"Called when a limitation notice arrvies\"\"\"\n logging.warning('Limit received for %s', track)\n return True\n\n def on_status_withheld(self, status_id, user_id, countries):\n \"\"\"Called when a status is withheld\"\"\"\n logging.warning('Status %s withheld for user %s', status_id, user_id)\n return True\n\n def on_user_withheld(self, user_id, countries):\n \"\"\"Called when a user is withheld\"\"\"\n logging.warning('User %s withheld', user_id)\n return True\n\n def on_disconnect(self, code, stream_name, reason):\n \"\"\"Called when a disconnect is received\"\"\"\n logging.error('Disconnect message: %s %s %s', code, stream_name, reason)\n return True\n\n def on_stall_warning(self, code, message, percent_full):\n logging.warning(\"Stall warning (%s): %s (%s%% full)\", code, message, percent_full)\n return True\n\n def on_error(self, status_code):\n \"\"\"Called when a non-200 status code is returned\"\"\"\n logging.error('Twitter returned error code %s', status_code)\n self.error = status_code\n return False\n\n def on_unknown(self, entity):\n \"\"\"Called when an unrecognized object arrives\"\"\"\n logging.error('Unknown object received: %s', repr(entity))\n return True\n\nprint(\"get users to monitor...\")\n\nwith r.connect(**rdb_config) as conn:\n for user in r.table('users').run(conn):\n users.append(user)\n\nuser_ids = [user['id_str'] for user in users]\n\nlogging.info(\"Following %i users\", len(user_ids))\n\nstream = tweepy.Stream(auth=api.auth, listener=listener())\n\nwhile True:\n try:\n print(\"starting stream...\")\n stream.filter(follow=user_ids)\n except Exception as e:\n print(e)\n time.sleep(2)","sub_path":"streaming.py","file_name":"streaming.py","file_ext":"py","file_size_in_byte":4132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"343313776","text":"import requests\r\nimport json\r\nimport sys\r\nimport os\r\nTOKEN = sys.argv[1]\r\nINVITE_LINK = sys.argv[2]\r\nPROXY = { 'http' : sys.argv[3] } \r\nurl = 'https://discordapp.com/api/v6/invite/'+INVITE_LINK+'?with_counts=true'\r\nprint(url)\r\nheaders = {\"content-type\": \"application/json\", \"Authorization\": TOKEN }\r\n\r\nr = requests.post(url,headers=headers, proxies=PROXY)\r\nif r.status_code == 200:\r\n print(\"Token:\"+\"'\"+TOKEN[-25]+\"'\"+\" Joined the server\")\r\nelse:\r\n print('error, something went wrong.')\r\n print('Make sure your token is correct | https://discordhelp.net/discord-token')\r\n print(r.json())","sub_path":"bots/misc/joinServer2.0.py","file_name":"joinServer2.0.py","file_ext":"py","file_size_in_byte":599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"256242611","text":"\n\n#MNIST with a BasicLSTMCell\n#try tf.app.run and def\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom Agent import Agent\n#import argparse\n#import sys\n\nimport tensorflow as tf\nimport math\nimport argparse \nimport sys\nimport numpy as np\n\nfrom tensorflow.examples.tutorials.mnist import input_data\n\n\nclass lmmodel(Agent):\n\n def __init__(self,config):\n #self._input = input_\n super(lmmodel,self).__init__('data/IF1601.CFE.csv', 3, 100, 100)\n self.config=config\n self.sess = tf.InteractiveSession() \n self.buildNetwork()\n self.batchsize=100 #batchsize\n self.numsteps=120 #120 price sequence \n self.hiddensize=20 #20features\n self.actionsize=3\n init = tf.global_variables_initializer()\n self.sess.run(init)\n #print(self.get_trajectories())\n\n def choose_action(self, state):\n \"\"\"Choose an action.\"\"\"\n print(state)\n return self.sess.run([self.action], feed_dict={self.states: [state]})\n\n def buildNetwork(self):\n with tf.name_scope('input'):\n # self.x = tf.placeholder(tf.float32, shape=[100,784], name='x')\n # self.y_= tf.placeholder(tf.float32,shape=[100,10],name=\"y_\")\n self.states = tf.placeholder(tf.float32,shape=[None,120,20],name= \"states\")\n self.actions_taken = tf.placeholder(tf.int32,shape=[None,3],name= \"actions_taken\")\n self.critic_feedback = tf.placeholder(tf.float32,shape=[ ],name= \"critic_feedback\")\n self.critic_rewards = tf.placeholder(tf.float32,shape=[ ],name= \"critic_rewards\")\n\n def lstm_cell(size):\n return tf.contrib.rnn.BasicLSTMCell(size, forget_bias=0.0, state_is_tuple=True)\n\n # ActorNetwork\n with tf.variable_scope(\"actor\") :\n \n L1= tf.contrib.layers.fully_connected(\n inputs=self.states,\n num_outputs= 20, #hidden \n activation_fn= tf.tanh,\n weights_initializer = tf.random_normal_initializer(),\n biases_initializer = tf.zeros_initializer()\n )\n print(\"L1:\",L1)\n \n lstmcell=tf.contrib.rnn.BasicLSTMCell(20, forget_bias=0.0, state_is_tuple=True)\n cell = tf.contrib.rnn.MultiRNNCell([lstmcell for _ in range(5)], state_is_tuple=True)\n #self._initial_state=cell.zero_state(batchsize,tf.float32)\n\n #input = tf.reshape(L1,[100,28,28])\n \n state = cell.zero_state(100,tf.float32) #batchsize*hidden cells\n outputs = []\n for time_step in range(120):\n if time_step > 0: tf.get_variable_scope().reuse_variables()\n (cell_output, state) = cell(L1[:,time_step,:], state)\n outputs.append(cell_output)\n # tf.get_variable_scope().reuse_variables()\n\n output = tf.reshape(tf.concat(axis=1, values=outputs), [-1, 20])\n print(\"output\",output)\n weights = tf.Variable(tf.truncated_normal([20, 3],stddev=1.0 / math.sqrt(float(1200))),name='weights')\n biases = tf.Variable(tf.zeros([3]),name='biases')\n logits = tf.matmul(output, weights) + biases\n #weights = tf.Variable(\"softmax_w\", [20, 3], dtype=float32)\n #softmax_w = tf.get_variable( \"softmax_w\", [20, 3], dtype=tf.float32)\n #softmax_b = tf.get_variable(\"softmax_b\", [3], dtype=tf.float32)\n #logits = tf.matmul(output, softmax_w) + softmax_b\n self.probs = tf.nn.softmax(logits,name=\"action\")\n #print(\"action\",self.action)\n #print(tf.shape(self.action))\n #self.action =np.amax(self.action0,axis=self.action0[0])\n #self.action =tf.multinomial(tf.log(self.action0),1)\n #self.action = tf.shape(self.action0)[1]\n #gather_indices = tf.range(100) * tf.shape(self.action0)[1] + self.actions_taken\n #self.action = tf.gather(tf.reshape(self.action0, [-1]), gather_indices)\n #print(\"action\",self.action)\n gather_indices = tf.range(tf.shape(self.probs)[0]) * tf.shape(self.probs)[1] + self.actions_taken\n self.action = tf.gather(tf.reshape(self.probs, [-1]), gather_indices)\n \n\n #loss,train\n policyloss = tf.log(self.action)*(self.critic_rewards-self.critic_feedback)\n loss = tf.negative(tf.reduce_mean(policyloss),name=\"loss\")\n with tf.variable_scope(\"actor-train\"):\n self.actor_train = tf.train.AdamOptimizer(0.01).minimize(loss)\n tf.get_variable_scope().reuse_variables()\n\n \n\n \n # Critic Network\n with tf.variable_scope(\"critic\") as scopeB:\n \n self.critic_target = tf.placeholder(tf.float32,name= \"critic_target\")\n \n critic_L1= tf.contrib.layers.fully_connected(\n inputs=self.states,\n num_outputs= 20, #hidden \n activation_fn= tf.tanh,\n weights_initializer = tf.random_normal_initializer(),\n biases_initializer = tf.zeros_initializer()\n )\n\n # lstmcell=lstm_cell()\n lstmcell=tf.contrib.rnn.BasicLSTMCell(20, forget_bias=0.0, state_is_tuple=True)\n cell = tf.contrib.rnn.MultiRNNCell([lstmcell for _ in range(5)], state_is_tuple=True)\n self._initial_state=cell.zero_state(100,tf.float32)\n\n #scopeB.reuse_variables()\n state = cell.zero_state(100,tf.float32) #batchsize*hidden cells\n outputs = []\n for time_step in range(120):\n if time_step > 0: tf.get_variable_scope().reuse_variables()\n (cell_output, state) = cell(critic_L1[:,time_step,:], state)\n outputs.append(cell_output)\n\n # weights = tf.Variable(tf.truncated_normal([28, 10],stddev=1.0 / math.sqrt(float(28))),name='weights')\n # biases = tf.Variable(tf.zeros([10]),name='biases')\n # logits = tf.matmul(cell_output, weights) + biases\n # self.critic_value = tf.nn.softmax(logits,name=\"action\")\n output = tf.reshape(tf.concat(axis=1, values=outputs), [-1, 20])\n self.critic_value = tf.contrib.layers.fully_connected(\n inputs=output,\n num_outputs= 1, #hidden \n activation_fn= tf.tanh,\n weights_initializer = tf.random_normal_initializer(),\n biases_initializer = tf.zeros_initializer()\n )\n\n #loss,train\n critic_loss = tf.reduce_mean(tf.square(self.critic_target - self.critic_value) , name =\"loss\" )\n self.critic_train = tf.train.AdamOptimizer(0.01).minimize(critic_loss) #global_step\n\n def learn(self):\n\n for iteration in range(1000):\n\n trajectories = self.get_trajectories()\n all_action = np.concatenate([trajectory[\"action\"] for trajectory in trajectories])\n all_state = np.concatenate([trajectory[\"state\"] for trajectory in trajectories])\n # discounted sums of rewards\n returns = np.concatenate([trajectory[\"reward\"] for trajectory in trajectories])\n #returns = np.concatenate([discount_rewards(trajectory[\"reward\"],\"gama\") for trajectory in trajectories]) #???\n qw_new = self.session.run([self.critic_value],feed_dict={self.states:[all_state]}) #???\n\n\n #episode_rewards = np.concatenate([trajectory[\"reward\"].sum() for trajectory in trajectories])\n #episode_length = np.concatenate([len(trajectory[\"reward\"]) for trajectory in trajectories]) ##???\n\n results = self.session.run([self.critic_train,self.actor_train],feed_dict={\n self.states: all_state,\n self.critic_target:returns,\n self.states: all_state,\n self.actions_taken: all_action,\n self.critic_feedback:qw_new,\n self.critic_rewards:returns\n })\n\n \n\nclass config(object):\n learning_rate= 1.0\n num_layers =2\n num_steps= 20\n hidden_size = 28\n batch_size=100\n number=1000\n\ndef get_config():\n return config()\n \n\ndef main():\n # testAgent = Agent('data/IF1601.CFE.csv', 3, 5, 2)\n \n\n # mnist = input_data.read_data_sets('/tmp/tensorflow/mnist/input_data',one_hot=True)\n # train_input,ys = mnist.train.next_batch(100)\n\n config=get_config()\n\n with tf.name_scope(\"train\"):\n out = lmmodel(config=config)\n # out.buildNetwork()\n out.learn()\n # with tf.variable_scope(\"Model\",reuse=True):\n \n #for i in range(config.number):\n # if i%10 ==0:\n # acc= sess.run(out.accuracy,feed_dict=feed_dict())\n # print('Accuracy at step %s: %s'%(i,acc))\n #out=sess.run(out.train_step,feed_dict=feed_dict())\n\n\nif __name__ == '__main__':\n main()\n #tf.app.run()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n\n\n\n\n\n \n\n","sub_path":"test5_lmRL.py","file_name":"test5_lmRL.py","file_ext":"py","file_size_in_byte":9027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"361755633","text":"\"\"\"\nShows a list of all current issues (AKA tripped triggers)\n\"\"\"\n\nfrom getpass import getpass\nfrom pyzabbix import ZabbixAPI\n\n# The hostname at which the Zabbix web interface is available\nZABBIX_SERVER = 'http://192.168.1.203:82'\nzapi = ZabbixAPI(ZABBIX_SERVER)\nzapi.login('Admin', 'zabbix')\n\n# Get a list of all issues (AKA tripped triggers)\ntriggers = zapi.trigger.get(only_true=1,\n skipDependent=1,\n monitored=1,\n active=1,\n output='extend',\n expandDescription=1,\n expandData='host',\n selectItems='',\n)\n\n# Do another query to find out which issues are Unacknowledged\nunack_triggers = zapi.trigger.get(only_true=1,\n skipDependent=1,\n monitored=1,\n active=1,\n output='extend',\n expandDescription=1,\n expandData='host',\n withLastEventUnacknowledged=1,\n)\nunack_trigger_ids = [t['triggerid'] for t in unack_triggers]\nfor t in triggers:\n t['unacknowledged'] = True if t['triggerid'] in unack_trigger_ids\\\n else False\n\n# Print a list containing only \"tripped\" triggers\nfor t in triggers:\n if int(t['value']) == 1:\n print(\"{0} - {1} {2}\".format(\n t['host'],\n t['description'],\n '(Unack)' if t['unacknowledged'] else '')\n )","sub_path":"web_site/zabbix_center/screens/current_issues.py","file_name":"current_issues.py","file_ext":"py","file_size_in_byte":1216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"588921806","text":"import xlrd\nimport numpy as np\n\n#根据索引获取Excel表格中的数据 参数:file:Excel文件路径 colnameindex:表头列名所在行的所以 ,by_index:表的索引\ndef excel_table_byindex(file,colnameindex=0,by_index=0):\n data = xlrd.open_workbook(file)\n table = data.sheets()[by_index]\n nrows = table.nrows #行数\n ncols = table.ncols #列数\n colnames = table.row_values(colnameindex) #某一行数据\n list =[]\n for rownum in range(1,nrows):\n\n row = table.row_values(rownum)\n if row:\n app = {}\n for i in range(len(colnames)):\n app[colnames[i]] = row[i]\n list.append(app)\n return list\n\nqxTable=excel_table_byindex(\"D:\\\\2\\\\1QX.xls\")\ndetailTable=excel_table_byindex(\"D:\\\\2\\\\1600016_detail.xls\")\nfhTable=excel_table_byindex(\"D:\\\\2\\\\1600016fh.xls\")\n\n#结果表,用于存放结果\nresult=[]\n\n\n#分红总共条数,用于显示输出\nfhLen=fhTable.__len__()\nfor row in fhTable:\n stkcode=row['stkcode']\n fhDetail={}\n fhDetail['证券代码']=stkcode\n fhDetail['登记日']=row['交易日期']\n fhDetail['登记股份']=row['对应持仓数量']\n fhDetail['红利金额'] = row['红利金额']\n fhDetail['最晚持有日期'] = row['交易日期']\n #得到该分红股票的所有持仓数据\n stkList=[]\n for row in detailTable:\n if row['证券代码']==stkcode :\n stkList.append(row)\n print('应该与detail数量一致')\n print(stkList.__len__())\n #分布根据分红日期来得到每次分红一年内的数据\n #逻辑判断分支,如果不行,就跳入else执行\n if (stkList.__len__()==0):\n break\n if(int(stkList[0]['备份时间']))<(int(fhDetail['登记日'])-10000):\n #print(int(stkList[0]['备份时间']))\n #print(int(fhDetail['登记日'])-10000)\n print('这是我们要处理的逻辑')\n #获得免税股数、最早持有日期、最晚持有日期\n yearList=[]\n djr=(int(fhDetail['登记日'])-10000)\n #获取每次分后一年内的数据\n for row in stkList:\n if(int(row['备份时间']))>=djr:\n yearList.append(float(row['当前持仓']))\n\n min1 = min(yearList)\n\n print(min1)\n for row in stkList:\n if min1==float(row['当前持仓']):\n #print(row)\n fhDetail['免税股数'] = row['当前持仓']\n fhDetail['最早持有日期'] = row['备份时间']\n\n\n\n\n\n else:\n print('首次持仓就不足一年,另外一个逻辑,需要请教代���')\n\n\n result.append(fhDetail)\n\n#输出结果=+++++++++++++++++++++\nfor row in result:\n print(row)\n\n\n'''\nfor row in fhTable:\n print(row)\nfor row in detailTable:\n print(row)\n\nfor row in qxTable:\n print(row['zqdm1'])\n'''\n\n\n","sub_path":"work/hongli2.py","file_name":"hongli2.py","file_ext":"py","file_size_in_byte":2853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"186947167","text":"#!/usr/bin/env python\nimport rospy\nimport math\nimport rospy\nimport tf2_ros\nimport tf2_geometry_msgs\nimport numpy as np\nimport json\nfrom tf.transformations import euler_from_quaternion, quaternion_from_euler\nfrom geometry_msgs.msg import PoseStamped\nfrom visualization_msgs.msg import Marker\nfrom crazyflie_driver.msg import Position\n\ndef publish_wall(center, size, id = 0):\n marker = Marker()\n marker.id = id\n marker.header.frame_id = 'map'\n marker.type = 1\n [marker.pose.orientation.x,\n marker.pose.orientation.y,\n marker.pose.orientation.z,\n marker.pose.orientation.w] = quaternion_from_euler(0,0,0)\n marker.pose.position.x = center[0]\n marker.pose.position.y = center[1]\n marker.pose.position.z = center[2]\n marker.color.a = 0.5\n marker.color.r = 1.0\n marker.color.g = 1.0\n marker.color.b = 1.0\n marker.scale.x = size[0]\n marker.scale.y = size[1]\n marker.scale.z = size[2]\n marker.header.stamp = rospy.Time()\n pub_wall.publish(marker)\n\n\ndef publish_airspace(line, size, id=100):\n marker = Marker()\n marker.id = id\n marker.header.frame_id = 'map'\n marker.type = 1\n [marker.pose.orientation.x,\n marker.pose.orientation.y,\n marker.pose.orientation.z,\n marker.pose.orientation.w] = quaternion_from_euler(0,0,0)\n marker.pose.position.x = line[0]\n marker.pose.position.y = line[1]\n marker.pose.position.z = 0\n marker.color.a = 1\n marker.color.r = 1.0\n marker.color.g = 1.0\n marker.color.b = 1.0\n marker.scale.x = size[0]\n marker.scale.y = size[1]\n marker.scale.z = 0.01\n marker.header.stamp = rospy.Time()\n pub_wall.publish(marker)\n\nrospy.init_node('walls')\npub_wall = rospy.Publisher('visualization_marker', Marker, queue_size=20)\n\ndef main():\n rospy.loginfo(\"Initilizing the world map...\")\n rospy.loginfo(\"done initilizing.\")\n rate = rospy.Rate(30) # Hz\n cSpace=0.2\n jsonfile=\"/home/robot/dd2419_ws/src/project_packages/milestone_2_pkg/src/worlds/test.world.json\"\n with open(jsonfile, 'rb') as f:\n world = json.load(f)\n init = False\n while not rospy.is_shutdown():\n id = 0\n for wall in world[\"walls\"]:\n pos_start = np.array(wall[\"plane\"][\"start\"])\n pos_stop = np.array(wall[\"plane\"][\"stop\"])\n size = np.subtract(pos_stop, pos_start)\n center = np.add(pos_start,np.divide(np.subtract(pos_stop, pos_start),2))\n if pos_start[0]-pos_stop[0] == 0: size[0] = cSpace\n if pos_start[1]-pos_stop[1] == 0: size[1] = cSpace\n if pos_start[2]-pos_stop[2] == 0: size[2] = cSpace\n publish_wall(center, size, id)\n id += 1\n rate.sleep()\n\n \n line=world[\"airspace\"]\n pos_start = np.array(line[\"min\"])\n pos_stop = np.array(line[\"max\"])\n sizeX = pos_stop[0]-pos_start[0]\n sizeY = pos_stop[1]-pos_start[1]\n CP = np.subtract(pos_stop, pos_start)/2\n\n\n publish_airspace(CP, [sizeX,sizeY])\n rate.sleep()\n \n\n\n\n\nif __name__=='__main__':\n main()\n","sub_path":"milestone_2_pkg/src/scripts/walls.py","file_name":"walls.py","file_ext":"py","file_size_in_byte":3063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"121843274","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport pandas as pd\nimport numpy as np\nget_ipython().run_line_magic('matplotlib', 'inline')\n\n\n# In[2]:\n\n\n# 1.\nseries = pd.Series([\"kiwi\", \"mango\", \"strawberry\", \"pineapple\", \"gala apple\", \"honeycrisp apple\", \"tomato\", \n \"watermelon\", \"honeydew\", \"kiwi\", \"kiwi\", \"kiwi\", \"mango\", \"blueberry\", \"blackberry\", \"gooseberry\", \n \"papaya\"])\n\n# a. naming of the variable that holds the series to 'fruits'\n\nfruits = series\nfruits\n\n\n# In[4]:\n\n\n#b. sees what 'describe()' returns for a series of strings\n\nfruits.describe()\n\n\n# In[5]:\n\n\n#c. returns only the unique names in the series\n\nfruits.unique()\n\n\n# In[6]:\n\n\n#d. determines how many times each value occurs in the series\n\nfruits.value_counts()\n\n\n# In[27]:\n\n\n#e. determine the most frequently occurring fruit names from the series\n\nfruits.mode() # the zero on the left indicates its original index in the series list\n\n\n# In[28]:\n\n\n#f. determine the least frequently occuring fruit names from the series\n\nfruits.unique().min()[:]\n\n\n# In[29]:\n\n\n#g. the code to get the longest string from the series of fruits\n\nfruits.astype('str').max()\n\n\n# In[30]:\n\n\n#h. find the fruits with five or more letters in the name\nfruits.str.len() \n\n\n# In[31]:\n\n\n#i. capitalize all the fruit strings in the series\ndef new_fruit(fruit):\n return fruit.capitalize()\n\nfruits.apply(new_fruit)\n\n\n# In[32]:\n\n\n#j. count the letter \"a\" in all the fruits (use string vectorization)\nfruits.apply(lambda x: x.count('a')).sum()\n\n\n# In[41]:\n\n\n#k. output the number of vowels in each and every fruit\n\nfruits.str.lower().str.count(r'[aeiou]')\n\n\n# In[42]:\n\n\n#l. use .apply method along with lambda function to find the fruit(s) containing two or more 'o' letters in name\nfruits.apply(lambda x: x.count('o')).sum()\n\n\n# In[53]:\n\n\n#m. write the code to get fruits only with the name 'berry' in them\nfruits.str.contains('berry')\nfruits[fruits.str.contains('berry')]\n\n\n# In[54]:\n\n\n#n. write the code to get fruits only with the name 'apple' in them\nfruits[fruits.str.contains('apple')]\n\n\n# In[57]:\n\n\n#o. which fruit has the highest amounts of vowels\nfruits[fruits.str.lower().str.count(r'[aeiou]')]\n\n\n# In[3]:\n\n\n#2 \nseries = pd.Series(['$796,459.41', '$278.60', '$482,571.67', '$4,503,915.98', \n '$2,121,418.3', '$1,260,813.3', '$87,231.01', '$1,509,175.45', \n '$4,138,548.00', '$2,848,913.80', '$594,715.39', '$4,789,988.17', \n '$4,513,644.5', '$3,191,059.97', '$1,758,712.24', '$4,338,283.54', \n '$4,738,303.38', '$2,791,759.67', '$769,681.94', '$452,650.23'])\n\n\n# In[20]:\n\n\nseries\n\n\n# In[4]:\n\n\n# what is the data type of the series?\ntype(series)\n\n\n# In[24]:\n\n\n#3\ngrades = pd.Series([60, 86, 75, 62, 93, 71, 60, 83, 95, 78, 65, 72, 69, 81, 96, 80, 85, 92, 82, 78])\ngrades\n\n\n# In[25]:\n\n\n# lowest grade\n\ngrades.min()\n\n\n# In[26]:\n\n\n# highest grade\n\ngrades.max()\n\n\n# In[27]:\n\n\n# mean grade\n\ngrades.mean()\n\n\n# In[28]:\n\n\n# median grade\n\ngrades.median()\n\n\n# In[2]:\n\n\n# plot histogram of the scores\nimport matplotlib.pyplot as plt\n\ngrades.plot.hist()\n\n\n# In[40]:\n\n\n# convert each of the numbers above to a letter grade\n\ndef Letter_Grade(grade):\n if grade >= 90:\n result = ['A']\n elif grade >= 80:\n result = ['B']\n elif grade >= 70:\n result = ['C']\n elif grade >= 60:\n result = ['D']\n else:\n result = ['F']\n return result\n\ngrades.apply(Letter_Grade)\n\n\n# In[ ]:\n\n\n#Write the code necessary to implement a curve. I.e. that grade closest to 100 should be converted to a 100, \n# and that many points should be given to every other score as well.\n\n\n# In[3]:\n\n\n#4:\nseries = pd.Series(['hnvidduckkqxwymbimkccexbkmqygkxoyndmcxnwqarhyffsjpsrabtjzsypmzadfavyrnndndvswreauxovncxtwzpwejilzjrmmbbgbyxvjtewqthafnbkqplarokkyydtubbmnexoypulzwfhqvckdpqtpoppzqrmcvhhpwgjwupgzhiofohawytlsiyecuproguy'])\n\n\n# In[80]:\n\n\nseries.describe()\n\n\n# In[4]:\n\n\nseriesArray = series.to_numpy()\nseriesArray\n\n\n# In[60]:\n\n\nletzgo = 'hnvidduckkqxwymbimkccexbkmqygkxoyndmcxnwqarhyffsjpsrabtjzsypmzadfavyrnndndvswreauxovncxtwzpwejilzjrmmbbgbyxvjtewqthafnbkqplarokkyydtubbmnexoypulzwfhqvckdpqtpoppzqrmcvhhpwgjwupgzhiofohawytlsiyecuproguy'\nlistgo = list(letzgo)\nprint(listgo)\n\n\n# In[11]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"4.8.4.2_pandas_series2.py","file_name":"4.8.4.2_pandas_series2.py","file_ext":"py","file_size_in_byte":4291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"444075377","text":"import collections\nimport os.path\nimport sys\nimport tempfile\nimport textwrap\n\nimport six\n\nimport perf\nfrom perf import tests\nfrom perf._utils import create_pipe, MS_WINDOWS\nfrom perf.tests import mock\nfrom perf.tests import unittest\nfrom perf.tests import ExitStack\n\n\ndef check_args(loops, a, b):\n if a != 1:\n raise ValueError\n if b != 2:\n raise ValueError\n # number of loops => number of seconds\n return loops\n\n\nResult = collections.namedtuple('Result', 'runner bench stdout')\n\n\nclass TestRunner(unittest.TestCase):\n def exec_runner(self, *args, **kwargs):\n def fake_timer():\n t = fake_timer.value\n fake_timer.value += 1.0\n return t\n fake_timer.value = 0.0\n\n name = kwargs.pop('name', 'bench')\n time_func = kwargs.pop('time_func', None)\n\n runner = perf.Runner(**kwargs)\n # disable CPU affinity to not pollute stdout\n runner._cpu_affinity = lambda: None\n runner.parse_args(args)\n\n with mock.patch('perf.perf_counter', fake_timer):\n with tests.capture_stdout() as stdout:\n with tests.capture_stderr() as stderr:\n if time_func:\n bench = runner.bench_time_func(name, time_func)\n else:\n bench = runner.bench_func(name, check_args, None, 1, 2)\n\n stdout = stdout.getvalue()\n stderr = stderr.getvalue()\n if '--stdout' not in args:\n self.assertEqual(stderr, '')\n\n # check bench_time_func() bench\n self.assertIsInstance(bench, perf.Benchmark)\n self.assertEqual(bench.get_name(), name)\n self.assertEqual(bench.get_nrun(), 1)\n\n return Result(runner, bench, stdout)\n\n def test_worker(self):\n result = self.exec_runner('--worker')\n self.assertRegex(result.stdout,\n r'^bench: Mean \\+- std dev: 1\\.00 sec \\+- 0\\.00 sec\\n$')\n\n def test_debug_single_value(self):\n result = self.exec_runner('--debug-single-value', '--worker')\n self.assertEqual(result.bench.get_nvalue(), 1)\n\n def test_pipe(self):\n rpipe, wpipe = create_pipe()\n with rpipe:\n with wpipe:\n arg = wpipe.to_subprocess()\n # Don't close the file descriptor, it is closed by\n # the Runner class\n wpipe._fd = None\n\n result = self.exec_runner('--pipe', str(arg), '--worker')\n\n with rpipe.open_text() as rfile:\n bench_json = rfile.read()\n\n self.assertEqual(bench_json,\n tests.benchmark_as_json(result.bench))\n\n def test_json_exists(self):\n with tempfile.NamedTemporaryFile('wb+') as tmp:\n\n runner = perf.Runner()\n with tests.capture_stdout() as stdout:\n try:\n runner.parse_args(['--worker', '--output', tmp.name])\n except SystemExit as exc:\n self.assertEqual(exc.code, 1)\n\n self.assertEqual('ERROR: The JSON file %r already exists'\n % tmp.name,\n stdout.getvalue().rstrip())\n\n def test_verbose_metadata(self):\n result = self.exec_runner('--worker', '--verbose', '--metadata')\n self.assertRegex(result.stdout,\n r'^'\n r'(?:Calibration [0-9]+: 1\\.00 sec \\(1 loop: 1\\.00 sec\\)\\n)+'\n r'Calibration: use [0-9^]+ loops\\n'\n r'\\n'\n r'(?:Warmup [0-9]+: 1\\.00 sec \\(1 loop: 1\\.00 sec\\)\\n)+'\n r'\\n'\n r'(?:Value [0-9]+: 1\\.00 sec\\n)+'\n r'\\n'\n r'Metadata:\\n'\n r'(?:- .*\\n)+'\n r'\\n'\n r'bench: Mean \\+- std dev: 1\\.00 sec \\+- 0\\.00 sec\\n$')\n\n def test_loops_calibration(self):\n def time_func(loops):\n # number of iterations => number of microseconds\n return loops * 1e-6\n\n result = self.exec_runner('--worker', '-v', time_func=time_func)\n\n for run in result.bench.get_runs():\n self.assertEqual(run.get_total_loops(), 2 ** 17)\n\n expected = textwrap.dedent('''\n Calibration 1: 1.00 us (1 loop: 1.00 us)\n Calibration 2: 1.00 us (2 loops: 2.00 us)\n Calibration 3: 1.00 us (4 loops: 4.00 us)\n Calibration 4: 1.00 us (8 loops: 8.00 us)\n Calibration 5: 1.00 us (16 loops: 16.0 us)\n Calibration 6: 1.00 us (32 loops: 32.0 us)\n Calibration 7: 1.00 us (64 loops: 64.0 us)\n Calibration 8: 1.00 us (128 loops: 128 us)\n Calibration 9: 1.00 us (256 loops: 256 us)\n Calibration 10: 1.00 us (512 loops: 512 us)\n Calibration 11: 1.00 us (1024 loops: 1.02 ms)\n Calibration 12: 1.00 us (2048 loops: 2.05 ms)\n Calibration 13: 1.00 us (4096 loops: 4.10 ms)\n Calibration 14: 1.00 us (8192 loops: 8.19 ms)\n Calibration 15: 1.00 us (2^14 loops: 16.4 ms)\n Calibration 16: 1.00 us (2^15 loops: 32.8 ms)\n Calibration 17: 1.00 us (2^16 loops: 65.5 ms)\n Calibration 18: 1.00 us (2^17 loops: 131 ms)\n\n ''').strip()\n self.assertIn(expected, result.stdout)\n\n def test_loops_calibration_min_time(self):\n def time_func(loops):\n # number of iterations => number of microseconds\n return loops * 1e-6\n\n result = self.exec_runner('--worker', '--min-time', '0.001',\n time_func=time_func)\n for run in result.bench.get_runs():\n self.assertEqual(run.get_total_loops(), 2 ** 10)\n\n def test_json_file(self):\n with tests.temporary_directory() as tmpdir:\n filename = os.path.join(tmpdir, 'test.json')\n\n result = self.exec_runner('--worker', '--output', filename)\n\n loaded = perf.Benchmark.load(filename)\n tests.compare_benchmarks(self, loaded, result.bench)\n\n def test_time_func_zero(self):\n if perf.python_has_jit():\n # If Python has a JIT, perf forces calibration which is already\n # tested by test_calibration_zero()\n self.skipTest(\"Python has a JIT\")\n\n runner = perf.Runner()\n # disable CPU affinity to not pollute stdout\n runner._cpu_affinity = lambda: None\n runner.parse_args(['--worker', '-l1'])\n\n def time_func(loops):\n return 0\n\n with self.assertRaises(ValueError) as cm:\n runner.bench_time_func('bench', time_func)\n self.assertEqual(str(cm.exception),\n 'benchmark function returned zero')\n\n def test_calibration_zero(self):\n runner = perf.Runner()\n # disable CPU affinity to not pollute stdout\n runner._cpu_affinity = lambda: None\n runner.parse_args(['--worker'])\n\n def time_func(loops):\n return 0\n\n with self.assertRaises(ValueError) as cm:\n runner.bench_time_func('bench', time_func)\n self.assertIn('error in calibration, loops is too big:',\n str(cm.exception))\n\n def test_calibration(self):\n runner = perf.Runner()\n # disable CPU affinity to not pollute stdout\n runner._cpu_affinity = lambda: None\n runner.parse_args(['--worker', '-w2', '-n1', '--min-time=1.0'])\n\n # Simulate PyPy JIT: running the same function becomes faster\n # after 2 values while running warmup values\n def time_func(loops):\n if loops < 16:\n return 0\n\n time_func.step += 1\n if time_func.step == 1:\n return 3.0\n elif time_func.step == 2:\n return 0.5\n else:\n return 1.0\n time_func.step = 0\n\n with tests.capture_stdout():\n bench = runner.bench_time_func('bench', time_func)\n\n runs = bench.get_runs()\n self.assertEqual(len(runs), 1)\n\n run = runs[0]\n self.assertEqual(run.warmups,\n # first calibration values are zero\n ((1, 0.0),\n (2, 0.0),\n (4, 0.0),\n (8, 0.0),\n\n # first non-zero calibration value\n (16, 3.0 / 16),\n\n # warmup 1, JIT triggered, 3.0 => 0.5 for loops=128\n (16, 0.5 / 16),\n # warmup 1, new try with loops x 2\n (32, 1.0 / 32),\n\n # warmup 2\n (32, 1.0 / 32)))\n\n def test_loops_power(self):\n runner = perf.Runner()\n runner.parse_args(['--loops', '2^8'])\n self.assertEqual(runner.args.loops, 256)\n\n def check_two_benchmarks(self, task=None):\n runner = perf.Runner()\n args = ['--worker', '--loops=1', '-w0', '-n3']\n if task is not None:\n args.append('--worker-task=%s' % task)\n runner.parse_args(args)\n\n def time_func(loops):\n return 1.0\n\n def time_func2(loops):\n return 2.0\n\n with tests.capture_stdout():\n bench1 = runner.bench_time_func('bench1', time_func)\n bench2 = runner.bench_time_func('bench2', time_func2)\n\n return (bench1, bench2)\n\n def test_two_benchmarks(self):\n bench1, bench2 = self.check_two_benchmarks()\n\n self.assertEqual(bench1.get_name(), 'bench1')\n self.assertEqual(bench1.get_values(), (1.0, 1.0, 1.0))\n self.assertEqual(bench2.get_name(), 'bench2')\n self.assertEqual(bench2.get_values(), (2.0, 2.0, 2.0))\n\n def test_worker_task(self):\n bench1, bench2 = self.check_two_benchmarks(task=0)\n self.assertEqual(bench1.get_name(), 'bench1')\n self.assertEqual(bench1.get_values(), (1.0, 1.0, 1.0))\n self.assertIs(bench2, None)\n\n bench1, bench2 = self.check_two_benchmarks(task=1)\n self.assertIs(bench1, None)\n self.assertEqual(bench2.get_name(), 'bench2')\n self.assertEqual(bench2.get_values(), (2.0, 2.0, 2.0))\n\n bench1, bench2 = self.check_two_benchmarks(task=2)\n self.assertIs(bench1, None)\n self.assertIs(bench2, None)\n\n def test_show_name(self):\n result = self.exec_runner('--worker', name='NAME')\n self.assertRegex(result.stdout,\n r'^NAME: Mean \\+- std dev: 1\\.00 sec \\+- 0\\.00 sec\\n$')\n\n result = self.exec_runner('--worker', name='NAME', show_name=False)\n self.assertRegex(result.stdout,\n r'^Mean \\+- std dev: 1\\.00 sec \\+- 0\\.00 sec\\n$')\n\n def test_compare_to(self):\n def time_func(loops):\n return 1.0\n\n def abs_executable(python):\n return python\n\n run = perf.Run([1.5],\n metadata={'name': 'name'},\n collect_metadata=False)\n bench = perf.Benchmark([run])\n suite = perf.BenchmarkSuite([bench])\n\n with ExitStack() as cm:\n def popen(*args, **kw):\n mock_popen = mock.Mock()\n mock_popen.wait.return_value = 0\n return mock_popen\n\n mock_subprocess = cm.enter_context(mock.patch('perf._runner.subprocess'))\n mock_subprocess.Popen.side_effect = popen\n\n cm.enter_context(mock.patch('perf._runner.abs_executable',\n side_effect=abs_executable))\n cm.enter_context(mock.patch('perf._runner._load_suite_from_pipe',\n return_value=suite))\n\n runner = perf.Runner()\n\n args = [\"--python=python1\", \"--compare-to=python2\", \"--min-time=5\",\n \"-p1\", \"-w3\", \"-n7\", \"-l11\"]\n runner.parse_args(args)\n with tests.capture_stdout():\n runner.bench_time_func('name', time_func)\n\n def popen_call(python):\n args = [python, mock.ANY, '--worker',\n '--pipe', mock.ANY, '--worker-task=0',\n '--values', '7', '--warmups', '3',\n '--loops', '11', '--min-time', '5.0']\n kw = {}\n if MS_WINDOWS:\n kw['close_fds'] = False\n elif six.PY3:\n kw['pass_fds'] = mock.ANY\n return mock.call(args, env=mock.ANY, **kw)\n\n call1 = popen_call('python2')\n call2 = popen_call('python1')\n mock_subprocess.Popen.assert_has_calls([call1, call2])\n\n def test_parse_args_twice_error(self):\n args = [\"--worker\"]\n runner = perf.Runner()\n runner.parse_args(args)\n with self.assertRaises(RuntimeError):\n runner.parse_args(args)\n\n def test_duplicated_named(self):\n def time_func(loops):\n return 1.0\n\n runner = perf.Runner()\n runner.parse_args('-l1 -w0 -n1 --worker'.split())\n with tests.capture_stdout():\n runner.bench_time_func('optim', time_func)\n with self.assertRaises(ValueError) as cm:\n runner.bench_time_func('optim', time_func)\n\n self.assertEqual(str(cm.exception),\n \"duplicated benchmark name: 'optim'\")\n\n def test_bench_command(self):\n args = [sys.executable, '-c', 'pass']\n\n runner = perf.Runner()\n runner.parse_args('-l1 -w0 -n1 --worker'.split())\n with tests.capture_stdout():\n bench = runner.bench_command('bench', args)\n\n self.assertEqual(bench.get_metadata()['command'],\n ' '.join(map(repr, args)))\n\n\nclass TestRunnerCPUAffinity(unittest.TestCase):\n def test_cpu_affinity_args(self):\n runner = perf.Runner()\n runner.parse_args(['-v', '--affinity=3,7'])\n\n with mock.patch('perf._runner.set_cpu_affinity') as mock_setaffinity:\n with tests.capture_stdout() as stdout:\n runner._cpu_affinity()\n\n self.assertEqual(runner.args.affinity, '3,7')\n self.assertEqual(stdout.getvalue(),\n 'Pin process to CPUs: 3,7\\n')\n mock_setaffinity.assert_called_once_with([3, 7])\n\n def test_cpu_affinity_isolcpus(self):\n runner = perf.Runner()\n runner.parse_args(['-v'])\n\n with mock.patch('perf._runner.set_cpu_affinity') as mock_setaffinity:\n with mock.patch('perf._runner.get_isolated_cpus', return_value=[1, 2]):\n with tests.capture_stdout() as stdout:\n runner._cpu_affinity()\n\n self.assertEqual(runner.args.affinity, '1-2')\n self.assertEqual(stdout.getvalue(),\n 'Pin process to isolated CPUs: 1-2\\n')\n mock_setaffinity.assert_called_once_with([1, 2])\n\n def test_cpu_affinity_no_isolcpus(self):\n runner = perf.Runner()\n runner.parse_args(['-v'])\n\n with mock.patch('perf._runner.set_cpu_affinity') as mock_setaffinity:\n with mock.patch('perf._runner.get_isolated_cpus', return_value=None):\n runner._cpu_affinity()\n\n self.assertFalse(runner.args.affinity)\n self.assertEqual(mock_setaffinity.call_count, 0)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"perf/tests/test_runner.py","file_name":"test_runner.py","file_ext":"py","file_size_in_byte":15463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"607423006","text":"import pygame\r\nimport random\r\nimport shelve\r\n\r\nclass Game:\r\n\tdef __init__(self):\r\n\t\tself.save_date = Save()\r\n\r\n\r\n\r\ndef draw_main_game():\r\n\twin.blit(bg,(0,0))\r\n\tshop_anim_button()\r\n\thome_anim_button()\r\n\tmission_anim_button()\r\n\tpygame.display.update()\r\n\r\ndef main_game():\r\n\tmain_game = True\r\n\twhile main_game:\r\n\t\tclock.tick(60)\r\n\t\tdraw_main_game()\r\n\t\tfor event in pygame.event.get():\r\n\t\t\tif event.type == pygame.QUIT:\r\n\t\t\t\tsave.save_data()\r\n\t\t\t\tpygame.quit()\r\n\t\t\t\tquit()\r\n\r\n# --------------------------------- Магазин внутри\r\n\r\ndef draw_shop():\r\n\twin.blit(shop_in,(0,0))\r\n\tshop_exit_anim_button()\r\n\tgoing_to_1()\r\n\tpygame.display.update()\r\n\r\ndef shop():\r\n\tglobal main_shop\r\n\tmain_shop = True\r\n\tpreview_shop()\r\n\twhile main_shop:\r\n\t\tclock.tick(60)\r\n\t\tdraw_shop()\r\n\t\tfor event in pygame.event.get():\r\n\t\t\tif event.type == pygame.QUIT:\r\n\t\t\t\tsave.save_data()\r\n\t\t\t\tpygame.quit()\r\n\t\t\t\tquit()\r\n\r\n# --------------------------------- Квартира внутри\r\n\r\ndef draw_home():\r\n\twin.blit(home_in,(0,0))\r\n\thome_exit_anim_button()\r\n\tpygame.display.update()\r\n\r\ndef home():\r\n\tglobal main_home\r\n\tmain_home = True\r\n\twhile main_home:\r\n\t\tclock.tick(60)\r\n\t\tdraw_home()\r\n\t\tfor event in pygame.event.get():\r\n\t\t\tif event.type == pygame.QUIT:\r\n\t\t\t\tsave.save_data()\r\n\t\t\t\tpygame.quit()\r\n\t\t\t\tquit()\r\n\r\n# --------------------------------- Меню выбора миссий\r\n\r\ndef draw_mission_select():\r\n\twin.fill((255,255,255))\r\n\tprint_text_in_rect(message = \"level 1\", x = 100, y = 30, font_color = (0,0,0), font_size = 30, font_type = \"D:\\\\JustMonika\\\\_RunFatCat(1)\\\\ara\\\\langue.ttf\", link = mission_1, level = 1)\r\n\tprint_text_in_rect(message = \"level 2\", x = 250, y = 30, font_color = (0,0,0), font_size = 30, font_type = \"D:\\\\JustMonika\\\\_RunFatCat(1)\\\\ara\\\\langue.ttf\", link = mission_2, level = 2)\r\n\tprint_text_in_rect(message = \"level 3\", x = 400, y = 30, font_color = (0,0,0), font_size = 30, font_type = \"D:\\\\JustMonika\\\\_RunFatCat(1)\\\\ara\\\\langue.ttf\", link = mission_3, level = 3)\r\n\tmission_exit_anim_button()\r\n\tpygame.display.update()\r\n\tfor event in pygame.event.get():\r\n\t\t\tif event.type == pygame.QUIT:\r\n\t\t\t\tsave.save_data()\r\n\t\t\t\tpygame.quit()\r\n\t\t\t\tquit()\r\ndef mission_select():\r\n\tglobal main_mission_select\r\n\tmain_mission_select = True\r\n\twhile main_mission_select:\r\n\t\tclock.tick(60)\r\n\t\tdraw_mission_select()\r\n\t\r\n# --------------------------------- Анимации магазина снаружи и переход в магазин при нажатие \r\n\r\ndef shop_anim_button():\r\n\tglobal click_press, shop_anim_count\r\n\tmouse = pygame.mouse.get_pos()\r\n\tclick = pygame.mouse.get_pressed()\r\n\r\n\tif 345 < mouse[1] < 510 and 785 < mouse[0] < 936:\r\n\t\t\tif 12 < shop_anim_count <= 30:\r\n\t\t\t\twin.blit(shop_anim[0],(790,349))\r\n\t\t\t\tshop_anim_count -= 1\r\n\t\t\telif 11 < shop_anim_count <= 12:\r\n\t\t\t\twin.blit(shop_anim[1],(790,349))\r\n\t\t\t\tshop_anim_count -= 1\r\n\t\t\telif 3 < shop_anim_count <= 11:\r\n\t\t\t\twin.blit(shop_anim[0],(790,349))\r\n\t\t\t\tshop_anim_count -= 1\r\n\t\t\telif shop_anim_count == 0:\r\n\t\t\t\twin.blit(shop_anim[0],(790,349))\r\n\t\t\t\tshop_anim_count = 30\r\n\t\t\telse:\r\n\t\t\t\twin.blit(shop_anim[1],(790,349))\r\n\t\t\t\tshop_anim_count -= 1\r\n\t\t\tif click[0] == 1 and click_press:\r\n\t\t\t\tshop()\r\n\r\n# --------------------------------- Анимации магазина внутри и выход из магазина при нажатие \r\n\r\ndef shop_exit_anim_button():\r\n\tglobal click_press, main_shop\r\n\tmouse = pygame.mouse.get_pos()\r\n\tclick = pygame.mouse.get_pressed()\r\n\r\n\tif 285 < mouse[0] < 479 and 513 < mouse[1] < 690:\r\n\t\twin.blit(shop_in_door_active_2,(268,505))\r\n\t\tif click[0] == 1 and click_press:\r\n\t\t\tmain_shop = False\r\n\t\telif click[0] != 1:\r\n\t\t\tclick_press = True\r\n\t\t\t\r\n\telse:\r\n\t\twin.blit(shop_in_door_active_1,(268,505))\r\n\r\n# --------------------------------- Анимации квартиры снаружи и переход в квартиру при нажатие \r\n\r\ndef home_anim_button():\r\n\tglobal home_anim_count\r\n\tmouse = pygame.mouse.get_pos()\r\n\tclick = pygame.mouse.get_pressed()\r\n\tif 56 < mouse[0] < 223 and 583 < mouse[1] < 724:\r\n\t\tif click[0] == 1 and click_press:\r\n\t\t\t\thome()\r\n\t\twin.blit(home_anim, (56,583))\r\n\r\n# --------------------------------- Анимации квартиры внутри и выход из квартиры при нажатие \r\n\r\ndef home_exit_anim_button():\r\n\tglobal main_home\r\n\tmouse = pygame.mouse.get_pos()\r\n\tclick = pygame.mouse.get_pressed()\r\n\tif 0 < mouse[0] < 50 and 0 < mouse[1] < 50:\r\n\t\tpygame.draw.rect(win,(0,0,0),(0,0,50,50))\r\n\t\tif click[0] == 1 and click_press:\r\n\t\t\tmain_home = False \r\n\r\n# --------------------------------- Анимации выбора миссий снаружи и переход в выбор миссий при нажатие \r\n\r\ndef mission_anim_button(): # upgrade graf\r\n\tglobal click_press\r\n\tmouse = pygame.mouse.get_pos()\r\n\tclick = pygame.mouse.get_pressed()\r\n\tif 437 < mouse[0] < 550 and 345 < mouse[1] < 420:\r\n\t\tpygame.draw.rect(win,(0,255,0),(437,345,113,75))\r\n\t\tif click[0] == 1 and click_press:\r\n\t\t\tclick_press = False\r\n\t\t\tmission_select()\r\n\t\telif click[0] != 1:\r\n\t\t\tclick_press = True\r\n# --------------------------------- Анимации выбора миссий внутр�� и выход из выбора миссий при нажатие \r\n\r\ndef mission_exit_anim_button():\r\n\tglobal main_mission_select, click_press\r\n\tmouse = pygame.mouse.get_pos()\r\n\tclick = pygame.mouse.get_pressed()\r\n\tif 0 < mouse[0] < 50 and 0 < mouse[1] < 50:\r\n\t\tpygame.draw.rect(win,(0,0,0),(0,0,50,50))\r\n\t\tif click[0] == 1 and click_press:\r\n\t\t\tmain_mission_select = False \r\n\t\telif click[0] != 1:\r\n\t\t\tclick_press = True\r\n\r\n\r\n\r\nclass Save:\r\n\tdef __init__(self):\r\n\t\tself.file = shelve.open('data')\r\n\r\n\tdef save_data(self):\r\n\t\tself.file['unlock_level'] = unlock_level.unlock_level \r\n\t\tself.file['shop_item'] = save_item_pls.list_shop_item\r\n\t\tself.file['home_item'] = save_item_pls.list_home_item\r\n\tdef add(self, name, value):\r\n\t\tself.file[name] = value\r\n\r\n\tdef get_date(self, name):\r\n\t\treturn self.file[name]\r\n\tdef delete_all_saves(self):\r\n\t\tself.file['unlock_level'] = 1\r\n\r\n\tdef __del__(self):\r\n\t\tself.file.close()\r\nsave = Save()\r\n\r\n\r\ndef going_to_1():\r\n\tglobal click_press\r\n\tmouse = pygame.mouse.get_pos()\r\n\tclick = pygame.mouse.get_pressed()\r\n\tif 490 < mouse[0] < 800 and 245 < mouse[1] < 450:\r\n\t\t\twin.blit(shop_in_active,(490, 240))\r\n\t\t\tif click[0] == 1 and click_press:\r\n\t\t\t\tclick_press = False\r\n\t\t\t\track()\r\n\t\t\tif click[0] != 1:\r\n\t\t\t\tclick_press = True\r\n\r\n\r\ndef draw_rack():\r\n\tx = 100\r\n\ty = 120\r\n\ti = 0\r\n\twin.blit(rack_image,(0,0))\r\n\tleave_from_rack()\r\n\tfor item in save_item_pls.list_shop_item:\r\n\t\titem.draw(x,y)\r\n\t\tif item.sold:\r\n\t\t\tsave_item_pls.list_home_item.append(item) \r\n\t\t\tsave_item_pls.list_shop_item.remove(item)\r\n\t\tx += 230\r\n\t\ti += 1\r\n\t\tif i % 5 == 0:\r\n\t\t\ty += 120\r\n\t\t\tx = 100\r\n\t\t\r\n\r\n\tpygame.display.update()\r\n\r\n\r\ndef rack():\r\n\tglobal main_rack\r\n\tmain_rack = True\r\n\twin.fill((255,255,255))\r\n\twhile main_rack:\r\n\t\tclock.tick(60)\r\n\t\tdraw_rack()\r\n\t\tfor event in pygame.event.get():\r\n\t\t\tif event.type == pygame.QUIT:\r\n\t\t\t\tsave.save_data()\r\n\t\t\t\tpygame.quit()\r\n\t\t\t\tquit()\r\n\r\ndef leave_from_rack():\r\n\tglobal main_rack, click_press\r\n\tmouse = pygame.mouse.get_pos()\r\n\tclick = pygame.mouse.get_pressed()\r\n\tif 0 < mouse[0] < 50 and 0 < mouse[1] < 50:\r\n\t\t\tpygame.draw.rect(win,(60,90,60),(0, 0, 50, 50))\r\n\t\t\tif click[0] == 1 and click_press:\r\n\t\t\t\tclick_press = False\r\n\t\t\t\tmain_rack = False\r\n\t\t\tif click[0] != 1:\r\n\t\t\t\tclick_press = True\r\n\r\nclass Shop_item():\r\n\tdef __init__(self, widht, height): # image, active_image,\r\n\t\t#self.image = image\r\n\t\t#self.active_image = active_image\r\n\t\tself.widht = widht\r\n\t\tself.height = height\r\n\t\tself.sold = False\r\n\tdef draw(self,x,y):\r\n\t\tglobal click_press\r\n\t\tmouse = pygame.mouse.get_pos()\r\n\t\tclick = pygame.mouse.get_pressed()\r\n\t\tif x <= mouse[0] <= x + self.widht and y <= mouse[1] <= y + self.height:\r\n\t\t\tpygame.draw.rect(win,(255,0,0),(x, y, self.widht, self.height))\r\n\t\t\t#win.blit(self.image_active,(x,y))\r\n\t\t\tif click[0] == 1 and click_press:\r\n\t\t\t\tclick_press = False\r\n\t\t\t\tself.sold = True\r\n\t\t\telif click[0] != 1:\r\n\t\t\t\tclick_press = True\r\n\t\telse:\r\n\t\t\tpygame.draw.rect(win,(155,0,0),(x, y, self.widht, self.height))\r\n\t\t\t#win.blit(self.image,(self.x,self.y))\r\n\r\nclass Home_item():\r\n\r\n\tdef draw_button(self):\r\n\t\tglobal click_press\r\n\t\tmouse = pygame.mouse.get_pos()\r\n\t\tclick = pygame.mouse.get_pressed()\r\n\t\tif self.x <= mouse[0] <= self.x + self.widht and self.y <= mouse[1] <= self.y + self.height:\r\n\t\t\twin.blit(self.image_active,(self.x,self.y))\r\n\t\t\tif mouse[0] == 1 and click_press:\r\n\t\t\t\tclick_press = False\r\n\r\n\t\t\telif mouse[0] != 1:\r\n\t\t\t\tclick_press = True\t\r\n\t\telse:\r\n\t\t\twin.blit(self.image,(self.x,self.y))\r\n\tdef add_item(self, image, active_image, widht, height):\r\n\t\tself.image = image\r\n\t\tself.active_image = active_image\r\n\t\tself.widht = widht\r\n\t\tself.height = height\r\n\t\tself.x = 100\r\n\t\tself.y = 120\r\n\r\n\r\nclass Save_item:\r\n\tdef __init__(self,item):\r\n\t\tself.list_shop_item = item\r\n\t\tself.list_home_item = []\r\n\r\n\r\n\r\n# Превьюшка в начале игры или при переходе куда-то\r\ndef preview_1():\r\n\ttmp_3 = -30\r\n\ttmp_2 = -800\r\n\ttmp_1 = 100\r\n\twhile 0 < tmp_1:\r\n\t\tclock.tick(30)\r\n\t\twin.fill((0,0,0))\r\n\t\twin.blit(bg,(0,tmp_2))\r\n\t\tprint_text(message = \"AlleyWay\", x = 400, y = tmp_3 , font_color = (255,255,255), font_size = 90, font_type = \"D:\\\\JustMonika\\\\_RunFatCat(1)\\\\ara\\\\langue.ttf\")\r\n\t\tpygame.display.update()\r\n\t\ttmp_1 -= 1\r\n\t\tif tmp_2 < 0:\r\n\t\t\ttmp_2 += 10\r\n\t\tif tmp_3 < 100: \r\n\t\t\ttmp_3 += 5\r\n\r\n\t\tfor event in pygame.event.get():\r\n\t\t\t\tif event.type == pygame.QUIT:\r\n\t\t\t\t\tquit()\r\n\r\ndef preview_2():\r\n\ttmp_3 = -100\r\n\ttmp_1 = 120\r\n\twhile 0 < tmp_1:\r\n\t\tclock.tick(30)\r\n\t\twin.fill((0,0,0))\r\n\t\tprint_text(message = \"AlleyWay\", x = 400, y = tmp_3 , font_color = (255,255,255), font_size = 90, font_type = \"D:\\\\JustMonika\\\\_RunFatCat(1)\\\\ara\\\\langue.ttf\")\r\n\t\tpygame.display.update()\r\n\t\ttmp_1 -= 1\r\n\t\tif tmp_3 < 220:\r\n\t\t\ttmp_3 += 5\r\n\t\telse:\r\n\t\t\ttmp_3 += 12\r\n\r\n\t\tfor event in pygame.event.get():\r\n\t\t\t\tif event.type == pygame.QUIT:\r\n\t\t\t\t\tpygame.quit()\r\n\t\t\t\t\tquit()\r\n\r\n\ttmp_2 = -800\t\t\t\t\r\n\ttmp_1 = 80\r\n\twhile 0 < tmp_1:\r\n\t\tclock.tick(30)\r\n\t\twin.fill((0,0,0))\r\n\t\twin.blit(bg,(0,tmp_2))\r\n\t\tpygame.display.update()\r\n\t\ttmp_2 += 10\t\t\t\t\r\n\t\ttmp_1 -= 1\r\n\r\n\t\tfor event in pygame.event.get():\r\n\t\t\t\tif event.type == pygame.QUIT:\r\n\t\t\t\t\tpygame.quit()\r\n\t\t\t\t\tquit()\r\n\r\ndef preview_shop():\r\n\ttmp_1 = 12\r\n\ttmp_2 = 12\r\n\twhile tmp_1 > 0:\r\n\t\tclock.tick(30)\r\n\t\twin.blit(shop_in,(0,0))\r\n\t\tif tmp_2 > 2:\r\n\t\t\twin.blit(shop_in_preview[1],(268,505))\r\n\t\telse:\r\n\t\t\twin.blit(shop_in_preview[0],(268,505))\r\n\t\ttmp_1 -= 1\r\n\t\ttmp_2 -= 1\r\n\t\tpygame.display.update()\r\n\t\tfor event in pygame.event.get():\r\n\t\t\t\tif event.type == pygame.QUIT:\r\n\t\t\t\t\tpygame.quit()\r\n\t\t\t\t\tquit()\r\n\r\n# Создание простого текста\r\ndef print_text(message, x, y, font_color = (0,0,0), font_size = 30, font_type = \"D:\\\\JustMonika\\\\_RunFatCat(1)\\\\ara\\\\langue.ttf\"):\r\n\tfont = pygame.font.Font(font_type, font_size)\r\n\ttext = font.render(message, True, font_color) \r\n\twin.blit(text, (x, y))\r\n# СПЕЦИАЛЬНО создание текста для уровней, только для них\r\ndef print_text_in_rect(message, x, y, font_color = (0,0,0), font_size = 30, font_type = \"D:\\\\JustMonika\\\\_RunFatCat(1)\\\\ara\\\\langue.ttf\", link = None, level = None):\r\n\tglobal click_press\r\n\tfont = pygame.font.Font(font_type, font_size)\r\n\ttext = font.render(message, True, font_color)\r\n\tmouse = pygame.mouse.get_pos()\r\n\tclick = pygame.mouse.get_pressed()\r\n\tif x < mouse[0] < x + 120 and y < mouse[1] < y + 30:\r\n\t\tif level <= unlock_level.unlock_level:\r\n\t\t\tpygame.draw.rect(win,(60,90,60),(x, y, 120, 30))\r\n\t\t\tif click[0] == 1 and click_press:\r\n\t\t\t\tclick_press = False\r\n\t\t\t\tlink()\r\n\t\t\tif click[0] != 1:\r\n\t\t\t\tclick_press = True\r\n\t\telse:\r\n\t\t\tpygame.draw.rect(win,(80,60,60),(x, y, 120, 30))\r\n\t\t\tif click[0] == 1 and click_press:\r\n\t\t\t\tprint_text(message = \"Не дорос еще\", x = 100, y = 200, font_color = (200,0,0), font_size = 70, font_type = \"D:\\\\JustMonika\\\\_RunFatCat(1)\\\\ara\\\\langue.ttf\")\r\n\telse:\r\n\t\tpygame.draw.rect(win,(60,60,60),(x, y, 120, 30))\r\n\twin.blit(text, (x, y))\r\n\r\n\r\ndef back_or_fight():\r\n\tglobal mission_key, wait, click_press\r\n\tfont = pygame.font.Font(\"D:\\\\JustMonika\\\\_RunFatCat(1)\\\\ara\\\\langue.ttf\", 50)\r\n\ttext = font.render(\"В бой или домой?\", True, (0,0,0))\r\n\tmouse = pygame.mouse.get_pos()\r\n\tclick = pygame.mouse.get_pressed()\r\n\tif 56 <= mouse[1] <= 106:\r\n\t\tif 544 <= mouse[0] <= 630:\r\n\t\t\tpygame.draw.rect(win,(0,155,0), (544, 56, 86, 50))\r\n\t\t\tpygame.draw.rect(win,(255,255,255), (735, 56, 156, 50))\r\n\t\t\tif click[0] == 1 and click_press:\r\n\t\t\t\tclick_press = False\r\n\t\t\t\twait = False\r\n\t\t\telif click[0] != click_press:\r\n\t\t\t\tclick_press = True\r\n\t\telif 735 <= mouse[0] <= 891:\r\n\t\t\tpygame.draw.rect(win,(0,155,0), (735, 56, 156, 50))\r\n\t\t\tpygame.draw.rect(win,(255,255,255), (544, 56, 86, 50))\r\n\t\t\tif click[0] == 1 and click_press:\r\n\t\t\t\tclick_press = False\r\n\t\t\t\twait = False\r\n\t\t\t\tmission_key = False\r\n\t\t\telif click[0] != click_press:\r\n\t\t\t\tclick_press = True\r\n\t\telse:\r\n\t\t\tpygame.draw.rect(win,(255,255,255), (544, 56, 86, 50))\r\n\t\t\tpygame.draw.rect(win,(255,255,255), (735, 56, 156, 50))\r\n\telse:\t\r\n\t\tpygame.draw.rect(win,(255,255,255), (544, 56, 86, 50))\r\n\t\tpygame.draw.rect(win,(255,255,255), (735, 56, 156, 50))\r\n\twin.blit(text, (500, 50))\r\n\r\n\r\n\r\n\r\n# ------------------------------------------- Сливное меню\r\n\r\ndef draw_lose():\r\n\tglobal main_lose\r\n\twin.fill((200,200,200))\r\n\tfont = pygame.font.Font(\"D:\\\\JustMonika\\\\_RunFatCat(1)\\\\ara\\\\langue.ttf\", 50)\r\n\ttext = font.render(\"Слив\", True, (0,0,0))\r\n\tmouse = pygame.mouse.get_pos()\r\n\tclick = pygame.mouse.get_pressed()\r\n\tif 0 <= mouse[1] <= 50 and 0 <= mouse[0] <= 50:\r\n\t\tpygame.draw.rect(win,(255,200,255), (0, 0, 50, 50))\r\n\t\tif click[0] == 1 and click_press:\r\n\t\t\tmain_lose = False\r\n\telse:\r\n\t\tpygame.draw.rect(win,(255,255,255), (0, 0, 50, 50))\r\n\twin.blit(text, (500, 50))\r\n\tpygame.display.update()\r\n\r\n\r\ndef lose():\r\n\tglobal mission_key, main_lose\r\n\tmain_lose = True\r\n\tmission_key = False\r\n\thero.hp = hero_hp\r\n\thero.x = hero_x\r\n\thero.y = hero_y\r\n\thero.touch = False\r\n\thero.touch_count = 15\r\n\twhile main_lose:\r\n\t\tdraw_lose()\r\n\t\tfor event in pygame.event.get():\r\n\t\t\tif event.type == pygame.QUIT:\r\n\t\t\t\tsave.save_data()\r\n\t\t\t\tpygame.quit()\r\n\t\t\t\tquit()\r\n\r\n# ------------------------------------------- Победное меню\r\n\r\ndef draw_victory():\r\n\tglobal main_victory, click_press\r\n\twin.fill((200,200,200))\r\n\tfont = pygame.font.Font(\"D:\\\\JustMonika\\\\_RunFatCat(1)\\\\ara\\\\langue.ttf\", 50)\r\n\ttext = font.render(\"Победка\", True, (0,0,0))\r\n\tmouse = pygame.mouse.get_pos()\r\n\tclick = pygame.mouse.get_pressed()\r\n\tif 0 <= mouse[1] <= 50 and 600 <= mouse[0] <= 680:\r\n\t\tpygame.draw.rect(win,(255,200,255), (600, 0, 80, 50))\r\n\t\tif click[0] == 1 and click_press:\r\n\t\t\tmain_victory = False\r\n\t\t\tclick_press = False\r\n\t\tif click[0] != 1:\r\n\t\t\tclick_press = True\r\n\telse:\r\n\t\tpygame.draw.rect(win,(255,255,255), (600, 0, 80, 50))\r\n\twin.blit(text, (500, 50))\r\n\tpygame.display.update()\r\n\r\n\r\n\r\ndef victory():\r\n\tglobal mission_key, main_victory\r\n\tmain_victory = True\r\n\tmission_key = False\r\n\thero.hp = hero_hp\r\n\thero.x = hero_x\r\n\thero.y = hero_y\r\n\thero.touch = False\r\n\thero.touch_count = 15\r\n\r\n\twhile main_victory:\r\n\t\tdraw_victory()\r\n\t\tfor event in pygame.event.get():\r\n\t\t\tif event.type == pygame.QUIT:\r\n\t\t\t\tsave.save_data()\r\n\t\t\t\tpygame.quit()\r\n\t\t\t\tquit()\r\n\r\n\r\n# ------------------------------------------- 1 LEVEL ---------------------------------\r\ndef draw_stay_mision_1():\r\n\twin.fill((200,200,200))\r\n\tfor enemy in enemy_mision_1:\r\n\t\tenemy.stay_to_fight()\r\n\tback_or_fight()\r\n\tpygame.display.update()\r\n\r\n\r\n\r\ndef draw_mision_1():\r\n\tglobal defeat, enemy_mision_1\r\n\twin.fill((200,200,200))\r\n\tcheck_melee(enemy_mision_1)\r\n\r\n\tfor enemy in enemy_mision_1:\r\n\t\tenemy.health_bar_enemy()\r\n\t\tif enemy.touch == True:\r\n\t\t\tenemy.touch_enemy()\r\n\t\telse:\r\n\t\t\tenemy.move()\r\n\t\tif enemy.hp <= 0:\r\n\t\t\tenemy_mision_1.remove(enemy)\r\n\r\n\thero.healt_bar_hero()\r\n\tif hero.touch == True:\r\n\t\thero.hero_touch()\r\n\telse:\r\n\t\thero.hero_move()\r\n\tif hero.hp <= 0:\r\n\t\tlose()\r\n\tif not enemy_mision_1:\r\n\t\tif unlock_level.unlock_level == 1:\r\n\t\t\tunlock_level.unlock_level += 1\r\n\t\tvictory()\r\n\r\n\tpygame.display.update()\r\n\r\ndef mission_1():\r\n\tglobal mission_key, wait, enemy_mision_1\r\n\tenemy_mision_1 = [Enemy_easy_nogune(x = 1080, y = 500, model = enemy[0] , speed = 2, hp = 15, damage = 10, kick = 4, resistance_to_kick = 2, weapon = None, touch = False, touch_count = 15, touch_kick = None),\r\n\t\t\t\t\tEnemy_easy_nogune(x = 1200, y = 500, model = enemy[0] , speed = 2, hp = 15, damage = 10, kick = 4, resistance_to_kick = 2, weapon = None, touch = False, touch_count = 15, touch_kick = None),\r\n\t\t\t\t\tEnemy_easy_nogune(x = 1080, y = 400, model = enemy[0] , speed = 2, hp = 15, damage = 10, kick = 4, resistance_to_kick = 2, weapon = None, touch = False, touch_count = 15, touch_kick = None),\r\n\t\t\t\t\tEnemy_easy_nogune(x = 1200, y = 600, model = enemy[0] , speed = 2, hp = 15, damage = 10, kick = 4, resistance_to_kick = 2, weapon = None, touch = False, touch_count = 15, touch_kick = None),\r\n\t\t\t\t\tEnemy_easy_nogune(x = 1080, y = 600, model = enemy[0] , speed = 2, hp = 15, damage = 10, kick = 4, resistance_to_kick = 2, weapon = None, touch = False, touch_count = 15, touch_kick = None),\r\n\t\t\t\t\tEnemy_easy_nogune(x = 1200, y = 400, model = enemy[0] , speed = 2, hp = 15, damage = 10, kick = 4, resistance_to_kick = 2, weapon = None, touch = False, touch_count = 15, touch_kick = None)]\r\n\twait = True\r\n\tmission_key = True\r\n\twhile wait:\r\n\t\tclock.tick(60)\r\n\t\tdraw_stay_mision_1()\r\n\t\tfor event in pygame.event.get():\r\n\t\t\tif event.type == pygame.QUIT:\r\n\t\t\t\tsave.save_data()\r\n\t\t\t\tpygame.quit()\r\n\t\t\t\tquit()\r\n\r\n\twhile mission_key:\r\n\t\tclock.tick(60)\r\n\t\tdraw_mision_1()\r\n\t\tfor event in pygame.event.get():\r\n\t\t\tif event.type == pygame.QUIT:\r\n\t\t\t\tsave.save_data()\r\n\t\t\t\tpygame.quit()\r\n\t\t\t\tquit()\r\n\r\n# ------------------------------------------- 2 LEVEL ---------------------------------\r\ndef draw_mision_2():\r\n\twin.fill((200,200,200))\r\n\tpygame.display.update()\r\n\tfor event in pygame.event.get():\r\n\t\tif event.type == pygame.QUIT:\r\n\t\t\tpygame.quit()\r\n\t\t\tquit()\r\n\r\ndef mission_2():\r\n\tglobal mission_key\r\n\tmission_key = True\r\n\twhile mission_key:\r\n\t\tclock.tick(60)\r\n\t\tdraw_mision_2()\r\n# ------------------------------------------- 3 LEVEL ---------------------------------\r\ndef draw_mision_3():\r\n\twin.fill((200,200,200))\r\n\tpygame.display.update()\r\n\tfor event in pygame.event.get():\r\n\t\tif event.type == pygame.QUIT:\r\n\t\t\tpygame.quit()\r\n\t\t\tquit()\r\n\r\ndef mission_3():\r\n\tglobal mission_key\r\n\tmission_key = True\r\n\twhile mission_key:\r\n\t\tclock.tick(60)\r\n\t\tdraw_mision_3()\t\t\r\n\t\t\r\n\t\t\r\n\r\nclass Button: # Класс для создание простых кнопок с ссылкой\r\n\r\n\tdef __init__(self, width, height, active_button = (200,200,200), unactive_button = (200,200,255), link = None):\r\n\t\tself.width = width\r\n\t\tself.height = height\r\n\t\tself.active_button = active_button\r\n\t\tself.unactive_button = unactive_button\r\n\t\tself.link = link\r\n\tdef draw_rect(self, x, y,):\r\n\t\tglobal click_press\r\n\t\tmouse = pygame.mouse.get_pos() # print(mouse) >>> [x, y]\r\n\t\tclick = pygame.mouse.get_pressed() # print(click) >>> [0, 0]\r\n\r\n\t\tif x < mouse[0] < x + self.width and y < mouse[1] < y + self.height:\r\n\t\t\tpygame.draw.rect(win, self.active_button, (x, y, self.width, self.height))\r\n\t\t\r\n\t\t\tif click[0] == 1 and self.link != None and click_press:\r\n\t\t\t\tclick_press = False\r\n\t\t\t\tself.link()\r\n\t\t\tif click[0] != 1:\r\n\t\t\t\tclick_press = True\r\n\t\t\t\r\n\t\telse:\r\n\t\t\tpygame.draw.rect(win, self.unactive_button, (x, y, self.width, self.height))\r\n\r\n\r\n\r\nclass Enemy_easy_nogune:\r\n\tdef __init__(self, x, y, model, speed, hp, damage, kick, resistance_to_kick, weapon = None, touch = False, touch_count = None, touch_kick = None):\r\n\t\tself.x = x\r\n\t\tself.y = y\r\n\t\tself.model = model\r\n\t\tself.speed = speed\r\n\t\tself.hp = hp\r\n\t\tself.damage = damage\r\n\t\tself.kick = kick\r\n\t\tself.resistance_to_kick = resistance_to_kick\r\n\t\tself.weapon = weapon\r\n\t\tself.type = \"bad\"\r\n\t\tself.attack = \"good\"\r\n\t\tself.touch = touch\r\n\t\tself.touch_count = touch_count\r\n\t\tself.touch_kick = touch_kick\r\n\t\tself.healt_bar = 140\r\n\t\tself.healt_bar_persent = self.hp / 130\r\n\tdef stay_to_fight(self):\r\n\t\twin.blit(self.model,(self.x,self.y))\r\n\t\tif not self.weapon == None:\r\n\t\t\twin.blit(self.weapon,(self.x,self.y))\r\n\tdef move(self):\r\n\t\tif self.x > 100:\r\n\t\t\tself.x -= self.speed\r\n\t\t\twin.blit(self.model,(self.x,self.y))\r\n\t\telse:\r\n\t\t\twin.blit(self.model,(self.x,self.y))\r\n\tdef touch_enemy(self):\r\n\t\tif self.x < 1280:\r\n\t\t\tif self.touch_count > 0:\r\n\t\t\t\tself.x += self.touch_kick\r\n\t\t\t\tself.touch_count -= 1\r\n\t\t\telse:\r\n\t\t\t\tself.touch_count = 15\r\n\t\t\t\tself.touch = False\t\r\n\t\t\twin.blit(self.model,(self.x,self.y))\r\n\tdef health_bar_enemy(self):\r\n\t\tpygame.draw.rect(win,(155,0,0),(self.x, self.y - 30 ,self.healt_bar, 20))\r\n\t\tself.healt_bar = self.hp / self.healt_bar_persent\r\n\r\n\r\nclass Hero:\r\n\tdef __init__(self, x, y, model, speed, hp, damage, kick, resistance_to_kick, weapon = None, touch = False, touch_count = None, touch_kick = None):\r\n\t\tself.x = x\r\n\t\tself.y = y\r\n\t\tself.model = model\r\n\t\tself.speed = speed\r\n\t\tself.hp = hp\r\n\t\tself.damage = damage\r\n\t\tself.kick = kick\r\n\t\tself.resistance_to_kick = resistance_to_kick\r\n\t\tself.weapon = weapon\r\n\t\tself.type = \"good\"\r\n\t\tself.attack = \"bad\"\r\n\t\tself.touch = touch\r\n\t\tself.touch_count = touch_count\r\n\t\tself.touch_kick = touch_kick\r\n\t\tself.healt_bar = 100\r\n\t\tself.healt_bar_persent = self.hp / 100\r\n\r\n\tdef hero_move(self):\r\n\t\tif self.x < 1000:\r\n\t\t\tself.x += self.speed\r\n\t\t\twin.blit(self.model,(self.x, self.y))\r\n\t\telse:\r\n\t\t\twin.blit(self.model,(self.x, self.y))\r\n\r\n\r\n\tdef hero_touch(self):\r\n\t\tglobal touch_count, hero_x, touch\r\n\t\tif self.touch_count > 0:\r\n\t\t\tself.x -= self.touch_kick\r\n\t\t\tself.touch_count -= 1\r\n\t\telse:\r\n\t\t\tself.touch_count = 15\r\n\t\t\tself.touch = False\r\n\t\twin.blit(self.model,(self.x, self.y))\r\n\tdef healt_bar_hero(self):\r\n\t\tpygame.draw.rect(win,(155,0,0),(self.x, self.y - 30 ,self.healt_bar, 20))\r\n\t\tself.healt_bar = self.hp / self.healt_bar_persent\r\n\r\n\r\n\r\n\r\n\r\n\r\ndef check_melee(enemy_list):\r\n\tfor enemy in enemy_list:\r\n\t\tif hero.x + 120 > enemy.x:\r\n\t\t\tenemy.hp -= hero.damage\r\n\t\t\thero.hp -= enemy.damage\r\n\t\t\tenemy.touch = True\r\n\t\t\tenemy.touch_kick = hero.kick\r\n\t\t\thero.touch = True\r\n\t\t\thero.touch_kick = enemy.kick\r\n\r\n\r\n\r\nwin_width = 1280 # Ширина окна\r\nwin_height = 800 # Высота окна\r\npygame.init() # Запуск pygame\r\nwin = pygame.display.set_mode((win_width, win_height)) # Создание основного окна\r\npygame.display.set_caption(\"AlleyWay\") # Изменение названия окна\r\n\r\n# --------------------------------- Основная игра(вид сверху)\r\n\r\nbg = pygame.image.load(\"D:\\\\JustMonika\\\\_AlleyWay(3)\\\\bg.png\")\r\nbg = pygame.transform.scale(bg,(1280,800))\r\n\r\nhome_anim = pygame.image.load(\"D:\\\\JustMonika\\\\_AlleyWay(3)\\\\home_active.png\")\r\n\r\nshop_anim = [pygame.image.load(\"D:\\\\JustMonika\\\\_AlleyWay(3)\\\\shop_active_1.png\"),\r\n\t\t\tpygame.image.load(\"D:\\\\JustMonika\\\\_AlleyWay(3)\\\\shop_active_2.png\")]\r\nshop_anim_count = 30\r\n\r\n# --------------------------------- Магазин внутри\r\nmain_rack = False\r\nmain_shop = False\r\nshop_in_preview = [pygame.image.load(\"D:\\\\JustMonika\\\\_AlleyWay(3)\\\\door_close_2.png\"),pygame.image.load(\"D:\\\\JustMonika\\\\_AlleyWay(3)\\\\door_close_1.png\")]\r\nshop_in = pygame.image.load(\"D:\\\\JustMonika\\\\_AlleyWay(3)\\\\shop_in.png\")\r\nshop_in_door_active_1 = pygame.image.load(\"D:\\\\JustMonika\\\\_AlleyWay(3)\\\\shop_in_door_active_1.png\")\r\nshop_in_door_active_2 = pygame.image.load(\"D:\\\\JustMonika\\\\_AlleyWay(3)\\\\shop_in_door_active_2.png\")\r\nshop_in_active = pygame.image.load(\"D:\\\\JustMonika\\\\_AlleyWay(3)\\\\shop_in_active.png\")\r\nshop_in_active = pygame.transform.scale(shop_in_active, (312,235))\r\nrack_image = pygame.image.load(\"D:\\\\JustMonika\\\\_AlleyWay(3)\\\\Rack.png\")\r\n\r\n# --------------------------------- Квартика внутри\r\n\r\nmain_home = False\r\nhome_in = pygame.image.load(\"D:\\\\JustMonika\\\\_AlleyWay(3)\\\\home_in.png\")\r\n\r\n# --------------------------------- Меню выбора миссий\r\n\r\nmain_mission_select = False\r\nwait = False\r\n# Должны быть модельки\r\n\r\n# --------------------------------- Враги\r\n\r\nenemy = [pygame.image.load(\"D:\\\\JustMonika\\\\_AlleyWay(3)\\\\enemy_test.png\")]\r\n\r\n# --------------------------------- Остальное\r\n\r\nclock = pygame.time.Clock() # Таймер смены кадров\r\nclick_press = True # пока не используется \r\n\r\n\r\n# Создание ключей для всех уровней, чтобы потом можно было выйти. уровень или пройти его\r\nmission_key = False\r\nmain_lose = False\r\n\r\nhero_hp = 130\r\nhero_x = 15\r\nhero_y = 500\r\n\r\n# --------------------------------- Главный герой\r\nhero_model = pygame.image.load(\"D:\\\\JustMonika\\\\_AlleyWay(3)\\\\charapter.png\")\r\ndefeat = []\r\n\r\nhero = Hero(x = 15 , y = 500, model = hero_model, speed = 3, hp = hero_hp, damage = 15, kick = 3, resistance_to_kick = 2, weapon = None, touch = False, touch_count = 15, touch_kick = None)\r\n\r\n\r\nenemy_mision_1 = []\r\nclass Unlock_level_class:\r\n\tdef __init__(self, unlock_level):\r\n\t\tself.unlock_level = unlock_level\r\nunlock_level = Unlock_level_class(1)\r\n\r\nsave_item_pls = Save_item([Shop_item(50, 50),Shop_item(50, 50),Shop_item(50, 50),Shop_item(50, 50),Shop_item(50, 50),Shop_item(50, 50),Shop_item(50, 50),Shop_item(50, 50),\r\n\t\t\t\t\t\t\tShop_item(50, 50),Shop_item(50, 50),Shop_item(50, 50),Shop_item(50, 50),Shop_item(50, 50),Shop_item(50, 50),Shop_item(50, 50)])\r\n\r\n\r\n\r\nhero_hp = 130\r\nhero_model = pygame.image.load(\"D:\\\\JustMonika\\\\_AlleyWay(3)\\\\charapter.png\")\r\n\r\nunlock_level.unlock_level = save.get_date('unlock_level')\r\nsave_item_pls.list_shop_item = save.get_date('shop_item')\r\nsave_item_pls.list_home_item = save.get_date('home_item')\r\n\r\n#preview_2()\r\nwhile main_game():\r\n\tpass\r\npygame.quit()\r\nquit()","sub_path":"_AlleyWay(3)/all_code.py","file_name":"all_code.py","file_ext":"py","file_size_in_byte":25767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"49528296","text":"from pathlib import Path\nimport subprocess\nimport argparse\n\n\ndef make_operation(command: str):\n root = Path(__file__).absolute().parent\n if not Path.joinpath(root, 'build').exists():\n Path.joinpath(root, 'build').mkdir(exist_ok=True)\n for cwe in Path.joinpath(root, 'testcases').rglob('*'):\n if str(cwe).endswith('Makefile'):\n print(f'Makefile found at {cwe}!')\n try:\n subprocess.run(args=['make', command], stderr=subprocess.STDOUT, cwd=str(cwe.parent), check=True)\n except subprocess.CalledProcessError as err:\n print('Status : FAIL', err.returncode)\n\n\ndef delete_bat_files():\n for cwe in Path.joinpath(Path(__file__).absolute().parent, 'testcases').rglob('*'):\n if str(cwe).endswith('.bat'):\n cwe.unlink(missing_ok=True)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n\n parser.add_argument('-a', '--all', dest='all', action='store_true',\n help='Iterates over all testcase directories and executes the corresponding '\n 'Makefile with \"make all\".')\n parser.add_argument('-c', '--clean', dest='clean', action='store_true',\n help='Iterates over all testcase directories and executes the corresponding '\n 'Makefile with \"make clean\".')\n parser.add_argument('-rb', '--remove-bat', dest='remove_bat', action='store_true',\n help='Removes bat files in all testcase directories. As they are not needed'\n 'for this project.')\n args = parser.parse_args()\n\n if args.all:\n make_operation(command='all')\n if args.clean:\n make_operation(command='clean')\n if args.remove_bat:\n delete_bat_files()\n","sub_path":"handle_make.py","file_name":"handle_make.py","file_ext":"py","file_size_in_byte":1805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"246353507","text":"from __future__ import absolute_import, print_function, unicode_literals\n\nfrom jinja2 import Template\n\nfrom actions.named_shell_task import render_task\nfrom .interface import Action\n\n_SCRIPT_TITLE = \"EXECUTE A SCRIPT ON THE REMOTE HOST\"\n_SCRIPT_ACTION_TEMPLATE = Template(\"\"\"script=\"$( mktemp )\"\ncat <